blob: 8ed795abbb7a56a412a1542a7e1b3ba7cf8d1b65 [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
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000011/// Implements semantic analysis for C++ expressions.
James Dennett84053fb2012-06-22 05:14:59 +000012///
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"
Akira Hatanaka3e40c302017-07-19 17:17:50 +000027#include "clang/Basic/AlignedAllocation.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000028#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000029#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000030#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000037#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000039#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000040#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000041#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000042using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000043using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000044
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000045/// Handle the result of the special case name lookup for inheriting
Richard Smith7447af42013-03-26 01:15:19 +000046/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000071 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000072 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
Richard Smith715ee072018-06-20 21:58:20 +000083ParsedType Sema::getConstructorName(IdentifierInfo &II,
84 SourceLocation NameLoc,
Richard Smith69bc9aa2018-06-22 19:50:19 +000085 Scope *S, CXXScopeSpec &SS,
86 bool EnteringContext) {
Richard Smith715ee072018-06-20 21:58:20 +000087 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88 assert(CurClass && &II == CurClass->getIdentifier() &&
89 "not a constructor name");
90
Richard Smith69bc9aa2018-06-22 19:50:19 +000091 // When naming a constructor as a member of a dependent context (eg, in a
92 // friend declaration or an inherited constructor declaration), form an
93 // unresolved "typename" type.
94 if (CurClass->isDependentContext() && !EnteringContext) {
95 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96 return ParsedType::make(T);
97 }
98
Richard Smith715ee072018-06-20 21:58:20 +000099 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
100 return ParsedType();
101
102 // Find the injected-class-name declaration. Note that we make no attempt to
103 // diagnose cases where the injected-class-name is shadowed: the only
104 // declaration that can validly shadow the injected-class-name is a
105 // non-static data member, and if the class contains both a non-static data
106 // member and a constructor then it is ill-formed (we check that in
107 // CheckCompletedCXXClass).
108 CXXRecordDecl *InjectedClassName = nullptr;
109 for (NamedDecl *ND : CurClass->lookup(&II)) {
110 auto *RD = dyn_cast<CXXRecordDecl>(ND);
111 if (RD && RD->isInjectedClassName()) {
112 InjectedClassName = RD;
113 break;
114 }
115 }
Ilya Biryukova2d58252018-07-04 08:50:12 +0000116 if (!InjectedClassName && CurClass->isInvalidDecl())
117 return ParsedType();
Richard Smith715ee072018-06-20 21:58:20 +0000118 assert(InjectedClassName && "couldn't find injected class name");
119
120 QualType T = Context.getTypeDeclType(InjectedClassName);
121 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
122 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
123
124 return ParsedType::make(T);
125}
126
John McCallba7bf592010-08-24 05:47:05 +0000127ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000128 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +0000129 SourceLocation NameLoc,
130 Scope *S, CXXScopeSpec &SS,
131 ParsedType ObjectTypePtr,
132 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000133 // Determine where to perform name lookup.
134
135 // FIXME: This area of the standard is very messy, and the current
136 // wording is rather unclear about which scopes we search for the
137 // destructor name; see core issues 399 and 555. Issue 399 in
138 // particular shows where the current description of destructor name
139 // lookup is completely out of line with existing practice, e.g.,
140 // this appears to be ill-formed:
141 //
142 // namespace N {
143 // template <typename T> struct S {
144 // ~S();
145 // };
146 // }
147 //
148 // void f(N::S<int>* s) {
149 // s->N::S<int>::~S();
150 // }
151 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000152 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000153 // For this reason, we're currently only doing the C++03 version of this
154 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000155 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000156 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000157 bool isDependent = false;
158 bool LookInScope = false;
159
Richard Smith64e033f2015-01-15 00:48:52 +0000160 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000161 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000162
Douglas Gregorfe17d252010-02-16 19:09:40 +0000163 // If we have an object type, it's because we are in a
164 // pseudo-destructor-expression or a member access expression, and
165 // we know what type we're looking for.
166 if (ObjectTypePtr)
167 SearchType = GetTypeFromParser(ObjectTypePtr);
168
169 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000170 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000171
Douglas Gregor46841e12010-02-23 00:15:22 +0000172 bool AlreadySearched = false;
173 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000174 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000175 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000176 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000177 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000178 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000179 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000180 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000181 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000182 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000183 // Here, we determine whether the code below is permitted to look at the
184 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000185 DeclContext *DC = computeDeclContext(SS, EnteringContext);
186 if (DC && DC->isFileContext()) {
187 AlreadySearched = true;
188 LookupCtx = DC;
189 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000190 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000191 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000192 LookInScope = true;
193 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000194
Sebastian Redla771d222010-07-07 23:17:38 +0000195 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000196 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000197 if (AlreadySearched) {
198 // Nothing left to do.
199 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
200 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000201 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000202 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
203 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000204 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000205 LookupCtx = computeDeclContext(SearchType);
206 isDependent = SearchType->isDependentType();
207 } else {
208 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000209 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000210 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000211 } else if (ObjectTypePtr) {
212 // C++ [basic.lookup.classref]p3:
213 // If the unqualified-id is ~type-name, the type-name is looked up
214 // in the context of the entire postfix-expression. If the type T
215 // of the object expression is of a class type C, the type-name is
216 // also looked up in the scope of class C. At least one of the
217 // lookups shall find a name that refers to (possibly
218 // cv-qualified) T.
219 LookupCtx = computeDeclContext(SearchType);
220 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000221 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000222 "Caller should have completed object type");
223
224 LookInScope = true;
225 } else {
226 // Perform lookup into the current scope (only).
227 LookInScope = true;
228 }
229
Craig Topperc3ec1492014-05-26 06:22:03 +0000230 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000231 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
232 for (unsigned Step = 0; Step != 2; ++Step) {
233 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000234 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000235 // we're allowed to look there).
236 Found.clear();
John McCallcb731542017-06-11 20:33:00 +0000237 if (Step == 0 && LookupCtx) {
238 if (RequireCompleteDeclContext(SS, LookupCtx))
239 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000240 LookupQualifiedName(Found, LookupCtx);
John McCallcb731542017-06-11 20:33:00 +0000241 } else if (Step == 1 && LookInScope && S) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000242 LookupName(Found, S);
John McCallcb731542017-06-11 20:33:00 +0000243 } else {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000244 continue;
John McCallcb731542017-06-11 20:33:00 +0000245 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000246
247 // FIXME: Should we be suppressing ambiguities here?
248 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000249 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000250
251 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
252 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000253 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000254
255 if (SearchType.isNull() || SearchType->isDependentType() ||
256 Context.hasSameUnqualifiedType(T, SearchType)) {
257 // We found our type!
258
Richard Smithc278c002014-01-22 00:30:17 +0000259 return CreateParsedType(T,
260 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000261 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000262
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000263 if (!SearchType.isNull())
264 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000265 }
266
267 // If the name that we found is a class template name, and it is
268 // the same name as the template name in the last part of the
269 // nested-name-specifier (if present) or the object type, then
270 // this is the destructor for that class.
271 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000272 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000273 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
274 QualType MemberOfType;
275 if (SS.isSet()) {
276 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
277 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000278 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
279 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000280 }
281 }
282 if (MemberOfType.isNull())
283 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000284
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285 if (MemberOfType.isNull())
286 continue;
287
288 // We're referring into a class template specialization. If the
289 // class template we found is the same as the template being
290 // specialized, we found what we are looking for.
291 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
292 if (ClassTemplateSpecializationDecl *Spec
293 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
294 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
295 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000296 return CreateParsedType(
297 MemberOfType,
298 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000299 }
300
301 continue;
302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000303
Douglas Gregorfe17d252010-02-16 19:09:40 +0000304 // We're referring to an unresolved class template
305 // specialization. Determine whether we class template we found
306 // is the same as the template being specialized or, if we don't
307 // know which template is being specialized, that it at least
308 // has the same name.
309 if (const TemplateSpecializationType *SpecType
310 = MemberOfType->getAs<TemplateSpecializationType>()) {
311 TemplateName SpecName = SpecType->getTemplateName();
312
313 // The class template we found is the same template being
314 // specialized.
315 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
316 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000317 return CreateParsedType(
318 MemberOfType,
319 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000320
321 continue;
322 }
323
324 // The class template we found has the same name as the
325 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000326 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000327 = SpecName.getAsDependentTemplateName()) {
328 if (DepTemplate->isIdentifier() &&
329 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000330 return CreateParsedType(
331 MemberOfType,
332 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000333
334 continue;
335 }
336 }
337 }
338 }
339
340 if (isDependent) {
341 // We didn't find our type, but that's okay: it's dependent
342 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000343
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000344 // FIXME: What if we have no nested-name-specifier?
345 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
346 SS.getWithLocInContext(Context),
347 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000348 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000349 }
350
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000351 if (NonMatchingTypeDecl) {
352 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
353 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
354 << T << SearchType;
355 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
356 << T;
357 } else if (ObjectTypePtr)
358 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000360 else {
361 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
362 diag::err_destructor_class_name);
363 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000364 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000365 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
366 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
367 Class->getNameAsString());
368 }
369 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000370
David Blaikieefdccaa2016-01-15 23:43:34 +0000371 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000372}
373
Richard Smithef2cd8f2017-02-08 20:39:08 +0000374ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
375 ParsedType ObjectType) {
376 if (DS.getTypeSpecType() == DeclSpec::TST_error)
377 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000378
Richard Smithef2cd8f2017-02-08 20:39:08 +0000379 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
380 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
381 return nullptr;
382 }
383
384 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
385 "unexpected type in getDestructorType");
386 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
387
388 // If we know the type of the object, check that the correct destructor
389 // type was named now; we can give better diagnostics this way.
390 QualType SearchType = GetTypeFromParser(ObjectType);
391 if (!SearchType.isNull() && !SearchType->isDependentType() &&
392 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000393 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
394 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000395 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000396 }
397
398 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000399}
400
Richard Smithd091dc12013-12-05 00:58:33 +0000401bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
402 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000403 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000404
405 if (!SS.isValid())
406 return false;
407
408 switch (SS.getScopeRep()->getKind()) {
409 case NestedNameSpecifier::Identifier:
410 case NestedNameSpecifier::TypeSpec:
411 case NestedNameSpecifier::TypeSpecWithTemplate:
412 // Per C++11 [over.literal]p2, literal operators can only be declared at
413 // namespace scope. Therefore, this unqualified-id cannot name anything.
414 // Reject it early, because we have no AST representation for this in the
415 // case where the scope is dependent.
416 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
417 << SS.getScopeRep();
418 return true;
419
420 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000421 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000422 case NestedNameSpecifier::Namespace:
423 case NestedNameSpecifier::NamespaceAlias:
424 return false;
425 }
426
427 llvm_unreachable("unknown nested name specifier kind");
428}
429
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000430/// Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000431ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000432 SourceLocation TypeidLoc,
433 TypeSourceInfo *Operand,
434 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000435 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000436 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000437 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000438 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000439 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000440 Qualifiers Quals;
441 QualType T
442 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
443 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000444 if (T->getAs<RecordType>() &&
445 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
446 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000447
David Majnemer6f3150a2014-11-21 21:09:12 +0000448 if (T->isVariablyModifiedType())
449 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
450
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000451 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
452 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000453}
454
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000455/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000456ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000457 SourceLocation TypeidLoc,
458 Expr *E,
459 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000460 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000461 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000462 if (E->getType()->isPlaceholderType()) {
463 ExprResult result = CheckPlaceholderExpr(E);
464 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000465 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000466 }
467
Douglas Gregor9da64192010-04-26 22:37:10 +0000468 QualType T = E->getType();
469 if (const RecordType *RecordT = T->getAs<RecordType>()) {
470 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
471 // C++ [expr.typeid]p3:
472 // [...] If the type of the expression is a class type, the class
473 // shall be completely-defined.
474 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
475 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000476
Douglas Gregor9da64192010-04-26 22:37:10 +0000477 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000478 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000479 // polymorphic class type [...] [the] expression is an unevaluated
480 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000481 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000482 // The subexpression is potentially evaluated; switch the context
483 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000484 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000485 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000486 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000487
488 // We require a vtable to query the type at run time.
489 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000490 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000491 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493
Douglas Gregor9da64192010-04-26 22:37:10 +0000494 // C++ [expr.typeid]p4:
495 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000496 // cv-qualified type, the result of the typeid expression refers to a
497 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000498 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000499 Qualifiers Quals;
500 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
501 if (!Context.hasSameType(T, UnqualT)) {
502 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000503 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 }
505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000506
David Majnemer6f3150a2014-11-21 21:09:12 +0000507 if (E->getType()->isVariablyModifiedType())
508 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
509 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000510 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000511 E->HasSideEffects(Context, WasEvaluated)) {
512 // The expression operand for typeid is in an unevaluated expression
513 // context, so side effects could result in unintended consequences.
514 Diag(E->getExprLoc(), WasEvaluated
515 ? diag::warn_side_effects_typeid
516 : diag::warn_side_effects_unevaluated_context);
517 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000518
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000519 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
520 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000521}
522
523/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000524ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000525Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
526 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000527 // OpenCL C++ 1.0 s2.9: typeid is not supported.
528 if (getLangOpts().OpenCLCPlusPlus) {
529 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
530 << "typeid");
531 }
532
Douglas Gregor9da64192010-04-26 22:37:10 +0000533 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000534 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000535 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000536
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000537 if (!CXXTypeInfoDecl) {
538 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
539 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
540 LookupQualifiedName(R, getStdNamespace());
541 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000542 // Microsoft's typeinfo doesn't have type_info in std but in the global
543 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000544 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000545 LookupQualifiedName(R, Context.getTranslationUnitDecl());
546 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
547 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000548 if (!CXXTypeInfoDecl)
549 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
550 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
Nico Weber1b7f39d2012-05-20 01:27:21 +0000552 if (!getLangOpts().RTTI) {
553 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
554 }
555
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000556 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000557
Douglas Gregor9da64192010-04-26 22:37:10 +0000558 if (isType) {
559 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000560 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000561 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
562 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000563 if (T.isNull())
564 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregor9da64192010-04-26 22:37:10 +0000566 if (!TInfo)
567 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000568
Douglas Gregor9da64192010-04-26 22:37:10 +0000569 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000570 }
Mike Stump11289f42009-09-09 15:08:12 +0000571
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000572 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000573 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000574}
575
David Majnemer1dbc7a72016-03-27 04:46:07 +0000576/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
577/// a single GUID.
578static void
579getUuidAttrOfType(Sema &SemaRef, QualType QT,
580 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
581 // Optionally remove one level of pointer, reference or array indirection.
582 const Type *Ty = QT.getTypePtr();
583 if (QT->isPointerType() || QT->isReferenceType())
584 Ty = QT->getPointeeType().getTypePtr();
585 else if (QT->isArrayType())
586 Ty = Ty->getBaseElementTypeUnsafe();
587
Reid Klecknere516eab2016-12-13 18:58:09 +0000588 const auto *TD = Ty->getAsTagDecl();
589 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000590 return;
591
Reid Klecknere516eab2016-12-13 18:58:09 +0000592 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000593 UuidAttrs.insert(Uuid);
594 return;
595 }
596
597 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000598 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000599 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
600 for (const TemplateArgument &TA : TAL.asArray()) {
601 const UuidAttr *UuidForTA = nullptr;
602 if (TA.getKind() == TemplateArgument::Type)
603 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
604 else if (TA.getKind() == TemplateArgument::Declaration)
605 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
606
607 if (UuidForTA)
608 UuidAttrs.insert(UuidForTA);
609 }
610 }
611}
612
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000613/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000614ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
615 SourceLocation TypeidLoc,
616 TypeSourceInfo *Operand,
617 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000618 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000619 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000620 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
621 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
622 if (UuidAttrs.empty())
623 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
624 if (UuidAttrs.size() > 1)
625 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000626 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000627 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000628
David Majnemer2041b462016-03-28 03:19:50 +0000629 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000630 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000631}
632
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000633/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000634ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
635 SourceLocation TypeidLoc,
636 Expr *E,
637 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000638 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000639 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000640 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
641 UuidStr = "00000000-0000-0000-0000-000000000000";
642 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000643 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
644 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
645 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000646 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000647 if (UuidAttrs.size() > 1)
648 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000649 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000650 }
Francois Pichetb7577652010-12-27 01:32:00 +0000651 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000652
David Majnemer2041b462016-03-28 03:19:50 +0000653 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000654 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000655}
656
657/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
658ExprResult
659Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
660 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000661 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000662 if (!MSVCGuidDecl) {
663 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
664 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
665 LookupQualifiedName(R, Context.getTranslationUnitDecl());
666 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
667 if (!MSVCGuidDecl)
668 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669 }
670
Francois Pichet9f4f2072010-09-08 12:20:18 +0000671 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000672
Francois Pichet9f4f2072010-09-08 12:20:18 +0000673 if (isType) {
674 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000675 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000676 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
677 &TInfo);
678 if (T.isNull())
679 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Francois Pichet9f4f2072010-09-08 12:20:18 +0000681 if (!TInfo)
682 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
683
684 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
685 }
686
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000687 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000688 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
689}
690
Steve Naroff66356bd2007-09-16 14:56:35 +0000691/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000692ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000693Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000694 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000695 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000696 return new (Context)
697 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000698}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000699
Sebastian Redl576fd422009-05-10 18:38:11 +0000700/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000701ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000702Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000703 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000704}
705
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000706/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000707ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000708Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
709 bool IsThrownVarInScope = false;
710 if (Ex) {
711 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000712 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000713 // copy/move construction of a class object [...]
714 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000715 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000716 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000717 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000718 // innermost enclosing try-block (if there is one), the copy/move
719 // operation from the operand to the exception object (15.1) can be
720 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000721 // exception object
722 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
723 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
724 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
725 for( ; S; S = S->getParent()) {
726 if (S->isDeclScope(Var)) {
727 IsThrownVarInScope = true;
728 break;
729 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000730
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000731 if (S->getFlags() &
732 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
733 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
734 Scope::TryScope))
735 break;
736 }
737 }
738 }
739 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000740
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000741 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
742}
743
Simon Pilgrim75c26882016-09-30 14:25:09 +0000744ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000745 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000746 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000747 if (!getLangOpts().CXXExceptions &&
Alexey Bataev1ab34572018-05-02 16:52:07 +0000748 !getSourceManager().isInSystemHeader(OpLoc) &&
749 (!getLangOpts().OpenMPIsDevice ||
750 !getLangOpts().OpenMPHostCXXExceptions ||
751 isInOpenMPTargetExecutionDirective() ||
752 isInOpenMPDeclareTargetContext()))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000753 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000754
Justin Lebar2a8db342016-09-28 22:45:54 +0000755 // Exceptions aren't allowed in CUDA device code.
756 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000757 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
758 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000759
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000760 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
761 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
762
John Wiegley01296292011-04-08 18:41:53 +0000763 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000764 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
765 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000766 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000767
768 // Initialize the exception result. This implicitly weeds out
769 // abstract types or types with inaccessible copy constructors.
770
771 // C++0x [class.copymove]p31:
772 // When certain criteria are met, an implementation is allowed to omit the
773 // copy/move construction of a class object [...]
774 //
775 // - in a throw-expression, when the operand is the name of a
776 // non-volatile automatic object (other than a function or
777 // catch-clause
778 // parameter) whose scope does not extend beyond the end of the
779 // innermost enclosing try-block (if there is one), the copy/move
780 // operation from the operand to the exception object (15.1) can be
781 // omitted by constructing the automatic object directly into the
782 // exception object
783 const VarDecl *NRVOVariable = nullptr;
784 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000785 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000786
787 InitializedEntity Entity = InitializedEntity::InitializeException(
788 OpLoc, ExceptionObjectTy,
789 /*NRVO=*/NRVOVariable != nullptr);
790 ExprResult Res = PerformMoveOrCopyInitialization(
791 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
792 if (Res.isInvalid())
793 return ExprError();
794 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000795 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000796
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000797 return new (Context)
798 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000799}
800
David Majnemere7a818f2015-03-06 18:53:55 +0000801static void
802collectPublicBases(CXXRecordDecl *RD,
803 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
804 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
805 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
806 bool ParentIsPublic) {
807 for (const CXXBaseSpecifier &BS : RD->bases()) {
808 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
809 bool NewSubobject;
810 // Virtual bases constitute the same subobject. Non-virtual bases are
811 // always distinct subobjects.
812 if (BS.isVirtual())
813 NewSubobject = VBases.insert(BaseDecl).second;
814 else
815 NewSubobject = true;
816
817 if (NewSubobject)
818 ++SubobjectsSeen[BaseDecl];
819
820 // Only add subobjects which have public access throughout the entire chain.
821 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
822 if (PublicPath)
823 PublicSubobjectsSeen.insert(BaseDecl);
824
825 // Recurse on to each base subobject.
826 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
827 PublicPath);
828 }
829}
830
831static void getUnambiguousPublicSubobjects(
832 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
833 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
834 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
835 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
836 SubobjectsSeen[RD] = 1;
837 PublicSubobjectsSeen.insert(RD);
838 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
839 /*ParentIsPublic=*/true);
840
841 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
842 // Skip ambiguous objects.
843 if (SubobjectsSeen[PublicSubobject] > 1)
844 continue;
845
846 Objects.push_back(PublicSubobject);
847 }
848}
849
Sebastian Redl4de47b42009-04-27 20:27:31 +0000850/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000851bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
852 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000853 // If the type of the exception would be an incomplete type or a pointer
854 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000855 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000856 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000857 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000858 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000859 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000860 }
861 if (!isPointer || !Ty->isVoidType()) {
862 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000863 isPointer ? diag::err_throw_incomplete_ptr
864 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000865 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000866 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000867
David Majnemerd09a51c2015-03-03 01:50:05 +0000868 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000869 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000870 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000871 }
872
Eli Friedman91a3d272010-06-03 20:39:03 +0000873 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000874 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
875 if (!RD)
876 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000877
Douglas Gregor88d292c2010-05-13 16:44:06 +0000878 // If we are throwing a polymorphic class type or pointer thereof,
879 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000880 MarkVTableUsed(ThrowLoc, RD);
881
Eli Friedman36ebbec2010-10-12 20:32:36 +0000882 // If a pointer is thrown, the referenced object will not be destroyed.
883 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000884 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000885
Richard Smitheec915d62012-02-18 04:13:32 +0000886 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000887 if (!RD->hasIrrelevantDestructor()) {
888 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
889 MarkFunctionReferenced(E->getExprLoc(), Destructor);
890 CheckDestructorAccess(E->getExprLoc(), Destructor,
891 PDiag(diag::err_access_dtor_exception) << Ty);
892 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000893 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000894 }
895 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000896
David Majnemerdfa6d202015-03-11 18:36:39 +0000897 // The MSVC ABI creates a list of all types which can catch the exception
898 // object. This list also references the appropriate copy constructor to call
899 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000900 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000901 // We are only interested in the public, unambiguous bases contained within
902 // the exception object. Bases which are ambiguous or otherwise
903 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000904 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
905 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000906
David Majnemere7a818f2015-03-06 18:53:55 +0000907 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000908 // Attempt to lookup the copy constructor. Various pieces of machinery
909 // will spring into action, like template instantiation, which means this
910 // cannot be a simple walk of the class's decls. Instead, we must perform
911 // lookup and overload resolution.
912 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
913 if (!CD)
914 continue;
915
916 // Mark the constructor referenced as it is used by this throw expression.
917 MarkFunctionReferenced(E->getExprLoc(), CD);
918
919 // Skip this copy constructor if it is trivial, we don't need to record it
920 // in the catchable type data.
921 if (CD->isTrivial())
922 continue;
923
924 // The copy constructor is non-trivial, create a mapping from this class
925 // type to this constructor.
926 // N.B. The selection of copy constructor is not sensitive to this
927 // particular throw-site. Lookup will be performed at the catch-site to
928 // ensure that the copy constructor is, in fact, accessible (via
929 // friendship or any other means).
930 Context.addCopyConstructorForExceptionObject(Subobject, CD);
931
932 // We don't keep the instantiated default argument expressions around so
933 // we must rebuild them here.
934 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000935 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
936 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000937 }
938 }
939 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000940
David Majnemerba3e5ec2015-03-13 18:26:17 +0000941 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000942}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000943
Faisal Vali67b04462016-06-11 16:41:54 +0000944static QualType adjustCVQualifiersForCXXThisWithinLambda(
945 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
946 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
947
948 QualType ClassType = ThisTy->getPointeeType();
949 LambdaScopeInfo *CurLSI = nullptr;
950 DeclContext *CurDC = CurSemaContext;
951
952 // Iterate through the stack of lambdas starting from the innermost lambda to
953 // the outermost lambda, checking if '*this' is ever captured by copy - since
954 // that could change the cv-qualifiers of the '*this' object.
955 // The object referred to by '*this' starts out with the cv-qualifiers of its
956 // member function. We then start with the innermost lambda and iterate
957 // outward checking to see if any lambda performs a by-copy capture of '*this'
958 // - and if so, any nested lambda must respect the 'constness' of that
959 // capturing lamdbda's call operator.
960 //
961
Faisal Vali999f27e2017-05-02 20:56:34 +0000962 // Since the FunctionScopeInfo stack is representative of the lexical
963 // nesting of the lambda expressions during initial parsing (and is the best
964 // place for querying information about captures about lambdas that are
965 // partially processed) and perhaps during instantiation of function templates
966 // that contain lambda expressions that need to be transformed BUT not
967 // necessarily during instantiation of a nested generic lambda's function call
968 // operator (which might even be instantiated at the end of the TU) - at which
969 // time the DeclContext tree is mature enough to query capture information
970 // reliably - we use a two pronged approach to walk through all the lexically
971 // enclosing lambda expressions:
972 //
973 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
974 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
975 // enclosed by the call-operator of the LSI below it on the stack (while
976 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
977 // the stack represents the innermost lambda.
978 //
979 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
980 // represents a lambda's call operator. If it does, we must be instantiating
981 // a generic lambda's call operator (represented by the Current LSI, and
982 // should be the only scenario where an inconsistency between the LSI and the
983 // DeclContext should occur), so climb out the DeclContexts if they
984 // represent lambdas, while querying the corresponding closure types
985 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000986
Faisal Vali999f27e2017-05-02 20:56:34 +0000987 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000988 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000989 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
990 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
991 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000992 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
993 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000994
995 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000996 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000997
Faisal Vali67b04462016-06-11 16:41:54 +0000998 auto C = CurLSI->getCXXThisCapture();
999
1000 if (C.isCopyCapture()) {
1001 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1002 if (CurLSI->CallOperator->isConst())
1003 ClassType.addConst();
1004 return ASTCtx.getPointerType(ClassType);
1005 }
1006 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001007
1008 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1009 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001010 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001011 assert(CurLSI && "While computing 'this' capture-type for a generic "
1012 "lambda, we must have a corresponding LambdaScopeInfo");
1013 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1014 "While computing 'this' capture-type for a generic lambda, when we "
1015 "run out of enclosing LSI's, yet the enclosing DC is a "
1016 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1017 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001018 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001019
Faisal Vali67b04462016-06-11 16:41:54 +00001020 auto IsThisCaptured =
1021 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1022 IsConst = false;
1023 IsByCopy = false;
1024 for (auto &&C : Closure->captures()) {
1025 if (C.capturesThis()) {
1026 if (C.getCaptureKind() == LCK_StarThis)
1027 IsByCopy = true;
1028 if (Closure->getLambdaCallOperator()->isConst())
1029 IsConst = true;
1030 return true;
1031 }
1032 }
1033 return false;
1034 };
1035
1036 bool IsByCopyCapture = false;
1037 bool IsConstCapture = false;
1038 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1039 while (Closure &&
1040 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1041 if (IsByCopyCapture) {
1042 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1043 if (IsConstCapture)
1044 ClassType.addConst();
1045 return ASTCtx.getPointerType(ClassType);
1046 }
1047 Closure = isLambdaCallOperator(Closure->getParent())
1048 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1049 : nullptr;
1050 }
1051 }
1052 return ASTCtx.getPointerType(ClassType);
1053}
1054
Eli Friedman73a04092012-01-07 04:59:52 +00001055QualType Sema::getCurrentThisType() {
1056 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001057 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001058
Richard Smith938f40b2011-06-11 17:19:42 +00001059 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1060 if (method && method->isInstance())
1061 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001062 }
Faisal Validc6b5962016-03-21 09:25:37 +00001063
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001064 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001065 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001066
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001067 assert(isa<CXXRecordDecl>(DC) &&
1068 "Trying to get 'this' type from static method?");
1069
1070 // This is a lambda call operator that is being instantiated as a default
1071 // initializer. DC must point to the enclosing class type, so we can recover
1072 // the 'this' type from it.
1073
1074 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1075 // There are no cv-qualifiers for 'this' within default initializers,
1076 // per [expr.prim.general]p4.
1077 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001078 }
Faisal Vali67b04462016-06-11 16:41:54 +00001079
1080 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1081 // might need to be adjusted if the lambda or any of its enclosing lambda's
1082 // captures '*this' by copy.
1083 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1084 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1085 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001086 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001087}
1088
Simon Pilgrim75c26882016-09-30 14:25:09 +00001089Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001090 Decl *ContextDecl,
1091 unsigned CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001092 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001093 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1094{
1095 if (!Enabled || !ContextDecl)
1096 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001097
1098 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001099 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1100 Record = Template->getTemplatedDecl();
1101 else
1102 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001103
Andrey Bokhanko67a41862016-05-26 10:06:01 +00001104 // We care only for CVR qualifiers here, so cut everything else.
1105 CXXThisTypeQuals &= Qualifiers::FastMask;
Douglas Gregor3024f072012-04-16 07:05:22 +00001106 S.CXXThisTypeOverride
1107 = S.Context.getPointerType(
1108 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001109
Douglas Gregor3024f072012-04-16 07:05:22 +00001110 this->Enabled = true;
1111}
1112
1113
1114Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1115 if (Enabled) {
1116 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1117 }
1118}
1119
Faisal Validc6b5962016-03-21 09:25:37 +00001120static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1121 QualType ThisTy, SourceLocation Loc,
1122 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001123
Faisal Vali67b04462016-06-11 16:41:54 +00001124 QualType AdjustedThisTy = ThisTy;
1125 // The type of the corresponding data member (not a 'this' pointer if 'by
1126 // copy').
1127 QualType CaptureThisFieldTy = ThisTy;
1128 if (ByCopy) {
1129 // If we are capturing the object referred to by '*this' by copy, ignore any
1130 // cv qualifiers inherited from the type of the member function for the type
1131 // of the closure-type's corresponding data member and any use of 'this'.
1132 CaptureThisFieldTy = ThisTy->getPointeeType();
1133 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1134 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1135 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001136
Faisal Vali67b04462016-06-11 16:41:54 +00001137 FieldDecl *Field = FieldDecl::Create(
1138 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1139 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1140 ICIS_NoInit);
1141
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001142 Field->setImplicit(true);
1143 Field->setAccess(AS_private);
1144 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001145 Expr *This =
1146 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001147 if (ByCopy) {
1148 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1149 UO_Deref,
1150 This).get();
1151 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001152 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001153 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1154 InitializationSequence Init(S, Entity, InitKind, StarThis);
1155 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1156 if (ER.isInvalid()) return nullptr;
1157 return ER.get();
1158 }
1159 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001160}
1161
Simon Pilgrim75c26882016-09-30 14:25:09 +00001162bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001163 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1164 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001165 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001166 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001167 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001168
Faisal Validc6b5962016-03-21 09:25:37 +00001169 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001170
Reid Kleckner87a31802018-03-12 21:43:02 +00001171 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1172 ? *FunctionScopeIndexToStopAt
1173 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001174
Simon Pilgrim75c26882016-09-30 14:25:09 +00001175 // Check that we can capture the *enclosing object* (referred to by '*this')
1176 // by the capturing-entity/closure (lambda/block/etc) at
1177 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1178
1179 // Note: The *enclosing object* can only be captured by-value by a
1180 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001181 // [*this] { ... }.
1182 // Every other capture of the *enclosing object* results in its by-reference
1183 // capture.
1184
1185 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1186 // stack), we can capture the *enclosing object* only if:
1187 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1188 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001189 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001190 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001191 // -- or, there is some enclosing closure 'E' that has already captured the
1192 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001193 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001194 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001195 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001196
1197
Faisal Validc6b5962016-03-21 09:25:37 +00001198 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001199 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001200 if (CapturingScopeInfo *CSI =
1201 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1202 if (CSI->CXXThisCaptureIndex != 0) {
1203 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001204 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001205 break;
1206 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001207 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1208 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1209 // This context can't implicitly capture 'this'; fail out.
1210 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001211 Diag(Loc, diag::err_this_capture)
1212 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001213 return true;
1214 }
Eli Friedman20139d32012-01-11 02:36:31 +00001215 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001216 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001217 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001218 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001219 (Explicit && idx == MaxFunctionScopesIndex)) {
1220 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1221 // iteration through can be an explicit capture, all enclosing closures,
1222 // if any, must perform implicit captures.
1223
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001224 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001225 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001226 continue;
1227 }
Eli Friedman20139d32012-01-11 02:36:31 +00001228 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001229 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001230 Diag(Loc, diag::err_this_capture)
1231 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001232 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001233 }
Eli Friedman73a04092012-01-07 04:59:52 +00001234 break;
1235 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001236 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001237
1238 // If we got here, then the closure at MaxFunctionScopesIndex on the
1239 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1240 // (including implicit by-reference captures in any enclosing closures).
1241
1242 // In the loop below, respect the ByCopy flag only for the closure requesting
1243 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001244 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001245 // implicitly capturing the *enclosing object* by reference (see loop
1246 // above)).
1247 assert((!ByCopy ||
1248 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1249 "Only a lambda can capture the enclosing object (referred to by "
1250 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001251 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1252 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001253 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001254 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1255 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001256 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001257 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001258
Faisal Validc6b5962016-03-21 09:25:37 +00001259 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1260 // For lambda expressions, build a field and an initializing expression,
1261 // and capture the *enclosing object* by copy only if this is the first
1262 // iteration.
1263 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1264 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001265
Faisal Validc6b5962016-03-21 09:25:37 +00001266 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001267 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001268 ThisExpr =
1269 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1270 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001271
Faisal Validc6b5962016-03-21 09:25:37 +00001272 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001273 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001274 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001275 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001276}
1277
Richard Smith938f40b2011-06-11 17:19:42 +00001278ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001279 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1280 /// is a non-lvalue expression whose value is the address of the object for
1281 /// which the function is called.
1282
Douglas Gregor09deffa2011-10-18 16:47:30 +00001283 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001284 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001285
Eli Friedman73a04092012-01-07 04:59:52 +00001286 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001287 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001288}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001289
Douglas Gregor3024f072012-04-16 07:05:22 +00001290bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1291 // If we're outside the body of a member function, then we'll have a specified
1292 // type for 'this'.
1293 if (CXXThisTypeOverride.isNull())
1294 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001295
Douglas Gregor3024f072012-04-16 07:05:22 +00001296 // Determine whether we're looking into a class that's currently being
1297 // defined.
1298 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1299 return Class && Class->isBeingDefined();
1300}
1301
Vedant Kumara14a1f92018-01-17 18:53:51 +00001302/// Parse construction of a specified type.
1303/// Can be interpreted either as function-style casting ("int(x)")
1304/// or class type construction ("ClassType(x,y,z)")
1305/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001306ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001307Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001308 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001309 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001310 SourceLocation RParenOrBraceLoc,
1311 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001312 if (!TypeRep)
1313 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001314
John McCall97513962010-01-15 18:39:57 +00001315 TypeSourceInfo *TInfo;
1316 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1317 if (!TInfo)
1318 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001319
Vedant Kumara14a1f92018-01-17 18:53:51 +00001320 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1321 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001322 // Avoid creating a non-type-dependent expression that contains typos.
1323 // Non-type-dependent expressions are liable to be discarded without
1324 // checking for embedded typos.
1325 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1326 !Result.get()->isTypeDependent())
1327 Result = CorrectDelayedTyposInExpr(Result.get());
1328 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001329}
1330
Douglas Gregor2b88c112010-09-08 00:15:04 +00001331ExprResult
1332Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001333 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001334 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001335 SourceLocation RParenOrBraceLoc,
1336 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001337 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001338 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001339
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001340 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001341 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1342 // directly. We work around this by dropping the locations of the braces.
1343 SourceRange Locs = ListInitialization
1344 ? SourceRange()
1345 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1346 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1347 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001348 }
1349
Richard Smith600b5262017-01-26 20:40:47 +00001350 assert((!ListInitialization ||
1351 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1352 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001353 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001354
Richard Smith60437622017-02-09 19:17:44 +00001355 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1356 InitializationKind Kind =
1357 Exprs.size()
1358 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001359 ? InitializationKind::CreateDirectList(
1360 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1361 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1362 RParenOrBraceLoc)
1363 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1364 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001365
1366 // C++1z [expr.type.conv]p1:
1367 // If the type is a placeholder for a deduced class type, [...perform class
1368 // template argument deduction...]
1369 DeducedType *Deduced = Ty->getContainedDeducedType();
1370 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1371 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1372 Kind, Exprs);
1373 if (Ty.isNull())
1374 return ExprError();
1375 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1376 }
1377
Douglas Gregordd04d332009-01-16 18:33:17 +00001378 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001379 // If the expression list is a parenthesized single expression, the type
1380 // conversion expression is equivalent (in definedness, and if defined in
1381 // meaning) to the corresponding cast expression.
1382 if (Exprs.size() == 1 && !ListInitialization &&
1383 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001384 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001385 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1386 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001387 }
1388
Richard Smith49a6b6e2017-03-24 01:14:25 +00001389 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001390 QualType ElemTy = Ty;
1391 if (Ty->isArrayType()) {
1392 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001393 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1394 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001395 ElemTy = Context.getBaseElementType(Ty);
1396 }
1397
Richard Smith49a6b6e2017-03-24 01:14:25 +00001398 // There doesn't seem to be an explicit rule against this but sanity demands
1399 // we only construct objects with object types.
1400 if (Ty->isFunctionType())
1401 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1402 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001403
Richard Smith49a6b6e2017-03-24 01:14:25 +00001404 // C++17 [expr.type.conv]p2:
1405 // If the type is cv void and the initializer is (), the expression is a
1406 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001407 if (!Ty->isVoidType() &&
1408 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001409 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001410 return ExprError();
1411
Richard Smith49a6b6e2017-03-24 01:14:25 +00001412 // Otherwise, the expression is a prvalue of the specified type whose
1413 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001414 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1415 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001416
Richard Smith49a6b6e2017-03-24 01:14:25 +00001417 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001418 return Result;
1419
1420 Expr *Inner = Result.get();
1421 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1422 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001423 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1424 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001425 // If we created a CXXTemporaryObjectExpr, that node also represents the
1426 // functional cast. Otherwise, create an explicit cast to represent
1427 // the syntactic form of a functional-style cast that was used here.
1428 //
1429 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1430 // would give a more consistent AST representation than using a
1431 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1432 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001433 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001434 SourceRange Locs = ListInitialization
1435 ? SourceRange()
1436 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001437 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001438 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1439 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001440 }
1441
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001442 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001443}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001444
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001445/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001446/// deallocation function.
1447static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001448 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1449 return Method->isUsualDeallocationFunction();
1450
1451 if (FD->getOverloadedOperator() != OO_Delete &&
1452 FD->getOverloadedOperator() != OO_Array_Delete)
1453 return false;
1454
1455 unsigned UsualParams = 1;
1456
1457 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1458 S.Context.hasSameUnqualifiedType(
1459 FD->getParamDecl(UsualParams)->getType(),
1460 S.Context.getSizeType()))
1461 ++UsualParams;
1462
1463 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1464 S.Context.hasSameUnqualifiedType(
1465 FD->getParamDecl(UsualParams)->getType(),
1466 S.Context.getTypeDeclType(S.getStdAlignValT())))
1467 ++UsualParams;
1468
1469 return UsualParams == FD->getNumParams();
1470}
1471
1472namespace {
1473 struct UsualDeallocFnInfo {
1474 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001475 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001476 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001477 Destroying(false), HasSizeT(false), HasAlignValT(false),
1478 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001479 // A function template declaration is never a usual deallocation function.
1480 if (!FD)
1481 return;
Richard Smith5b349582017-10-13 01:55:36 +00001482 unsigned NumBaseParams = 1;
1483 if (FD->isDestroyingOperatorDelete()) {
1484 Destroying = true;
1485 ++NumBaseParams;
1486 }
1487 if (FD->getNumParams() == NumBaseParams + 2)
Richard Smithb2f0f052016-10-10 18:54:32 +00001488 HasAlignValT = HasSizeT = true;
Richard Smith5b349582017-10-13 01:55:36 +00001489 else if (FD->getNumParams() == NumBaseParams + 1) {
1490 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
Richard Smithb2f0f052016-10-10 18:54:32 +00001491 HasAlignValT = !HasSizeT;
1492 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001493
1494 // In CUDA, determine how much we'd like / dislike to call this.
1495 if (S.getLangOpts().CUDA)
1496 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1497 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001498 }
1499
Eric Fiselierfa752f22018-03-21 19:19:48 +00001500 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001501
Richard Smithf75dcbe2016-10-11 00:21:10 +00001502 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1503 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001504 // C++ P0722:
1505 // A destroying operator delete is preferred over a non-destroying
1506 // operator delete.
1507 if (Destroying != Other.Destroying)
1508 return Destroying;
1509
Richard Smithf75dcbe2016-10-11 00:21:10 +00001510 // C++17 [expr.delete]p10:
1511 // If the type has new-extended alignment, a function with a parameter
1512 // of type std::align_val_t is preferred; otherwise a function without
1513 // such a parameter is preferred
1514 if (HasAlignValT != Other.HasAlignValT)
1515 return HasAlignValT == WantAlign;
1516
1517 if (HasSizeT != Other.HasSizeT)
1518 return HasSizeT == WantSize;
1519
1520 // Use CUDA call preference as a tiebreaker.
1521 return CUDAPref > Other.CUDAPref;
1522 }
1523
Richard Smithb2f0f052016-10-10 18:54:32 +00001524 DeclAccessPair Found;
1525 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001526 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001527 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001528 };
1529}
1530
1531/// Determine whether a type has new-extended alignment. This may be called when
1532/// the type is incomplete (for a delete-expression with an incomplete pointee
1533/// type), in which case it will conservatively return false if the alignment is
1534/// not known.
1535static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1536 return S.getLangOpts().AlignedAllocation &&
1537 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1538 S.getASTContext().getTargetInfo().getNewAlign();
1539}
1540
1541/// Select the correct "usual" deallocation function to use from a selection of
1542/// deallocation functions (either global or class-scope).
1543static UsualDeallocFnInfo resolveDeallocationOverload(
1544 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1545 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1546 UsualDeallocFnInfo Best;
1547
Richard Smithb2f0f052016-10-10 18:54:32 +00001548 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001549 UsualDeallocFnInfo Info(S, I.getPair());
1550 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1551 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001552 continue;
1553
1554 if (!Best) {
1555 Best = Info;
1556 if (BestFns)
1557 BestFns->push_back(Info);
1558 continue;
1559 }
1560
Richard Smithf75dcbe2016-10-11 00:21:10 +00001561 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001562 continue;
1563
1564 // If more than one preferred function is found, all non-preferred
1565 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001566 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001567 BestFns->clear();
1568
1569 Best = Info;
1570 if (BestFns)
1571 BestFns->push_back(Info);
1572 }
1573
1574 return Best;
1575}
1576
1577/// Determine whether a given type is a class for which 'delete[]' would call
1578/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1579/// we need to store the array size (even if the type is
1580/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001581static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1582 QualType allocType) {
1583 const RecordType *record =
1584 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1585 if (!record) return false;
1586
1587 // Try to find an operator delete[] in class scope.
1588
1589 DeclarationName deleteName =
1590 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1591 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1592 S.LookupQualifiedName(ops, record->getDecl());
1593
1594 // We're just doing this for information.
1595 ops.suppressDiagnostics();
1596
1597 // Very likely: there's no operator delete[].
1598 if (ops.empty()) return false;
1599
1600 // If it's ambiguous, it should be illegal to call operator delete[]
1601 // on this thing, so it doesn't matter if we allocate extra space or not.
1602 if (ops.isAmbiguous()) return false;
1603
Richard Smithb2f0f052016-10-10 18:54:32 +00001604 // C++17 [expr.delete]p10:
1605 // If the deallocation functions have class scope, the one without a
1606 // parameter of type std::size_t is selected.
1607 auto Best = resolveDeallocationOverload(
1608 S, ops, /*WantSize*/false,
1609 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1610 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001611}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001612
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001613/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001614///
Sebastian Redld74dd492012-02-12 18:41:05 +00001615/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001616/// @code new (memory) int[size][4] @endcode
1617/// or
1618/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001619///
1620/// \param StartLoc The first location of the expression.
1621/// \param UseGlobal True if 'new' was prefixed with '::'.
1622/// \param PlacementLParen Opening paren of the placement arguments.
1623/// \param PlacementArgs Placement new arguments.
1624/// \param PlacementRParen Closing paren of the placement arguments.
1625/// \param TypeIdParens If the type is in parens, the source range.
1626/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001627/// \param Initializer The initializing expression or initializer-list, or null
1628/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001629ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001630Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001631 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001632 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001633 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001634 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001635 // If the specified type is an array, unwrap it and save the expression.
1636 if (D.getNumTypeObjects() > 0 &&
1637 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001638 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001639 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001640 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1641 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001642 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001643 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1644 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001645 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001646 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1647 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001648
Sebastian Redl351bb782008-12-02 14:43:59 +00001649 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001650 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001651 }
1652
Douglas Gregor73341c42009-09-11 00:18:58 +00001653 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001654 if (ArraySize) {
1655 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001656 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1657 break;
1658
1659 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1660 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001661 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001662 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001663 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1664 // shall be a converted constant expression (5.19) of type std::size_t
1665 // and shall evaluate to a strictly positive value.
1666 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1667 assert(IntWidth && "Builtin type of size 0?");
1668 llvm::APSInt Value(IntWidth);
1669 Array.NumElts
1670 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1671 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001672 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001673 } else {
1674 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001675 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001676 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001677 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001678 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001679 if (!Array.NumElts)
1680 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001681 }
1682 }
1683 }
1684 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001685
Craig Topperc3ec1492014-05-26 06:22:03 +00001686 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001687 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001688 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001689 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001690
Sebastian Redl6047f072012-02-16 12:22:20 +00001691 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001692 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001693 DirectInitRange = List->getSourceRange();
1694
David Blaikie7b97aef2012-11-07 00:12:38 +00001695 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001696 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001697 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001698 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001699 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001700 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001701 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001702 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001703 DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001704 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001705}
1706
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001707static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1708 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001709 if (!Init)
1710 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001711 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1712 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001713 if (isa<ImplicitValueInitExpr>(Init))
1714 return true;
1715 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1716 return !CCE->isListInitialization() &&
1717 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001718 else if (Style == CXXNewExpr::ListInit) {
1719 assert(isa<InitListExpr>(Init) &&
1720 "Shouldn't create list CXXConstructExprs for arrays.");
1721 return true;
1722 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001723 return false;
1724}
1725
Akira Hatanakacae83f72017-06-29 18:48:40 +00001726// Emit a diagnostic if an aligned allocation/deallocation function that is not
1727// implemented in the standard library is selected.
1728static void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1729 SourceLocation Loc, bool IsDelete,
1730 Sema &S) {
1731 if (!S.getLangOpts().AlignedAllocationUnavailable)
1732 return;
1733
1734 // Return if there is a definition.
1735 if (FD.isDefined())
1736 return;
1737
1738 bool IsAligned = false;
1739 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) {
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001740 const llvm::Triple &T = S.getASTContext().getTargetInfo().getTriple();
1741 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1742 S.getASTContext().getTargetInfo().getPlatformName());
1743
Akira Hatanakacae83f72017-06-29 18:48:40 +00001744 S.Diag(Loc, diag::warn_aligned_allocation_unavailable)
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001745 << IsDelete << FD.getType().getAsString() << OSName
1746 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanakacae83f72017-06-29 18:48:40 +00001747 S.Diag(Loc, diag::note_silence_unligned_allocation_unavailable);
1748 }
1749}
1750
John McCalldadc5752010-08-24 06:29:42 +00001751ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001752Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001753 SourceLocation PlacementLParen,
1754 MultiExprArg PlacementArgs,
1755 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001756 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001757 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001758 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001759 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001760 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001761 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001762 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001763 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001764
Sebastian Redl6047f072012-02-16 12:22:20 +00001765 CXXNewExpr::InitializationStyle initStyle;
1766 if (DirectInitRange.isValid()) {
1767 assert(Initializer && "Have parens but no initializer.");
1768 initStyle = CXXNewExpr::CallInit;
1769 } else if (Initializer && isa<InitListExpr>(Initializer))
1770 initStyle = CXXNewExpr::ListInit;
1771 else {
1772 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1773 isa<CXXConstructExpr>(Initializer)) &&
1774 "Initializer expression that cannot have been implicitly created.");
1775 initStyle = CXXNewExpr::NoInit;
1776 }
1777
1778 Expr **Inits = &Initializer;
1779 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001780 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1781 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1782 Inits = List->getExprs();
1783 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001784 }
1785
Richard Smith60437622017-02-09 19:17:44 +00001786 // C++11 [expr.new]p15:
1787 // A new-expression that creates an object of type T initializes that
1788 // object as follows:
1789 InitializationKind Kind
1790 // - If the new-initializer is omitted, the object is default-
1791 // initialized (8.5); if no initialization is performed,
1792 // the object has indeterminate value
1793 = initStyle == CXXNewExpr::NoInit
1794 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1795 // - Otherwise, the new-initializer is interpreted according to the
1796 // initialization rules of 8.5 for direct-initialization.
1797 : initStyle == CXXNewExpr::ListInit
Vedant Kumara14a1f92018-01-17 18:53:51 +00001798 ? InitializationKind::CreateDirectList(TypeRange.getBegin(),
1799 Initializer->getLocStart(),
1800 Initializer->getLocEnd())
Richard Smith60437622017-02-09 19:17:44 +00001801 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1802 DirectInitRange.getBegin(),
1803 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001804
Richard Smith60437622017-02-09 19:17:44 +00001805 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1806 auto *Deduced = AllocType->getContainedDeducedType();
1807 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1808 if (ArraySize)
1809 return ExprError(Diag(ArraySize->getExprLoc(),
1810 diag::err_deduced_class_template_compound_type)
1811 << /*array*/ 2 << ArraySize->getSourceRange());
1812
1813 InitializedEntity Entity
1814 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1815 AllocType = DeduceTemplateSpecializationFromInitializer(
1816 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1817 if (AllocType.isNull())
1818 return ExprError();
1819 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001820 bool Braced = (initStyle == CXXNewExpr::ListInit);
1821 if (NumInits == 1) {
1822 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1823 Inits = p->getInits();
1824 NumInits = p->getNumInits();
1825 Braced = true;
1826 }
1827 }
1828
Sebastian Redl6047f072012-02-16 12:22:20 +00001829 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001830 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1831 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001832 if (NumInits > 1) {
1833 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001834 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001835 diag::err_auto_new_ctor_multiple_expressions)
1836 << AllocType << TypeRange);
1837 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001838 if (Braced && !getLangOpts().CPlusPlus17)
1839 Diag(Initializer->getLocStart(), diag::ext_auto_new_list_init)
1840 << AllocType << TypeRange;
Sebastian Redl6047f072012-02-16 12:22:20 +00001841 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001842 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001843 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001844 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001845 << AllocType << Deduce->getType()
1846 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001847 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001848 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001849 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001850 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001851
Douglas Gregorcda95f42010-05-16 16:01:03 +00001852 // Per C++0x [expr.new]p5, the type being constructed may be a
1853 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001854 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001855 if (const ConstantArrayType *Array
1856 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001857 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1858 Context.getSizeType(),
1859 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001860 AllocType = Array->getElementType();
1861 }
1862 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001863
Douglas Gregor3999e152010-10-06 16:00:31 +00001864 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1865 return ExprError();
1866
Craig Topperc3ec1492014-05-26 06:22:03 +00001867 if (initStyle == CXXNewExpr::ListInit &&
1868 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001869 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1870 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001871 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001872 }
1873
Simon Pilgrim75c26882016-09-30 14:25:09 +00001874 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001875 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001876 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1877 AllocType->isObjCLifetimeType()) {
1878 AllocType = Context.getLifetimeQualifiedType(AllocType,
1879 AllocType->getObjCARCImplicitLifetime());
1880 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001881
John McCall31168b02011-06-15 23:02:42 +00001882 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001883
John McCall5e77d762013-04-16 07:28:30 +00001884 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1885 ExprResult result = CheckPlaceholderExpr(ArraySize);
1886 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001887 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001888 }
Richard Smith8dd34252012-02-04 07:07:42 +00001889 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1890 // integral or enumeration type with a non-negative value."
1891 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1892 // enumeration type, or a class type for which a single non-explicit
1893 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001894 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001895 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001896 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001897 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001898 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001899 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001900 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1901
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001902 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1903 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001904
Simon Pilgrim75c26882016-09-30 14:25:09 +00001905 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001906 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001907 // Diagnose the compatibility of this conversion.
1908 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1909 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001910 } else {
1911 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1912 protected:
1913 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001914
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001915 public:
1916 SizeConvertDiagnoser(Expr *ArraySize)
1917 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1918 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001919
1920 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1921 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001922 return S.Diag(Loc, diag::err_array_size_not_integral)
1923 << S.getLangOpts().CPlusPlus11 << T;
1924 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001925
1926 SemaDiagnosticBuilder diagnoseIncomplete(
1927 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001928 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1929 << T << ArraySize->getSourceRange();
1930 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001931
1932 SemaDiagnosticBuilder diagnoseExplicitConv(
1933 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001934 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1935 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001936
1937 SemaDiagnosticBuilder noteExplicitConv(
1938 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001939 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1940 << ConvTy->isEnumeralType() << ConvTy;
1941 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001942
1943 SemaDiagnosticBuilder diagnoseAmbiguous(
1944 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001945 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1946 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001947
1948 SemaDiagnosticBuilder noteAmbiguous(
1949 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001950 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1951 << ConvTy->isEnumeralType() << ConvTy;
1952 }
Richard Smithccc11812013-05-21 19:05:48 +00001953
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001954 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1955 QualType T,
1956 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001957 return S.Diag(Loc,
1958 S.getLangOpts().CPlusPlus11
1959 ? diag::warn_cxx98_compat_array_size_conversion
1960 : diag::ext_array_size_conversion)
1961 << T << ConvTy->isEnumeralType() << ConvTy;
1962 }
1963 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001964
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001965 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1966 SizeDiagnoser);
1967 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001968 if (ConvertedSize.isInvalid())
1969 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001971 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001972 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001973
Douglas Gregor0bf31402010-10-08 23:50:27 +00001974 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001975 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001977 // C++98 [expr.new]p7:
1978 // The expression in a direct-new-declarator shall have integral type
1979 // with a non-negative value.
1980 //
Richard Smith0511d232016-10-05 22:41:02 +00001981 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1982 // per CWG1464. Otherwise, if it's not a constant, we must have an
1983 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001984 if (!ArraySize->isValueDependent()) {
1985 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001986 // We've already performed any required implicit conversion to integer or
1987 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001988 // FIXME: Per CWG1464, we are required to check the value prior to
1989 // converting to size_t. This will never find a negative array size in
1990 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001991 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00001992 if (Value.isSigned() && Value.isNegative()) {
1993 return ExprError(Diag(ArraySize->getLocStart(),
1994 diag::err_typecheck_negative_array_size)
1995 << ArraySize->getSourceRange());
1996 }
1997
1998 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001999 unsigned ActiveSizeBits =
2000 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002001 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2002 return ExprError(Diag(ArraySize->getLocStart(),
2003 diag::err_array_too_large)
2004 << Value.toString(10)
2005 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002006 }
Richard Smith0511d232016-10-05 22:41:02 +00002007
2008 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002009 } else if (TypeIdParens.isValid()) {
2010 // Can't have dynamic array size when the type-id is in parentheses.
2011 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
2012 << ArraySize->getSourceRange()
2013 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2014 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002015
Douglas Gregorf2753b32010-07-13 15:54:32 +00002016 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002017 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002018 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002019
John McCall036f2f62011-05-15 07:14:44 +00002020 // Note that we do *not* convert the argument in any way. It can
2021 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002022 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002023
Craig Topperc3ec1492014-05-26 06:22:03 +00002024 FunctionDecl *OperatorNew = nullptr;
2025 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002026 unsigned Alignment =
2027 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2028 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2029 bool PassAlignment = getLangOpts().AlignedAllocation &&
2030 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031
Brian Gesiakcb024022018-04-01 22:59:22 +00002032 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002033 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002034 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002035 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002036 SourceRange(PlacementLParen, PlacementRParen),
Brian Gesiakcb024022018-04-01 22:59:22 +00002037 Scope, Scope, AllocType, ArraySize, PassAlignment,
Richard Smithb2f0f052016-10-10 18:54:32 +00002038 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002039 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002040
2041 // If this is an array allocation, compute whether the usual array
2042 // deallocation function for the type has a size_t parameter.
2043 bool UsualArrayDeleteWantsSize = false;
2044 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002045 UsualArrayDeleteWantsSize =
2046 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002047
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002048 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002049 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002050 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002051 OperatorNew->getType()->getAs<FunctionProtoType>();
2052 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2053 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054
Richard Smithd6f9e732014-05-13 19:56:21 +00002055 // We've already converted the placement args, just fill in any default
2056 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002057 // argument. Skip the second parameter too if we're passing in the
2058 // alignment; we've already filled it in.
2059 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2060 PassAlignment ? 2 : 1, PlacementArgs,
2061 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002062 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002063
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002064 if (!AllPlaceArgs.empty())
2065 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002066
Richard Smithd6f9e732014-05-13 19:56:21 +00002067 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002068 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002069
2070 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071
Richard Smithb2f0f052016-10-10 18:54:32 +00002072 // Warn if the type is over-aligned and is being allocated by (unaligned)
2073 // global operator new.
2074 if (PlacementArgs.empty() && !PassAlignment &&
2075 (OperatorNew->isImplicit() ||
2076 (OperatorNew->getLocStart().isValid() &&
2077 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
2078 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002079 Diag(StartLoc, diag::warn_overaligned_type)
2080 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002081 << unsigned(Alignment / Context.getCharWidth())
2082 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002083 }
2084 }
2085
Sebastian Redl6047f072012-02-16 12:22:20 +00002086 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002087 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2088 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002089 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2090 SourceRange InitRange(Inits[0]->getLocStart(),
2091 Inits[NumInits - 1]->getLocEnd());
2092 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2093 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002094 }
2095
Richard Smithdd2ca572012-11-26 08:32:48 +00002096 // If we can perform the initialization, and we've not already done so,
2097 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002098 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002099 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002100 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002101 // The type we initialize is the complete type, including the array bound.
2102 QualType InitType;
2103 if (KnownArraySize)
2104 InitType = Context.getConstantArrayType(
2105 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2106 *KnownArraySize),
2107 ArrayType::Normal, 0);
2108 else if (ArraySize)
2109 InitType =
2110 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2111 else
2112 InitType = AllocType;
2113
Douglas Gregor85dabae2009-12-16 01:38:02 +00002114 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002115 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002116 InitializationSequence InitSeq(*this, Entity, Kind,
2117 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002118 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002119 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002120 if (FullInit.isInvalid())
2121 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002122
Sebastian Redl6047f072012-02-16 12:22:20 +00002123 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2124 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002125 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002126 if (CXXBindTemporaryExpr *Binder =
2127 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002128 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002129
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002130 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002132
Douglas Gregor6642ca22010-02-26 05:06:18 +00002133 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002134 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002135 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2136 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002137 MarkFunctionReferenced(StartLoc, OperatorNew);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002138 diagnoseUnavailableAlignedAllocation(*OperatorNew, StartLoc, false, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002139 }
2140 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002141 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2142 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002143 MarkFunctionReferenced(StartLoc, OperatorDelete);
Akira Hatanakacae83f72017-06-29 18:48:40 +00002144 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true, *this);
Nick Lewyckya096b142013-02-12 08:08:54 +00002145 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002146
John McCall928a2572011-07-13 20:12:57 +00002147 // C++0x [expr.new]p17:
2148 // If the new expression creates an array of objects of class type,
2149 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002150 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2151 if (ArraySize && !BaseAllocType->isDependentType()) {
2152 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2153 if (CXXDestructorDecl *dtor = LookupDestructor(
2154 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2155 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002156 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002157 PDiag(diag::err_access_dtor)
2158 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002159 if (DiagnoseUseOfDecl(dtor, StartLoc))
2160 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002161 }
John McCall928a2572011-07-13 20:12:57 +00002162 }
2163 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002165 return new (Context)
Richard Smithb2f0f052016-10-10 18:54:32 +00002166 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002167 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2168 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2169 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002170}
2171
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002172/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002173/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002174bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002175 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002176 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2177 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002178 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002179 return Diag(Loc, diag::err_bad_new_type)
2180 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002181 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002182 return Diag(Loc, diag::err_bad_new_type)
2183 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002184 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002185 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002186 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002187 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002188 diag::err_allocation_of_abstract_type))
2189 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002190 else if (AllocType->isVariablyModifiedType())
2191 return Diag(Loc, diag::err_variably_modified_new_type)
2192 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002193 else if (AllocType.getAddressSpace() != LangAS::Default &&
2194 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002195 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002196 << AllocType.getUnqualifiedType()
2197 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002198 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002199 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2200 QualType BaseAllocType = Context.getBaseElementType(AT);
2201 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2202 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002203 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002204 << BaseAllocType;
2205 }
2206 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002207
Sebastian Redlbd150f42008-11-21 19:14:01 +00002208 return false;
2209}
2210
Brian Gesiak87412d92018-02-15 20:09:25 +00002211static bool resolveAllocationOverload(
2212 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2213 bool &PassAlignment, FunctionDecl *&Operator,
2214 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002215 OverloadCandidateSet Candidates(R.getNameLoc(),
2216 OverloadCandidateSet::CSK_Normal);
2217 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2218 Alloc != AllocEnd; ++Alloc) {
2219 // Even member operator new/delete are implicitly treated as
2220 // static, so don't use AddMemberCandidate.
2221 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2222
2223 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2224 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2225 /*ExplicitTemplateArgs=*/nullptr, Args,
2226 Candidates,
2227 /*SuppressUserConversions=*/false);
2228 continue;
2229 }
2230
2231 FunctionDecl *Fn = cast<FunctionDecl>(D);
2232 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2233 /*SuppressUserConversions=*/false);
2234 }
2235
2236 // Do the resolution.
2237 OverloadCandidateSet::iterator Best;
2238 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2239 case OR_Success: {
2240 // Got one!
2241 FunctionDecl *FnDecl = Best->Function;
2242 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2243 Best->FoundDecl) == Sema::AR_inaccessible)
2244 return true;
2245
2246 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002247 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002248 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002249
Richard Smithb2f0f052016-10-10 18:54:32 +00002250 case OR_No_Viable_Function:
2251 // C++17 [expr.new]p13:
2252 // If no matching function is found and the allocated object type has
2253 // new-extended alignment, the alignment argument is removed from the
2254 // argument list, and overload resolution is performed again.
2255 if (PassAlignment) {
2256 PassAlignment = false;
2257 AlignArg = Args[1];
2258 Args.erase(Args.begin() + 1);
2259 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002260 Operator, &Candidates, AlignArg,
2261 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002262 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002263
Richard Smithb2f0f052016-10-10 18:54:32 +00002264 // MSVC will fall back on trying to find a matching global operator new
2265 // if operator new[] cannot be found. Also, MSVC will leak by not
2266 // generating a call to operator delete or operator delete[], but we
2267 // will not replicate that bug.
2268 // FIXME: Find out how this interacts with the std::align_val_t fallback
2269 // once MSVC implements it.
2270 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2271 S.Context.getLangOpts().MSVCCompat) {
2272 R.clear();
2273 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2274 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2275 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2276 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002277 Operator, /*Candidates=*/nullptr,
2278 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002279 }
Richard Smith1cdec012013-09-29 04:40:38 +00002280
Brian Gesiak87412d92018-02-15 20:09:25 +00002281 if (Diagnose) {
2282 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2283 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002284
Brian Gesiak87412d92018-02-15 20:09:25 +00002285 // If we have aligned candidates, only note the align_val_t candidates
2286 // from AlignedCandidates and the non-align_val_t candidates from
2287 // Candidates.
2288 if (AlignedCandidates) {
2289 auto IsAligned = [](OverloadCandidate &C) {
2290 return C.Function->getNumParams() > 1 &&
2291 C.Function->getParamDecl(1)->getType()->isAlignValT();
2292 };
2293 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002294
Brian Gesiak87412d92018-02-15 20:09:25 +00002295 // This was an overaligned allocation, so list the aligned candidates
2296 // first.
2297 Args.insert(Args.begin() + 1, AlignArg);
2298 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2299 R.getNameLoc(), IsAligned);
2300 Args.erase(Args.begin() + 1);
2301 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2302 IsUnaligned);
2303 } else {
2304 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2305 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002306 }
Richard Smith1cdec012013-09-29 04:40:38 +00002307 return true;
2308
Richard Smithb2f0f052016-10-10 18:54:32 +00002309 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002310 if (Diagnose) {
2311 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2312 << R.getLookupName() << Range;
2313 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2314 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002315 return true;
2316
2317 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002318 if (Diagnose) {
2319 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2320 << Best->Function->isDeleted() << R.getLookupName()
2321 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2322 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2323 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002324 return true;
2325 }
2326 }
2327 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002328}
2329
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002330bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002331 AllocationFunctionScope NewScope,
2332 AllocationFunctionScope DeleteScope,
2333 QualType AllocType, bool IsArray,
2334 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002335 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002336 FunctionDecl *&OperatorDelete,
2337 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002338 // --- Choosing an allocation function ---
2339 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002340 // 1) If looking in AFS_Global scope for allocation functions, only look in
2341 // the global scope. Else, if AFS_Class, only look in the scope of the
2342 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002343 // 2) If an array size is given, look for operator new[], else look for
2344 // operator new.
2345 // 3) The first argument is always size_t. Append the arguments from the
2346 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002347
Richard Smithb2f0f052016-10-10 18:54:32 +00002348 SmallVector<Expr*, 8> AllocArgs;
2349 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2350
2351 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002352 // FIXME: Should the Sema create the expression and embed it in the syntax
2353 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002354 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002355 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002356 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002357 Context.getSizeType(),
2358 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002359 AllocArgs.push_back(&Size);
2360
2361 QualType AlignValT = Context.VoidTy;
2362 if (PassAlignment) {
2363 DeclareGlobalNewDelete();
2364 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2365 }
2366 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2367 if (PassAlignment)
2368 AllocArgs.push_back(&Align);
2369
2370 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002371
Douglas Gregor6642ca22010-02-26 05:06:18 +00002372 // C++ [expr.new]p8:
2373 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002374 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002375 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002376 // type, the allocation function's name is operator new[] and the
2377 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002378 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002379 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002380
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002381 QualType AllocElemType = Context.getBaseElementType(AllocType);
2382
Richard Smithb2f0f052016-10-10 18:54:32 +00002383 // Find the allocation function.
2384 {
2385 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2386
2387 // C++1z [expr.new]p9:
2388 // If the new-expression begins with a unary :: operator, the allocation
2389 // function's name is looked up in the global scope. Otherwise, if the
2390 // allocated type is a class type T or array thereof, the allocation
2391 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002392 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002393 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2394
2395 // We can see ambiguity here if the allocation function is found in
2396 // multiple base classes.
2397 if (R.isAmbiguous())
2398 return true;
2399
2400 // If this lookup fails to find the name, or if the allocated type is not
2401 // a class type, the allocation function's name is looked up in the
2402 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002403 if (R.empty()) {
2404 if (NewScope == AFS_Class)
2405 return true;
2406
Richard Smithb2f0f052016-10-10 18:54:32 +00002407 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002408 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002409
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002410 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2411 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2412 return true;
2413 }
2414
Richard Smithb2f0f052016-10-10 18:54:32 +00002415 assert(!R.empty() && "implicitly declared allocation functions not found");
2416 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2417
2418 // We do our own custom access checks below.
2419 R.suppressDiagnostics();
2420
2421 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002422 OperatorNew, /*Candidates=*/nullptr,
2423 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002424 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002425 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002426
Richard Smithb2f0f052016-10-10 18:54:32 +00002427 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002428 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002429 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002430 return false;
2431 }
2432
Richard Smithb2f0f052016-10-10 18:54:32 +00002433 // Note, the name of OperatorNew might have been changed from array to
2434 // non-array by resolveAllocationOverload.
2435 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2436 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2437 ? OO_Array_Delete
2438 : OO_Delete);
2439
Douglas Gregor6642ca22010-02-26 05:06:18 +00002440 // C++ [expr.new]p19:
2441 //
2442 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002443 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002444 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002445 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002446 // the scope of T. If this lookup fails to find the name, or if
2447 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002448 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002449 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002450 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002451 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002452 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002453 LookupQualifiedName(FoundDelete, RD);
2454 }
John McCallfb6f5262010-03-18 08:19:33 +00002455 if (FoundDelete.isAmbiguous())
2456 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002457
Richard Smithb2f0f052016-10-10 18:54:32 +00002458 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002459 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002460 if (DeleteScope == AFS_Class)
2461 return true;
2462
Douglas Gregor6642ca22010-02-26 05:06:18 +00002463 DeclareGlobalNewDelete();
2464 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2465 }
2466
2467 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002468
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002469 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002470
John McCalld3be2c82010-09-14 21:34:24 +00002471 // Whether we're looking for a placement operator delete is dictated
2472 // by whether we selected a placement operator new, not by whether
2473 // we had explicit placement arguments. This matters for things like
2474 // struct A { void *operator new(size_t, int = 0); ... };
2475 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002476 //
2477 // We don't have any definition for what a "placement allocation function"
2478 // is, but we assume it's any allocation function whose
2479 // parameter-declaration-clause is anything other than (size_t).
2480 //
2481 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2482 // This affects whether an exception from the constructor of an overaligned
2483 // type uses the sized or non-sized form of aligned operator delete.
2484 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2485 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002486
2487 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002488 // C++ [expr.new]p20:
2489 // A declaration of a placement deallocation function matches the
2490 // declaration of a placement allocation function if it has the
2491 // same number of parameters and, after parameter transformations
2492 // (8.3.5), all parameter types except the first are
2493 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002494 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002495 // To perform this comparison, we compute the function type that
2496 // the deallocation function should have, and use that type both
2497 // for template argument deduction and for comparison purposes.
2498 QualType ExpectedFunctionType;
2499 {
2500 const FunctionProtoType *Proto
2501 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002502
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002503 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002504 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002505 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2506 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002507
John McCalldb40c7f2010-12-14 08:05:40 +00002508 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002509 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002510 EPI.Variadic = Proto->isVariadic();
2511
Douglas Gregor6642ca22010-02-26 05:06:18 +00002512 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002513 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002514 }
2515
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002516 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002517 DEnd = FoundDelete.end();
2518 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002519 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002520 if (FunctionTemplateDecl *FnTmpl =
2521 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002522 // Perform template argument deduction to try to match the
2523 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002524 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002525 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2526 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002527 continue;
2528 } else
2529 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2530
Richard Smithbaa47832016-12-01 02:11:49 +00002531 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2532 ExpectedFunctionType,
2533 /*AdjustExcpetionSpec*/true),
2534 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002535 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002536 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002537
Richard Smithb2f0f052016-10-10 18:54:32 +00002538 if (getLangOpts().CUDA)
2539 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2540 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002541 // C++1y [expr.new]p22:
2542 // For a non-placement allocation function, the normal deallocation
2543 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002544 //
2545 // Per [expr.delete]p10, this lookup prefers a member operator delete
2546 // without a size_t argument, but prefers a non-member operator delete
2547 // with a size_t where possible (which it always is in this case).
2548 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2549 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2550 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2551 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2552 &BestDeallocFns);
2553 if (Selected)
2554 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2555 else {
2556 // If we failed to select an operator, all remaining functions are viable
2557 // but ambiguous.
2558 for (auto Fn : BestDeallocFns)
2559 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002560 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002561 }
2562
2563 // C++ [expr.new]p20:
2564 // [...] If the lookup finds a single matching deallocation
2565 // function, that function will be called; otherwise, no
2566 // deallocation function will be called.
2567 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002568 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002569
Richard Smithb2f0f052016-10-10 18:54:32 +00002570 // C++1z [expr.new]p23:
2571 // If the lookup finds a usual deallocation function (3.7.4.2)
2572 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002573 // as a placement deallocation function, would have been
2574 // selected as a match for the allocation function, the program
2575 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002576 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002577 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002578 UsualDeallocFnInfo Info(*this,
2579 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002580 // Core issue, per mail to core reflector, 2016-10-09:
2581 // If this is a member operator delete, and there is a corresponding
2582 // non-sized member operator delete, this isn't /really/ a sized
2583 // deallocation function, it just happens to have a size_t parameter.
2584 bool IsSizedDelete = Info.HasSizeT;
2585 if (IsSizedDelete && !FoundGlobalDelete) {
2586 auto NonSizedDelete =
2587 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2588 /*WantAlign*/Info.HasAlignValT);
2589 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2590 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2591 IsSizedDelete = false;
2592 }
2593
2594 if (IsSizedDelete) {
2595 SourceRange R = PlaceArgs.empty()
2596 ? SourceRange()
2597 : SourceRange(PlaceArgs.front()->getLocStart(),
2598 PlaceArgs.back()->getLocEnd());
2599 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2600 if (!OperatorDelete->isImplicit())
2601 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2602 << DeleteName;
2603 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002604 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002605
2606 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2607 Matches[0].first);
2608 } else if (!Matches.empty()) {
2609 // We found multiple suitable operators. Per [expr.new]p20, that means we
2610 // call no 'operator delete' function, but we should at least warn the user.
2611 // FIXME: Suppress this warning if the construction cannot throw.
2612 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2613 << DeleteName << AllocElemType;
2614
2615 for (auto &Match : Matches)
2616 Diag(Match.second->getLocation(),
2617 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002618 }
2619
Sebastian Redlfaf68082008-12-03 20:26:15 +00002620 return false;
2621}
2622
2623/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2624/// delete. These are:
2625/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002626/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002627/// void* operator new(std::size_t) throw(std::bad_alloc);
2628/// void* operator new[](std::size_t) throw(std::bad_alloc);
2629/// void operator delete(void *) throw();
2630/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002631/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002632/// void* operator new(std::size_t);
2633/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002634/// void operator delete(void *) noexcept;
2635/// void operator delete[](void *) noexcept;
2636/// // C++1y:
2637/// void* operator new(std::size_t);
2638/// void* operator new[](std::size_t);
2639/// void operator delete(void *) noexcept;
2640/// void operator delete[](void *) noexcept;
2641/// void operator delete(void *, std::size_t) noexcept;
2642/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002643/// @endcode
2644/// Note that the placement and nothrow forms of new are *not* implicitly
2645/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002646void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002647 if (GlobalNewDeleteDeclared)
2648 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002649
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002650 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2651 // are not supported.
2652 if (getLangOpts().OpenCLCPlusPlus)
2653 return;
2654
Douglas Gregor87f54062009-09-15 22:30:29 +00002655 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002656 // [...] The following allocation and deallocation functions (18.4) are
2657 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002658 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002659 //
Sebastian Redl37588092011-03-14 18:08:30 +00002660 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002661 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002662 // void* operator new[](std::size_t) throw(std::bad_alloc);
2663 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002664 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002665 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002666 // void* operator new(std::size_t);
2667 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002668 // void operator delete(void*) noexcept;
2669 // void operator delete[](void*) noexcept;
2670 // C++1y:
2671 // void* operator new(std::size_t);
2672 // void* operator new[](std::size_t);
2673 // void operator delete(void*) noexcept;
2674 // void operator delete[](void*) noexcept;
2675 // void operator delete(void*, std::size_t) noexcept;
2676 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002677 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002678 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002679 // new, operator new[], operator delete, operator delete[].
2680 //
2681 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2682 // "std" or "bad_alloc" as necessary to form the exception specification.
2683 // However, we do not make these implicit declarations visible to name
2684 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002685 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002686 // The "std::bad_alloc" class has not yet been declared, so build it
2687 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002688 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2689 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002690 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002691 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002692 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002693 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002694 }
Richard Smith59139022016-09-30 22:41:36 +00002695 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002696 // The "std::align_val_t" enum class has not yet been declared, so build it
2697 // implicitly.
2698 auto *AlignValT = EnumDecl::Create(
2699 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2700 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2701 AlignValT->setIntegerType(Context.getSizeType());
2702 AlignValT->setPromotionType(Context.getSizeType());
2703 AlignValT->setImplicit(true);
2704 StdAlignValT = AlignValT;
2705 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706
Sebastian Redlfaf68082008-12-03 20:26:15 +00002707 GlobalNewDeleteDeclared = true;
2708
2709 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2710 QualType SizeT = Context.getSizeType();
2711
Richard Smith96269c52016-09-29 22:49:46 +00002712 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2713 QualType Return, QualType Param) {
2714 llvm::SmallVector<QualType, 3> Params;
2715 Params.push_back(Param);
2716
2717 // Create up to four variants of the function (sized/aligned).
2718 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2719 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002720 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002721
2722 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2723 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2724 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002725 if (Sized)
2726 Params.push_back(SizeT);
2727
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002728 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002729 if (Aligned)
2730 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2731
2732 DeclareGlobalAllocationFunction(
2733 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2734
2735 if (Aligned)
2736 Params.pop_back();
2737 }
2738 }
2739 };
2740
2741 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2742 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2743 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2744 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002745}
2746
2747/// DeclareGlobalAllocationFunction - Declares a single implicit global
2748/// allocation function if it doesn't already exist.
2749void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002750 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002751 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002752 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2753
2754 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002755 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2756 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2757 Alloc != AllocEnd; ++Alloc) {
2758 // Only look at non-template functions, as it is the predefined,
2759 // non-templated allocation function we are trying to declare here.
2760 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002761 if (Func->getNumParams() == Params.size()) {
2762 llvm::SmallVector<QualType, 3> FuncParams;
2763 for (auto *P : Func->parameters())
2764 FuncParams.push_back(
2765 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2766 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002767 // Make the function visible to name lookup, even if we found it in
2768 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002769 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002770 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002771 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002772 }
Chandler Carruth93538422010-02-03 11:02:14 +00002773 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002774 }
2775 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002776
Richard Smithc015bc22014-02-07 22:39:53 +00002777 FunctionProtoType::ExtProtoInfo EPI;
2778
Richard Smithf8b417c2014-02-08 00:42:45 +00002779 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002780 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002781 = (Name.getCXXOverloadedOperator() == OO_New ||
2782 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002783 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002784 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002785 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002786 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002787 EPI.ExceptionSpec.Type = EST_Dynamic;
2788 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002789 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002790 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002791 EPI.ExceptionSpec =
2792 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002794
Artem Belevich07db5cf2016-10-21 20:34:05 +00002795 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2796 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2797 FunctionDecl *Alloc = FunctionDecl::Create(
2798 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2799 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2800 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002801 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002802 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002803
Artem Belevich07db5cf2016-10-21 20:34:05 +00002804 // Implicit sized deallocation functions always have default visibility.
2805 Alloc->addAttr(
2806 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002807
Artem Belevich07db5cf2016-10-21 20:34:05 +00002808 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2809 for (QualType T : Params) {
2810 ParamDecls.push_back(ParmVarDecl::Create(
2811 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2812 /*TInfo=*/nullptr, SC_None, nullptr));
2813 ParamDecls.back()->setImplicit();
2814 }
2815 Alloc->setParams(ParamDecls);
2816 if (ExtraAttr)
2817 Alloc->addAttr(ExtraAttr);
2818 Context.getTranslationUnitDecl()->addDecl(Alloc);
2819 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2820 };
2821
2822 if (!LangOpts.CUDA)
2823 CreateAllocationFunctionDecl(nullptr);
2824 else {
2825 // Host and device get their own declaration so each can be
2826 // defined or re-declared independently.
2827 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2828 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002829 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002830}
2831
Richard Smith1cdec012013-09-29 04:40:38 +00002832FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2833 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002834 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002835 DeclarationName Name) {
2836 DeclareGlobalNewDelete();
2837
2838 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2839 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2840
Richard Smithb2f0f052016-10-10 18:54:32 +00002841 // FIXME: It's possible for this to result in ambiguity, through a
2842 // user-declared variadic operator delete or the enable_if attribute. We
2843 // should probably not consider those cases to be usual deallocation
2844 // functions. But for now we just make an arbitrary choice in that case.
2845 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2846 Overaligned);
2847 assert(Result.FD && "operator delete missing from global scope?");
2848 return Result.FD;
2849}
Richard Smith1cdec012013-09-29 04:40:38 +00002850
Richard Smithb2f0f052016-10-10 18:54:32 +00002851FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2852 CXXRecordDecl *RD) {
2853 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002854
Richard Smithb2f0f052016-10-10 18:54:32 +00002855 FunctionDecl *OperatorDelete = nullptr;
2856 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2857 return nullptr;
2858 if (OperatorDelete)
2859 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002860
Richard Smithb2f0f052016-10-10 18:54:32 +00002861 // If there's no class-specific operator delete, look up the global
2862 // non-array delete.
2863 return FindUsualDeallocationFunction(
2864 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2865 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002866}
2867
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002868bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2869 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002870 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002871 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002872 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002873 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002874
John McCall27b18f82009-11-17 02:14:36 +00002875 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002876 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002877
Chandler Carruthb6f99172010-06-28 00:30:51 +00002878 Found.suppressDiagnostics();
2879
Richard Smithb2f0f052016-10-10 18:54:32 +00002880 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002881
Richard Smithb2f0f052016-10-10 18:54:32 +00002882 // C++17 [expr.delete]p10:
2883 // If the deallocation functions have class scope, the one without a
2884 // parameter of type std::size_t is selected.
2885 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2886 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2887 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002888
Richard Smithb2f0f052016-10-10 18:54:32 +00002889 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002890 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002891 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002892
Richard Smithb2f0f052016-10-10 18:54:32 +00002893 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002894 if (Operator->isDeleted()) {
2895 if (Diagnose) {
2896 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002897 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002898 }
2899 return true;
2900 }
2901
Richard Smith921bd202012-02-26 09:11:52 +00002902 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002903 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002904 return true;
2905
John McCall66a87592010-08-04 00:31:26 +00002906 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002907 }
John McCall66a87592010-08-04 00:31:26 +00002908
Richard Smithb2f0f052016-10-10 18:54:32 +00002909 // We found multiple suitable operators; complain about the ambiguity.
2910 // FIXME: The standard doesn't say to do this; it appears that the intent
2911 // is that this should never happen.
2912 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002913 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002914 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2915 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002916 for (auto &Match : Matches)
2917 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002918 }
John McCall66a87592010-08-04 00:31:26 +00002919 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002920 }
2921
2922 // We did find operator delete/operator delete[] declarations, but
2923 // none of them were suitable.
2924 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002925 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002926 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2927 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002928
Richard Smithb2f0f052016-10-10 18:54:32 +00002929 for (NamedDecl *D : Found)
2930 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002931 diag::note_member_declared_here) << Name;
2932 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002933 return true;
2934 }
2935
Craig Topperc3ec1492014-05-26 06:22:03 +00002936 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002937 return false;
2938}
2939
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002940namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002941/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002942/// initializing deletee have the same array form.
2943class MismatchingNewDeleteDetector {
2944public:
2945 enum MismatchResult {
2946 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2947 NoMismatch,
2948 /// Indicates that variable is initialized with mismatching form of \a new.
2949 VarInitMismatches,
2950 /// Indicates that member is initialized with mismatching form of \a new.
2951 MemberInitMismatches,
2952 /// Indicates that 1 or more constructors' definitions could not been
2953 /// analyzed, and they will be checked again at the end of translation unit.
2954 AnalyzeLater
2955 };
2956
2957 /// \param EndOfTU True, if this is the final analysis at the end of
2958 /// translation unit. False, if this is the initial analysis at the point
2959 /// delete-expression was encountered.
2960 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002961 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002962 HasUndefinedConstructors(false) {}
2963
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002964 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002965 /// matching form of new-expression.
2966 ///
2967 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2968 /// point where delete-expression is encountered, then a warning will be
2969 /// issued immediately. If return value is \c AnalyzeLater at the point where
2970 /// delete-expression is seen, then member will be analyzed at the end of
2971 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2972 /// couldn't be analyzed. If at least one constructor initializes the member
2973 /// with matching type of new, the return value is \c NoMismatch.
2974 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002975 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002976 /// \param Field Class member to analyze.
2977 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2978 /// for deleting the \p Field.
2979 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002980 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002981 /// List of mismatching new-expressions used for initialization of the pointee
2982 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2983 /// Indicates whether delete-expression was in array form.
2984 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002985
2986private:
2987 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002988 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002989 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002990 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002991 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002992 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002993 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002994 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002995 /// \c new either by the member initializer or in-class initialization.
2996 ///
2997 /// If bodies of all constructors are not visible at the end of translation
2998 /// unit or at least one constructor initializes member with the matching
2999 /// form of \c new, mismatch cannot be proven, and this function will return
3000 /// \c NoMismatch.
3001 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003002 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003003 /// \c new.
3004 ///
3005 /// If variable is initialized with matching form of \c new or variable is not
3006 /// initialized with a \c new expression, this function will return true.
3007 /// If variable is initialized with mismatching form of \c new, returns false.
3008 /// \param D Variable to analyze.
3009 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003010 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003011 /// form of \c new.
3012 ///
3013 /// Returns true, if member is initialized with matching form of \c new in
3014 /// member initializer list. Returns false, if member is initialized with the
3015 /// matching form of \c new in this constructor's initializer or given
3016 /// constructor isn't defined at the point where delete-expression is seen, or
3017 /// member isn't initialized by the constructor.
3018 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003019 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003020 /// \c new in member initializer list.
3021 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3022 /// Checks whether member is initialized with mismatching form of \c new by
3023 /// in-class initializer.
3024 MismatchResult analyzeInClassInitializer();
3025};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003026}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003027
3028MismatchingNewDeleteDetector::MismatchResult
3029MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3030 NewExprs.clear();
3031 assert(DE && "Expected delete-expression");
3032 IsArrayForm = DE->isArrayForm();
3033 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3034 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3035 return analyzeMemberExpr(ME);
3036 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3037 if (!hasMatchingVarInit(D))
3038 return VarInitMismatches;
3039 }
3040 return NoMismatch;
3041}
3042
3043const CXXNewExpr *
3044MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3045 assert(E != nullptr && "Expected a valid initializer expression");
3046 E = E->IgnoreParenImpCasts();
3047 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3048 if (ILE->getNumInits() == 1)
3049 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3050 }
3051
3052 return dyn_cast_or_null<const CXXNewExpr>(E);
3053}
3054
3055bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3056 const CXXCtorInitializer *CI) {
3057 const CXXNewExpr *NE = nullptr;
3058 if (Field == CI->getMember() &&
3059 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3060 if (NE->isArray() == IsArrayForm)
3061 return true;
3062 else
3063 NewExprs.push_back(NE);
3064 }
3065 return false;
3066}
3067
3068bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3069 const CXXConstructorDecl *CD) {
3070 if (CD->isImplicit())
3071 return false;
3072 const FunctionDecl *Definition = CD;
3073 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3074 HasUndefinedConstructors = true;
3075 return EndOfTU;
3076 }
3077 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3078 if (hasMatchingNewInCtorInit(CI))
3079 return true;
3080 }
3081 return false;
3082}
3083
3084MismatchingNewDeleteDetector::MismatchResult
3085MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3086 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003087 const Expr *InitExpr = Field->getInClassInitializer();
3088 if (!InitExpr)
3089 return EndOfTU ? NoMismatch : AnalyzeLater;
3090 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003091 if (NE->isArray() != IsArrayForm) {
3092 NewExprs.push_back(NE);
3093 return MemberInitMismatches;
3094 }
3095 }
3096 return NoMismatch;
3097}
3098
3099MismatchingNewDeleteDetector::MismatchResult
3100MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3101 bool DeleteWasArrayForm) {
3102 assert(Field != nullptr && "Analysis requires a valid class member.");
3103 this->Field = Field;
3104 IsArrayForm = DeleteWasArrayForm;
3105 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3106 for (const auto *CD : RD->ctors()) {
3107 if (hasMatchingNewInCtor(CD))
3108 return NoMismatch;
3109 }
3110 if (HasUndefinedConstructors)
3111 return EndOfTU ? NoMismatch : AnalyzeLater;
3112 if (!NewExprs.empty())
3113 return MemberInitMismatches;
3114 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3115 : NoMismatch;
3116}
3117
3118MismatchingNewDeleteDetector::MismatchResult
3119MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3120 assert(ME != nullptr && "Expected a member expression");
3121 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3122 return analyzeField(F, IsArrayForm);
3123 return NoMismatch;
3124}
3125
3126bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3127 const CXXNewExpr *NE = nullptr;
3128 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3129 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3130 NE->isArray() != IsArrayForm) {
3131 NewExprs.push_back(NE);
3132 }
3133 }
3134 return NewExprs.empty();
3135}
3136
3137static void
3138DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3139 const MismatchingNewDeleteDetector &Detector) {
3140 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3141 FixItHint H;
3142 if (!Detector.IsArrayForm)
3143 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3144 else {
3145 SourceLocation RSquare = Lexer::findLocationAfterToken(
3146 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3147 SemaRef.getLangOpts(), true);
3148 if (RSquare.isValid())
3149 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3150 }
3151 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3152 << Detector.IsArrayForm << H;
3153
3154 for (const auto *NE : Detector.NewExprs)
3155 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3156 << Detector.IsArrayForm;
3157}
3158
3159void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3160 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3161 return;
3162 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3163 switch (Detector.analyzeDeleteExpr(DE)) {
3164 case MismatchingNewDeleteDetector::VarInitMismatches:
3165 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3166 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3167 break;
3168 }
3169 case MismatchingNewDeleteDetector::AnalyzeLater: {
3170 DeleteExprs[Detector.Field].push_back(
3171 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3172 break;
3173 }
3174 case MismatchingNewDeleteDetector::NoMismatch:
3175 break;
3176 }
3177}
3178
3179void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3180 bool DeleteWasArrayForm) {
3181 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3182 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3183 case MismatchingNewDeleteDetector::VarInitMismatches:
3184 llvm_unreachable("This analysis should have been done for class members.");
3185 case MismatchingNewDeleteDetector::AnalyzeLater:
3186 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3187 "translation unit.");
3188 case MismatchingNewDeleteDetector::MemberInitMismatches:
3189 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3190 break;
3191 case MismatchingNewDeleteDetector::NoMismatch:
3192 break;
3193 }
3194}
3195
Sebastian Redlbd150f42008-11-21 19:14:01 +00003196/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3197/// @code ::delete ptr; @endcode
3198/// or
3199/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003200ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003201Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003202 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003203 // C++ [expr.delete]p1:
3204 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003205 // non-explicit conversion function to a pointer type. The result has type
3206 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003207 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003208 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3209
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003210 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003211 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003212 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003213 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003214
John Wiegley01296292011-04-08 18:41:53 +00003215 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003216 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003217 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003218 if (Ex.isInvalid())
3219 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003220
John Wiegley01296292011-04-08 18:41:53 +00003221 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003222
Richard Smithccc11812013-05-21 19:05:48 +00003223 class DeleteConverter : public ContextualImplicitConverter {
3224 public:
3225 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003226
Craig Toppere14c0f82014-03-12 04:55:44 +00003227 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003228 // FIXME: If we have an operator T* and an operator void*, we must pick
3229 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003230 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003231 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003232 return true;
3233 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003234 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003235
Richard Smithccc11812013-05-21 19:05:48 +00003236 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003237 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003238 return S.Diag(Loc, diag::err_delete_operand) << T;
3239 }
3240
3241 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003242 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003243 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3244 }
3245
3246 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003247 QualType T,
3248 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003249 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3250 }
3251
3252 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003253 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003254 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3255 << ConvTy;
3256 }
3257
3258 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003259 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003260 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3261 }
3262
3263 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003264 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003265 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3266 << ConvTy;
3267 }
3268
3269 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003270 QualType T,
3271 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003272 llvm_unreachable("conversion functions are permitted");
3273 }
3274 } Converter;
3275
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003276 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003277 if (Ex.isInvalid())
3278 return ExprError();
3279 Type = Ex.get()->getType();
3280 if (!Converter.match(Type))
3281 // FIXME: PerformContextualImplicitConversion should return ExprError
3282 // itself in this case.
3283 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003284
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003285 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003286 QualType PointeeElem = Context.getBaseElementType(Pointee);
3287
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003288 if (Pointee.getAddressSpace() != LangAS::Default &&
3289 !getLangOpts().OpenCLCPlusPlus)
Simon Pilgrim75c26882016-09-30 14:25:09 +00003290 return Diag(Ex.get()->getLocStart(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003291 diag::err_address_space_qualified_delete)
Yaxun Liub34ec822017-04-11 17:24:23 +00003292 << Pointee.getUnqualifiedType()
3293 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003294
Craig Topperc3ec1492014-05-26 06:22:03 +00003295 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003296 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003297 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003298 // effectively bans deletion of "void*". However, most compilers support
3299 // this, so we treat it as a warning unless we're in a SFINAE context.
3300 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003301 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003302 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003303 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003304 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003305 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003306 // FIXME: This can result in errors if the definition was imported from a
3307 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003308 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003309 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003310 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3311 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3312 }
3313 }
3314
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003315 if (Pointee->isArrayType() && !ArrayForm) {
3316 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003317 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003318 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003319 ArrayForm = true;
3320 }
3321
Anders Carlssona471db02009-08-16 20:29:29 +00003322 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3323 ArrayForm ? OO_Array_Delete : OO_Delete);
3324
Eli Friedmanae4280f2011-07-26 22:25:31 +00003325 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003326 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003327 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3328 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003329 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003330
John McCall284c48f2011-01-27 09:37:56 +00003331 // If we're allocating an array of records, check whether the
3332 // usual operator delete[] has a size_t parameter.
3333 if (ArrayForm) {
3334 // If the user specifically asked to use the global allocator,
3335 // we'll need to do the lookup into the class.
3336 if (UseGlobal)
3337 UsualArrayDeleteWantsSize =
3338 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3339
3340 // Otherwise, the usual operator delete[] should be the
3341 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003342 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003343 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003344 UsualDeallocFnInfo(*this,
3345 DeclAccessPair::make(OperatorDelete, AS_public))
3346 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003347 }
3348
Richard Smitheec915d62012-02-18 04:13:32 +00003349 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003350 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003351 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003352 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003353 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3354 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003355 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003356
Nico Weber5a9259c2016-01-15 21:45:31 +00003357 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3358 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3359 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3360 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003361 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362
Richard Smithb2f0f052016-10-10 18:54:32 +00003363 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003364 if (getLangOpts().OpenCLCPlusPlus) {
3365 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3366 return ExprError();
3367 }
3368
Richard Smithb2f0f052016-10-10 18:54:32 +00003369 bool IsComplete = isCompleteType(StartLoc, Pointee);
3370 bool CanProvideSize =
3371 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3372 Pointee.isDestructedType());
3373 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3374
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003375 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003376 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3377 Overaligned, DeleteName);
3378 }
Mike Stump11289f42009-09-09 15:08:12 +00003379
Eli Friedmanfa0df832012-02-02 03:46:19 +00003380 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003381
Richard Smith5b349582017-10-13 01:55:36 +00003382 // Check access and ambiguity of destructor if we're going to call it.
3383 // Note that this is required even for a virtual delete.
3384 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003385 if (PointeeRD) {
3386 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003387 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3388 PDiag(diag::err_access_dtor) << PointeeElem);
3389 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003390 }
3391 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003392
3393 diagnoseUnavailableAlignedAllocation(*OperatorDelete, StartLoc, true,
3394 *this);
Richard Smith5b349582017-10-13 01:55:36 +00003395
3396 // Convert the operand to the type of the first parameter of operator
3397 // delete. This is only necessary if we selected a destroying operator
3398 // delete that we are going to call (non-virtually); converting to void*
3399 // is trivial and left to AST consumers to handle.
3400 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3401 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003402 Qualifiers Qs = Pointee.getQualifiers();
3403 if (Qs.hasCVRQualifiers()) {
3404 // Qualifiers are irrelevant to this conversion; we're only looking
3405 // for access and ambiguity.
3406 Qs.removeCVRQualifiers();
3407 QualType Unqual = Context.getPointerType(
3408 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3409 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3410 }
Richard Smith5b349582017-10-13 01:55:36 +00003411 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3412 if (Ex.isInvalid())
3413 return ExprError();
3414 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003415 }
3416
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003417 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003418 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3419 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003420 AnalyzeDeleteExprMismatch(Result);
3421 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003422}
3423
Eric Fiselierfa752f22018-03-21 19:19:48 +00003424static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3425 bool IsDelete,
3426 FunctionDecl *&Operator) {
3427
3428 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3429 IsDelete ? OO_Delete : OO_New);
3430
3431 LookupResult R(S, NewName, TheCall->getLocStart(), Sema::LookupOrdinaryName);
3432 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3433 assert(!R.empty() && "implicitly declared allocation functions not found");
3434 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3435
3436 // We do our own custom access checks below.
3437 R.suppressDiagnostics();
3438
3439 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3440 OverloadCandidateSet Candidates(R.getNameLoc(),
3441 OverloadCandidateSet::CSK_Normal);
3442 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3443 FnOvl != FnOvlEnd; ++FnOvl) {
3444 // Even member operator new/delete are implicitly treated as
3445 // static, so don't use AddMemberCandidate.
3446 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3447
3448 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3449 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3450 /*ExplicitTemplateArgs=*/nullptr, Args,
3451 Candidates,
3452 /*SuppressUserConversions=*/false);
3453 continue;
3454 }
3455
3456 FunctionDecl *Fn = cast<FunctionDecl>(D);
3457 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3458 /*SuppressUserConversions=*/false);
3459 }
3460
3461 SourceRange Range = TheCall->getSourceRange();
3462
3463 // Do the resolution.
3464 OverloadCandidateSet::iterator Best;
3465 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3466 case OR_Success: {
3467 // Got one!
3468 FunctionDecl *FnDecl = Best->Function;
3469 assert(R.getNamingClass() == nullptr &&
3470 "class members should not be considered");
3471
3472 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3473 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3474 << (IsDelete ? 1 : 0) << Range;
3475 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3476 << R.getLookupName() << FnDecl->getSourceRange();
3477 return true;
3478 }
3479
3480 Operator = FnDecl;
3481 return false;
3482 }
3483
3484 case OR_No_Viable_Function:
3485 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3486 << R.getLookupName() << Range;
3487 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3488 return true;
3489
3490 case OR_Ambiguous:
3491 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3492 << R.getLookupName() << Range;
3493 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3494 return true;
3495
3496 case OR_Deleted: {
3497 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3498 << Best->Function->isDeleted() << R.getLookupName()
3499 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3500 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3501 return true;
3502 }
3503 }
3504 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3505}
3506
3507ExprResult
3508Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3509 bool IsDelete) {
3510 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3511 if (!getLangOpts().CPlusPlus) {
3512 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3513 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3514 << "C++";
3515 return ExprError();
3516 }
3517 // CodeGen assumes it can find the global new and delete to call,
3518 // so ensure that they are declared.
3519 DeclareGlobalNewDelete();
3520
3521 FunctionDecl *OperatorNewOrDelete = nullptr;
3522 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3523 OperatorNewOrDelete))
3524 return ExprError();
3525 assert(OperatorNewOrDelete && "should be found");
3526
3527 TheCall->setType(OperatorNewOrDelete->getReturnType());
3528 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3529 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3530 InitializedEntity Entity =
3531 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3532 ExprResult Arg = PerformCopyInitialization(
3533 Entity, TheCall->getArg(i)->getLocStart(), TheCall->getArg(i));
3534 if (Arg.isInvalid())
3535 return ExprError();
3536 TheCall->setArg(i, Arg.get());
3537 }
3538 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3539 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3540 "Callee expected to be implicit cast to a builtin function pointer");
3541 Callee->setType(OperatorNewOrDelete->getType());
3542
3543 return TheCallResult;
3544}
3545
Nico Weber5a9259c2016-01-15 21:45:31 +00003546void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3547 bool IsDelete, bool CallCanBeVirtual,
3548 bool WarnOnNonAbstractTypes,
3549 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003550 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003551 return;
3552
3553 // C++ [expr.delete]p3:
3554 // In the first alternative (delete object), if the static type of the
3555 // object to be deleted is different from its dynamic type, the static
3556 // type shall be a base class of the dynamic type of the object to be
3557 // deleted and the static type shall have a virtual destructor or the
3558 // behavior is undefined.
3559 //
3560 const CXXRecordDecl *PointeeRD = dtor->getParent();
3561 // Note: a final class cannot be derived from, no issue there
3562 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3563 return;
3564
Nico Weberbf2260c2017-08-31 06:17:08 +00003565 // If the superclass is in a system header, there's nothing that can be done.
3566 // The `delete` (where we emit the warning) can be in a system header,
3567 // what matters for this warning is where the deleted type is defined.
3568 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3569 return;
3570
Nico Weber5a9259c2016-01-15 21:45:31 +00003571 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3572 if (PointeeRD->isAbstract()) {
3573 // If the class is abstract, we warn by default, because we're
3574 // sure the code has undefined behavior.
3575 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3576 << ClassType;
3577 } else if (WarnOnNonAbstractTypes) {
3578 // Otherwise, if this is not an array delete, it's a bit suspect,
3579 // but not necessarily wrong.
3580 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3581 << ClassType;
3582 }
3583 if (!IsDelete) {
3584 std::string TypeStr;
3585 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3586 Diag(DtorLoc, diag::note_delete_non_virtual)
3587 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3588 }
3589}
3590
Richard Smith03a4aa32016-06-23 19:02:52 +00003591Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3592 SourceLocation StmtLoc,
3593 ConditionKind CK) {
3594 ExprResult E =
3595 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3596 if (E.isInvalid())
3597 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003598 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3599 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003600}
3601
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003602/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003603/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003604ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003605 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003606 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003607 if (ConditionVar->isInvalidDecl())
3608 return ExprError();
3609
Douglas Gregor633caca2009-11-23 23:44:04 +00003610 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003611
Douglas Gregor633caca2009-11-23 23:44:04 +00003612 // C++ [stmt.select]p2:
3613 // The declarator shall not specify a function or an array.
3614 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003616 diag::err_invalid_use_of_function_type)
3617 << ConditionVar->getSourceRange());
3618 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003619 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003620 diag::err_invalid_use_of_array_type)
3621 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003622
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003623 ExprResult Condition = DeclRefExpr::Create(
3624 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3625 /*enclosing*/ false, ConditionVar->getLocation(),
3626 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003627
Eli Friedmanfa0df832012-02-02 03:46:19 +00003628 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003629
Richard Smith03a4aa32016-06-23 19:02:52 +00003630 switch (CK) {
3631 case ConditionKind::Boolean:
3632 return CheckBooleanCondition(StmtLoc, Condition.get());
3633
Richard Smithb130fe72016-06-23 19:16:49 +00003634 case ConditionKind::ConstexprIf:
3635 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3636
Richard Smith03a4aa32016-06-23 19:02:52 +00003637 case ConditionKind::Switch:
3638 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003639 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003640
Richard Smith03a4aa32016-06-23 19:02:52 +00003641 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003642}
3643
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003644/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003645ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003646 // C++ 6.4p4:
3647 // The value of a condition that is an initialized declaration in a statement
3648 // other than a switch statement is the value of the declared variable
3649 // implicitly converted to type bool. If that conversion is ill-formed, the
3650 // program is ill-formed.
3651 // The value of a condition that is an expression is the value of the
3652 // expression, implicitly converted to bool.
3653 //
Richard Smithb130fe72016-06-23 19:16:49 +00003654 // FIXME: Return this value to the caller so they don't need to recompute it.
3655 llvm::APSInt Value(/*BitWidth*/1);
3656 return (IsConstexpr && !CondExpr->isValueDependent())
3657 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3658 CCEK_ConstexprIf)
3659 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003660}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003661
3662/// Helper function to determine whether this is the (deprecated) C++
3663/// conversion from a string literal to a pointer to non-const char or
3664/// non-const wchar_t (for narrow and wide string literals,
3665/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003666bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003667Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3668 // Look inside the implicit cast, if it exists.
3669 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3670 From = Cast->getSubExpr();
3671
3672 // A string literal (2.13.4) that is not a wide string literal can
3673 // be converted to an rvalue of type "pointer to char"; a wide
3674 // string literal can be converted to an rvalue of type "pointer
3675 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003676 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003677 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003678 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003679 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003680 // This conversion is considered only when there is an
3681 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003682 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3683 switch (StrLit->getKind()) {
3684 case StringLiteral::UTF8:
3685 case StringLiteral::UTF16:
3686 case StringLiteral::UTF32:
3687 // We don't allow UTF literals to be implicitly converted
3688 break;
3689 case StringLiteral::Ascii:
3690 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3691 ToPointeeType->getKind() == BuiltinType::Char_S);
3692 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003693 return Context.typesAreCompatible(Context.getWideCharType(),
3694 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003695 }
3696 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003697 }
3698
3699 return false;
3700}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003701
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003702static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003703 SourceLocation CastLoc,
3704 QualType Ty,
3705 CastKind Kind,
3706 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003707 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003708 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003709 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003710 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003711 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003712 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003713 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003714 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715
Richard Smith72d74052013-07-20 19:41:36 +00003716 if (S.RequireNonAbstractType(CastLoc, Ty,
3717 diag::err_allocation_of_abstract_type))
3718 return ExprError();
3719
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003720 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003721 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722
Richard Smith5179eb72016-06-28 19:03:57 +00003723 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3724 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003725 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003726 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003727
Richard Smithf8adcdc2014-07-17 05:12:35 +00003728 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003729 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003730 ConstructorArgs, HadMultipleCandidates,
3731 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3732 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003733 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003734 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003735
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003736 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003737 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003738
John McCalle3027922010-08-25 11:45:40 +00003739 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003740 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741
Richard Smithd3f2d322015-02-24 21:16:19 +00003742 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003743 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003744 return ExprError();
3745
Douglas Gregora4253922010-04-16 22:17:36 +00003746 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003747 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3748 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003749 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003750 if (Result.isInvalid())
3751 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003752 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003753 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3754 CK_UserDefinedConversion, Result.get(),
3755 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756
Douglas Gregor668443e2011-01-20 00:18:04 +00003757 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003758 }
3759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003760}
Douglas Gregora4253922010-04-16 22:17:36 +00003761
Douglas Gregor5fb53972009-01-14 15:45:31 +00003762/// PerformImplicitConversion - Perform an implicit conversion of the
3763/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003764/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003765/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003766/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003767ExprResult
3768Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003769 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003770 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003771 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003772 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3773 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3774 return From;
3775
John McCall0d1da222010-01-12 00:44:57 +00003776 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003777 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003778 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3779 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003780 if (Res.isInvalid())
3781 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003782 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003783 break;
John Wiegley01296292011-04-08 18:41:53 +00003784 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003785
Anders Carlsson110b07b2009-09-15 06:28:28 +00003786 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003788 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003789 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003790 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003791 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003792 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003793 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794
Anders Carlsson110b07b2009-09-15 06:28:28 +00003795 // If the user-defined conversion is specified by a conversion function,
3796 // the initial standard conversion sequence converts the source type to
3797 // the implicit object parameter of the conversion function.
3798 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003799 } else {
3800 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003801 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003802 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003803 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003804 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003805 // initial standard conversion sequence converts the source type to
3806 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003807 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3808 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809 }
Richard Smith72d74052013-07-20 19:41:36 +00003810 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003811 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003812 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003813 PerformImplicitConversion(From, BeforeToType,
3814 ICS.UserDefined.Before, AA_Converting,
3815 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003816 if (Res.isInvalid())
3817 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003818 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
3821 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003822 = BuildCXXCastArgument(*this,
3823 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003824 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003825 CastKind, cast<CXXMethodDecl>(FD),
3826 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003827 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003828 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003829
3830 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003831 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003832
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003833 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003834
Richard Smith1ef75542018-06-27 20:30:34 +00003835 // C++ [over.match.oper]p7:
3836 // [...] the second standard conversion sequence of a user-defined
3837 // conversion sequence is not applied.
3838 if (CCK == CCK_ForBuiltinOverloadedOp)
3839 return From;
3840
Richard Smith507840d2011-11-29 22:48:16 +00003841 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3842 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003843 }
John McCall0d1da222010-01-12 00:44:57 +00003844
3845 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003846 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003847 PDiag(diag::err_typecheck_ambiguous_condition)
3848 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003849 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003850
Douglas Gregor39c16d42008-10-24 04:54:22 +00003851 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003852 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003853
3854 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003855 bool Diagnosed =
3856 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3857 From->getType(), From, Action);
3858 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003859 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003860 }
3861
3862 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003863 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003864}
3865
Richard Smith507840d2011-11-29 22:48:16 +00003866/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003867/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003868/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003869/// expression. Flavor is the context in which we're performing this
3870/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003871ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003872Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003873 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003874 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003875 CheckedConversionKind CCK) {
3876 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003877
Mike Stump87c57ac2009-05-16 07:39:55 +00003878 // Overall FIXME: we are recomputing too many types here and doing far too
3879 // much extra work. What this means is that we need to keep track of more
3880 // information that is computed when we try the implicit conversion initially,
3881 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003882 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003883
Douglas Gregor2fe98832008-11-03 19:09:14 +00003884 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003885 // FIXME: When can ToType be a reference type?
3886 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003887 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003888 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003889 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003890 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003891 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003892 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003893 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003894 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3895 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003896 ConstructorArgs, /*HadMultipleCandidates*/ false,
3897 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3898 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003899 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003900 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003901 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3902 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003903 From, /*HadMultipleCandidates*/ false,
3904 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3905 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003906 }
3907
Douglas Gregor980fb162010-04-29 18:24:40 +00003908 // Resolve overloaded function references.
3909 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3910 DeclAccessPair Found;
3911 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3912 true, Found);
3913 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003914 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003915
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003916 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003917 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003918
Douglas Gregor980fb162010-04-29 18:24:40 +00003919 From = FixOverloadedFunctionReference(From, Found, Fn);
3920 FromType = From->getType();
3921 }
3922
Richard Smitha23ab512013-05-23 00:30:41 +00003923 // If we're converting to an atomic type, first convert to the corresponding
3924 // non-atomic type.
3925 QualType ToAtomicType;
3926 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3927 ToAtomicType = ToType;
3928 ToType = ToAtomic->getValueType();
3929 }
3930
George Burgess IV8d141e02015-12-14 22:00:49 +00003931 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003932 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003933 switch (SCS.First) {
3934 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003935 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3936 FromType = FromAtomic->getValueType().getUnqualifiedType();
3937 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3938 From, /*BasePath=*/nullptr, VK_RValue);
3939 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003940 break;
3941
Eli Friedman946b7b52012-01-24 22:51:26 +00003942 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003943 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003944 ExprResult FromRes = DefaultLvalueConversion(From);
3945 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003946 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003947 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003948 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003949 }
John McCall34376a62010-12-04 03:47:34 +00003950
Douglas Gregor39c16d42008-10-24 04:54:22 +00003951 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003952 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003953 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003954 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003955 break;
3956
3957 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003958 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003959 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003960 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003961 break;
3962
3963 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003964 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003965 }
3966
Richard Smith507840d2011-11-29 22:48:16 +00003967 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003968 switch (SCS.Second) {
3969 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003970 // C++ [except.spec]p5:
3971 // [For] assignment to and initialization of pointers to functions,
3972 // pointers to member functions, and references to functions: the
3973 // target entity shall allow at least the exceptions allowed by the
3974 // source value in the assignment or initialization.
3975 switch (Action) {
3976 case AA_Assigning:
3977 case AA_Initializing:
3978 // Note, function argument passing and returning are initialization.
3979 case AA_Passing:
3980 case AA_Returning:
3981 case AA_Sending:
3982 case AA_Passing_CFAudited:
3983 if (CheckExceptionSpecCompatibility(From, ToType))
3984 return ExprError();
3985 break;
3986
3987 case AA_Casting:
3988 case AA_Converting:
3989 // Casts and implicit conversions are not initialization, so are not
3990 // checked for exception specification mismatches.
3991 break;
3992 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003993 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003994 break;
3995
3996 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003997 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003998 if (ToType->isBooleanType()) {
3999 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4000 SCS.Second == ICK_Integral_Promotion &&
4001 "only enums with fixed underlying type can promote to bool");
4002 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004003 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004004 } else {
4005 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004006 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004007 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004008 break;
4009
4010 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004011 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004012 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004013 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004014 break;
4015
4016 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004017 case ICK_Complex_Conversion: {
4018 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4019 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4020 CastKind CK;
4021 if (FromEl->isRealFloatingType()) {
4022 if (ToEl->isRealFloatingType())
4023 CK = CK_FloatingComplexCast;
4024 else
4025 CK = CK_FloatingComplexToIntegralComplex;
4026 } else if (ToEl->isRealFloatingType()) {
4027 CK = CK_IntegralComplexToFloatingComplex;
4028 } else {
4029 CK = CK_IntegralComplexCast;
4030 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004031 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004032 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004033 break;
John McCall8cb679e2010-11-15 09:13:47 +00004034 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004035
Douglas Gregor39c16d42008-10-24 04:54:22 +00004036 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004037 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004038 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004039 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004040 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004041 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004042 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004043 break;
4044
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004045 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004046 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004047 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004048 break;
4049
John McCall31168b02011-06-15 23:02:42 +00004050 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004051 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004052 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004053 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004054 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004055 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004056 diag::ext_typecheck_convert_incompatible_pointer)
4057 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00004058 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004059 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004060 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004061 diag::ext_typecheck_convert_incompatible_pointer)
4062 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00004063 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00004064
Douglas Gregor33823722011-06-11 01:09:30 +00004065 if (From->getType()->isObjCObjectPointerType() &&
4066 ToType->isObjCObjectPointerType())
4067 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004068 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4069 !CheckObjCARCUnavailableWeakConversion(ToType,
4070 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004071 if (Action == AA_Initializing)
Simon Pilgrim75c26882016-09-30 14:25:09 +00004072 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00004073 diag::err_arc_weak_unavailable_assign);
4074 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004075 Diag(From->getLocStart(),
Simon Pilgrim75c26882016-09-30 14:25:09 +00004076 diag::err_arc_convesion_of_weak_unavailable)
4077 << (Action == AA_Casting) << From->getType() << ToType
John McCall9c3467e2011-09-09 06:12:06 +00004078 << From->getSourceRange();
4079 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004080
Richard Smith354abec2017-12-08 23:29:59 +00004081 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004082 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004083 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004084 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004085
4086 // Make sure we extend blocks if necessary.
4087 // FIXME: doing this here is really ugly.
4088 if (Kind == CK_BlockPointerToObjCPointerCast) {
4089 ExprResult E = From;
4090 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004091 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004092 }
Brian Kelley11352a82017-03-29 18:09:02 +00004093 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4094 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004095 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004096 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004097 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004099
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004100 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004101 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004102 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004103 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004104 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004105 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004106 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004107
4108 // We may not have been able to figure out what this member pointer resolved
4109 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004110 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004111 (void)isCompleteType(From->getExprLoc(), From->getType());
4112 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004113 }
David Majnemerd96b9972014-08-08 00:10:39 +00004114
Richard Smith507840d2011-11-29 22:48:16 +00004115 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004116 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004117 break;
4118 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004120 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004121 // Perform half-to-boolean conversion via float.
4122 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004123 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004124 FromType = Context.FloatTy;
4125 }
4126
Richard Smith507840d2011-11-29 22:48:16 +00004127 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004128 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004129 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004130 break;
4131
Douglas Gregor88d292c2010-05-13 16:44:06 +00004132 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004133 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004135 ToType.getNonReferenceType(),
4136 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004137 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00004138 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00004139 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004140 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004141
Richard Smith507840d2011-11-29 22:48:16 +00004142 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4143 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004144 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004145 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004146 }
4147
Douglas Gregor46188682010-05-18 22:42:18 +00004148 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004149 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004150 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004151 break;
4152
George Burgess IVdf1ed002016-01-13 01:52:39 +00004153 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004154 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004155 Expr *Elem = prepareVectorSplat(ToType, From).get();
4156 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4157 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004158 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160
Douglas Gregor46188682010-05-18 22:42:18 +00004161 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004162 // Case 1. x -> _Complex y
4163 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4164 QualType ElType = ToComplex->getElementType();
4165 bool isFloatingComplex = ElType->isRealFloatingType();
4166
4167 // x -> y
4168 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4169 // do nothing
4170 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004171 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004172 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004173 } else {
4174 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004175 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004176 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004177 }
4178 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004179 From = ImpCastExprToType(From, ToType,
4180 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004181 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004182
4183 // Case 2. _Complex x -> y
4184 } else {
4185 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4186 assert(FromComplex);
4187
4188 QualType ElType = FromComplex->getElementType();
4189 bool isFloatingComplex = ElType->isRealFloatingType();
4190
4191 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004192 From = ImpCastExprToType(From, ElType,
4193 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004194 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004195 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004196
4197 // x -> y
4198 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4199 // do nothing
4200 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004201 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004202 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004203 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004204 } else {
4205 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004206 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004207 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004208 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004209 }
4210 }
Douglas Gregor46188682010-05-18 22:42:18 +00004211 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004212
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004213 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004214 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004215 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004216 break;
4217 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004218
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004219 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004220 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004221 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004222 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4223 if (FromRes.isInvalid())
4224 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004225 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004226 assert ((ConvTy == Sema::Compatible) &&
4227 "Improper transparent union conversion");
4228 (void)ConvTy;
4229 break;
4230 }
4231
Guy Benyei259f9f42013-02-07 16:05:33 +00004232 case ICK_Zero_Event_Conversion:
4233 From = ImpCastExprToType(From, ToType,
4234 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004235 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00004236 break;
4237
Egor Churaev89831422016-12-23 14:55:49 +00004238 case ICK_Zero_Queue_Conversion:
4239 From = ImpCastExprToType(From, ToType,
4240 CK_ZeroToOCLQueue,
4241 From->getValueKind()).get();
4242 break;
4243
Douglas Gregor46188682010-05-18 22:42:18 +00004244 case ICK_Lvalue_To_Rvalue:
4245 case ICK_Array_To_Pointer:
4246 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004247 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004248 case ICK_Qualification:
4249 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004250 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004251 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004252 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004253 }
4254
4255 switch (SCS.Third) {
4256 case ICK_Identity:
4257 // Nothing to do.
4258 break;
4259
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004260 case ICK_Function_Conversion:
4261 // If both sides are functions (or pointers/references to them), there could
4262 // be incompatible exception declarations.
4263 if (CheckExceptionSpecCompatibility(From, ToType))
4264 return ExprError();
4265
4266 From = ImpCastExprToType(From, ToType, CK_NoOp,
4267 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4268 break;
4269
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004270 case ICK_Qualification: {
4271 // The qualification keeps the category of the inner expression, unless the
4272 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00004273 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004274 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00004275 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004276 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004277
Douglas Gregore981bb02011-03-14 16:13:32 +00004278 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004279 !getLangOpts().WritableStrings) {
4280 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
4281 ? diag::ext_deprecated_string_literal_conversion
4282 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00004283 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004284 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004285
Douglas Gregor39c16d42008-10-24 04:54:22 +00004286 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004287 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004288
Douglas Gregor39c16d42008-10-24 04:54:22 +00004289 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004290 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004291 }
4292
Douglas Gregor298f43d2012-04-12 20:42:30 +00004293 // If this conversion sequence involved a scalar -> atomic conversion, perform
4294 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004295 if (!ToAtomicType.isNull()) {
4296 assert(Context.hasSameType(
4297 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4298 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004299 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004300 }
4301
George Burgess IV8d141e02015-12-14 22:00:49 +00004302 // If this conversion sequence succeeded and involved implicitly converting a
4303 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004304 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004305 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4306 From->getLocStart());
4307
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004308 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004309}
4310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004311/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004312///
4313/// If the particular type trait requires a complete type, tries to complete
4314/// it. If completing the type fails, a diagnostic is emitted and false
4315/// returned. If completing the type succeeds or no completion was required,
4316/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004317static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004318 SourceLocation Loc,
4319 QualType ArgTy) {
4320 // C++0x [meta.unary.prop]p3:
4321 // For all of the class templates X declared in this Clause, instantiating
4322 // that template with a template argument that is a class template
4323 // specialization may result in the implicit instantiation of the template
4324 // argument if and only if the semantics of X require that the argument
4325 // must be a complete type.
4326 // We apply this rule to all the type trait expressions used to implement
4327 // these class templates. We also try to follow any GCC documented behavior
4328 // in these expressions to ensure portability of standard libraries.
4329 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004330 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004331 // is_complete_type somewhat obviously cannot require a complete type.
4332 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004333 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004334
4335 // These traits are modeled on the type predicates in C++0x
4336 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4337 // requiring a complete type, as whether or not they return true cannot be
4338 // impacted by the completeness of the type.
4339 case UTT_IsVoid:
4340 case UTT_IsIntegral:
4341 case UTT_IsFloatingPoint:
4342 case UTT_IsArray:
4343 case UTT_IsPointer:
4344 case UTT_IsLvalueReference:
4345 case UTT_IsRvalueReference:
4346 case UTT_IsMemberFunctionPointer:
4347 case UTT_IsMemberObjectPointer:
4348 case UTT_IsEnum:
4349 case UTT_IsUnion:
4350 case UTT_IsClass:
4351 case UTT_IsFunction:
4352 case UTT_IsReference:
4353 case UTT_IsArithmetic:
4354 case UTT_IsFundamental:
4355 case UTT_IsObject:
4356 case UTT_IsScalar:
4357 case UTT_IsCompound:
4358 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004359 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004360
4361 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4362 // which requires some of its traits to have the complete type. However,
4363 // the completeness of the type cannot impact these traits' semantics, and
4364 // so they don't require it. This matches the comments on these traits in
4365 // Table 49.
4366 case UTT_IsConst:
4367 case UTT_IsVolatile:
4368 case UTT_IsSigned:
4369 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004370
4371 // This type trait always returns false, checking the type is moot.
4372 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004373 return true;
4374
David Majnemer213bea32015-11-16 06:58:51 +00004375 // C++14 [meta.unary.prop]:
4376 // If T is a non-union class type, T shall be a complete type.
4377 case UTT_IsEmpty:
4378 case UTT_IsPolymorphic:
4379 case UTT_IsAbstract:
4380 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4381 if (!RD->isUnion())
4382 return !S.RequireCompleteType(
4383 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4384 return true;
4385
4386 // C++14 [meta.unary.prop]:
4387 // If T is a class type, T shall be a complete type.
4388 case UTT_IsFinal:
4389 case UTT_IsSealed:
4390 if (ArgTy->getAsCXXRecordDecl())
4391 return !S.RequireCompleteType(
4392 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4393 return true;
4394
Richard Smithf03e9082017-06-01 00:28:16 +00004395 // C++1z [meta.unary.prop]:
4396 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004397 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004398 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004399 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004400 case UTT_IsStandardLayout:
4401 case UTT_IsPOD:
4402 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004403 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4404 // or an array of unknown bound. But GCC actually imposes the same constraints
4405 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004406 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004407 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004408 case UTT_HasNothrowConstructor:
4409 case UTT_HasNothrowCopy:
4410 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004411 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004412 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004413 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004414 case UTT_HasTrivialCopy:
4415 case UTT_HasTrivialDestructor:
4416 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004417 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4418 LLVM_FALLTHROUGH;
4419
4420 // C++1z [meta.unary.prop]:
4421 // T shall be a complete type, cv void, or an array of unknown bound.
4422 case UTT_IsDestructible:
4423 case UTT_IsNothrowDestructible:
4424 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004425 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004426 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004427 return true;
4428
4429 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004430 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004431 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004432}
4433
Joao Matosc9523d42013-03-27 01:34:16 +00004434static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4435 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004436 bool (CXXRecordDecl::*HasTrivial)() const,
4437 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004438 bool (CXXMethodDecl::*IsDesiredOp)() const)
4439{
4440 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4441 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4442 return true;
4443
4444 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4445 DeclarationNameInfo NameInfo(Name, KeyLoc);
4446 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4447 if (Self.LookupQualifiedName(Res, RD)) {
4448 bool FoundOperator = false;
4449 Res.suppressDiagnostics();
4450 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4451 Op != OpEnd; ++Op) {
4452 if (isa<FunctionTemplateDecl>(*Op))
4453 continue;
4454
4455 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4456 if((Operator->*IsDesiredOp)()) {
4457 FoundOperator = true;
4458 const FunctionProtoType *CPT =
4459 Operator->getType()->getAs<FunctionProtoType>();
4460 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004461 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004462 return false;
4463 }
4464 }
4465 return FoundOperator;
4466 }
4467 return false;
4468}
4469
Alp Toker95e7ff22014-01-01 05:57:51 +00004470static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004471 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004472 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004473
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004474 ASTContext &C = Self.Context;
4475 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004476 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004477 // Type trait expressions corresponding to the primary type category
4478 // predicates in C++0x [meta.unary.cat].
4479 case UTT_IsVoid:
4480 return T->isVoidType();
4481 case UTT_IsIntegral:
4482 return T->isIntegralType(C);
4483 case UTT_IsFloatingPoint:
4484 return T->isFloatingType();
4485 case UTT_IsArray:
4486 return T->isArrayType();
4487 case UTT_IsPointer:
4488 return T->isPointerType();
4489 case UTT_IsLvalueReference:
4490 return T->isLValueReferenceType();
4491 case UTT_IsRvalueReference:
4492 return T->isRValueReferenceType();
4493 case UTT_IsMemberFunctionPointer:
4494 return T->isMemberFunctionPointerType();
4495 case UTT_IsMemberObjectPointer:
4496 return T->isMemberDataPointerType();
4497 case UTT_IsEnum:
4498 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004499 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004500 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004501 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004502 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004503 case UTT_IsFunction:
4504 return T->isFunctionType();
4505
4506 // Type trait expressions which correspond to the convenient composition
4507 // predicates in C++0x [meta.unary.comp].
4508 case UTT_IsReference:
4509 return T->isReferenceType();
4510 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004511 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004512 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004513 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004514 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004515 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004516 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004517 // Note: semantic analysis depends on Objective-C lifetime types to be
4518 // considered scalar types. However, such types do not actually behave
4519 // like scalar types at run time (since they may require retain/release
4520 // operations), so we report them as non-scalar.
4521 if (T->isObjCLifetimeType()) {
4522 switch (T.getObjCLifetime()) {
4523 case Qualifiers::OCL_None:
4524 case Qualifiers::OCL_ExplicitNone:
4525 return true;
4526
4527 case Qualifiers::OCL_Strong:
4528 case Qualifiers::OCL_Weak:
4529 case Qualifiers::OCL_Autoreleasing:
4530 return false;
4531 }
4532 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004533
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004534 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004535 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004536 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004537 case UTT_IsMemberPointer:
4538 return T->isMemberPointerType();
4539
4540 // Type trait expressions which correspond to the type property predicates
4541 // in C++0x [meta.unary.prop].
4542 case UTT_IsConst:
4543 return T.isConstQualified();
4544 case UTT_IsVolatile:
4545 return T.isVolatileQualified();
4546 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004547 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004548 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004549 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004550 case UTT_IsStandardLayout:
4551 return T->isStandardLayoutType();
4552 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004553 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004554 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004555 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004556 case UTT_IsEmpty:
4557 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4558 return !RD->isUnion() && RD->isEmpty();
4559 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004560 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004561 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004562 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004563 return false;
4564 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004565 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004566 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004567 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004568 case UTT_IsAggregate:
4569 // Report vector extensions and complex types as aggregates because they
4570 // support aggregate initialization. GCC mirrors this behavior for vectors
4571 // but not _Complex.
4572 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4573 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004574 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4575 // even then only when it is used with the 'interface struct ...' syntax
4576 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004577 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004578 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004579 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004580 case UTT_IsSealed:
4581 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004582 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004583 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004584 case UTT_IsSigned:
4585 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004586 case UTT_IsUnsigned:
4587 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004588
4589 // Type trait expressions which query classes regarding their construction,
4590 // destruction, and copying. Rather than being based directly on the
4591 // related type predicates in the standard, they are specified by both
4592 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4593 // specifications.
4594 //
4595 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4596 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004597 //
4598 // Note that these builtins do not behave as documented in g++: if a class
4599 // has both a trivial and a non-trivial special member of a particular kind,
4600 // they return false! For now, we emulate this behavior.
4601 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4602 // does not correctly compute triviality in the presence of multiple special
4603 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004604 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004605 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4606 // If __is_pod (type) is true then the trait is true, else if type is
4607 // a cv class or union type (or array thereof) with a trivial default
4608 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004609 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004610 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004611 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4612 return RD->hasTrivialDefaultConstructor() &&
4613 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004614 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004615 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004616 // This trait is implemented by MSVC 2012 and needed to parse the
4617 // standard library headers. Specifically this is used as the logic
4618 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004619 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004620 return true;
4621 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4622 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4623 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004624 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004625 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4626 // If __is_pod (type) is true or type is a reference type then
4627 // the trait is true, else if type is a cv class or union type
4628 // with a trivial copy constructor ([class.copy]) then the trait
4629 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004630 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004631 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004632 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4633 return RD->hasTrivialCopyConstructor() &&
4634 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004635 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004636 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004637 // This trait is implemented by MSVC 2012 and needed to parse the
4638 // standard library headers. Specifically it is used as the logic
4639 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004640 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004641 return true;
4642 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4643 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4644 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004645 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004646 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4647 // If type is const qualified or is a reference type then the
4648 // trait is false. Otherwise if __is_pod (type) is true then the
4649 // trait is true, else if type is a cv class or union type with
4650 // a trivial copy assignment ([class.copy]) then the trait is
4651 // true, else it is false.
4652 // Note: the const and reference restrictions are interesting,
4653 // given that const and reference members don't prevent a class
4654 // from having a trivial copy assignment operator (but do cause
4655 // errors if the copy assignment operator is actually used, q.v.
4656 // [class.copy]p12).
4657
Richard Smith92f241f2012-12-08 02:53:02 +00004658 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004659 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004660 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004661 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004662 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4663 return RD->hasTrivialCopyAssignment() &&
4664 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004665 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004666 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004667 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004668 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004669 // C++14 [meta.unary.prop]:
4670 // For reference types, is_destructible<T>::value is true.
4671 if (T->isReferenceType())
4672 return true;
4673
4674 // Objective-C++ ARC: autorelease types don't require destruction.
4675 if (T->isObjCLifetimeType() &&
4676 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4677 return true;
4678
4679 // C++14 [meta.unary.prop]:
4680 // For incomplete types and function types, is_destructible<T>::value is
4681 // false.
4682 if (T->isIncompleteType() || T->isFunctionType())
4683 return false;
4684
Richard Smithf03e9082017-06-01 00:28:16 +00004685 // A type that requires destruction (via a non-trivial destructor or ARC
4686 // lifetime semantics) is not trivially-destructible.
4687 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4688 return false;
4689
David Majnemerac73de92015-08-11 03:03:28 +00004690 // C++14 [meta.unary.prop]:
4691 // For object types and given U equal to remove_all_extents_t<T>, if the
4692 // expression std::declval<U&>().~U() is well-formed when treated as an
4693 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4694 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4695 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4696 if (!Destructor)
4697 return false;
4698 // C++14 [dcl.fct.def.delete]p2:
4699 // A program that refers to a deleted function implicitly or
4700 // explicitly, other than to declare it, is ill-formed.
4701 if (Destructor->isDeleted())
4702 return false;
4703 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4704 return false;
4705 if (UTT == UTT_IsNothrowDestructible) {
4706 const FunctionProtoType *CPT =
4707 Destructor->getType()->getAs<FunctionProtoType>();
4708 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004709 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004710 return false;
4711 }
4712 }
4713 return true;
4714
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004715 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004716 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004717 // If __is_pod (type) is true or type is a reference type
4718 // then the trait is true, else if type is a cv class or union
4719 // type (or array thereof) with a trivial destructor
4720 // ([class.dtor]) then the trait is true, else it is
4721 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004722 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004723 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004724
John McCall31168b02011-06-15 23:02:42 +00004725 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004726 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004727 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4728 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004729
Richard Smith92f241f2012-12-08 02:53:02 +00004730 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4731 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004732 return false;
4733 // TODO: Propagate nothrowness for implicitly declared special members.
4734 case UTT_HasNothrowAssign:
4735 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4736 // If type is const qualified or is a reference type then the
4737 // trait is false. Otherwise if __has_trivial_assign (type)
4738 // is true then the trait is true, else if type is a cv class
4739 // or union type with copy assignment operators that are known
4740 // not to throw an exception then the trait is true, else it is
4741 // false.
4742 if (C.getBaseElementType(T).isConstQualified())
4743 return false;
4744 if (T->isReferenceType())
4745 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004746 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004747 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004748
Joao Matosc9523d42013-03-27 01:34:16 +00004749 if (const RecordType *RT = T->getAs<RecordType>())
4750 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4751 &CXXRecordDecl::hasTrivialCopyAssignment,
4752 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4753 &CXXMethodDecl::isCopyAssignmentOperator);
4754 return false;
4755 case UTT_HasNothrowMoveAssign:
4756 // This trait is implemented by MSVC 2012 and needed to parse the
4757 // standard library headers. Specifically this is used as the logic
4758 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004759 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004760 return true;
4761
4762 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4763 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4764 &CXXRecordDecl::hasTrivialMoveAssignment,
4765 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4766 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004767 return false;
4768 case UTT_HasNothrowCopy:
4769 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4770 // If __has_trivial_copy (type) is true then the trait is true, else
4771 // if type is a cv class or union type with copy constructors that are
4772 // known not to throw an exception then the trait is true, else it is
4773 // false.
John McCall31168b02011-06-15 23:02:42 +00004774 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004775 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004776 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4777 if (RD->hasTrivialCopyConstructor() &&
4778 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004779 return true;
4780
4781 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004782 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004783 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004784 // A template constructor is never a copy constructor.
4785 // FIXME: However, it may actually be selected at the actual overload
4786 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004787 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004788 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004789 // UsingDecl itself is not a constructor
4790 if (isa<UsingDecl>(ND))
4791 continue;
4792 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004793 if (Constructor->isCopyConstructor(FoundTQs)) {
4794 FoundConstructor = true;
4795 const FunctionProtoType *CPT
4796 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004797 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4798 if (!CPT)
4799 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004800 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004801 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004802 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004803 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004804 }
4805 }
4806
Richard Smith938f40b2011-06-11 17:19:42 +00004807 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004808 }
4809 return false;
4810 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004811 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004812 // If __has_trivial_constructor (type) is true then the trait is
4813 // true, else if type is a cv class or union type (or array
4814 // thereof) with a default constructor that is known not to
4815 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004816 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004817 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004818 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4819 if (RD->hasTrivialDefaultConstructor() &&
4820 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004821 return true;
4822
Alp Tokerb4bca412014-01-20 00:23:47 +00004823 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004824 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004825 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004826 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004827 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004828 // UsingDecl itself is not a constructor
4829 if (isa<UsingDecl>(ND))
4830 continue;
4831 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004832 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004833 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004834 const FunctionProtoType *CPT
4835 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004836 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4837 if (!CPT)
4838 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004839 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004840 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004841 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004842 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004843 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004844 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004845 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004846 }
4847 return false;
4848 case UTT_HasVirtualDestructor:
4849 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4850 // If type is a class type with a virtual destructor ([class.dtor])
4851 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004852 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004853 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004854 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004855 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004856
4857 // These type trait expressions are modeled on the specifications for the
4858 // Embarcadero C++0x type trait functions:
4859 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4860 case UTT_IsCompleteType:
4861 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4862 // Returns True if and only if T is a complete type at the point of the
4863 // function call.
4864 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004865 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004866 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004867 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004868}
Sebastian Redl5822f082009-02-07 20:10:22 +00004869
Alp Tokercbb90342013-12-13 20:49:58 +00004870static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4871 QualType RhsT, SourceLocation KeyLoc);
4872
Douglas Gregor29c42f22012-02-24 07:38:34 +00004873static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4874 ArrayRef<TypeSourceInfo *> Args,
4875 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004876 if (Kind <= UTT_Last)
4877 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4878
Eric Fiselier1af6c112018-01-12 00:09:37 +00004879 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4880 // traits to avoid duplication.
4881 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004882 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4883 Args[1]->getType(), RParenLoc);
4884
Douglas Gregor29c42f22012-02-24 07:38:34 +00004885 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004886 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004887 case clang::TT_IsConstructible:
4888 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004889 case clang::TT_IsTriviallyConstructible: {
4890 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004891 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004892 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004893 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004894 // definition for is_constructible, as defined below, is known to call
4895 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004896 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004897 // The predicate condition for a template specialization
4898 // is_constructible<T, Args...> shall be satisfied if and only if the
4899 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004900 // variable t:
4901 //
4902 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004903 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004904
4905 // Precondition: T and all types in the parameter pack Args shall be
4906 // complete types, (possibly cv-qualified) void, or arrays of
4907 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004908 for (const auto *TSI : Args) {
4909 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004910 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004911 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004912
Simon Pilgrim75c26882016-09-30 14:25:09 +00004913 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004914 diag::err_incomplete_type_used_in_type_trait_expr))
4915 return false;
4916 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004917
David Majnemer9658ecc2015-11-13 05:32:43 +00004918 // Make sure the first argument is not incomplete nor a function type.
4919 QualType T = Args[0]->getType();
4920 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004921 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004922
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004923 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004924 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004925 if (RD && RD->isAbstract())
4926 return false;
4927
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004928 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4929 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004930 ArgExprs.reserve(Args.size() - 1);
4931 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004932 QualType ArgTy = Args[I]->getType();
4933 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4934 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004935 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004936 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4937 ArgTy.getNonLValueExprType(S.Context),
4938 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004939 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004940 for (Expr &E : OpaqueArgExprs)
4941 ArgExprs.push_back(&E);
4942
Simon Pilgrim75c26882016-09-30 14:25:09 +00004943 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004944 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004945 EnterExpressionEvaluationContext Unevaluated(
4946 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004947 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4948 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4949 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4950 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4951 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004952 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004953 if (Init.Failed())
4954 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004955
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004956 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004957 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4958 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004959
Alp Toker73287bf2014-01-20 00:24:09 +00004960 if (Kind == clang::TT_IsConstructible)
4961 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004962
Eric Fiselier1af6c112018-01-12 00:09:37 +00004963 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4964 if (!T->isReferenceType())
4965 return false;
4966
4967 return !Init.isDirectReferenceBinding();
4968 }
4969
Alp Toker73287bf2014-01-20 00:24:09 +00004970 if (Kind == clang::TT_IsNothrowConstructible)
4971 return S.canThrow(Result.get()) == CT_Cannot;
4972
4973 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004974 // Under Objective-C ARC and Weak, if the destination has non-trivial
4975 // Objective-C lifetime, this is a non-trivial construction.
4976 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00004977 return false;
4978
4979 // The initialization succeeded; now make sure there are no non-trivial
4980 // calls.
4981 return !Result.get()->hasNonTrivialCall(S.Context);
4982 }
4983
4984 llvm_unreachable("unhandled type trait");
4985 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004986 }
Alp Tokercbb90342013-12-13 20:49:58 +00004987 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004988 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004989
Douglas Gregor29c42f22012-02-24 07:38:34 +00004990 return false;
4991}
4992
Simon Pilgrim75c26882016-09-30 14:25:09 +00004993ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4994 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004995 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004996 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004997
Alp Toker95e7ff22014-01-01 05:57:51 +00004998 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4999 *this, Kind, KWLoc, Args[0]->getType()))
5000 return ExprError();
5001
Douglas Gregor29c42f22012-02-24 07:38:34 +00005002 bool Dependent = false;
5003 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5004 if (Args[I]->getType()->isDependentType()) {
5005 Dependent = true;
5006 break;
5007 }
5008 }
Alp Tokercbb90342013-12-13 20:49:58 +00005009
5010 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005011 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005012 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5013
5014 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5015 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005016}
5017
Alp Toker88f64e62013-12-13 21:19:30 +00005018ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5019 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005020 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005021 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005022 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005023
Douglas Gregor29c42f22012-02-24 07:38:34 +00005024 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5025 TypeSourceInfo *TInfo;
5026 QualType T = GetTypeFromParser(Args[I], &TInfo);
5027 if (!TInfo)
5028 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005029
5030 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005031 }
Alp Tokercbb90342013-12-13 20:49:58 +00005032
Douglas Gregor29c42f22012-02-24 07:38:34 +00005033 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5034}
5035
Alp Tokercbb90342013-12-13 20:49:58 +00005036static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5037 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005038 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5039 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005040
5041 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005042 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005043 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005044 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005045 // Base and Derived are not unions and name the same class type without
5046 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005047
John McCall388ef532011-01-28 22:02:36 +00005048 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005049 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005050 if (!rhsRecord || !lhsRecord) {
5051 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5052 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5053 if (!LHSObjTy || !RHSObjTy)
5054 return false;
5055
5056 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5057 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5058 if (!BaseInterface || !DerivedInterface)
5059 return false;
5060
5061 if (Self.RequireCompleteType(
5062 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5063 return false;
5064
5065 return BaseInterface->isSuperClassOf(DerivedInterface);
5066 }
John McCall388ef532011-01-28 22:02:36 +00005067
5068 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5069 == (lhsRecord == rhsRecord));
5070
5071 if (lhsRecord == rhsRecord)
5072 return !lhsRecord->getDecl()->isUnion();
5073
5074 // C++0x [meta.rel]p2:
5075 // If Base and Derived are class types and are different types
5076 // (ignoring possible cv-qualifiers) then Derived shall be a
5077 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005078 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005079 diag::err_incomplete_type_used_in_type_trait_expr))
5080 return false;
5081
5082 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5083 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5084 }
John Wiegley65497cc2011-04-27 23:09:49 +00005085 case BTT_IsSame:
5086 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005087 case BTT_TypeCompatible: {
5088 // GCC ignores cv-qualifiers on arrays for this builtin.
5089 Qualifiers LhsQuals, RhsQuals;
5090 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5091 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5092 return Self.Context.typesAreCompatible(Lhs, Rhs);
5093 }
John Wiegley65497cc2011-04-27 23:09:49 +00005094 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005095 case BTT_IsConvertibleTo: {
5096 // C++0x [meta.rel]p4:
5097 // Given the following function prototype:
5098 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005099 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005100 // typename add_rvalue_reference<T>::type create();
5101 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005102 // the predicate condition for a template specialization
5103 // is_convertible<From, To> shall be satisfied if and only if
5104 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005105 // well-formed, including any implicit conversions to the return
5106 // type of the function:
5107 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005108 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005109 // return create<From>();
5110 // }
5111 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005112 // Access checking is performed as if in a context unrelated to To and
5113 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005114 // of the return-statement (including conversions to the return type)
5115 // is considered.
5116 //
5117 // We model the initialization as a copy-initialization of a temporary
5118 // of the appropriate type, which for this expression is identical to the
5119 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005120
5121 // Functions aren't allowed to return function or array types.
5122 if (RhsT->isFunctionType() || RhsT->isArrayType())
5123 return false;
5124
5125 // A return statement in a void function must have void type.
5126 if (RhsT->isVoidType())
5127 return LhsT->isVoidType();
5128
5129 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005130 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005131 return false;
5132
5133 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005134 if (LhsT->isObjectType() || LhsT->isFunctionType())
5135 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005136
5137 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005138 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005139 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005140 Expr::getValueKindForType(LhsT));
5141 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005142 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005143 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005144
5145 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005146 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005147 EnterExpressionEvaluationContext Unevaluated(
5148 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005149 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5150 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005151 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005152 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005153 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005154
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005155 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005156 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5157 }
Alp Toker73287bf2014-01-20 00:24:09 +00005158
David Majnemerb3d96882016-05-23 17:21:55 +00005159 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005160 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005161 case BTT_IsTriviallyAssignable: {
5162 // C++11 [meta.unary.prop]p3:
5163 // is_trivially_assignable is defined as:
5164 // is_assignable<T, U>::value is true and the assignment, as defined by
5165 // is_assignable, is known to call no operation that is not trivial
5166 //
5167 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005168 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005169 // treated as an unevaluated operand (Clause 5).
5170 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005171 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005172 // void, or arrays of unknown bound.
5173 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005174 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005175 diag::err_incomplete_type_used_in_type_trait_expr))
5176 return false;
5177 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005178 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005179 diag::err_incomplete_type_used_in_type_trait_expr))
5180 return false;
5181
5182 // cv void is never assignable.
5183 if (LhsT->isVoidType() || RhsT->isVoidType())
5184 return false;
5185
Simon Pilgrim75c26882016-09-30 14:25:09 +00005186 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005187 // declval<U>().
5188 if (LhsT->isObjectType() || LhsT->isFunctionType())
5189 LhsT = Self.Context.getRValueReferenceType(LhsT);
5190 if (RhsT->isObjectType() || RhsT->isFunctionType())
5191 RhsT = Self.Context.getRValueReferenceType(RhsT);
5192 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5193 Expr::getValueKindForType(LhsT));
5194 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5195 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005196
5197 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005198 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005199 EnterExpressionEvaluationContext Unevaluated(
5200 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005201 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005202 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005203 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5204 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005205 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5206 return false;
5207
David Majnemerb3d96882016-05-23 17:21:55 +00005208 if (BTT == BTT_IsAssignable)
5209 return true;
5210
Alp Toker73287bf2014-01-20 00:24:09 +00005211 if (BTT == BTT_IsNothrowAssignable)
5212 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005213
Alp Toker73287bf2014-01-20 00:24:09 +00005214 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005215 // Under Objective-C ARC and Weak, if the destination has non-trivial
5216 // Objective-C lifetime, this is a non-trivial assignment.
5217 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005218 return false;
5219
5220 return !Result.get()->hasNonTrivialCall(Self.Context);
5221 }
5222
5223 llvm_unreachable("unhandled type trait");
5224 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005225 }
Alp Tokercbb90342013-12-13 20:49:58 +00005226 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005227 }
5228 llvm_unreachable("Unknown type trait or not implemented");
5229}
5230
John Wiegley6242b6a2011-04-28 00:16:57 +00005231ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5232 SourceLocation KWLoc,
5233 ParsedType Ty,
5234 Expr* DimExpr,
5235 SourceLocation RParen) {
5236 TypeSourceInfo *TSInfo;
5237 QualType T = GetTypeFromParser(Ty, &TSInfo);
5238 if (!TSInfo)
5239 TSInfo = Context.getTrivialTypeSourceInfo(T);
5240
5241 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5242}
5243
5244static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5245 QualType T, Expr *DimExpr,
5246 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005247 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005248
5249 switch(ATT) {
5250 case ATT_ArrayRank:
5251 if (T->isArrayType()) {
5252 unsigned Dim = 0;
5253 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5254 ++Dim;
5255 T = AT->getElementType();
5256 }
5257 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005258 }
John Wiegleyd3522222011-04-28 02:06:46 +00005259 return 0;
5260
John Wiegley6242b6a2011-04-28 00:16:57 +00005261 case ATT_ArrayExtent: {
5262 llvm::APSInt Value;
5263 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005264 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005265 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005266 false).isInvalid())
5267 return 0;
5268 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005269 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5270 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005271 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005272 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005273 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005274
5275 if (T->isArrayType()) {
5276 unsigned D = 0;
5277 bool Matched = false;
5278 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5279 if (Dim == D) {
5280 Matched = true;
5281 break;
5282 }
5283 ++D;
5284 T = AT->getElementType();
5285 }
5286
John Wiegleyd3522222011-04-28 02:06:46 +00005287 if (Matched && T->isArrayType()) {
5288 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5289 return CAT->getSize().getLimitedValue();
5290 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005291 }
John Wiegleyd3522222011-04-28 02:06:46 +00005292 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005293 }
5294 }
5295 llvm_unreachable("Unknown type trait or not implemented");
5296}
5297
5298ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5299 SourceLocation KWLoc,
5300 TypeSourceInfo *TSInfo,
5301 Expr* DimExpr,
5302 SourceLocation RParen) {
5303 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005304
Chandler Carruthc5276e52011-05-01 08:48:21 +00005305 // FIXME: This should likely be tracked as an APInt to remove any host
5306 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005307 uint64_t Value = 0;
5308 if (!T->isDependentType())
5309 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5310
Chandler Carruthc5276e52011-05-01 08:48:21 +00005311 // While the specification for these traits from the Embarcadero C++
5312 // compiler's documentation says the return type is 'unsigned int', Clang
5313 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5314 // compiler, there is no difference. On several other platforms this is an
5315 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005316 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5317 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005318}
5319
John Wiegleyf9f65842011-04-25 06:54:41 +00005320ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005321 SourceLocation KWLoc,
5322 Expr *Queried,
5323 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005324 // If error parsing the expression, ignore.
5325 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005326 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005327
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005328 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005329
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005330 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005331}
5332
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005333static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5334 switch (ET) {
5335 case ET_IsLValueExpr: return E->isLValue();
5336 case ET_IsRValueExpr: return E->isRValue();
5337 }
5338 llvm_unreachable("Expression trait not covered by switch");
5339}
5340
John Wiegleyf9f65842011-04-25 06:54:41 +00005341ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005342 SourceLocation KWLoc,
5343 Expr *Queried,
5344 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005345 if (Queried->isTypeDependent()) {
5346 // Delay type-checking for type-dependent expressions.
5347 } else if (Queried->getType()->isPlaceholderType()) {
5348 ExprResult PE = CheckPlaceholderExpr(Queried);
5349 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005350 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005351 }
5352
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005353 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005354
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005355 return new (Context)
5356 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005357}
5358
Richard Trieu82402a02011-09-15 21:56:47 +00005359QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005360 ExprValueKind &VK,
5361 SourceLocation Loc,
5362 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005363 assert(!LHS.get()->getType()->isPlaceholderType() &&
5364 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005365 "placeholders should have been weeded out by now");
5366
Richard Smith4baaa5a2016-12-03 01:14:32 +00005367 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5368 // temporary materialization conversion otherwise.
5369 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005370 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005371 else if (LHS.get()->isRValue())
5372 LHS = TemporaryMaterializationConversion(LHS.get());
5373 if (LHS.isInvalid())
5374 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005375
5376 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005377 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005378 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005379
Sebastian Redl5822f082009-02-07 20:10:22 +00005380 const char *OpSpelling = isIndirect ? "->*" : ".*";
5381 // C++ 5.5p2
5382 // The binary operator .* [p3: ->*] binds its second operand, which shall
5383 // be of type "pointer to member of T" (where T is a completely-defined
5384 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005385 QualType RHSType = RHS.get()->getType();
5386 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005387 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005388 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005389 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005390 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005391 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005392
Sebastian Redl5822f082009-02-07 20:10:22 +00005393 QualType Class(MemPtr->getClass(), 0);
5394
Douglas Gregord07ba342010-10-13 20:41:14 +00005395 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5396 // member pointer points must be completely-defined. However, there is no
5397 // reason for this semantic distinction, and the rule is not enforced by
5398 // other compilers. Therefore, we do not check this property, as it is
5399 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005400
Sebastian Redl5822f082009-02-07 20:10:22 +00005401 // C++ 5.5p2
5402 // [...] to its first operand, which shall be of class T or of a class of
5403 // which T is an unambiguous and accessible base class. [p3: a pointer to
5404 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005405 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005406 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005407 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5408 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005409 else {
5410 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005411 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005412 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005413 return QualType();
5414 }
5415 }
5416
Richard Trieu82402a02011-09-15 21:56:47 +00005417 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005418 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005419 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5420 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005421 return QualType();
5422 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005423
Richard Smith0f59cb32015-12-18 21:45:41 +00005424 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005425 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005426 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005427 return QualType();
5428 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005429
5430 CXXCastPath BasePath;
5431 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5432 SourceRange(LHS.get()->getLocStart(),
5433 RHS.get()->getLocEnd()),
5434 &BasePath))
5435 return QualType();
5436
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005437 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005438 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5439 if (isIndirect)
5440 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005441 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005442 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005443 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005444 }
5445
Richard Trieu82402a02011-09-15 21:56:47 +00005446 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005447 // Diagnose use of pointer-to-member type which when used as
5448 // the functional cast in a pointer-to-member expression.
5449 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5450 return QualType();
5451 }
John McCall7decc9e2010-11-18 06:31:45 +00005452
Sebastian Redl5822f082009-02-07 20:10:22 +00005453 // C++ 5.5p2
5454 // The result is an object or a function of the type specified by the
5455 // second operand.
5456 // The cv qualifiers are the union of those in the pointer and the left side,
5457 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005458 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005459 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005460
Douglas Gregor1d042092011-01-26 16:40:18 +00005461 // C++0x [expr.mptr.oper]p6:
5462 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005463 // ill-formed if the second operand is a pointer to member function with
5464 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5465 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005466 // is a pointer to member function with ref-qualifier &&.
5467 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5468 switch (Proto->getRefQualifier()) {
5469 case RQ_None:
5470 // Do nothing
5471 break;
5472
5473 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005474 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5475 // C++2a allows functions with ref-qualifier & if they are also 'const'.
5476 if (Proto->isConst())
5477 Diag(Loc, getLangOpts().CPlusPlus2a
5478 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5479 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5480 else
5481 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5482 << RHSType << 1 << LHS.get()->getSourceRange();
5483 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005484 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005485
Douglas Gregor1d042092011-01-26 16:40:18 +00005486 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005487 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005488 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005489 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005490 break;
5491 }
5492 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005493
John McCall7decc9e2010-11-18 06:31:45 +00005494 // C++ [expr.mptr.oper]p6:
5495 // The result of a .* expression whose second operand is a pointer
5496 // to a data member is of the same value category as its
5497 // first operand. The result of a .* expression whose second
5498 // operand is a pointer to a member function is a prvalue. The
5499 // result of an ->* expression is an lvalue if its second operand
5500 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005501 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005502 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005503 return Context.BoundMemberTy;
5504 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005505 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005506 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005507 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005508 }
John McCall7decc9e2010-11-18 06:31:45 +00005509
Sebastian Redl5822f082009-02-07 20:10:22 +00005510 return Result;
5511}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005513/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005514///
5515/// This is part of the parameter validation for the ? operator. If either
5516/// value operand is a class type, the two operands are attempted to be
5517/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005518/// It returns true if the program is ill-formed and has already been diagnosed
5519/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005520static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5521 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005522 bool &HaveConversion,
5523 QualType &ToType) {
5524 HaveConversion = false;
5525 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005526
5527 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005528 SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005529 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005530 // The process for determining whether an operand expression E1 of type T1
5531 // can be converted to match an operand expression E2 of type T2 is defined
5532 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005533 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5534 // implicitly converted to type "lvalue reference to T2", subject to the
5535 // constraint that in the conversion the reference must bind directly to
5536 // an lvalue.
5537 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005538 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005539 // the constraint that the reference must bind directly.
5540 if (To->isLValue() || To->isXValue()) {
5541 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5542 : Self.Context.getRValueReferenceType(ToType);
5543
Douglas Gregor838fcc32010-03-26 20:14:36 +00005544 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005545
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005546 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005547 if (InitSeq.isDirectReferenceBinding()) {
5548 ToType = T;
5549 HaveConversion = true;
5550 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005552
Douglas Gregor838fcc32010-03-26 20:14:36 +00005553 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005554 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005555 }
John McCall65eb8792010-02-25 01:37:24 +00005556
Sebastian Redl1a99f442009-04-16 17:51:27 +00005557 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5558 // -- if E1 and E2 have class type, and the underlying class types are
5559 // the same or one is a base class of the other:
5560 QualType FTy = From->getType();
5561 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005562 const RecordType *FRec = FTy->getAs<RecordType>();
5563 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005564 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005565 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5566 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5567 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005568 // E1 can be converted to match E2 if the class of T2 is the
5569 // same type as, or a base class of, the class of T1, and
5570 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005571 if (FRec == TRec || FDerivedFromT) {
5572 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005573 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005574 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005575 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005576 HaveConversion = true;
5577 return false;
5578 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005579
Douglas Gregor838fcc32010-03-26 20:14:36 +00005580 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005581 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005582 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005584
Douglas Gregor838fcc32010-03-26 20:14:36 +00005585 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005587
Douglas Gregor838fcc32010-03-26 20:14:36 +00005588 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5589 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005590 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005591 // an rvalue).
5592 //
5593 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5594 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005595 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005596
Douglas Gregor838fcc32010-03-26 20:14:36 +00005597 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005598 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005599 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005600 ToType = TTy;
5601 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005602 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005603
Sebastian Redl1a99f442009-04-16 17:51:27 +00005604 return false;
5605}
5606
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005607/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005608///
5609/// This is part of the parameter validation for the ? operator. If either
5610/// value operand is a class type, overload resolution is used to find a
5611/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005612static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005613 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005614 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005615 OverloadCandidateSet CandidateSet(QuestionLoc,
5616 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005617 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005618 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005619
5620 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005621 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005622 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005623 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005624 ExprResult LHSRes = Self.PerformImplicitConversion(
5625 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5626 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005627 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005628 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005629 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005630
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005631 ExprResult RHSRes = Self.PerformImplicitConversion(
5632 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5633 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005634 if (RHSRes.isInvalid())
5635 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005636 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005637 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005638 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005639 return false;
John Wiegley01296292011-04-08 18:41:53 +00005640 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005641
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005642 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005643
5644 // Emit a better diagnostic if one of the expressions is a null pointer
5645 // constant and the other is a pointer type. In this case, the user most
5646 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005647 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005648 return true;
5649
5650 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005651 << LHS.get()->getType() << RHS.get()->getType()
5652 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005653 return true;
5654
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005655 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005656 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005657 << LHS.get()->getType() << RHS.get()->getType()
5658 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005659 // FIXME: Print the possible common types by printing the return types of
5660 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005661 break;
5662
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005663 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005664 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005665 }
5666 return true;
5667}
5668
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005669/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005670/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005671static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005672 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00005673 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00005674 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005675 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005676 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005677 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005678 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005679 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680
John Wiegley01296292011-04-08 18:41:53 +00005681 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005682 return false;
5683}
5684
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005685/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005686///
5687/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5688/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005689QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5690 ExprResult &RHS, ExprValueKind &VK,
5691 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005692 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005693 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5694 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005695
Richard Smith45edb702012-08-07 22:06:48 +00005696 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005697 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005698 //
5699 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5700 // a is that of a integer vector with the same number of elements and
5701 // size as the vectors of b and c. If one of either b or c is a scalar
5702 // it is implicitly converted to match the type of the vector.
5703 // Otherwise the expression is ill-formed. If both b and c are scalars,
5704 // then b and c are checked and converted to the type of a if possible.
5705 // Unlike the OpenCL ?: operator, the expression is evaluated as
5706 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005707 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005708 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005709 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005710 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005711 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005712 }
5713
John McCall7decc9e2010-11-18 06:31:45 +00005714 // Assume r-value.
5715 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005716 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005717
Sebastian Redl1a99f442009-04-16 17:51:27 +00005718 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005719 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005720 return Context.DependentTy;
5721
Richard Smith45edb702012-08-07 22:06:48 +00005722 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005723 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005724 QualType LTy = LHS.get()->getType();
5725 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005726 bool LVoid = LTy->isVoidType();
5727 bool RVoid = RTy->isVoidType();
5728 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005729 // ... one of the following shall hold:
5730 // -- The second or the third operand (but not both) is a (possibly
5731 // parenthesized) throw-expression; the result is of the type
5732 // and value category of the other.
5733 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5734 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5735 if (LThrow != RThrow) {
5736 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5737 VK = NonThrow->getValueKind();
5738 // DR (no number yet): the result is a bit-field if the
5739 // non-throw-expression operand is a bit-field.
5740 OK = NonThrow->getObjectKind();
5741 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005742 }
5743
Sebastian Redl1a99f442009-04-16 17:51:27 +00005744 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005745 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005746 if (LVoid && RVoid)
5747 return Context.VoidTy;
5748
5749 // Neither holds, error.
5750 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5751 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005752 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005753 return QualType();
5754 }
5755
5756 // Neither is void.
5757
Richard Smithf2b084f2012-08-08 06:13:49 +00005758 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005759 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005760 // either has (cv) class type [...] an attempt is made to convert each of
5761 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005762 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005763 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005764 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005765 QualType L2RType, R2LType;
5766 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005767 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005768 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005769 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005770 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005771
Sebastian Redl1a99f442009-04-16 17:51:27 +00005772 // If both can be converted, [...] the program is ill-formed.
5773 if (HaveL2R && HaveR2L) {
5774 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005775 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005776 return QualType();
5777 }
5778
5779 // If exactly one conversion is possible, that conversion is applied to
5780 // the chosen operand and the converted operands are used in place of the
5781 // original operands for the remainder of this section.
5782 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005783 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005784 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005785 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005786 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005787 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005788 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005789 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005790 }
5791 }
5792
Richard Smithf2b084f2012-08-08 06:13:49 +00005793 // C++11 [expr.cond]p3
5794 // if both are glvalues of the same value category and the same type except
5795 // for cv-qualification, an attempt is made to convert each of those
5796 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005797 // FIXME:
5798 // Resolving a defect in P0012R1: we extend this to cover all cases where
5799 // one of the operands is reference-compatible with the other, in order
5800 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005801 ExprValueKind LVK = LHS.get()->getValueKind();
5802 ExprValueKind RVK = RHS.get()->getValueKind();
5803 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005804 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005805 // DerivedToBase was already handled by the class-specific case above.
5806 // FIXME: Should we allow ObjC conversions here?
5807 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5808 if (CompareReferenceRelationship(
5809 QuestionLoc, LTy, RTy, DerivedToBase,
5810 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005811 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5812 // [...] subject to the constraint that the reference must bind
5813 // directly [...]
5814 !RHS.get()->refersToBitField() &&
5815 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005816 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005817 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005818 } else if (CompareReferenceRelationship(
5819 QuestionLoc, RTy, LTy, DerivedToBase,
5820 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005821 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5822 !LHS.get()->refersToBitField() &&
5823 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005824 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5825 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005826 }
5827 }
5828
5829 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005830 // If the second and third operands are glvalues of the same value
5831 // category and have the same type, the result is of that type and
5832 // value category and it is a bit-field if the second or the third
5833 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005834 // We only extend this to bitfields, not to the crazy other kinds of
5835 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005836 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005837 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005838 LHS.get()->isOrdinaryOrBitFieldObject() &&
5839 RHS.get()->isOrdinaryOrBitFieldObject()) {
5840 VK = LHS.get()->getValueKind();
5841 if (LHS.get()->getObjectKind() == OK_BitField ||
5842 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005843 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005844
5845 // If we have function pointer types, unify them anyway to unify their
5846 // exception specifications, if any.
5847 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5848 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005849 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005850 /*ConvertArgs*/false);
5851 LTy = Context.getQualifiedType(LTy, Qs);
5852
5853 assert(!LTy.isNull() && "failed to find composite pointer type for "
5854 "canonically equivalent function ptr types");
5855 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5856 }
5857
John McCall7decc9e2010-11-18 06:31:45 +00005858 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005859 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005860
Richard Smithf2b084f2012-08-08 06:13:49 +00005861 // C++11 [expr.cond]p5
5862 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005863 // do not have the same type, and either has (cv) class type, ...
5864 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5865 // ... overload resolution is used to determine the conversions (if any)
5866 // to be applied to the operands. If the overload resolution fails, the
5867 // program is ill-formed.
5868 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5869 return QualType();
5870 }
5871
Richard Smithf2b084f2012-08-08 06:13:49 +00005872 // C++11 [expr.cond]p6
5873 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005874 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005875 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5876 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005877 if (LHS.isInvalid() || RHS.isInvalid())
5878 return QualType();
5879 LTy = LHS.get()->getType();
5880 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005881
5882 // After those conversions, one of the following shall hold:
5883 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005884 // is of that type. If the operands have class type, the result
5885 // is a prvalue temporary of the result type, which is
5886 // copy-initialized from either the second operand or the third
5887 // operand depending on the value of the first operand.
5888 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5889 if (LTy->isRecordType()) {
5890 // The operands have class type. Make a temporary copy.
5891 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005892
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5894 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005895 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005896 if (LHSCopy.isInvalid())
5897 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005898
5899 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5900 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005901 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005902 if (RHSCopy.isInvalid())
5903 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005904
John Wiegley01296292011-04-08 18:41:53 +00005905 LHS = LHSCopy;
5906 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005907 }
5908
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005909 // If we have function pointer types, unify them anyway to unify their
5910 // exception specifications, if any.
5911 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5912 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5913 assert(!LTy.isNull() && "failed to find composite pointer type for "
5914 "canonically equivalent function ptr types");
5915 }
5916
Sebastian Redl1a99f442009-04-16 17:51:27 +00005917 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005918 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005919
Douglas Gregor46188682010-05-18 22:42:18 +00005920 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005921 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005922 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5923 /*AllowBothBool*/true,
5924 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005925
Sebastian Redl1a99f442009-04-16 17:51:27 +00005926 // -- The second and third operands have arithmetic or enumeration type;
5927 // the usual arithmetic conversions are performed to bring them to a
5928 // common type, and the result is of that type.
5929 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005930 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005931 if (LHS.isInvalid() || RHS.isInvalid())
5932 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005933 if (ResTy.isNull()) {
5934 Diag(QuestionLoc,
5935 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5936 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5937 return QualType();
5938 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005939
5940 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5941 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5942
5943 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005944 }
5945
5946 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005947 // type and the other is a null pointer constant, or both are null
5948 // pointer constants, at least one of which is non-integral; pointer
5949 // conversions and qualification conversions are performed to bring them
5950 // to their composite pointer type. The result is of the composite
5951 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005952 // -- The second and third operands have pointer to member type, or one has
5953 // pointer to member type and the other is a null pointer constant;
5954 // pointer to member conversions and qualification conversions are
5955 // performed to bring them to a common type, whose cv-qualification
5956 // shall match the cv-qualification of either the second or the third
5957 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005958 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5959 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005960 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005961
Douglas Gregor697a3912010-04-01 22:47:07 +00005962 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005963 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5964 if (!Composite.isNull())
5965 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005966
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005967 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005968 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005969 return QualType();
5970
Sebastian Redl1a99f442009-04-16 17:51:27 +00005971 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005972 << LHS.get()->getType() << RHS.get()->getType()
5973 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005974 return QualType();
5975}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005976
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005977static FunctionProtoType::ExceptionSpecInfo
5978mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5979 FunctionProtoType::ExceptionSpecInfo ESI2,
5980 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5981 ExceptionSpecificationType EST1 = ESI1.Type;
5982 ExceptionSpecificationType EST2 = ESI2.Type;
5983
5984 // If either of them can throw anything, that is the result.
5985 if (EST1 == EST_None) return ESI1;
5986 if (EST2 == EST_None) return ESI2;
5987 if (EST1 == EST_MSAny) return ESI1;
5988 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00005989 if (EST1 == EST_NoexceptFalse) return ESI1;
5990 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005991
5992 // If either of them is non-throwing, the result is the other.
5993 if (EST1 == EST_DynamicNone) return ESI2;
5994 if (EST2 == EST_DynamicNone) return ESI1;
5995 if (EST1 == EST_BasicNoexcept) return ESI2;
5996 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00005997 if (EST1 == EST_NoexceptTrue) return ESI2;
5998 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005999
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006000 // If we're left with value-dependent computed noexcept expressions, we're
6001 // stuck. Before C++17, we can just drop the exception specification entirely,
6002 // since it's not actually part of the canonical type. And this should never
6003 // happen in C++17, because it would mean we were computing the composite
6004 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006005 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006006 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006007 "computing composite pointer type of dependent types");
6008 return FunctionProtoType::ExceptionSpecInfo();
6009 }
6010
6011 // Switch over the possibilities so that people adding new values know to
6012 // update this function.
6013 switch (EST1) {
6014 case EST_None:
6015 case EST_DynamicNone:
6016 case EST_MSAny:
6017 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006018 case EST_DependentNoexcept:
6019 case EST_NoexceptFalse:
6020 case EST_NoexceptTrue:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006021 llvm_unreachable("handled above");
6022
6023 case EST_Dynamic: {
6024 // This is the fun case: both exception specifications are dynamic. Form
6025 // the union of the two lists.
6026 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6027 llvm::SmallPtrSet<QualType, 8> Found;
6028 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6029 for (QualType E : Exceptions)
6030 if (Found.insert(S.Context.getCanonicalType(E)).second)
6031 ExceptionTypeStorage.push_back(E);
6032
6033 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6034 Result.Exceptions = ExceptionTypeStorage;
6035 return Result;
6036 }
6037
6038 case EST_Unevaluated:
6039 case EST_Uninstantiated:
6040 case EST_Unparsed:
6041 llvm_unreachable("shouldn't see unresolved exception specifications here");
6042 }
6043
6044 llvm_unreachable("invalid ExceptionSpecificationType");
6045}
6046
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006047/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006048///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006049/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006050/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006051/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006052/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006053///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006054/// \param Loc The location of the operator requiring these two expressions to
6055/// be converted to the composite pointer type.
6056///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006057/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006058QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006059 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006060 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006061 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006062
6063 // C++1z [expr]p14:
6064 // The composite pointer type of two operands p1 and p2 having types T1
6065 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006066 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006067
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006068 // where at least one is a pointer or pointer to member type or
6069 // std::nullptr_t is:
6070 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6071 T1->isNullPtrType();
6072 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6073 T2->isNullPtrType();
6074 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006075 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006076
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006077 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6078 // This can't actually happen, following the standard, but we also use this
6079 // to implement the end of [expr.conv], which hits this case.
6080 //
6081 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6082 if (T1IsPointerLike &&
6083 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006084 if (ConvertArgs)
6085 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6086 ? CK_NullToMemberPointer
6087 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006088 return T1;
6089 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006090 if (T2IsPointerLike &&
6091 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006092 if (ConvertArgs)
6093 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6094 ? CK_NullToMemberPointer
6095 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006096 return T2;
6097 }
Mike Stump11289f42009-09-09 15:08:12 +00006098
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006099 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006100 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006101 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006102 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6103 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006104
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006105 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6106 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6107 // the union of cv1 and cv2;
6108 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6109 // "pointer to function", where the function types are otherwise the same,
6110 // "pointer to function";
6111 // FIXME: This rule is defective: it should also permit removing noexcept
6112 // from a pointer to member function. As a Clang extension, we also
6113 // permit removing 'noreturn', so we generalize this rule to;
6114 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6115 // "pointer to member function" and the pointee types can be unified
6116 // by a function pointer conversion, that conversion is applied
6117 // before checking the following rules.
6118 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6119 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6120 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6121 // respectively;
6122 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6123 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6124 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6125 // T1 or the cv-combined type of T1 and T2, respectively;
6126 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6127 // T2;
6128 //
6129 // If looked at in the right way, these bullets all do the same thing.
6130 // What we do here is, we build the two possible cv-combined types, and try
6131 // the conversions in both directions. If only one works, or if the two
6132 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006133 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006134 //
6135 // Note that this will fail to find a composite pointer type for "pointer
6136 // to void" and "pointer to function". We can't actually perform the final
6137 // conversion in this case, even though a composite pointer type formally
6138 // exists.
6139 SmallVector<unsigned, 4> QualifierUnion;
6140 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006141 QualType Composite1 = T1;
6142 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006143 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006144 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006145 const PointerType *Ptr1, *Ptr2;
6146 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6147 (Ptr2 = Composite2->getAs<PointerType>())) {
6148 Composite1 = Ptr1->getPointeeType();
6149 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006150
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006151 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006152 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006153 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006154 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006155
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006156 QualifierUnion.push_back(
6157 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006158 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006159 continue;
6160 }
Mike Stump11289f42009-09-09 15:08:12 +00006161
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006162 const MemberPointerType *MemPtr1, *MemPtr2;
6163 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6164 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6165 Composite1 = MemPtr1->getPointeeType();
6166 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006167
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006168 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006169 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006170 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006171 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006172
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006173 QualifierUnion.push_back(
6174 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6175 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6176 MemPtr2->getClass()));
6177 continue;
6178 }
Mike Stump11289f42009-09-09 15:08:12 +00006179
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006180 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006181
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006182 // Cannot unwrap any more types.
6183 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006184 }
Mike Stump11289f42009-09-09 15:08:12 +00006185
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006186 // Apply the function pointer conversion to unify the types. We've already
6187 // unwrapped down to the function types, and we want to merge rather than
6188 // just convert, so do this ourselves rather than calling
6189 // IsFunctionConversion.
6190 //
6191 // FIXME: In order to match the standard wording as closely as possible, we
6192 // currently only do this under a single level of pointers. Ideally, we would
6193 // allow this in general, and set NeedConstBefore to the relevant depth on
6194 // the side(s) where we changed anything.
6195 if (QualifierUnion.size() == 1) {
6196 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6197 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6198 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6199 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6200
6201 // The result is noreturn if both operands are.
6202 bool Noreturn =
6203 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6204 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6205 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6206
6207 // The result is nothrow if both operands are.
6208 SmallVector<QualType, 8> ExceptionTypeStorage;
6209 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6210 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6211 ExceptionTypeStorage);
6212
6213 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6214 FPT1->getParamTypes(), EPI1);
6215 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6216 FPT2->getParamTypes(), EPI2);
6217 }
6218 }
6219 }
6220
Richard Smith5e9746f2016-10-21 22:00:42 +00006221 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006222 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006223 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006224 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006225 for (unsigned I = 0; I != NeedConstBefore; ++I)
6226 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006227 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006229
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006230 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006231 auto MOC = MemberOfClass.rbegin();
6232 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6233 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6234 auto Classes = *MOC++;
6235 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006236 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006237 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006238 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006239 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006240 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006241 } else {
6242 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006243 Composite1 =
6244 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6245 Composite2 =
6246 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006247 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006248 }
6249
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006250 struct Conversion {
6251 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006252 Expr *&E1, *&E2;
6253 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006254 InitializedEntity Entity;
6255 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006256 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006257 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006258
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006259 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6260 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006261 : S(S), E1(E1), E2(E2), Composite(Composite),
6262 Entity(InitializedEntity::InitializeTemporary(Composite)),
6263 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6264 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6265 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006266
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006267 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006268 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6269 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006270 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006271 E1 = E1Result.getAs<Expr>();
6272
6273 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6274 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006275 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006276 E2 = E2Result.getAs<Expr>();
6277
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006278 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006279 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006280 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006281
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006282 // Try to convert to each composite pointer type.
6283 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006284 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6285 if (ConvertArgs && C1.perform())
6286 return QualType();
6287 return C1.Composite;
6288 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006289 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006290
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006291 if (C1.Viable == C2.Viable) {
6292 // Either Composite1 and Composite2 are viable and are different, or
6293 // neither is viable.
6294 // FIXME: How both be viable and different?
6295 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006296 }
6297
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006298 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006299 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6300 return QualType();
6301
6302 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006303}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006304
John McCalldadc5752010-08-24 06:29:42 +00006305ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006306 if (!E)
6307 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006308
John McCall31168b02011-06-15 23:02:42 +00006309 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6310
6311 // If the result is a glvalue, we shouldn't bind it.
6312 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006313 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006314
John McCall31168b02011-06-15 23:02:42 +00006315 // In ARC, calls that return a retainable type can return retained,
6316 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006317 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006318 E->getType()->isObjCRetainableType()) {
6319
6320 bool ReturnsRetained;
6321
6322 // For actual calls, we compute this by examining the type of the
6323 // called value.
6324 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6325 Expr *Callee = Call->getCallee()->IgnoreParens();
6326 QualType T = Callee->getType();
6327
6328 if (T == Context.BoundMemberTy) {
6329 // Handle pointer-to-members.
6330 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6331 T = BinOp->getRHS()->getType();
6332 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6333 T = Mem->getMemberDecl()->getType();
6334 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006335
John McCall31168b02011-06-15 23:02:42 +00006336 if (const PointerType *Ptr = T->getAs<PointerType>())
6337 T = Ptr->getPointeeType();
6338 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6339 T = Ptr->getPointeeType();
6340 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6341 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006342
John McCall31168b02011-06-15 23:02:42 +00006343 const FunctionType *FTy = T->getAs<FunctionType>();
6344 assert(FTy && "call to value not of function type?");
6345 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6346
6347 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6348 // type always produce a +1 object.
6349 } else if (isa<StmtExpr>(E)) {
6350 ReturnsRetained = true;
6351
Ted Kremeneke65b0862012-03-06 20:05:56 +00006352 // We hit this case with the lambda conversion-to-block optimization;
6353 // we don't want any extra casts here.
6354 } else if (isa<CastExpr>(E) &&
6355 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006356 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006357
John McCall31168b02011-06-15 23:02:42 +00006358 // For message sends and property references, we try to find an
6359 // actual method. FIXME: we should infer retention by selector in
6360 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006361 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006362 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006363 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6364 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006365 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6366 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006367 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006368 // Don't do reclaims if we're using the zero-element array
6369 // constant.
6370 if (ArrayLit->getNumElements() == 0 &&
6371 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6372 return E;
6373
Ted Kremeneke65b0862012-03-06 20:05:56 +00006374 D = ArrayLit->getArrayWithObjectsMethod();
6375 } else if (ObjCDictionaryLiteral *DictLit
6376 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006377 // Don't do reclaims if we're using the zero-element dictionary
6378 // constant.
6379 if (DictLit->getNumElements() == 0 &&
6380 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6381 return E;
6382
Ted Kremeneke65b0862012-03-06 20:05:56 +00006383 D = DictLit->getDictWithObjectsMethod();
6384 }
John McCall31168b02011-06-15 23:02:42 +00006385
6386 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006387
6388 // Don't do reclaims on performSelector calls; despite their
6389 // return type, the invoked method doesn't necessarily actually
6390 // return an object.
6391 if (!ReturnsRetained &&
6392 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006393 return E;
John McCall31168b02011-06-15 23:02:42 +00006394 }
6395
John McCall16de4d22011-11-14 19:53:16 +00006396 // Don't reclaim an object of Class type.
6397 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006398 return E;
John McCall16de4d22011-11-14 19:53:16 +00006399
Tim Shen4a05bb82016-06-21 20:29:17 +00006400 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006401
John McCall2d637d22011-09-10 06:18:15 +00006402 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6403 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006404 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6405 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006406 }
6407
David Blaikiebbafb8a2012-03-11 07:00:24 +00006408 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006409 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006410
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006411 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6412 // a fast path for the common case that the type is directly a RecordType.
6413 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006414 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006415 while (!RT) {
6416 switch (T->getTypeClass()) {
6417 case Type::Record:
6418 RT = cast<RecordType>(T);
6419 break;
6420 case Type::ConstantArray:
6421 case Type::IncompleteArray:
6422 case Type::VariableArray:
6423 case Type::DependentSizedArray:
6424 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6425 break;
6426 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006427 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006428 }
6429 }
Mike Stump11289f42009-09-09 15:08:12 +00006430
Richard Smithfd555f62012-02-22 02:04:18 +00006431 // That should be enough to guarantee that this type is complete, if we're
6432 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006433 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006434 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006435 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006436
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006437 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6438 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006439 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006440
John McCall31168b02011-06-15 23:02:42 +00006441 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006442 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006443 CheckDestructorAccess(E->getExprLoc(), Destructor,
6444 PDiag(diag::err_access_dtor_temp)
6445 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006446 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6447 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006448
Richard Smithfd555f62012-02-22 02:04:18 +00006449 // If destructor is trivial, we can avoid the extra copy.
6450 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006451 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006452
John McCall28fc7092011-11-10 05:35:25 +00006453 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006454 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006455 }
Richard Smitheec915d62012-02-18 04:13:32 +00006456
6457 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006458 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6459
6460 if (IsDecltype)
6461 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6462
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006463 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006464}
6465
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006466ExprResult
John McCall5d413782010-12-06 08:20:24 +00006467Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006468 if (SubExpr.isInvalid())
6469 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006470
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006471 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006472}
6473
John McCall28fc7092011-11-10 05:35:25 +00006474Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006475 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006476
Eli Friedman3bda6b12012-02-02 23:15:15 +00006477 CleanupVarDeclMarking();
6478
John McCall28fc7092011-11-10 05:35:25 +00006479 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6480 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006481 assert(Cleanup.exprNeedsCleanups() ||
6482 ExprCleanupObjects.size() == FirstCleanup);
6483 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006484 return SubExpr;
6485
Craig Topper5fc8fc22014-08-27 06:28:36 +00006486 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6487 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006488
Tim Shen4a05bb82016-06-21 20:29:17 +00006489 auto *E = ExprWithCleanups::Create(
6490 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006491 DiscardCleanupsInEvaluationContext();
6492
6493 return E;
6494}
6495
John McCall5d413782010-12-06 08:20:24 +00006496Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006497 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006498
Eli Friedman3bda6b12012-02-02 23:15:15 +00006499 CleanupVarDeclMarking();
6500
Tim Shen4a05bb82016-06-21 20:29:17 +00006501 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006502 return SubStmt;
6503
6504 // FIXME: In order to attach the temporaries, wrap the statement into
6505 // a StmtExpr; currently this is only used for asm statements.
6506 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6507 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006508 CompoundStmt *CompStmt = CompoundStmt::Create(
6509 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006510 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6511 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006512 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006513}
6514
Richard Smithfd555f62012-02-22 02:04:18 +00006515/// Process the expression contained within a decltype. For such expressions,
6516/// certain semantic checks on temporaries are delayed until this point, and
6517/// are omitted for the 'topmost' call in the decltype expression. If the
6518/// topmost call bound a temporary, strip that temporary off the expression.
6519ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006520 assert(ExprEvalContexts.back().ExprContext ==
6521 ExpressionEvaluationContextRecord::EK_Decltype &&
6522 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006523
6524 // C++11 [expr.call]p11:
6525 // If a function call is a prvalue of object type,
6526 // -- if the function call is either
6527 // -- the operand of a decltype-specifier, or
6528 // -- the right operand of a comma operator that is the operand of a
6529 // decltype-specifier,
6530 // a temporary object is not introduced for the prvalue.
6531
6532 // Recursively rebuild ParenExprs and comma expressions to strip out the
6533 // outermost CXXBindTemporaryExpr, if any.
6534 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6535 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6536 if (SubExpr.isInvalid())
6537 return ExprError();
6538 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006539 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006540 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006541 }
6542 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6543 if (BO->getOpcode() == BO_Comma) {
6544 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6545 if (RHS.isInvalid())
6546 return ExprError();
6547 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006548 return E;
6549 return new (Context) BinaryOperator(
6550 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006551 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006552 }
6553 }
6554
6555 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006556 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6557 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006558 if (TopCall)
6559 E = TopCall;
6560 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006561 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006562
6563 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006564 ExprEvalContexts.back().ExprContext =
6565 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00006566
Richard Smithf86b0ae2012-07-28 19:54:11 +00006567 // In MS mode, don't perform any extra checking of call return types within a
6568 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006569 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006570 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006571
Richard Smithfd555f62012-02-22 02:04:18 +00006572 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006573 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6574 I != N; ++I) {
6575 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006576 if (Call == TopCall)
6577 continue;
6578
David Majnemerced8bdf2015-02-25 17:36:15 +00006579 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00006580 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00006581 Call, Call->getDirectCallee()))
6582 return ExprError();
6583 }
6584
6585 // Now all relevant types are complete, check the destructors are accessible
6586 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006587 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6588 I != N; ++I) {
6589 CXXBindTemporaryExpr *Bind =
6590 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006591 if (Bind == TopBind)
6592 continue;
6593
6594 CXXTemporary *Temp = Bind->getTemporary();
6595
6596 CXXRecordDecl *RD =
6597 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6598 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6599 Temp->setDestructor(Destructor);
6600
Richard Smith7d847b12012-05-11 22:20:10 +00006601 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6602 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006603 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006604 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006605 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6606 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006607
6608 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006609 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006610 }
6611
6612 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006613 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006614}
6615
Richard Smith79c927b2013-11-06 19:31:51 +00006616/// Note a set of 'operator->' functions that were used for a member access.
6617static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006618 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006619 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6620 // FIXME: Make this configurable?
6621 unsigned Limit = 9;
6622 if (OperatorArrows.size() > Limit) {
6623 // Produce Limit-1 normal notes and one 'skipping' note.
6624 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6625 SkipCount = OperatorArrows.size() - (Limit - 1);
6626 }
6627
6628 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6629 if (I == SkipStart) {
6630 S.Diag(OperatorArrows[I]->getLocation(),
6631 diag::note_operator_arrows_suppressed)
6632 << SkipCount;
6633 I += SkipCount;
6634 } else {
6635 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6636 << OperatorArrows[I]->getCallResultType();
6637 ++I;
6638 }
6639 }
6640}
6641
Nico Weber964d3322015-02-16 22:35:45 +00006642ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6643 SourceLocation OpLoc,
6644 tok::TokenKind OpKind,
6645 ParsedType &ObjectType,
6646 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006647 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006648 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006649 if (Result.isInvalid()) return ExprError();
6650 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006651
John McCall526ab472011-10-25 17:37:35 +00006652 Result = CheckPlaceholderExpr(Base);
6653 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006654 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006655
John McCallb268a282010-08-23 23:25:46 +00006656 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006657 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006658 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006659 // If we have a pointer to a dependent type and are using the -> operator,
6660 // the object type is the type that the pointer points to. We might still
6661 // have enough information about that type to do something useful.
6662 if (OpKind == tok::arrow)
6663 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6664 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006665
John McCallba7bf592010-08-24 05:47:05 +00006666 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006667 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006668 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006669 }
Mike Stump11289f42009-09-09 15:08:12 +00006670
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006671 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006672 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006673 // returned, with the original second operand.
6674 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006675 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006676 bool NoArrowOperatorFound = false;
6677 bool FirstIteration = true;
6678 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006679 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006680 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006681 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006682 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006684 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006685 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6686 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006687 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006688 noteOperatorArrows(*this, OperatorArrows);
6689 Diag(OpLoc, diag::note_operator_arrow_depth)
6690 << getLangOpts().ArrowDepth;
6691 return ExprError();
6692 }
6693
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006694 Result = BuildOverloadedArrowExpr(
6695 S, Base, OpLoc,
6696 // When in a template specialization and on the first loop iteration,
6697 // potentially give the default diagnostic (with the fixit in a
6698 // separate note) instead of having the error reported back to here
6699 // and giving a diagnostic with a fixit attached to the error itself.
6700 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006701 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006702 : &NoArrowOperatorFound);
6703 if (Result.isInvalid()) {
6704 if (NoArrowOperatorFound) {
6705 if (FirstIteration) {
6706 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006707 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006708 << FixItHint::CreateReplacement(OpLoc, ".");
6709 OpKind = tok::period;
6710 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006711 }
6712 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6713 << BaseType << Base->getSourceRange();
6714 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006715 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006716 Diag(CD->getLocStart(),
6717 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006718 }
6719 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006720 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006721 }
John McCallb268a282010-08-23 23:25:46 +00006722 Base = Result.get();
6723 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006724 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006725 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006726 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006727 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006728 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6729 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006730 return ExprError();
6731 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006732 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006733 }
Mike Stump11289f42009-09-09 15:08:12 +00006734
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006735 if (OpKind == tok::arrow &&
6736 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006737 BaseType = BaseType->getPointeeType();
6738 }
Mike Stump11289f42009-09-09 15:08:12 +00006739
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006740 // Objective-C properties allow "." access on Objective-C pointer types,
6741 // so adjust the base type to the object type itself.
6742 if (BaseType->isObjCObjectPointerType())
6743 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006744
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006745 // C++ [basic.lookup.classref]p2:
6746 // [...] If the type of the object expression is of pointer to scalar
6747 // type, the unqualified-id is looked up in the context of the complete
6748 // postfix-expression.
6749 //
6750 // This also indicates that we could be parsing a pseudo-destructor-name.
6751 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006752 // expressions or normal member (ivar or property) access expressions, and
6753 // it's legal for the type to be incomplete if this is a pseudo-destructor
6754 // call. We'll do more incomplete-type checks later in the lookup process,
6755 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006756 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006757 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006758 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006759 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006760 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006761 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006762 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006763 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006764 }
Mike Stump11289f42009-09-09 15:08:12 +00006765
Douglas Gregor3024f072012-04-16 07:05:22 +00006766 // The object type must be complete (or dependent), or
6767 // C++11 [expr.prim.general]p3:
6768 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006769 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006770 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006771 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006772 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006773 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006774 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006775
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006776 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006777 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006778 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006779 // type C (or of pointer to a class type C), the unqualified-id is looked
6780 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006781 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006782 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006783}
6784
Simon Pilgrim75c26882016-09-30 14:25:09 +00006785static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006786 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006787 if (Base->hasPlaceholderType()) {
6788 ExprResult result = S.CheckPlaceholderExpr(Base);
6789 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006790 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006791 }
6792 ObjectType = Base->getType();
6793
David Blaikie1d578782011-12-16 16:03:09 +00006794 // C++ [expr.pseudo]p2:
6795 // The left-hand side of the dot operator shall be of scalar type. The
6796 // left-hand side of the arrow operator shall be of pointer to scalar type.
6797 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006798 // Note that this is rather different from the normal handling for the
6799 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006800 if (OpKind == tok::arrow) {
6801 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6802 ObjectType = Ptr->getPointeeType();
6803 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006804 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006805 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6806 << ObjectType << true
6807 << FixItHint::CreateReplacement(OpLoc, ".");
6808 if (S.isSFINAEContext())
6809 return true;
6810
6811 OpKind = tok::period;
6812 }
6813 }
6814
6815 return false;
6816}
6817
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006818/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006819/// pointer objects.
6820static bool
6821canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6822 QualType DestructedType) {
6823 // If this is a record type, check if its destructor is callable.
6824 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6825 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6826 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6827 return false;
6828 }
6829
6830 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6831 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6832 DestructedType->isVectorType();
6833}
6834
John McCalldadc5752010-08-24 06:29:42 +00006835ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006836 SourceLocation OpLoc,
6837 tok::TokenKind OpKind,
6838 const CXXScopeSpec &SS,
6839 TypeSourceInfo *ScopeTypeInfo,
6840 SourceLocation CCLoc,
6841 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006842 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006843 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006844
Eli Friedman0ce4de42012-01-25 04:35:06 +00006845 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006846 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6847 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006848
Douglas Gregorc5c57342012-09-10 14:57:06 +00006849 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6850 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006851 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006852 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006853 else {
Nico Weber58829272012-01-23 05:50:57 +00006854 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6855 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006856 return ExprError();
6857 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006858 }
6859
6860 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006861 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006862 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006863 if (DestructedTypeInfo) {
6864 QualType DestructedType = DestructedTypeInfo->getType();
6865 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006866 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006867 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6868 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006869 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6870 // Foo *foo;
6871 // foo.~Foo();
6872 if (OpKind == tok::period && ObjectType->isPointerType() &&
6873 Context.hasSameUnqualifiedType(DestructedType,
6874 ObjectType->getPointeeType())) {
6875 auto Diagnostic =
6876 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6877 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006879 // Issue a fixit only when the destructor is valid.
6880 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6881 *this, DestructedType))
6882 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6883
6884 // Recover by setting the object type to the destructed type and the
6885 // operator to '->'.
6886 ObjectType = DestructedType;
6887 OpKind = tok::arrow;
6888 } else {
6889 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6890 << ObjectType << DestructedType << Base->getSourceRange()
6891 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6892
6893 // Recover by setting the destructed type to the object type.
6894 DestructedType = ObjectType;
6895 DestructedTypeInfo =
6896 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6897 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6898 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006899 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006900 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006901
John McCall31168b02011-06-15 23:02:42 +00006902 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6903 // Okay: just pretend that the user provided the correctly-qualified
6904 // type.
6905 } else {
6906 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6907 << ObjectType << DestructedType << Base->getSourceRange()
6908 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6909 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006910
John McCall31168b02011-06-15 23:02:42 +00006911 // Recover by setting the destructed type to the object type.
6912 DestructedType = ObjectType;
6913 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6914 DestructedTypeStart);
6915 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6916 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006917 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006919
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006920 // C++ [expr.pseudo]p2:
6921 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6922 // form
6923 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006924 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006925 //
6926 // shall designate the same scalar type.
6927 if (ScopeTypeInfo) {
6928 QualType ScopeType = ScopeTypeInfo->getType();
6929 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006930 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006931
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006932 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006933 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006934 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006935 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006936
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006937 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006938 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006939 }
6940 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006941
John McCallb268a282010-08-23 23:25:46 +00006942 Expr *Result
6943 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6944 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006945 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006946 ScopeTypeInfo,
6947 CCLoc,
6948 TildeLoc,
6949 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006950
David Majnemerced8bdf2015-02-25 17:36:15 +00006951 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006952}
6953
John McCalldadc5752010-08-24 06:29:42 +00006954ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006955 SourceLocation OpLoc,
6956 tok::TokenKind OpKind,
6957 CXXScopeSpec &SS,
6958 UnqualifiedId &FirstTypeName,
6959 SourceLocation CCLoc,
6960 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006961 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006962 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6963 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006964 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006965 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6966 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006967 "Invalid second type name in pseudo-destructor");
6968
Eli Friedman0ce4de42012-01-25 04:35:06 +00006969 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006970 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6971 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006972
6973 // Compute the object type that we should use for name lookup purposes. Only
6974 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006975 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006976 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006977 if (ObjectType->isRecordType())
6978 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006979 else if (ObjectType->isDependentType())
6980 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006982
6983 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006984 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006985 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006986 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006987 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00006988 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006990 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00006991 S, &SS, true, false, ObjectTypePtrForLookup,
6992 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006993 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006994 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6995 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006996 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006997 // couldn't find anything useful in scope. Just store the identifier and
6998 // it's location, and we'll perform (qualified) name lookup again at
6999 // template instantiation time.
7000 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7001 SecondTypeName.StartLocation);
7002 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007003 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007004 diag::err_pseudo_dtor_destructor_non_type)
7005 << SecondTypeName.Identifier << ObjectType;
7006 if (isSFINAEContext())
7007 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007008
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007009 // Recover by assuming we had the right type all along.
7010 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007011 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007012 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007013 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007014 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007015 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007016 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007017 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007018 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007019 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007020 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007021 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007022 TemplateId->TemplateNameLoc,
7023 TemplateId->LAngleLoc,
7024 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007025 TemplateId->RAngleLoc,
7026 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007027 if (T.isInvalid() || !T.get()) {
7028 // Recover by assuming we had the right type all along.
7029 DestructedType = ObjectType;
7030 } else
7031 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007032 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007033
7034 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007035 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007036 if (!DestructedType.isNull()) {
7037 if (!DestructedTypeInfo)
7038 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007039 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007040 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007042
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007043 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007044 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007045 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007046 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007047 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007048 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007049 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007050 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007051 S, &SS, true, false, ObjectTypePtrForLookup,
7052 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007053 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007054 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007055 diag::err_pseudo_dtor_destructor_non_type)
7056 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007057
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007058 if (isSFINAEContext())
7059 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007060
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007061 // Just drop this type. It's unnecessary anyway.
7062 ScopeType = QualType();
7063 } else
7064 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007065 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007066 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007067 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007068 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007069 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007070 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007071 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007072 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007073 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007074 TemplateId->TemplateNameLoc,
7075 TemplateId->LAngleLoc,
7076 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007077 TemplateId->RAngleLoc,
7078 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007079 if (T.isInvalid() || !T.get()) {
7080 // Recover by dropping this type.
7081 ScopeType = QualType();
7082 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007083 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007084 }
7085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086
Douglas Gregor90ad9222010-02-24 23:02:30 +00007087 if (!ScopeType.isNull() && !ScopeTypeInfo)
7088 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7089 FirstTypeName.StartLocation);
7090
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007091
John McCallb268a282010-08-23 23:25:46 +00007092 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007093 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007094 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007095}
7096
David Blaikie1d578782011-12-16 16:03:09 +00007097ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7098 SourceLocation OpLoc,
7099 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007100 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007101 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007102 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007103 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7104 return ExprError();
7105
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007106 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7107 false);
David Blaikie1d578782011-12-16 16:03:09 +00007108
7109 TypeLocBuilder TLB;
7110 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7111 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7112 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7113 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7114
7115 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007116 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007117 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007118}
7119
John Wiegley01296292011-04-08 18:41:53 +00007120ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007121 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007122 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00007123 if (Method->getParent()->isLambda() &&
7124 Method->getConversionType()->isBlockPointerType()) {
7125 // This is a lambda coversion to block pointer; check if the argument
7126 // is a LambdaExpr.
7127 Expr *SubE = E;
7128 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7129 if (CE && CE->getCastKind() == CK_NoOp)
7130 SubE = CE->getSubExpr();
7131 SubE = SubE->IgnoreParens();
7132 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7133 SubE = BE->getSubExpr();
7134 if (isa<LambdaExpr>(SubE)) {
7135 // For the conversion to block pointer on a lambda expression, we
7136 // construct a special BlockLiteral instead; this doesn't really make
7137 // a difference in ARC, but outside of ARC the resulting block literal
7138 // follows the normal lifetime rules for block literals instead of being
7139 // autoreleased.
7140 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007141 PushExpressionEvaluationContext(
7142 ExpressionEvaluationContext::PotentiallyEvaluated);
Eli Friedman98b01ed2012-03-01 04:01:32 +00007143 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
7144 E->getExprLoc(),
7145 Method, E);
Akira Hatanakac482acd2016-05-04 18:07:20 +00007146 PopExpressionEvaluationContext();
7147
Eli Friedman98b01ed2012-03-01 04:01:32 +00007148 if (Exp.isInvalid())
7149 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
7150 return Exp;
7151 }
7152 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007153
Craig Topperc3ec1492014-05-26 06:22:03 +00007154 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00007155 FoundDecl, Method);
7156 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00007157 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00007158
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00007159 MemberExpr *ME = new (Context) MemberExpr(
7160 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7161 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007162 if (HadMultipleCandidates)
7163 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00007164 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007165
Alp Toker314cc812014-01-25 16:55:45 +00007166 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007167 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7168 ResultType = ResultType.getNonLValueExprType(Context);
7169
Douglas Gregor27381f32009-11-23 12:27:39 +00007170 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00007171 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00007172 Exp.get()->getLocEnd());
George Burgess IVce6284b2017-01-28 02:19:40 +00007173
7174 if (CheckFunctionCall(Method, CE,
7175 Method->getType()->castAs<FunctionProtoType>()))
7176 return ExprError();
7177
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007178 return CE;
7179}
7180
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007181ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7182 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007183 // If the operand is an unresolved lookup expression, the expression is ill-
7184 // formed per [over.over]p1, because overloaded function names cannot be used
7185 // without arguments except in explicit contexts.
7186 ExprResult R = CheckPlaceholderExpr(Operand);
7187 if (R.isInvalid())
7188 return R;
7189
7190 // The operand may have been modified when checking the placeholder type.
7191 Operand = R.get();
7192
Richard Smith51ec0cf2017-02-21 01:17:38 +00007193 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007194 // The expression operand for noexcept is in an unevaluated expression
7195 // context, so side effects could result in unintended consequences.
7196 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7197 }
7198
Richard Smithf623c962012-04-17 00:58:00 +00007199 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007200 return new (Context)
7201 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007202}
7203
7204ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7205 Expr *Operand, SourceLocation RParen) {
7206 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007207}
7208
Eli Friedmanf798f652012-05-24 22:04:19 +00007209static bool IsSpecialDiscardedValue(Expr *E) {
7210 // In C++11, discarded-value expressions of a certain form are special,
7211 // according to [expr]p10:
7212 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7213 // expression is an lvalue of volatile-qualified type and it has
7214 // one of the following forms:
7215 E = E->IgnoreParens();
7216
Eli Friedmanc49c2262012-05-24 22:36:31 +00007217 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007218 if (isa<DeclRefExpr>(E))
7219 return true;
7220
Eli Friedmanc49c2262012-05-24 22:36:31 +00007221 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007222 if (isa<ArraySubscriptExpr>(E))
7223 return true;
7224
Eli Friedmanc49c2262012-05-24 22:36:31 +00007225 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007226 if (isa<MemberExpr>(E))
7227 return true;
7228
Eli Friedmanc49c2262012-05-24 22:36:31 +00007229 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007230 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7231 if (UO->getOpcode() == UO_Deref)
7232 return true;
7233
7234 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007235 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007236 if (BO->isPtrMemOp())
7237 return true;
7238
Eli Friedmanc49c2262012-05-24 22:36:31 +00007239 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007240 if (BO->getOpcode() == BO_Comma)
7241 return IsSpecialDiscardedValue(BO->getRHS());
7242 }
7243
Eli Friedmanc49c2262012-05-24 22:36:31 +00007244 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007245 // operands are one of the above, or
7246 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7247 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7248 IsSpecialDiscardedValue(CO->getFalseExpr());
7249 // The related edge case of "*x ?: *x".
7250 if (BinaryConditionalOperator *BCO =
7251 dyn_cast<BinaryConditionalOperator>(E)) {
7252 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7253 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7254 IsSpecialDiscardedValue(BCO->getFalseExpr());
7255 }
7256
7257 // Objective-C++ extensions to the rule.
7258 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7259 return true;
7260
7261 return false;
7262}
7263
John McCall34376a62010-12-04 03:47:34 +00007264/// Perform the conversions required for an expression used in a
7265/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007266ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007267 if (E->hasPlaceholderType()) {
7268 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007269 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007270 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007271 }
7272
John McCallfee942d2010-12-02 02:07:15 +00007273 // C99 6.3.2.1:
7274 // [Except in specific positions,] an lvalue that does not have
7275 // array type is converted to the value stored in the
7276 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007277 if (E->isRValue()) {
7278 // In C, function designators (i.e. expressions of function type)
7279 // are r-values, but we still want to do function-to-pointer decay
7280 // on them. This is both technically correct and convenient for
7281 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007282 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007283 return DefaultFunctionArrayConversion(E);
7284
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007285 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007286 }
John McCallfee942d2010-12-02 02:07:15 +00007287
Eli Friedmanf798f652012-05-24 22:04:19 +00007288 if (getLangOpts().CPlusPlus) {
7289 // The C++11 standard defines the notion of a discarded-value expression;
7290 // normally, we don't need to do anything to handle it, but if it is a
7291 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7292 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007293 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007294 E->getType().isVolatileQualified() &&
7295 IsSpecialDiscardedValue(E)) {
7296 ExprResult Res = DefaultLvalueConversion(E);
7297 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007298 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007299 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007300 }
Richard Smith122f88d2016-12-06 23:52:28 +00007301
7302 // C++1z:
7303 // If the expression is a prvalue after this optional conversion, the
7304 // temporary materialization conversion is applied.
7305 //
7306 // We skip this step: IR generation is able to synthesize the storage for
7307 // itself in the aggregate case, and adding the extra node to the AST is
7308 // just clutter.
7309 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7310 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007311 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007312 }
John McCall34376a62010-12-04 03:47:34 +00007313
7314 // GCC seems to also exclude expressions of incomplete enum type.
7315 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7316 if (!T->getDecl()->isComplete()) {
7317 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007318 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007319 return E;
John McCall34376a62010-12-04 03:47:34 +00007320 }
7321 }
7322
John Wiegley01296292011-04-08 18:41:53 +00007323 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7324 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007325 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007326 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007327
John McCallca61b652010-12-04 12:29:11 +00007328 if (!E->getType()->isVoidType())
7329 RequireCompleteType(E->getExprLoc(), E->getType(),
7330 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007331 return E;
John McCall34376a62010-12-04 03:47:34 +00007332}
7333
Faisal Valia17d19f2013-11-07 05:17:06 +00007334// If we can unambiguously determine whether Var can never be used
7335// in a constant expression, return true.
7336// - if the variable and its initializer are non-dependent, then
7337// we can unambiguously check if the variable is a constant expression.
7338// - if the initializer is not value dependent - we can determine whether
7339// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007340// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007341// never be a constant expression.
7342// - FXIME: if the initializer is dependent, we can still do some analysis and
7343// identify certain cases unambiguously as non-const by using a Visitor:
7344// - such as those that involve odr-use of a ParmVarDecl, involve a new
7345// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007346static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007347 ASTContext &Context) {
7348 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007349 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007350
7351 // If there is no initializer - this can not be a constant expression.
7352 if (!Var->getAnyInitializer(DefVD)) return true;
7353 assert(DefVD);
7354 if (DefVD->isWeak()) return false;
7355 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007356
Faisal Valia17d19f2013-11-07 05:17:06 +00007357 Expr *Init = cast<Expr>(Eval->Value);
7358
7359 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007360 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7361 // of value-dependent expressions, and use it here to determine whether the
7362 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007363 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007364 }
7365
Simon Pilgrim75c26882016-09-30 14:25:09 +00007366 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007367}
7368
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007369/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007370/// that must be captured by any of its enclosing lambdas that are ready to
7371/// capture. If there is a lambda that can capture a nested
7372/// potential-capture, go ahead and do so. Also, check to see if any
7373/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007374/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007375
Faisal Valiab3d6462013-12-07 20:22:44 +00007376static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7377 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7378
Simon Pilgrim75c26882016-09-30 14:25:09 +00007379 assert(!S.isUnevaluatedContext());
7380 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007381#ifndef NDEBUG
7382 DeclContext *DC = S.CurContext;
7383 while (DC && isa<CapturedDecl>(DC))
7384 DC = DC->getParent();
7385 assert(
7386 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007387 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007388#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007389
7390 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7391
Faisal Valiab3d6462013-12-07 20:22:44 +00007392 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007393 // lambda (within a generic outer lambda), must be captured by an
7394 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007395 const unsigned NumPotentialCaptures =
7396 CurrentLSI->getNumPotentialVariableCaptures();
7397 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007398 Expr *VarExpr = nullptr;
7399 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007400 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007401 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007402 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007403 // need to check enclosing lambda's for speculative captures.
7404 // For e.g.:
7405 // Even though 'x' is not odr-used, it should be captured.
7406 // int test() {
7407 // const int x = 10;
7408 // auto L = [=](auto a) {
7409 // (void) +x + a;
7410 // };
7411 // }
7412 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007413 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007414 continue;
7415
7416 // If we have a capture-capable lambda for the variable, go ahead and
7417 // capture the variable in that lambda (and all its enclosing lambdas).
7418 if (const Optional<unsigned> Index =
7419 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007420 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007421 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7422 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7423 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007424 }
7425 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007426 VariableCanNeverBeAConstantExpression(Var, S.Context);
7427 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7428 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007429 // can not be used in a constant expression - which means
7430 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007431 // capture violation early, if the variable is un-captureable.
7432 // This is purely for diagnosing errors early. Otherwise, this
7433 // error would get diagnosed when the lambda becomes capture ready.
7434 QualType CaptureType, DeclRefType;
7435 SourceLocation ExprLoc = VarExpr->getExprLoc();
7436 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007437 /*EllipsisLoc*/ SourceLocation(),
7438 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007439 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007440 // We will never be able to capture this variable, and we need
7441 // to be able to in any and all instantiations, so diagnose it.
7442 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007443 /*EllipsisLoc*/ SourceLocation(),
7444 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007445 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007446 }
7447 }
7448 }
7449
Faisal Valiab3d6462013-12-07 20:22:44 +00007450 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007451 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007452 // If we have a capture-capable lambda for 'this', go ahead and capture
7453 // 'this' in that lambda (and all its enclosing lambdas).
7454 if (const Optional<unsigned> Index =
7455 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007456 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007457 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7458 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7459 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7460 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007461 }
7462 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007463
7464 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007465 CurrentLSI->clearPotentialCaptures();
7466}
7467
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007468static ExprResult attemptRecovery(Sema &SemaRef,
7469 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007470 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007471 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7472 Consumer.getLookupResult().getLookupKind());
7473 const CXXScopeSpec *SS = Consumer.getSS();
7474 CXXScopeSpec NewSS;
7475
7476 // Use an approprate CXXScopeSpec for building the expr.
7477 if (auto *NNS = TC.getCorrectionSpecifier())
7478 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7479 else if (SS && !TC.WillReplaceSpecifier())
7480 NewSS = *SS;
7481
Richard Smithde6d6c42015-12-29 19:43:10 +00007482 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007483 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007484 R.addDecl(ND);
7485 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007486 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007487 CXXRecordDecl *Record = nullptr;
7488 if (auto *NNS = TC.getCorrectionSpecifier())
7489 Record = NNS->getAsType()->getAsCXXRecordDecl();
7490 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007491 Record =
7492 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7493 if (Record)
7494 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007495
7496 // Detect and handle the case where the decl might be an implicit
7497 // member.
7498 bool MightBeImplicitMember;
7499 if (!Consumer.isAddressOfOperand())
7500 MightBeImplicitMember = true;
7501 else if (!NewSS.isEmpty())
7502 MightBeImplicitMember = false;
7503 else if (R.isOverloadedResult())
7504 MightBeImplicitMember = false;
7505 else if (R.isUnresolvableResult())
7506 MightBeImplicitMember = true;
7507 else
7508 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7509 isa<IndirectFieldDecl>(ND) ||
7510 isa<MSPropertyDecl>(ND);
7511
7512 if (MightBeImplicitMember)
7513 return SemaRef.BuildPossibleImplicitMemberExpr(
7514 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007515 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007516 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7517 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7518 Ivar->getIdentifier());
7519 }
7520 }
7521
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007522 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7523 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007524}
7525
Kaelyn Takata6c759512014-10-27 18:07:37 +00007526namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007527class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7528 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7529
7530public:
7531 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7532 : TypoExprs(TypoExprs) {}
7533 bool VisitTypoExpr(TypoExpr *TE) {
7534 TypoExprs.insert(TE);
7535 return true;
7536 }
7537};
7538
Kaelyn Takata6c759512014-10-27 18:07:37 +00007539class TransformTypos : public TreeTransform<TransformTypos> {
7540 typedef TreeTransform<TransformTypos> BaseTransform;
7541
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007542 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7543 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007544 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007545 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007546 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007547 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007548
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007549 /// Emit diagnostics for all of the TypoExprs encountered.
Kaelyn Takata6c759512014-10-27 18:07:37 +00007550 /// If the TypoExprs were successfully corrected, then the diagnostics should
7551 /// suggest the corrections. Otherwise the diagnostics will not suggest
7552 /// anything (having been passed an empty TypoCorrection).
7553 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007554 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007555 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007556 if (State.DiagHandler) {
7557 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7558 ExprResult Replacement = TransformCache[TE];
7559
7560 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7561 // TypoCorrection, replacing the existing decls. This ensures the right
7562 // NamedDecl is used in diagnostics e.g. in the case where overload
7563 // resolution was used to select one from several possible decls that
7564 // had been stored in the TypoCorrection.
7565 if (auto *ND = getDeclFromExpr(
7566 Replacement.isInvalid() ? nullptr : Replacement.get()))
7567 TC.setCorrectionDecl(ND);
7568
7569 State.DiagHandler(TC);
7570 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007571 SemaRef.clearDelayedTypo(TE);
7572 }
7573 }
7574
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007575 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007576 /// given combination of the other TypoExprs, retry those corrections against
7577 /// the next combination of substitutions for the other TypoExprs by advancing
7578 /// to the next potential correction of the second TypoExpr. For the second
7579 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7580 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7581 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7582 /// TransformCache). Returns true if there is still any untried combinations
7583 /// of corrections.
7584 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7585 for (auto TE : TypoExprs) {
7586 auto &State = SemaRef.getTypoExprState(TE);
7587 TransformCache.erase(TE);
7588 if (!State.Consumer->finished())
7589 return true;
7590 State.Consumer->resetCorrectionStream();
7591 }
7592 return false;
7593 }
7594
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007595 NamedDecl *getDeclFromExpr(Expr *E) {
7596 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7597 E = OverloadResolution[OE];
7598
7599 if (!E)
7600 return nullptr;
7601 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007602 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007603 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007604 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007605 // FIXME: Add any other expr types that could be be seen by the delayed typo
7606 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007607 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007608 return nullptr;
7609 }
7610
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007611 ExprResult TryTransform(Expr *E) {
7612 Sema::SFINAETrap Trap(SemaRef);
7613 ExprResult Res = TransformExpr(E);
7614 if (Trap.hasErrorOccurred() || Res.isInvalid())
7615 return ExprError();
7616
7617 return ExprFilter(Res.get());
7618 }
7619
Kaelyn Takata6c759512014-10-27 18:07:37 +00007620public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007621 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7622 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007623
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007624 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7625 MultiExprArg Args,
7626 SourceLocation RParenLoc,
7627 Expr *ExecConfig = nullptr) {
7628 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7629 RParenLoc, ExecConfig);
7630 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007631 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007632 Expr *ResultCall = Result.get();
7633 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7634 ResultCall = BE->getSubExpr();
7635 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7636 OverloadResolution[OE] = CE->getCallee();
7637 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007638 }
7639 return Result;
7640 }
7641
Kaelyn Takata6c759512014-10-27 18:07:37 +00007642 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7643
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007644 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7645
Kaelyn Takata6c759512014-10-27 18:07:37 +00007646 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007647 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007648 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007649 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007650
Kaelyn Takata6c759512014-10-27 18:07:37 +00007651 // Exit if either the transform was valid or if there were no TypoExprs
7652 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007653 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007654 !CheckAndAdvanceTypoExprCorrectionStreams())
7655 break;
7656 }
7657
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007658 // Ensure none of the TypoExprs have multiple typo correction candidates
7659 // with the same edit length that pass all the checks and filters.
7660 // TODO: Properly handle various permutations of possible corrections when
7661 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007662 // Also, disable typo correction while attempting the transform when
7663 // handling potentially ambiguous typo corrections as any new TypoExprs will
7664 // have been introduced by the application of one of the correction
7665 // candidates and add little to no value if corrected.
7666 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007667 while (!AmbiguousTypoExprs.empty()) {
7668 auto TE = AmbiguousTypoExprs.back();
7669 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007670 auto &State = SemaRef.getTypoExprState(TE);
7671 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007672 TransformCache.erase(TE);
7673 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007674 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007675 TransformCache.erase(TE);
7676 Res = ExprError();
7677 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007678 }
7679 AmbiguousTypoExprs.remove(TE);
7680 State.Consumer->restoreSavedPosition();
7681 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007682 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007683 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007684
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007685 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007686 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007687 FindTypoExprs(TypoExprs).TraverseStmt(E);
7688
Kaelyn Takata6c759512014-10-27 18:07:37 +00007689 EmitAllDiagnostics();
7690
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007691 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007692 }
7693
7694 ExprResult TransformTypoExpr(TypoExpr *E) {
7695 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7696 // cached transformation result if there is one and the TypoExpr isn't the
7697 // first one that was encountered.
7698 auto &CacheEntry = TransformCache[E];
7699 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7700 return CacheEntry;
7701 }
7702
7703 auto &State = SemaRef.getTypoExprState(E);
7704 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7705
7706 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7707 // typo correction and return it.
7708 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007709 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007710 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007711 // FIXME: If we would typo-correct to an invalid declaration, it's
7712 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007713 ExprResult NE = State.RecoveryHandler ?
7714 State.RecoveryHandler(SemaRef, E, TC) :
7715 attemptRecovery(SemaRef, *State.Consumer, TC);
7716 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007717 // Check whether there may be a second viable correction with the same
7718 // edit distance; if so, remember this TypoExpr may have an ambiguous
7719 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007720 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007721 if ((Next = State.Consumer->peekNextCorrection()) &&
7722 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7723 AmbiguousTypoExprs.insert(E);
7724 } else {
7725 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007726 }
7727 assert(!NE.isUnset() &&
7728 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007729 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007730 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007731 }
7732 return CacheEntry = ExprError();
7733 }
7734};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007735}
Faisal Valia17d19f2013-11-07 05:17:06 +00007736
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007737ExprResult
7738Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7739 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007740 // If the current evaluation context indicates there are uncorrected typos
7741 // and the current expression isn't guaranteed to not have typos, try to
7742 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007743 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007744 (E->isTypeDependent() || E->isValueDependent() ||
7745 E->isInstantiationDependent())) {
7746 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007747 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007748 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007749 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007750 ExprEvalContexts.back().NumTypos -= TyposResolved;
7751 return Result;
7752 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007753 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007754 }
7755 return E;
7756}
7757
Richard Smith945f8d32013-01-14 22:39:08 +00007758ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007759 bool DiscardedValue,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007760 bool IsConstexpr,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007761 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007762 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007763
7764 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007765 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007766
7767 // If we are an init-expression in a lambdas init-capture, we should not
7768 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007769 // containing full-expression is done).
7770 // template<class ... Ts> void test(Ts ... t) {
7771 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7772 // return a;
7773 // }() ...);
7774 // }
7775 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7776 // when we parse the lambda introducer, and teach capturing (but not
7777 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7778 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7779 // lambda where we've entered the introducer but not the body, or represent a
7780 // lambda where we've entered the body, depending on where the
7781 // parser/instantiation has got to).
Simon Pilgrim75c26882016-09-30 14:25:09 +00007782 if (!IsLambdaInitCaptureInitializer &&
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00007783 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007784 return ExprError();
7785
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007786 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00007787 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00007788 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007789 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00007790 if (FullExpr.isInvalid())
7791 return ExprError();
7792 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00007793
Richard Smith945f8d32013-01-14 22:39:08 +00007794 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007795 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007796 if (FullExpr.isInvalid())
7797 return ExprError();
7798
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007799 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007800 if (FullExpr.isInvalid())
7801 return ExprError();
7802 }
John Wiegley01296292011-04-08 18:41:53 +00007803
Kaelyn Takata49d84322014-11-11 23:26:56 +00007804 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7805 if (FullExpr.isInvalid())
7806 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007807
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007808 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007809
Simon Pilgrim75c26882016-09-30 14:25:09 +00007810 // At the end of this full expression (which could be a deeply nested
7811 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007812 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007813 // Consider the following code:
7814 // void f(int, int);
7815 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007816 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007817 // const int x = 10, y = 20;
7818 // auto L = [=](auto a) {
7819 // auto M = [=](auto b) {
7820 // f(x, b); <-- requires x to be captured by L and M
7821 // f(y, a); <-- requires y to be captured by L, but not all Ms
7822 // };
7823 // };
7824 // }
7825
Simon Pilgrim75c26882016-09-30 14:25:09 +00007826 // FIXME: Also consider what happens for something like this that involves
7827 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007828 // void f() {
7829 // const int n = 0;
7830 // auto L = [&](auto a) {
7831 // +n + ({ 0; a; });
7832 // };
7833 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007834 //
7835 // Here, we see +n, and then the full-expression 0; ends, so we don't
7836 // capture n (and instead remove it from our list of potential captures),
7837 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007838 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007839
Alexey Bataev31939e32016-11-11 12:36:20 +00007840 LambdaScopeInfo *const CurrentLSI =
7841 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007842 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007843 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007844 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007845 // By ensuring we are in the context of a lambda's call operator
7846 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007847 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007848 // PR, a proper fix would entail :
7849 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007850 // - Add to Sema an integer holding the smallest (outermost) scope
7851 // index that we are *lexically* within, and save/restore/set to
7852 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007853 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007854 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007855 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007856 DeclContext *DC = CurContext;
7857 while (DC && isa<CapturedDecl>(DC))
7858 DC = DC->getParent();
7859 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007860 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007861 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007862 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7863 *this);
John McCall5d413782010-12-06 08:20:24 +00007864 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007865}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007866
7867StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7868 if (!FullStmt) return StmtError();
7869
John McCall5d413782010-12-06 08:20:24 +00007870 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007871}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007872
Simon Pilgrim75c26882016-09-30 14:25:09 +00007873Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007874Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7875 CXXScopeSpec &SS,
7876 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007877 DeclarationName TargetName = TargetNameInfo.getName();
7878 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007879 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007880
Douglas Gregor43edb322011-10-24 22:31:10 +00007881 // If the name itself is dependent, then the result is dependent.
7882 if (TargetName.isDependentName())
7883 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007884
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007885 // Do the redeclaration lookup in the current scope.
7886 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7887 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007888 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007889 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007890
Douglas Gregor43edb322011-10-24 22:31:10 +00007891 switch (R.getResultKind()) {
7892 case LookupResult::Found:
7893 case LookupResult::FoundOverloaded:
7894 case LookupResult::FoundUnresolvedValue:
7895 case LookupResult::Ambiguous:
7896 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007897
Douglas Gregor43edb322011-10-24 22:31:10 +00007898 case LookupResult::NotFound:
7899 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007900
Douglas Gregor43edb322011-10-24 22:31:10 +00007901 case LookupResult::NotFoundInCurrentInstantiation:
7902 return IER_Dependent;
7903 }
David Blaikie8a40f702012-01-17 06:56:22 +00007904
7905 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007906}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007907
Simon Pilgrim75c26882016-09-30 14:25:09 +00007908Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007909Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7910 bool IsIfExists, CXXScopeSpec &SS,
7911 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007912 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007913
Richard Smith151c4562016-12-20 21:35:28 +00007914 // Check for an unexpanded parameter pack.
7915 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7916 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7917 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007918 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007919
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007920 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7921}