blob: a25e86b95c37c23171efd31094cf6f9cae437142 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner29375652006-12-04 18:06:35 +00006//
7//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00008///
9/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000010/// Implements semantic analysis for C++ expressions.
James Dennett84053fb2012-06-22 05:14:59 +000011///
12//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000013
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000015#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000017#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000018#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000022#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000023#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000024#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000025#include "clang/AST/TypeLoc.h"
Akira Hatanaka3e40c302017-07-19 17:17:50 +000026#include "clang/Basic/AlignedAllocation.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000036#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000038#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000041using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000043
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Handle the result of the special case name lookup for inheriting
Richard Smith7447af42013-03-26 01:15:19 +000045/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000070 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000071 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
Richard Smith715ee072018-06-20 21:58:20 +000082ParsedType Sema::getConstructorName(IdentifierInfo &II,
83 SourceLocation NameLoc,
Richard Smith69bc9aa2018-06-22 19:50:19 +000084 Scope *S, CXXScopeSpec &SS,
85 bool EnteringContext) {
Richard Smith715ee072018-06-20 21:58:20 +000086 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
87 assert(CurClass && &II == CurClass->getIdentifier() &&
88 "not a constructor name");
89
Richard Smith69bc9aa2018-06-22 19:50:19 +000090 // When naming a constructor as a member of a dependent context (eg, in a
91 // friend declaration or an inherited constructor declaration), form an
92 // unresolved "typename" type.
Gauthier Harnischef629c72019-06-14 08:25:52 +000093 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
Richard Smith69bc9aa2018-06-22 19:50:19 +000094 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
95 return ParsedType::make(T);
96 }
97
Richard Smith715ee072018-06-20 21:58:20 +000098 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
99 return ParsedType();
100
101 // Find the injected-class-name declaration. Note that we make no attempt to
102 // diagnose cases where the injected-class-name is shadowed: the only
103 // declaration that can validly shadow the injected-class-name is a
104 // non-static data member, and if the class contains both a non-static data
105 // member and a constructor then it is ill-formed (we check that in
106 // CheckCompletedCXXClass).
107 CXXRecordDecl *InjectedClassName = nullptr;
108 for (NamedDecl *ND : CurClass->lookup(&II)) {
109 auto *RD = dyn_cast<CXXRecordDecl>(ND);
110 if (RD && RD->isInjectedClassName()) {
111 InjectedClassName = RD;
112 break;
113 }
114 }
Richard Smith2e34bbd2018-08-08 00:42:42 +0000115 if (!InjectedClassName) {
116 if (!CurClass->isInvalidDecl()) {
117 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
118 // properly. Work around it here for now.
119 Diag(SS.getLastQualifierNameLoc(),
120 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
121 }
Ilya Biryukova2d58252018-07-04 08:50:12 +0000122 return ParsedType();
Richard Smith2e34bbd2018-08-08 00:42:42 +0000123 }
Richard Smith715ee072018-06-20 21:58:20 +0000124
125 QualType T = Context.getTypeDeclType(InjectedClassName);
126 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
127 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
128
129 return ParsedType::make(T);
130}
131
John McCallba7bf592010-08-24 05:47:05 +0000132ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000133 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +0000134 SourceLocation NameLoc,
135 Scope *S, CXXScopeSpec &SS,
136 ParsedType ObjectTypePtr,
137 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000138 // Determine where to perform name lookup.
139
140 // FIXME: This area of the standard is very messy, and the current
141 // wording is rather unclear about which scopes we search for the
142 // destructor name; see core issues 399 and 555. Issue 399 in
143 // particular shows where the current description of destructor name
144 // lookup is completely out of line with existing practice, e.g.,
145 // this appears to be ill-formed:
146 //
147 // namespace N {
148 // template <typename T> struct S {
149 // ~S();
150 // };
151 // }
152 //
153 // void f(N::S<int>* s) {
154 // s->N::S<int>::~S();
155 // }
156 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000157 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000158 // For this reason, we're currently only doing the C++03 version of this
159 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000161 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000162 bool isDependent = false;
163 bool LookInScope = false;
164
Richard Smith64e033f2015-01-15 00:48:52 +0000165 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000166 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000167
Douglas Gregorfe17d252010-02-16 19:09:40 +0000168 // If we have an object type, it's because we are in a
169 // pseudo-destructor-expression or a member access expression, and
170 // we know what type we're looking for.
171 if (ObjectTypePtr)
172 SearchType = GetTypeFromParser(ObjectTypePtr);
173
174 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000175 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176
Douglas Gregor46841e12010-02-23 00:15:22 +0000177 bool AlreadySearched = false;
178 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000179 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000180 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000181 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000182 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000183 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000184 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000185 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000186 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000187 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000188 // Here, we determine whether the code below is permitted to look at the
189 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000190 DeclContext *DC = computeDeclContext(SS, EnteringContext);
191 if (DC && DC->isFileContext()) {
192 AlreadySearched = true;
193 LookupCtx = DC;
194 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000195 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000196 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000197 LookInScope = true;
198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000199
Sebastian Redla771d222010-07-07 23:17:38 +0000200 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000201 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000202 if (AlreadySearched) {
203 // Nothing left to do.
204 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
205 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000206 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000207 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
208 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000209 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000210 LookupCtx = computeDeclContext(SearchType);
211 isDependent = SearchType->isDependentType();
212 } else {
213 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000214 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000215 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000216 } else if (ObjectTypePtr) {
217 // C++ [basic.lookup.classref]p3:
218 // If the unqualified-id is ~type-name, the type-name is looked up
219 // in the context of the entire postfix-expression. If the type T
220 // of the object expression is of a class type C, the type-name is
221 // also looked up in the scope of class C. At least one of the
222 // lookups shall find a name that refers to (possibly
223 // cv-qualified) T.
224 LookupCtx = computeDeclContext(SearchType);
225 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000226 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000227 "Caller should have completed object type");
228
229 LookInScope = true;
230 } else {
231 // Perform lookup into the current scope (only).
232 LookInScope = true;
233 }
234
Craig Topperc3ec1492014-05-26 06:22:03 +0000235 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000236 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
237 for (unsigned Step = 0; Step != 2; ++Step) {
238 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000239 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000240 // we're allowed to look there).
241 Found.clear();
John McCallcb731542017-06-11 20:33:00 +0000242 if (Step == 0 && LookupCtx) {
243 if (RequireCompleteDeclContext(SS, LookupCtx))
244 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000245 LookupQualifiedName(Found, LookupCtx);
John McCallcb731542017-06-11 20:33:00 +0000246 } else if (Step == 1 && LookInScope && S) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000247 LookupName(Found, S);
John McCallcb731542017-06-11 20:33:00 +0000248 } else {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000249 continue;
John McCallcb731542017-06-11 20:33:00 +0000250 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251
252 // FIXME: Should we be suppressing ambiguities here?
253 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000254 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000255
256 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
257 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000258 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000259
260 if (SearchType.isNull() || SearchType->isDependentType() ||
261 Context.hasSameUnqualifiedType(T, SearchType)) {
262 // We found our type!
263
Richard Smithc278c002014-01-22 00:30:17 +0000264 return CreateParsedType(T,
265 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000266 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000267
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000268 if (!SearchType.isNull())
269 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000270 }
271
272 // If the name that we found is a class template name, and it is
273 // the same name as the template name in the last part of the
274 // nested-name-specifier (if present) or the object type, then
275 // this is the destructor for that class.
276 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000277 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000278 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
279 QualType MemberOfType;
280 if (SS.isSet()) {
281 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
282 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000283 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
284 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285 }
286 }
287 if (MemberOfType.isNull())
288 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000289
Douglas Gregorfe17d252010-02-16 19:09:40 +0000290 if (MemberOfType.isNull())
291 continue;
292
293 // We're referring into a class template specialization. If the
294 // class template we found is the same as the template being
295 // specialized, we found what we are looking for.
296 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
297 if (ClassTemplateSpecializationDecl *Spec
298 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
299 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
300 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000301 return CreateParsedType(
302 MemberOfType,
303 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000304 }
305
306 continue;
307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000308
Douglas Gregorfe17d252010-02-16 19:09:40 +0000309 // We're referring to an unresolved class template
310 // specialization. Determine whether we class template we found
311 // is the same as the template being specialized or, if we don't
312 // know which template is being specialized, that it at least
313 // has the same name.
314 if (const TemplateSpecializationType *SpecType
315 = MemberOfType->getAs<TemplateSpecializationType>()) {
316 TemplateName SpecName = SpecType->getTemplateName();
317
318 // The class template we found is the same template being
319 // specialized.
320 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
321 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000322 return CreateParsedType(
323 MemberOfType,
324 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000325
326 continue;
327 }
328
329 // The class template we found has the same name as the
330 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000331 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000332 = SpecName.getAsDependentTemplateName()) {
333 if (DepTemplate->isIdentifier() &&
334 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000335 return CreateParsedType(
336 MemberOfType,
337 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000338
339 continue;
340 }
341 }
342 }
343 }
344
345 if (isDependent) {
346 // We didn't find our type, but that's okay: it's dependent
347 // anyway.
Simon Pilgrim75c26882016-09-30 14:25:09 +0000348
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000349 // FIXME: What if we have no nested-name-specifier?
350 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
351 SS.getWithLocInContext(Context),
352 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000353 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000354 }
355
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000356 if (NonMatchingTypeDecl) {
357 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
358 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
359 << T << SearchType;
360 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
361 << T;
362 } else if (ObjectTypePtr)
363 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000364 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000365 else {
366 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
367 diag::err_destructor_class_name);
368 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000369 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000370 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
371 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
372 Class->getNameAsString());
373 }
374 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000375
David Blaikieefdccaa2016-01-15 23:43:34 +0000376 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000377}
378
Richard Smithef2cd8f2017-02-08 20:39:08 +0000379ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
380 ParsedType ObjectType) {
381 if (DS.getTypeSpecType() == DeclSpec::TST_error)
382 return nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +0000383
Richard Smithef2cd8f2017-02-08 20:39:08 +0000384 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
385 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
386 return nullptr;
387 }
388
389 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
390 "unexpected type in getDestructorType");
391 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
392
393 // If we know the type of the object, check that the correct destructor
394 // type was named now; we can give better diagnostics this way.
395 QualType SearchType = GetTypeFromParser(ObjectType);
396 if (!SearchType.isNull() && !SearchType->isDependentType() &&
397 !Context.hasSameUnqualifiedType(T, SearchType)) {
David Blaikieecd8a942011-12-08 16:13:53 +0000398 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
399 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000400 return nullptr;
Richard Smithef2cd8f2017-02-08 20:39:08 +0000401 }
402
403 return ParsedType::make(T);
David Blaikieecd8a942011-12-08 16:13:53 +0000404}
405
Richard Smithd091dc12013-12-05 00:58:33 +0000406bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
407 const UnqualifiedId &Name) {
Faisal Vali2ab8c152017-12-30 04:15:27 +0000408 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
Richard Smithd091dc12013-12-05 00:58:33 +0000409
410 if (!SS.isValid())
411 return false;
412
413 switch (SS.getScopeRep()->getKind()) {
414 case NestedNameSpecifier::Identifier:
415 case NestedNameSpecifier::TypeSpec:
416 case NestedNameSpecifier::TypeSpecWithTemplate:
417 // Per C++11 [over.literal]p2, literal operators can only be declared at
418 // namespace scope. Therefore, this unqualified-id cannot name anything.
419 // Reject it early, because we have no AST representation for this in the
420 // case where the scope is dependent.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000421 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
422 << SS.getScopeRep();
Richard Smithd091dc12013-12-05 00:58:33 +0000423 return true;
424
425 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000426 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000427 case NestedNameSpecifier::Namespace:
428 case NestedNameSpecifier::NamespaceAlias:
429 return false;
430 }
431
432 llvm_unreachable("unknown nested name specifier kind");
433}
434
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000435/// Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000436ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000437 SourceLocation TypeidLoc,
438 TypeSourceInfo *Operand,
439 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000440 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000442 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000443 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000444 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000445 Qualifiers Quals;
446 QualType T
447 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
448 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000449 if (T->getAs<RecordType>() &&
450 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
451 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000452
David Majnemer6f3150a2014-11-21 21:09:12 +0000453 if (T->isVariablyModifiedType())
454 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
455
Richard Smith5d96b4c2019-10-03 18:55:23 +0000456 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
457 return ExprError();
458
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000459 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
460 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000461}
462
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000463/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000464ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000465 SourceLocation TypeidLoc,
466 Expr *E,
467 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000468 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000469 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000470 if (E->getType()->isPlaceholderType()) {
471 ExprResult result = CheckPlaceholderExpr(E);
472 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000473 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000474 }
475
Douglas Gregor9da64192010-04-26 22:37:10 +0000476 QualType T = E->getType();
477 if (const RecordType *RecordT = T->getAs<RecordType>()) {
478 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
479 // C++ [expr.typeid]p3:
480 // [...] If the type of the expression is a class type, the class
481 // shall be completely-defined.
482 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
483 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000484
Douglas Gregor9da64192010-04-26 22:37:10 +0000485 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000486 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000487 // polymorphic class type [...] [the] expression is an unevaluated
488 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000489 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000490 // The subexpression is potentially evaluated; switch the context
491 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000492 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000493 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000494 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000495
496 // We require a vtable to query the type at run time.
497 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000498 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000499 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501
Douglas Gregor9da64192010-04-26 22:37:10 +0000502 // C++ [expr.typeid]p4:
503 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000504 // cv-qualified type, the result of the typeid expression refers to a
505 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000506 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000507 Qualifiers Quals;
508 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
509 if (!Context.hasSameType(T, UnqualT)) {
510 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000511 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000512 }
513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000514
David Majnemer6f3150a2014-11-21 21:09:12 +0000515 if (E->getType()->isVariablyModifiedType())
516 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
517 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000518 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000519 E->HasSideEffects(Context, WasEvaluated)) {
520 // The expression operand for typeid is in an unevaluated expression
521 // context, so side effects could result in unintended consequences.
522 Diag(E->getExprLoc(), WasEvaluated
523 ? diag::warn_side_effects_typeid
524 : diag::warn_side_effects_unevaluated_context);
525 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000526
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000527 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
528 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000529}
530
531/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000532ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000533Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
534 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Anastasia Stulova46b55fa2019-07-18 10:02:35 +0000535 // typeid is not supported in OpenCL.
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000536 if (getLangOpts().OpenCLCPlusPlus) {
537 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
538 << "typeid");
539 }
540
Douglas Gregor9da64192010-04-26 22:37:10 +0000541 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000542 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000543 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000544
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000545 if (!CXXTypeInfoDecl) {
546 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
547 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
548 LookupQualifiedName(R, getStdNamespace());
549 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000550 // Microsoft's typeinfo doesn't have type_info in std but in the global
551 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000552 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000553 LookupQualifiedName(R, Context.getTranslationUnitDecl());
554 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
555 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000556 if (!CXXTypeInfoDecl)
557 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000559
Nico Weber1b7f39d2012-05-20 01:27:21 +0000560 if (!getLangOpts().RTTI) {
561 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
562 }
563
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000564 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000565
Douglas Gregor9da64192010-04-26 22:37:10 +0000566 if (isType) {
567 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000568 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000569 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
570 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000571 if (T.isNull())
572 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000573
Douglas Gregor9da64192010-04-26 22:37:10 +0000574 if (!TInfo)
575 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000576
Douglas Gregor9da64192010-04-26 22:37:10 +0000577 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000580 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000581 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000582}
583
David Majnemer1dbc7a72016-03-27 04:46:07 +0000584/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
585/// a single GUID.
586static void
587getUuidAttrOfType(Sema &SemaRef, QualType QT,
588 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
589 // Optionally remove one level of pointer, reference or array indirection.
590 const Type *Ty = QT.getTypePtr();
591 if (QT->isPointerType() || QT->isReferenceType())
592 Ty = QT->getPointeeType().getTypePtr();
593 else if (QT->isArrayType())
594 Ty = Ty->getBaseElementTypeUnsafe();
595
Reid Klecknere516eab2016-12-13 18:58:09 +0000596 const auto *TD = Ty->getAsTagDecl();
597 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000598 return;
599
Reid Klecknere516eab2016-12-13 18:58:09 +0000600 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000601 UuidAttrs.insert(Uuid);
602 return;
603 }
604
605 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000606 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000607 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
608 for (const TemplateArgument &TA : TAL.asArray()) {
609 const UuidAttr *UuidForTA = nullptr;
610 if (TA.getKind() == TemplateArgument::Type)
611 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
612 else if (TA.getKind() == TemplateArgument::Declaration)
613 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
614
615 if (UuidForTA)
616 UuidAttrs.insert(UuidForTA);
617 }
618 }
619}
620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000621/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000622ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
623 SourceLocation TypeidLoc,
624 TypeSourceInfo *Operand,
625 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000626 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000627 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000628 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
629 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
630 if (UuidAttrs.empty())
631 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
632 if (UuidAttrs.size() > 1)
633 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000634 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000636
David Majnemer2041b462016-03-28 03:19:50 +0000637 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000638 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000639}
640
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000641/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000642ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
643 SourceLocation TypeidLoc,
644 Expr *E,
645 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000646 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000647 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000648 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
649 UuidStr = "00000000-0000-0000-0000-000000000000";
650 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000651 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
652 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
653 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000654 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000655 if (UuidAttrs.size() > 1)
656 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000657 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000658 }
Francois Pichetb7577652010-12-27 01:32:00 +0000659 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000660
David Majnemer2041b462016-03-28 03:19:50 +0000661 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000662 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000663}
664
665/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
666ExprResult
667Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
668 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000669 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000670 if (!MSVCGuidDecl) {
671 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
672 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
673 LookupQualifiedName(R, Context.getTranslationUnitDecl());
674 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
675 if (!MSVCGuidDecl)
676 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000677 }
678
Francois Pichet9f4f2072010-09-08 12:20:18 +0000679 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000680
Francois Pichet9f4f2072010-09-08 12:20:18 +0000681 if (isType) {
682 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000683 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000684 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
685 &TInfo);
686 if (T.isNull())
687 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000688
Francois Pichet9f4f2072010-09-08 12:20:18 +0000689 if (!TInfo)
690 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
691
692 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
693 }
694
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000696 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
697}
698
Steve Naroff66356bd2007-09-16 14:56:35 +0000699/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000700ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000701Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000702 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000703 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000704 return new (Context)
705 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000706}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000707
Sebastian Redl576fd422009-05-10 18:38:11 +0000708/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000709ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000710Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000711 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000712}
713
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000714/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000715ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000716Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
717 bool IsThrownVarInScope = false;
718 if (Ex) {
719 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000720 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000721 // copy/move construction of a class object [...]
722 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000723 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000724 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000725 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000726 // innermost enclosing try-block (if there is one), the copy/move
727 // operation from the operand to the exception object (15.1) can be
728 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000729 // exception object
730 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
731 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
732 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
733 for( ; S; S = S->getParent()) {
734 if (S->isDeclScope(Var)) {
735 IsThrownVarInScope = true;
736 break;
737 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000738
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000739 if (S->getFlags() &
740 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
741 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
742 Scope::TryScope))
743 break;
744 }
745 }
746 }
747 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000748
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000749 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
750}
751
Simon Pilgrim75c26882016-09-30 14:25:09 +0000752ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000753 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000754 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000755 if (!getLangOpts().CXXExceptions &&
Alexey Bataev3167b302019-02-22 14:42:48 +0000756 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
Alexey Bataevc416e642019-02-08 18:02:25 +0000757 // Delay error emission for the OpenMP device code.
Alexey Bataev7feae052019-02-20 19:37:17 +0000758 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexey Bataevc416e642019-02-08 18:02:25 +0000759 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000760
Justin Lebar2a8db342016-09-28 22:45:54 +0000761 // Exceptions aren't allowed in CUDA device code.
762 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000763 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
764 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000765
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000766 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
767 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
768
John Wiegley01296292011-04-08 18:41:53 +0000769 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000770 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
771 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000772 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000773
774 // Initialize the exception result. This implicitly weeds out
775 // abstract types or types with inaccessible copy constructors.
776
777 // C++0x [class.copymove]p31:
778 // When certain criteria are met, an implementation is allowed to omit the
779 // copy/move construction of a class object [...]
780 //
781 // - in a throw-expression, when the operand is the name of a
782 // non-volatile automatic object (other than a function or
783 // catch-clause
784 // parameter) whose scope does not extend beyond the end of the
785 // innermost enclosing try-block (if there is one), the copy/move
786 // operation from the operand to the exception object (15.1) can be
787 // omitted by constructing the automatic object directly into the
788 // exception object
789 const VarDecl *NRVOVariable = nullptr;
790 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000791 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000792
793 InitializedEntity Entity = InitializedEntity::InitializeException(
794 OpLoc, ExceptionObjectTy,
795 /*NRVO=*/NRVOVariable != nullptr);
796 ExprResult Res = PerformMoveOrCopyInitialization(
797 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
798 if (Res.isInvalid())
799 return ExprError();
800 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000801 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000802
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000803 return new (Context)
804 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000805}
806
David Majnemere7a818f2015-03-06 18:53:55 +0000807static void
808collectPublicBases(CXXRecordDecl *RD,
809 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
810 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
811 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
812 bool ParentIsPublic) {
813 for (const CXXBaseSpecifier &BS : RD->bases()) {
814 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
815 bool NewSubobject;
816 // Virtual bases constitute the same subobject. Non-virtual bases are
817 // always distinct subobjects.
818 if (BS.isVirtual())
819 NewSubobject = VBases.insert(BaseDecl).second;
820 else
821 NewSubobject = true;
822
823 if (NewSubobject)
824 ++SubobjectsSeen[BaseDecl];
825
826 // Only add subobjects which have public access throughout the entire chain.
827 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
828 if (PublicPath)
829 PublicSubobjectsSeen.insert(BaseDecl);
830
831 // Recurse on to each base subobject.
832 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
833 PublicPath);
834 }
835}
836
837static void getUnambiguousPublicSubobjects(
838 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
839 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
840 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
841 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
842 SubobjectsSeen[RD] = 1;
843 PublicSubobjectsSeen.insert(RD);
844 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
845 /*ParentIsPublic=*/true);
846
847 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
848 // Skip ambiguous objects.
849 if (SubobjectsSeen[PublicSubobject] > 1)
850 continue;
851
852 Objects.push_back(PublicSubobject);
853 }
854}
855
Sebastian Redl4de47b42009-04-27 20:27:31 +0000856/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000857bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
858 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000859 // If the type of the exception would be an incomplete type or a pointer
860 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000861 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000862 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000863 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000864 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000865 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000866 }
867 if (!isPointer || !Ty->isVoidType()) {
868 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000869 isPointer ? diag::err_throw_incomplete_ptr
870 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000871 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000872 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000873
David Majnemerd09a51c2015-03-03 01:50:05 +0000874 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000875 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000876 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000877 }
878
Eli Friedman91a3d272010-06-03 20:39:03 +0000879 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000880 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
881 if (!RD)
882 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000883
Douglas Gregor88d292c2010-05-13 16:44:06 +0000884 // If we are throwing a polymorphic class type or pointer thereof,
885 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000886 MarkVTableUsed(ThrowLoc, RD);
887
Eli Friedman36ebbec2010-10-12 20:32:36 +0000888 // If a pointer is thrown, the referenced object will not be destroyed.
889 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000890 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000891
Richard Smitheec915d62012-02-18 04:13:32 +0000892 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000893 if (!RD->hasIrrelevantDestructor()) {
894 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
895 MarkFunctionReferenced(E->getExprLoc(), Destructor);
896 CheckDestructorAccess(E->getExprLoc(), Destructor,
897 PDiag(diag::err_access_dtor_exception) << Ty);
898 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000899 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000900 }
901 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000902
David Majnemerdfa6d202015-03-11 18:36:39 +0000903 // The MSVC ABI creates a list of all types which can catch the exception
904 // object. This list also references the appropriate copy constructor to call
905 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000906 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000907 // We are only interested in the public, unambiguous bases contained within
908 // the exception object. Bases which are ambiguous or otherwise
909 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000910 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
911 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000912
David Majnemere7a818f2015-03-06 18:53:55 +0000913 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000914 // Attempt to lookup the copy constructor. Various pieces of machinery
915 // will spring into action, like template instantiation, which means this
916 // cannot be a simple walk of the class's decls. Instead, we must perform
917 // lookup and overload resolution.
918 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
919 if (!CD)
920 continue;
921
922 // Mark the constructor referenced as it is used by this throw expression.
923 MarkFunctionReferenced(E->getExprLoc(), CD);
924
925 // Skip this copy constructor if it is trivial, we don't need to record it
926 // in the catchable type data.
927 if (CD->isTrivial())
928 continue;
929
930 // The copy constructor is non-trivial, create a mapping from this class
931 // type to this constructor.
932 // N.B. The selection of copy constructor is not sensitive to this
933 // particular throw-site. Lookup will be performed at the catch-site to
934 // ensure that the copy constructor is, in fact, accessible (via
935 // friendship or any other means).
936 Context.addCopyConstructorForExceptionObject(Subobject, CD);
937
938 // We don't keep the instantiated default argument expressions around so
939 // we must rebuild them here.
940 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000941 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
942 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000943 }
944 }
945 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000946
Akira Hatanakac39a2432019-05-10 02:16:37 +0000947 // Under the Itanium C++ ABI, memory for the exception object is allocated by
948 // the runtime with no ability for the compiler to request additional
949 // alignment. Warn if the exception type requires alignment beyond the minimum
950 // guaranteed by the target C++ runtime.
951 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
952 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
953 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
954 if (ExnObjAlign < TypeAlign) {
955 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
956 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
957 << Ty << (unsigned)TypeAlign.getQuantity()
958 << (unsigned)ExnObjAlign.getQuantity();
959 }
960 }
961
David Majnemerba3e5ec2015-03-13 18:26:17 +0000962 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000963}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000964
Faisal Vali67b04462016-06-11 16:41:54 +0000965static QualType adjustCVQualifiersForCXXThisWithinLambda(
966 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
967 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
968
969 QualType ClassType = ThisTy->getPointeeType();
970 LambdaScopeInfo *CurLSI = nullptr;
971 DeclContext *CurDC = CurSemaContext;
972
973 // Iterate through the stack of lambdas starting from the innermost lambda to
974 // the outermost lambda, checking if '*this' is ever captured by copy - since
975 // that could change the cv-qualifiers of the '*this' object.
976 // The object referred to by '*this' starts out with the cv-qualifiers of its
977 // member function. We then start with the innermost lambda and iterate
978 // outward checking to see if any lambda performs a by-copy capture of '*this'
979 // - and if so, any nested lambda must respect the 'constness' of that
980 // capturing lamdbda's call operator.
981 //
982
Faisal Vali999f27e2017-05-02 20:56:34 +0000983 // Since the FunctionScopeInfo stack is representative of the lexical
984 // nesting of the lambda expressions during initial parsing (and is the best
985 // place for querying information about captures about lambdas that are
986 // partially processed) and perhaps during instantiation of function templates
987 // that contain lambda expressions that need to be transformed BUT not
988 // necessarily during instantiation of a nested generic lambda's function call
989 // operator (which might even be instantiated at the end of the TU) - at which
990 // time the DeclContext tree is mature enough to query capture information
991 // reliably - we use a two pronged approach to walk through all the lexically
992 // enclosing lambda expressions:
993 //
994 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
995 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
996 // enclosed by the call-operator of the LSI below it on the stack (while
997 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
998 // the stack represents the innermost lambda.
999 //
1000 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1001 // represents a lambda's call operator. If it does, we must be instantiating
1002 // a generic lambda's call operator (represented by the Current LSI, and
1003 // should be the only scenario where an inconsistency between the LSI and the
1004 // DeclContext should occur), so climb out the DeclContexts if they
1005 // represent lambdas, while querying the corresponding closure types
1006 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +00001007
Faisal Vali999f27e2017-05-02 20:56:34 +00001008 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +00001009 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +00001010 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1011 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1012 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +00001013 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1014 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001015
1016 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +00001017 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001018
Faisal Vali67b04462016-06-11 16:41:54 +00001019 auto C = CurLSI->getCXXThisCapture();
1020
1021 if (C.isCopyCapture()) {
1022 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1023 if (CurLSI->CallOperator->isConst())
1024 ClassType.addConst();
1025 return ASTCtx.getPointerType(ClassType);
1026 }
1027 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001028
1029 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1030 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001031 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001032 assert(CurLSI && "While computing 'this' capture-type for a generic "
1033 "lambda, we must have a corresponding LambdaScopeInfo");
1034 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1035 "While computing 'this' capture-type for a generic lambda, when we "
1036 "run out of enclosing LSI's, yet the enclosing DC is a "
1037 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1038 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001039 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001040
Faisal Vali67b04462016-06-11 16:41:54 +00001041 auto IsThisCaptured =
1042 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1043 IsConst = false;
1044 IsByCopy = false;
1045 for (auto &&C : Closure->captures()) {
1046 if (C.capturesThis()) {
1047 if (C.getCaptureKind() == LCK_StarThis)
1048 IsByCopy = true;
1049 if (Closure->getLambdaCallOperator()->isConst())
1050 IsConst = true;
1051 return true;
1052 }
1053 }
1054 return false;
1055 };
1056
1057 bool IsByCopyCapture = false;
1058 bool IsConstCapture = false;
1059 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1060 while (Closure &&
1061 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1062 if (IsByCopyCapture) {
1063 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1064 if (IsConstCapture)
1065 ClassType.addConst();
1066 return ASTCtx.getPointerType(ClassType);
1067 }
1068 Closure = isLambdaCallOperator(Closure->getParent())
1069 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1070 : nullptr;
1071 }
1072 }
1073 return ASTCtx.getPointerType(ClassType);
1074}
1075
Eli Friedman73a04092012-01-07 04:59:52 +00001076QualType Sema::getCurrentThisType() {
1077 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001078 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001079
Richard Smith938f40b2011-06-11 17:19:42 +00001080 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1081 if (method && method->isInstance())
Brian Gesiak5488ab42019-01-11 01:54:53 +00001082 ThisTy = method->getThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001083 }
Faisal Validc6b5962016-03-21 09:25:37 +00001084
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001085 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001086 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001087
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001088 assert(isa<CXXRecordDecl>(DC) &&
1089 "Trying to get 'this' type from static method?");
1090
1091 // This is a lambda call operator that is being instantiated as a default
1092 // initializer. DC must point to the enclosing class type, so we can recover
1093 // the 'this' type from it.
1094
1095 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1096 // There are no cv-qualifiers for 'this' within default initializers,
1097 // per [expr.prim.general]p4.
1098 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001099 }
Faisal Vali67b04462016-06-11 16:41:54 +00001100
1101 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1102 // might need to be adjusted if the lambda or any of its enclosing lambda's
1103 // captures '*this' by copy.
1104 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1105 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1106 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001107 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001108}
1109
Simon Pilgrim75c26882016-09-30 14:25:09 +00001110Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001111 Decl *ContextDecl,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001112 Qualifiers CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001113 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001114 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1115{
1116 if (!Enabled || !ContextDecl)
1117 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001118
1119 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001120 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1121 Record = Template->getTemplatedDecl();
1122 else
1123 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001124
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001125 QualType T = S.Context.getRecordType(Record);
1126 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1127
1128 S.CXXThisTypeOverride = S.Context.getPointerType(T);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001129
Douglas Gregor3024f072012-04-16 07:05:22 +00001130 this->Enabled = true;
1131}
1132
1133
1134Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1135 if (Enabled) {
1136 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1137 }
1138}
1139
Simon Pilgrim75c26882016-09-30 14:25:09 +00001140bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001141 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1142 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001143 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001144 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001145 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001146
Faisal Validc6b5962016-03-21 09:25:37 +00001147 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001148
Reid Kleckner87a31802018-03-12 21:43:02 +00001149 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1150 ? *FunctionScopeIndexToStopAt
1151 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001152
Simon Pilgrim75c26882016-09-30 14:25:09 +00001153 // Check that we can capture the *enclosing object* (referred to by '*this')
1154 // by the capturing-entity/closure (lambda/block/etc) at
1155 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1156
1157 // Note: The *enclosing object* can only be captured by-value by a
1158 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001159 // [*this] { ... }.
1160 // Every other capture of the *enclosing object* results in its by-reference
1161 // capture.
1162
1163 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1164 // stack), we can capture the *enclosing object* only if:
1165 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1166 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001167 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001168 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001169 // -- or, there is some enclosing closure 'E' that has already captured the
1170 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001171 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001172 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001173 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001174
1175
Faisal Validc6b5962016-03-21 09:25:37 +00001176 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001177 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001178 if (CapturingScopeInfo *CSI =
1179 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1180 if (CSI->CXXThisCaptureIndex != 0) {
1181 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001182 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001183 break;
1184 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001185 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1186 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1187 // This context can't implicitly capture 'this'; fail out.
1188 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001189 Diag(Loc, diag::err_this_capture)
1190 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001191 return true;
1192 }
Eli Friedman20139d32012-01-11 02:36:31 +00001193 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001194 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001195 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001196 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001197 (Explicit && idx == MaxFunctionScopesIndex)) {
1198 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1199 // iteration through can be an explicit capture, all enclosing closures,
1200 // if any, must perform implicit captures.
1201
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001202 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001203 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001204 continue;
1205 }
Eli Friedman20139d32012-01-11 02:36:31 +00001206 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001207 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001208 Diag(Loc, diag::err_this_capture)
1209 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001210 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001211 }
Eli Friedman73a04092012-01-07 04:59:52 +00001212 break;
1213 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001214 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001215
1216 // If we got here, then the closure at MaxFunctionScopesIndex on the
1217 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1218 // (including implicit by-reference captures in any enclosing closures).
1219
1220 // In the loop below, respect the ByCopy flag only for the closure requesting
1221 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001222 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001223 // implicitly capturing the *enclosing object* by reference (see loop
1224 // above)).
1225 assert((!ByCopy ||
1226 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1227 "Only a lambda can capture the enclosing object (referred to by "
1228 "*this) by copy");
Faisal Vali67b04462016-06-11 16:41:54 +00001229 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001230 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1231 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001232 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001233
Richard Smith30116532019-05-28 23:09:46 +00001234 // The type of the corresponding data member (not a 'this' pointer if 'by
1235 // copy').
1236 QualType CaptureType = ThisTy;
1237 if (ByCopy) {
1238 // If we are capturing the object referred to by '*this' by copy, ignore
1239 // any cv qualifiers inherited from the type of the member function for
1240 // the type of the closure-type's corresponding data member and any use
1241 // of 'this'.
1242 CaptureType = ThisTy->getPointeeType();
1243 CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1244 }
1245
Faisal Validc6b5962016-03-21 09:25:37 +00001246 bool isNested = NumCapturingClosures > 1;
Richard Smithb5a45bb2019-05-31 01:17:04 +00001247 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001248 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001249 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001250}
1251
Richard Smith938f40b2011-06-11 17:19:42 +00001252ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001253 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1254 /// is a non-lvalue expression whose value is the address of the object for
1255 /// which the function is called.
1256
Douglas Gregor09deffa2011-10-18 16:47:30 +00001257 QualType ThisTy = getCurrentThisType();
Richard Smith8458c9e2019-05-24 01:35:07 +00001258 if (ThisTy.isNull())
1259 return Diag(Loc, diag::err_invalid_this_use);
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001260 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
Richard Smith8458c9e2019-05-24 01:35:07 +00001261}
John McCallf3a88602011-02-03 08:15:49 +00001262
Richard Smith8458c9e2019-05-24 01:35:07 +00001263Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1264 bool IsImplicit) {
1265 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1266 MarkThisReferenced(This);
1267 return This;
1268}
1269
1270void Sema::MarkThisReferenced(CXXThisExpr *This) {
1271 CheckCXXThisCapture(This->getExprLoc());
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001272}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001273
Douglas Gregor3024f072012-04-16 07:05:22 +00001274bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1275 // If we're outside the body of a member function, then we'll have a specified
1276 // type for 'this'.
1277 if (CXXThisTypeOverride.isNull())
1278 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001279
Douglas Gregor3024f072012-04-16 07:05:22 +00001280 // Determine whether we're looking into a class that's currently being
1281 // defined.
1282 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1283 return Class && Class->isBeingDefined();
1284}
1285
Vedant Kumara14a1f92018-01-17 18:53:51 +00001286/// Parse construction of a specified type.
1287/// Can be interpreted either as function-style casting ("int(x)")
1288/// or class type construction ("ClassType(x,y,z)")
1289/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001290ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001291Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001292 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001293 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001294 SourceLocation RParenOrBraceLoc,
1295 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001296 if (!TypeRep)
1297 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001298
John McCall97513962010-01-15 18:39:57 +00001299 TypeSourceInfo *TInfo;
1300 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1301 if (!TInfo)
1302 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001303
Vedant Kumara14a1f92018-01-17 18:53:51 +00001304 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1305 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001306 // Avoid creating a non-type-dependent expression that contains typos.
1307 // Non-type-dependent expressions are liable to be discarded without
1308 // checking for embedded typos.
1309 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1310 !Result.get()->isTypeDependent())
1311 Result = CorrectDelayedTyposInExpr(Result.get());
1312 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001313}
1314
Douglas Gregor2b88c112010-09-08 00:15:04 +00001315ExprResult
1316Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001317 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001318 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001319 SourceLocation RParenOrBraceLoc,
1320 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001321 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001322 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001323
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001324 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001325 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1326 // directly. We work around this by dropping the locations of the braces.
1327 SourceRange Locs = ListInitialization
1328 ? SourceRange()
1329 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1330 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1331 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001332 }
1333
Richard Smith600b5262017-01-26 20:40:47 +00001334 assert((!ListInitialization ||
1335 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1336 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001337 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001338
Richard Smith60437622017-02-09 19:17:44 +00001339 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1340 InitializationKind Kind =
1341 Exprs.size()
1342 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001343 ? InitializationKind::CreateDirectList(
1344 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1345 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1346 RParenOrBraceLoc)
1347 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1348 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001349
1350 // C++1z [expr.type.conv]p1:
1351 // If the type is a placeholder for a deduced class type, [...perform class
1352 // template argument deduction...]
1353 DeducedType *Deduced = Ty->getContainedDeducedType();
1354 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1355 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1356 Kind, Exprs);
1357 if (Ty.isNull())
1358 return ExprError();
1359 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1360 }
1361
Douglas Gregordd04d332009-01-16 18:33:17 +00001362 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001363 // If the expression list is a parenthesized single expression, the type
1364 // conversion expression is equivalent (in definedness, and if defined in
1365 // meaning) to the corresponding cast expression.
1366 if (Exprs.size() == 1 && !ListInitialization &&
1367 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001368 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001369 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1370 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001371 }
1372
Richard Smith49a6b6e2017-03-24 01:14:25 +00001373 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001374 QualType ElemTy = Ty;
1375 if (Ty->isArrayType()) {
1376 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001377 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1378 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001379 ElemTy = Context.getBaseElementType(Ty);
1380 }
1381
Richard Smith49a6b6e2017-03-24 01:14:25 +00001382 // There doesn't seem to be an explicit rule against this but sanity demands
1383 // we only construct objects with object types.
1384 if (Ty->isFunctionType())
1385 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1386 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001387
Richard Smith49a6b6e2017-03-24 01:14:25 +00001388 // C++17 [expr.type.conv]p2:
1389 // If the type is cv void and the initializer is (), the expression is a
1390 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001391 if (!Ty->isVoidType() &&
1392 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001393 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001394 return ExprError();
1395
Richard Smith49a6b6e2017-03-24 01:14:25 +00001396 // Otherwise, the expression is a prvalue of the specified type whose
1397 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001398 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1399 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001400
Richard Smith49a6b6e2017-03-24 01:14:25 +00001401 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001402 return Result;
1403
1404 Expr *Inner = Result.get();
1405 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1406 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001407 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1408 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001409 // If we created a CXXTemporaryObjectExpr, that node also represents the
1410 // functional cast. Otherwise, create an explicit cast to represent
1411 // the syntactic form of a functional-style cast that was used here.
1412 //
1413 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1414 // would give a more consistent AST representation than using a
1415 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1416 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001417 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001418 SourceRange Locs = ListInitialization
1419 ? SourceRange()
1420 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001421 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001422 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1423 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001424 }
1425
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001426 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001427}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001428
Artem Belevich78929ef2018-09-21 17:29:33 +00001429bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1430 // [CUDA] Ignore this function, if we can't call it.
1431 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1432 if (getLangOpts().CUDA &&
1433 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1434 return false;
1435
1436 SmallVector<const FunctionDecl*, 4> PreventedBy;
1437 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1438
1439 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1440 return Result;
1441
1442 // In case of CUDA, return true if none of the 1-argument deallocator
1443 // functions are actually callable.
1444 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1445 assert(FD->getNumParams() == 1 &&
1446 "Only single-operand functions should be in PreventedBy");
1447 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1448 });
1449}
1450
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001451/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001452/// deallocation function.
1453static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001454 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
Artem Belevich78929ef2018-09-21 17:29:33 +00001455 return S.isUsualDeallocationFunction(Method);
Richard Smithb2f0f052016-10-10 18:54:32 +00001456
1457 if (FD->getOverloadedOperator() != OO_Delete &&
1458 FD->getOverloadedOperator() != OO_Array_Delete)
1459 return false;
1460
1461 unsigned UsualParams = 1;
1462
1463 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1464 S.Context.hasSameUnqualifiedType(
1465 FD->getParamDecl(UsualParams)->getType(),
1466 S.Context.getSizeType()))
1467 ++UsualParams;
1468
1469 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1470 S.Context.hasSameUnqualifiedType(
1471 FD->getParamDecl(UsualParams)->getType(),
1472 S.Context.getTypeDeclType(S.getStdAlignValT())))
1473 ++UsualParams;
1474
1475 return UsualParams == FD->getNumParams();
1476}
1477
1478namespace {
1479 struct UsualDeallocFnInfo {
1480 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001481 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001482 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001483 Destroying(false), HasSizeT(false), HasAlignValT(false),
1484 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001485 // A function template declaration is never a usual deallocation function.
1486 if (!FD)
1487 return;
Richard Smith5b349582017-10-13 01:55:36 +00001488 unsigned NumBaseParams = 1;
1489 if (FD->isDestroyingOperatorDelete()) {
1490 Destroying = true;
1491 ++NumBaseParams;
1492 }
Eric Fiselier8e920502019-01-16 02:34:36 +00001493
1494 if (NumBaseParams < FD->getNumParams() &&
1495 S.Context.hasSameUnqualifiedType(
1496 FD->getParamDecl(NumBaseParams)->getType(),
1497 S.Context.getSizeType())) {
1498 ++NumBaseParams;
1499 HasSizeT = true;
1500 }
1501
1502 if (NumBaseParams < FD->getNumParams() &&
1503 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1504 ++NumBaseParams;
1505 HasAlignValT = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001506 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001507
1508 // In CUDA, determine how much we'd like / dislike to call this.
1509 if (S.getLangOpts().CUDA)
1510 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1511 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001512 }
1513
Eric Fiselierfa752f22018-03-21 19:19:48 +00001514 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001515
Richard Smithf75dcbe2016-10-11 00:21:10 +00001516 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1517 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001518 // C++ P0722:
1519 // A destroying operator delete is preferred over a non-destroying
1520 // operator delete.
1521 if (Destroying != Other.Destroying)
1522 return Destroying;
1523
Richard Smithf75dcbe2016-10-11 00:21:10 +00001524 // C++17 [expr.delete]p10:
1525 // If the type has new-extended alignment, a function with a parameter
1526 // of type std::align_val_t is preferred; otherwise a function without
1527 // such a parameter is preferred
1528 if (HasAlignValT != Other.HasAlignValT)
1529 return HasAlignValT == WantAlign;
1530
1531 if (HasSizeT != Other.HasSizeT)
1532 return HasSizeT == WantSize;
1533
1534 // Use CUDA call preference as a tiebreaker.
1535 return CUDAPref > Other.CUDAPref;
1536 }
1537
Richard Smithb2f0f052016-10-10 18:54:32 +00001538 DeclAccessPair Found;
1539 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001540 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001541 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001542 };
1543}
1544
1545/// Determine whether a type has new-extended alignment. This may be called when
1546/// the type is incomplete (for a delete-expression with an incomplete pointee
1547/// type), in which case it will conservatively return false if the alignment is
1548/// not known.
1549static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1550 return S.getLangOpts().AlignedAllocation &&
1551 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1552 S.getASTContext().getTargetInfo().getNewAlign();
1553}
1554
1555/// Select the correct "usual" deallocation function to use from a selection of
1556/// deallocation functions (either global or class-scope).
1557static UsualDeallocFnInfo resolveDeallocationOverload(
1558 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1559 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1560 UsualDeallocFnInfo Best;
1561
Richard Smithb2f0f052016-10-10 18:54:32 +00001562 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001563 UsualDeallocFnInfo Info(S, I.getPair());
1564 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1565 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001566 continue;
1567
1568 if (!Best) {
1569 Best = Info;
1570 if (BestFns)
1571 BestFns->push_back(Info);
1572 continue;
1573 }
1574
Richard Smithf75dcbe2016-10-11 00:21:10 +00001575 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001576 continue;
1577
1578 // If more than one preferred function is found, all non-preferred
1579 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001580 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001581 BestFns->clear();
1582
1583 Best = Info;
1584 if (BestFns)
1585 BestFns->push_back(Info);
1586 }
1587
1588 return Best;
1589}
1590
1591/// Determine whether a given type is a class for which 'delete[]' would call
1592/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1593/// we need to store the array size (even if the type is
1594/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001595static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1596 QualType allocType) {
1597 const RecordType *record =
1598 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1599 if (!record) return false;
1600
1601 // Try to find an operator delete[] in class scope.
1602
1603 DeclarationName deleteName =
1604 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1605 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1606 S.LookupQualifiedName(ops, record->getDecl());
1607
1608 // We're just doing this for information.
1609 ops.suppressDiagnostics();
1610
1611 // Very likely: there's no operator delete[].
1612 if (ops.empty()) return false;
1613
1614 // If it's ambiguous, it should be illegal to call operator delete[]
1615 // on this thing, so it doesn't matter if we allocate extra space or not.
1616 if (ops.isAmbiguous()) return false;
1617
Richard Smithb2f0f052016-10-10 18:54:32 +00001618 // C++17 [expr.delete]p10:
1619 // If the deallocation functions have class scope, the one without a
1620 // parameter of type std::size_t is selected.
1621 auto Best = resolveDeallocationOverload(
1622 S, ops, /*WantSize*/false,
1623 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1624 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001625}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001627/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001628///
Sebastian Redld74dd492012-02-12 18:41:05 +00001629/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001630/// @code new (memory) int[size][4] @endcode
1631/// or
1632/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001633///
1634/// \param StartLoc The first location of the expression.
1635/// \param UseGlobal True if 'new' was prefixed with '::'.
1636/// \param PlacementLParen Opening paren of the placement arguments.
1637/// \param PlacementArgs Placement new arguments.
1638/// \param PlacementRParen Closing paren of the placement arguments.
1639/// \param TypeIdParens If the type is in parens, the source range.
1640/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001641/// \param Initializer The initializing expression or initializer-list, or null
1642/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001643ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001644Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001645 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001646 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001647 Declarator &D, Expr *Initializer) {
Richard Smithb9fb1212019-05-06 03:47:15 +00001648 Optional<Expr *> ArraySize;
Sebastian Redl351bb782008-12-02 14:43:59 +00001649 // If the specified type is an array, unwrap it and save the expression.
1650 if (D.getNumTypeObjects() > 0 &&
1651 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001652 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001653 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001654 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1655 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001656 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001657 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1658 << D.getSourceRange());
Richard Smithb9fb1212019-05-06 03:47:15 +00001659 if (!Chunk.Arr.NumElts && !Initializer)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001660 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1661 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001662
Sebastian Redl351bb782008-12-02 14:43:59 +00001663 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001664 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001665 }
1666
Douglas Gregor73341c42009-09-11 00:18:58 +00001667 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001668 if (ArraySize) {
1669 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001670 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1671 break;
1672
1673 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1674 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001675 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001676 if (getLangOpts().CPlusPlus14) {
Fangrui Song99337e22018-07-20 08:19:20 +00001677 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1678 // shall be a converted constant expression (5.19) of type std::size_t
1679 // and shall evaluate to a strictly positive value.
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001680 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1681 assert(IntWidth && "Builtin type of size 0?");
1682 llvm::APSInt Value(IntWidth);
1683 Array.NumElts
1684 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1685 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001686 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001687 } else {
1688 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001689 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001690 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001691 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001692 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001693 if (!Array.NumElts)
1694 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001695 }
1696 }
1697 }
1698 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001699
Craig Topperc3ec1492014-05-26 06:22:03 +00001700 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001701 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001702 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001703 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001704
Sebastian Redl6047f072012-02-16 12:22:20 +00001705 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001706 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001707 DirectInitRange = List->getSourceRange();
1708
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001709 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1710 PlacementLParen, PlacementArgs, PlacementRParen,
1711 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001712 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001713}
1714
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001715static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1716 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001717 if (!Init)
1718 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001719 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1720 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001721 if (isa<ImplicitValueInitExpr>(Init))
1722 return true;
1723 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1724 return !CCE->isListInitialization() &&
1725 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001726 else if (Style == CXXNewExpr::ListInit) {
1727 assert(isa<InitListExpr>(Init) &&
1728 "Shouldn't create list CXXConstructExprs for arrays.");
1729 return true;
1730 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001731 return false;
1732}
1733
Akira Hatanaka71645c22018-12-21 07:05:36 +00001734bool
1735Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1736 if (!getLangOpts().AlignedAllocationUnavailable)
1737 return false;
1738 if (FD.isDefined())
1739 return false;
1740 bool IsAligned = false;
1741 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1742 return true;
1743 return false;
1744}
1745
Akira Hatanakacae83f72017-06-29 18:48:40 +00001746// Emit a diagnostic if an aligned allocation/deallocation function that is not
1747// implemented in the standard library is selected.
Akira Hatanaka71645c22018-12-21 07:05:36 +00001748void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1749 SourceLocation Loc) {
1750 if (isUnavailableAlignedAllocationFunction(FD)) {
1751 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001752 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
Akira Hatanaka71645c22018-12-21 07:05:36 +00001753 getASTContext().getTargetInfo().getPlatformName());
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001754
Akira Hatanaka71645c22018-12-21 07:05:36 +00001755 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1756 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1757 Diag(Loc, diag::err_aligned_allocation_unavailable)
Volodymyr Sapsaie5015ab2018-08-03 23:12:37 +00001758 << IsDelete << FD.getType().getAsString() << OSName
1759 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanaka71645c22018-12-21 07:05:36 +00001760 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
Akira Hatanakacae83f72017-06-29 18:48:40 +00001761 }
1762}
1763
John McCalldadc5752010-08-24 06:29:42 +00001764ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001765Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001766 SourceLocation PlacementLParen,
1767 MultiExprArg PlacementArgs,
1768 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001769 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001770 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001771 TypeSourceInfo *AllocTypeInfo,
Richard Smithb9fb1212019-05-06 03:47:15 +00001772 Optional<Expr *> ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001773 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001774 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001775 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001776 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001777
Sebastian Redl6047f072012-02-16 12:22:20 +00001778 CXXNewExpr::InitializationStyle initStyle;
1779 if (DirectInitRange.isValid()) {
1780 assert(Initializer && "Have parens but no initializer.");
1781 initStyle = CXXNewExpr::CallInit;
1782 } else if (Initializer && isa<InitListExpr>(Initializer))
1783 initStyle = CXXNewExpr::ListInit;
1784 else {
1785 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1786 isa<CXXConstructExpr>(Initializer)) &&
1787 "Initializer expression that cannot have been implicitly created.");
1788 initStyle = CXXNewExpr::NoInit;
1789 }
1790
1791 Expr **Inits = &Initializer;
1792 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001793 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1794 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1795 Inits = List->getExprs();
1796 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001797 }
1798
Richard Smith60437622017-02-09 19:17:44 +00001799 // C++11 [expr.new]p15:
1800 // A new-expression that creates an object of type T initializes that
1801 // object as follows:
1802 InitializationKind Kind
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001803 // - If the new-initializer is omitted, the object is default-
1804 // initialized (8.5); if no initialization is performed,
1805 // the object has indeterminate value
1806 = initStyle == CXXNewExpr::NoInit
1807 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1808 // - Otherwise, the new-initializer is interpreted according to
1809 // the
1810 // initialization rules of 8.5 for direct-initialization.
1811 : initStyle == CXXNewExpr::ListInit
1812 ? InitializationKind::CreateDirectList(
1813 TypeRange.getBegin(), Initializer->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001814 Initializer->getEndLoc())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001815 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1816 DirectInitRange.getBegin(),
1817 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001818
Richard Smith60437622017-02-09 19:17:44 +00001819 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1820 auto *Deduced = AllocType->getContainedDeducedType();
1821 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1822 if (ArraySize)
Richard Smithb9fb1212019-05-06 03:47:15 +00001823 return ExprError(
1824 Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1825 diag::err_deduced_class_template_compound_type)
1826 << /*array*/ 2
1827 << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
Richard Smith60437622017-02-09 19:17:44 +00001828
1829 InitializedEntity Entity
1830 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1831 AllocType = DeduceTemplateSpecializationFromInitializer(
1832 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1833 if (AllocType.isNull())
1834 return ExprError();
1835 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001836 bool Braced = (initStyle == CXXNewExpr::ListInit);
1837 if (NumInits == 1) {
1838 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1839 Inits = p->getInits();
1840 NumInits = p->getNumInits();
1841 Braced = true;
1842 }
1843 }
1844
Sebastian Redl6047f072012-02-16 12:22:20 +00001845 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001846 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1847 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001848 if (NumInits > 1) {
1849 Expr *FirstBad = Inits[1];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001850 return ExprError(Diag(FirstBad->getBeginLoc(),
Richard Smith30482bc2011-02-20 03:19:35 +00001851 diag::err_auto_new_ctor_multiple_expressions)
1852 << AllocType << TypeRange);
1853 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001854 if (Braced && !getLangOpts().CPlusPlus17)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001855 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001856 << AllocType << TypeRange;
Richard Smith42a22372019-04-24 02:22:38 +00001857 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001858 QualType DeducedType;
Richard Smith42a22372019-04-24 02:22:38 +00001859 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001860 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Richard Smith42a22372019-04-24 02:22:38 +00001861 << AllocType << Deduce->getType()
1862 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001863 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001864 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001865 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001866 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001867
Douglas Gregorcda95f42010-05-16 16:01:03 +00001868 // Per C++0x [expr.new]p5, the type being constructed may be a
1869 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001870 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001871 if (const ConstantArrayType *Array
1872 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001873 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1874 Context.getSizeType(),
1875 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001876 AllocType = Array->getElementType();
1877 }
1878 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001879
Douglas Gregor3999e152010-10-06 16:00:31 +00001880 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1881 return ExprError();
1882
Simon Pilgrim75c26882016-09-30 14:25:09 +00001883 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001884 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001885 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1886 AllocType->isObjCLifetimeType()) {
1887 AllocType = Context.getLifetimeQualifiedType(AllocType,
1888 AllocType->getObjCARCImplicitLifetime());
1889 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001890
John McCall31168b02011-06-15 23:02:42 +00001891 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001892
Richard Smithb9fb1212019-05-06 03:47:15 +00001893 if (ArraySize && *ArraySize &&
1894 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1895 ExprResult result = CheckPlaceholderExpr(*ArraySize);
John McCall5e77d762013-04-16 07:28:30 +00001896 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001897 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001898 }
Richard Smith8dd34252012-02-04 07:07:42 +00001899 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1900 // integral or enumeration type with a non-negative value."
1901 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1902 // enumeration type, or a class type for which a single non-explicit
1903 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001904 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001905 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001906 llvm::Optional<uint64_t> KnownArraySize;
Richard Smithb9fb1212019-05-06 03:47:15 +00001907 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001908 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001909 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001910 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1911
Richard Smithb9fb1212019-05-06 03:47:15 +00001912 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
Fangrui Song99337e22018-07-20 08:19:20 +00001913 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001914
Simon Pilgrim75c26882016-09-30 14:25:09 +00001915 if (!ConvertedSize.isInvalid() &&
Richard Smithb9fb1212019-05-06 03:47:15 +00001916 (*ArraySize)->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001917 // Diagnose the compatibility of this conversion.
1918 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
Richard Smithb9fb1212019-05-06 03:47:15 +00001919 << (*ArraySize)->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001920 } else {
1921 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1922 protected:
1923 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001924
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001925 public:
1926 SizeConvertDiagnoser(Expr *ArraySize)
1927 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1928 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001929
1930 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1931 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001932 return S.Diag(Loc, diag::err_array_size_not_integral)
1933 << S.getLangOpts().CPlusPlus11 << T;
1934 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001935
1936 SemaDiagnosticBuilder diagnoseIncomplete(
1937 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001938 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1939 << T << ArraySize->getSourceRange();
1940 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001941
1942 SemaDiagnosticBuilder diagnoseExplicitConv(
1943 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001944 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1945 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001946
1947 SemaDiagnosticBuilder noteExplicitConv(
1948 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001949 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1950 << ConvTy->isEnumeralType() << ConvTy;
1951 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001952
1953 SemaDiagnosticBuilder diagnoseAmbiguous(
1954 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001955 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1956 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001957
1958 SemaDiagnosticBuilder noteAmbiguous(
1959 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001960 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1961 << ConvTy->isEnumeralType() << ConvTy;
1962 }
Richard Smithccc11812013-05-21 19:05:48 +00001963
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001964 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1965 QualType T,
1966 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001967 return S.Diag(Loc,
1968 S.getLangOpts().CPlusPlus11
1969 ? diag::warn_cxx98_compat_array_size_conversion
1970 : diag::ext_array_size_conversion)
1971 << T << ConvTy->isEnumeralType() << ConvTy;
1972 }
Richard Smithb9fb1212019-05-06 03:47:15 +00001973 } SizeDiagnoser(*ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001974
Richard Smithb9fb1212019-05-06 03:47:15 +00001975 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001976 SizeDiagnoser);
1977 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001978 if (ConvertedSize.isInvalid())
1979 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001980
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001981 ArraySize = ConvertedSize.get();
Richard Smithb9fb1212019-05-06 03:47:15 +00001982 QualType SizeType = (*ArraySize)->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001983
Douglas Gregor0bf31402010-10-08 23:50:27 +00001984 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001985 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001987 // C++98 [expr.new]p7:
1988 // The expression in a direct-new-declarator shall have integral type
1989 // with a non-negative value.
1990 //
Richard Smith0511d232016-10-05 22:41:02 +00001991 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1992 // per CWG1464. Otherwise, if it's not a constant, we must have an
1993 // unparenthesized array type.
Richard Smithb9fb1212019-05-06 03:47:15 +00001994 if (!(*ArraySize)->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001995 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001996 // We've already performed any required implicit conversion to integer or
1997 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00001998 // FIXME: Per CWG1464, we are required to check the value prior to
1999 // converting to size_t. This will never find a negative array size in
2000 // C++14 onwards, because Value is always unsigned here!
Richard Smithb9fb1212019-05-06 03:47:15 +00002001 if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00002002 if (Value.isSigned() && Value.isNegative()) {
Richard Smithb9fb1212019-05-06 03:47:15 +00002003 return ExprError(Diag((*ArraySize)->getBeginLoc(),
Richard Smith0511d232016-10-05 22:41:02 +00002004 diag::err_typecheck_negative_array_size)
Richard Smithb9fb1212019-05-06 03:47:15 +00002005 << (*ArraySize)->getSourceRange());
Richard Smith0511d232016-10-05 22:41:02 +00002006 }
2007
2008 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002009 unsigned ActiveSizeBits =
2010 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002011 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002012 return ExprError(
Richard Smithb9fb1212019-05-06 03:47:15 +00002013 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2014 << Value.toString(10) << (*ArraySize)->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002015 }
Richard Smith0511d232016-10-05 22:41:02 +00002016
2017 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002018 } else if (TypeIdParens.isValid()) {
2019 // Can't have dynamic array size when the type-id is in parentheses.
Richard Smithb9fb1212019-05-06 03:47:15 +00002020 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2021 << (*ArraySize)->getSourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002022 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2023 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002024
Douglas Gregorf2753b32010-07-13 15:54:32 +00002025 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002026 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002028
John McCall036f2f62011-05-15 07:14:44 +00002029 // Note that we do *not* convert the argument in any way. It can
2030 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002031 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002032
Craig Topperc3ec1492014-05-26 06:22:03 +00002033 FunctionDecl *OperatorNew = nullptr;
2034 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002035 unsigned Alignment =
2036 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2037 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2038 bool PassAlignment = getLangOpts().AlignedAllocation &&
2039 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002040
Brian Gesiakcb024022018-04-01 22:59:22 +00002041 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002042 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002043 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Richard Smithb9fb1212019-05-06 03:47:15 +00002044 FindAllocationFunctions(
2045 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2046 AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2047 OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002048 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002049
2050 // If this is an array allocation, compute whether the usual array
2051 // deallocation function for the type has a size_t parameter.
2052 bool UsualArrayDeleteWantsSize = false;
2053 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002054 UsualArrayDeleteWantsSize =
2055 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002056
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002057 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002058 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002059 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002060 OperatorNew->getType()->getAs<FunctionProtoType>();
2061 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2062 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002063
Richard Smithd6f9e732014-05-13 19:56:21 +00002064 // We've already converted the placement args, just fill in any default
2065 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002066 // argument. Skip the second parameter too if we're passing in the
2067 // alignment; we've already filled it in.
2068 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2069 PassAlignment ? 2 : 1, PlacementArgs,
2070 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002071 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002072
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002073 if (!AllPlaceArgs.empty())
2074 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002075
Richard Smithd6f9e732014-05-13 19:56:21 +00002076 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002077 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002078
2079 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002080
Richard Smithb2f0f052016-10-10 18:54:32 +00002081 // Warn if the type is over-aligned and is being allocated by (unaligned)
2082 // global operator new.
2083 if (PlacementArgs.empty() && !PassAlignment &&
2084 (OperatorNew->isImplicit() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002085 (OperatorNew->getBeginLoc().isValid() &&
2086 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002087 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002088 Diag(StartLoc, diag::warn_overaligned_type)
2089 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002090 << unsigned(Alignment / Context.getCharWidth())
2091 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002092 }
2093 }
2094
Sebastian Redl6047f072012-02-16 12:22:20 +00002095 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002096 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2097 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002098 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002099 SourceRange InitRange(Inits[0]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002100 Inits[NumInits - 1]->getEndLoc());
Richard Smith0511d232016-10-05 22:41:02 +00002101 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2102 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002103 }
2104
Richard Smithdd2ca572012-11-26 08:32:48 +00002105 // If we can perform the initialization, and we've not already done so,
2106 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002107 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002108 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002109 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002110 // The type we initialize is the complete type, including the array bound.
2111 QualType InitType;
2112 if (KnownArraySize)
2113 InitType = Context.getConstantArrayType(
2114 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2115 *KnownArraySize),
2116 ArrayType::Normal, 0);
2117 else if (ArraySize)
2118 InitType =
2119 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2120 else
2121 InitType = AllocType;
2122
Douglas Gregor85dabae2009-12-16 01:38:02 +00002123 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002124 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002125 InitializationSequence InitSeq(*this, Entity, Kind,
2126 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002128 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002129 if (FullInit.isInvalid())
2130 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002131
Sebastian Redl6047f072012-02-16 12:22:20 +00002132 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2133 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002134 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002135 if (CXXBindTemporaryExpr *Binder =
2136 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002137 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002138
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002139 Initializer = FullInit.get();
Richard Smithb9fb1212019-05-06 03:47:15 +00002140
2141 // FIXME: If we have a KnownArraySize, check that the array bound of the
2142 // initializer is no greater than that constant value.
2143
2144 if (ArraySize && !*ArraySize) {
2145 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2146 if (CAT) {
2147 // FIXME: Track that the array size was inferred rather than explicitly
2148 // specified.
2149 ArraySize = IntegerLiteral::Create(
2150 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2151 } else {
2152 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2153 << Initializer->getSourceRange();
2154 }
2155 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002157
Douglas Gregor6642ca22010-02-26 05:06:18 +00002158 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002159 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002160 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2161 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002162 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00002163 }
2164 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002165 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2166 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002167 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00002168 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002169
Bruno Ricci9b6dfac2019-01-07 15:04:45 +00002170 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2171 PassAlignment, UsualArrayDeleteWantsSize,
2172 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2173 Initializer, ResultType, AllocTypeInfo, Range,
2174 DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002175}
2176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002177/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002178/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002179bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002180 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002181 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2182 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002183 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002184 return Diag(Loc, diag::err_bad_new_type)
2185 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002186 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002187 return Diag(Loc, diag::err_bad_new_type)
2188 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002189 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002190 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002191 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002192 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002193 diag::err_allocation_of_abstract_type))
2194 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002195 else if (AllocType->isVariablyModifiedType())
2196 return Diag(Loc, diag::err_variably_modified_new_type)
2197 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002198 else if (AllocType.getAddressSpace() != LangAS::Default &&
2199 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002200 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002201 << AllocType.getUnqualifiedType()
2202 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002203 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002204 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2205 QualType BaseAllocType = Context.getBaseElementType(AT);
2206 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2207 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002208 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002209 << BaseAllocType;
2210 }
2211 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002212
Sebastian Redlbd150f42008-11-21 19:14:01 +00002213 return false;
2214}
2215
Brian Gesiak87412d92018-02-15 20:09:25 +00002216static bool resolveAllocationOverload(
2217 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2218 bool &PassAlignment, FunctionDecl *&Operator,
2219 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002220 OverloadCandidateSet Candidates(R.getNameLoc(),
2221 OverloadCandidateSet::CSK_Normal);
2222 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2223 Alloc != AllocEnd; ++Alloc) {
2224 // Even member operator new/delete are implicitly treated as
2225 // static, so don't use AddMemberCandidate.
2226 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2227
2228 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2229 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2230 /*ExplicitTemplateArgs=*/nullptr, Args,
2231 Candidates,
2232 /*SuppressUserConversions=*/false);
2233 continue;
2234 }
2235
2236 FunctionDecl *Fn = cast<FunctionDecl>(D);
2237 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2238 /*SuppressUserConversions=*/false);
2239 }
2240
2241 // Do the resolution.
2242 OverloadCandidateSet::iterator Best;
2243 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2244 case OR_Success: {
2245 // Got one!
2246 FunctionDecl *FnDecl = Best->Function;
2247 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2248 Best->FoundDecl) == Sema::AR_inaccessible)
2249 return true;
2250
2251 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002252 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002253 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002254
Richard Smithb2f0f052016-10-10 18:54:32 +00002255 case OR_No_Viable_Function:
2256 // C++17 [expr.new]p13:
2257 // If no matching function is found and the allocated object type has
2258 // new-extended alignment, the alignment argument is removed from the
2259 // argument list, and overload resolution is performed again.
2260 if (PassAlignment) {
2261 PassAlignment = false;
2262 AlignArg = Args[1];
2263 Args.erase(Args.begin() + 1);
2264 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002265 Operator, &Candidates, AlignArg,
2266 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002267 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002268
Richard Smithb2f0f052016-10-10 18:54:32 +00002269 // MSVC will fall back on trying to find a matching global operator new
2270 // if operator new[] cannot be found. Also, MSVC will leak by not
2271 // generating a call to operator delete or operator delete[], but we
2272 // will not replicate that bug.
2273 // FIXME: Find out how this interacts with the std::align_val_t fallback
2274 // once MSVC implements it.
2275 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2276 S.Context.getLangOpts().MSVCCompat) {
2277 R.clear();
2278 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2279 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2280 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2281 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002282 Operator, /*Candidates=*/nullptr,
2283 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002284 }
Richard Smith1cdec012013-09-29 04:40:38 +00002285
Brian Gesiak87412d92018-02-15 20:09:25 +00002286 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002287 PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2288 << R.getLookupName() << Range);
Richard Smithb2f0f052016-10-10 18:54:32 +00002289
Brian Gesiak87412d92018-02-15 20:09:25 +00002290 // If we have aligned candidates, only note the align_val_t candidates
2291 // from AlignedCandidates and the non-align_val_t candidates from
2292 // Candidates.
2293 if (AlignedCandidates) {
2294 auto IsAligned = [](OverloadCandidate &C) {
2295 return C.Function->getNumParams() > 1 &&
2296 C.Function->getParamDecl(1)->getType()->isAlignValT();
2297 };
2298 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002299
Brian Gesiak87412d92018-02-15 20:09:25 +00002300 // This was an overaligned allocation, so list the aligned candidates
2301 // first.
2302 Args.insert(Args.begin() + 1, AlignArg);
David Blaikie5e328052019-05-03 00:44:50 +00002303 AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
Brian Gesiak87412d92018-02-15 20:09:25 +00002304 R.getNameLoc(), IsAligned);
2305 Args.erase(Args.begin() + 1);
David Blaikie5e328052019-05-03 00:44:50 +00002306 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
Brian Gesiak87412d92018-02-15 20:09:25 +00002307 IsUnaligned);
2308 } else {
David Blaikie5e328052019-05-03 00:44:50 +00002309 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002310 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002311 }
Richard Smith1cdec012013-09-29 04:40:38 +00002312 return true;
2313
Richard Smithb2f0f052016-10-10 18:54:32 +00002314 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002315 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002316 Candidates.NoteCandidates(
2317 PartialDiagnosticAt(R.getNameLoc(),
2318 S.PDiag(diag::err_ovl_ambiguous_call)
2319 << R.getLookupName() << Range),
2320 S, OCD_ViableCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002321 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002322 return true;
2323
2324 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002325 if (Diagnose) {
David Blaikie5e328052019-05-03 00:44:50 +00002326 Candidates.NoteCandidates(
2327 PartialDiagnosticAt(R.getNameLoc(),
2328 S.PDiag(diag::err_ovl_deleted_call)
2329 << R.getLookupName() << Range),
2330 S, OCD_AllCandidates, Args);
Brian Gesiak87412d92018-02-15 20:09:25 +00002331 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002332 return true;
2333 }
2334 }
2335 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002336}
2337
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002338bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002339 AllocationFunctionScope NewScope,
2340 AllocationFunctionScope DeleteScope,
2341 QualType AllocType, bool IsArray,
2342 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002343 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002344 FunctionDecl *&OperatorDelete,
2345 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002346 // --- Choosing an allocation function ---
2347 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002348 // 1) If looking in AFS_Global scope for allocation functions, only look in
2349 // the global scope. Else, if AFS_Class, only look in the scope of the
2350 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002351 // 2) If an array size is given, look for operator new[], else look for
2352 // operator new.
2353 // 3) The first argument is always size_t. Append the arguments from the
2354 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002355
Richard Smithb2f0f052016-10-10 18:54:32 +00002356 SmallVector<Expr*, 8> AllocArgs;
2357 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2358
2359 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002360 // FIXME: Should the Sema create the expression and embed it in the syntax
2361 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002362 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002363 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002364 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002365 Context.getSizeType(),
2366 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002367 AllocArgs.push_back(&Size);
2368
2369 QualType AlignValT = Context.VoidTy;
2370 if (PassAlignment) {
2371 DeclareGlobalNewDelete();
2372 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2373 }
2374 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2375 if (PassAlignment)
2376 AllocArgs.push_back(&Align);
2377
2378 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002379
Douglas Gregor6642ca22010-02-26 05:06:18 +00002380 // C++ [expr.new]p8:
2381 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002382 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002383 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002384 // type, the allocation function's name is operator new[] and the
2385 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002386 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002387 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002388
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002389 QualType AllocElemType = Context.getBaseElementType(AllocType);
2390
Richard Smithb2f0f052016-10-10 18:54:32 +00002391 // Find the allocation function.
2392 {
2393 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2394
2395 // C++1z [expr.new]p9:
2396 // If the new-expression begins with a unary :: operator, the allocation
2397 // function's name is looked up in the global scope. Otherwise, if the
2398 // allocated type is a class type T or array thereof, the allocation
2399 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002400 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002401 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2402
2403 // We can see ambiguity here if the allocation function is found in
2404 // multiple base classes.
2405 if (R.isAmbiguous())
2406 return true;
2407
2408 // If this lookup fails to find the name, or if the allocated type is not
2409 // a class type, the allocation function's name is looked up in the
2410 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002411 if (R.empty()) {
2412 if (NewScope == AFS_Class)
2413 return true;
2414
Richard Smithb2f0f052016-10-10 18:54:32 +00002415 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002416 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002417
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002418 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
Sven van Haastregt1006a062019-06-26 13:31:24 +00002419 if (PlaceArgs.empty()) {
2420 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2421 } else {
2422 Diag(StartLoc, diag::err_openclcxx_placement_new);
2423 }
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002424 return true;
2425 }
2426
Richard Smithb2f0f052016-10-10 18:54:32 +00002427 assert(!R.empty() && "implicitly declared allocation functions not found");
2428 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2429
2430 // We do our own custom access checks below.
2431 R.suppressDiagnostics();
2432
2433 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002434 OperatorNew, /*Candidates=*/nullptr,
2435 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002436 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002437 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002438
Richard Smithb2f0f052016-10-10 18:54:32 +00002439 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002440 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002441 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002442 return false;
2443 }
2444
Richard Smithb2f0f052016-10-10 18:54:32 +00002445 // Note, the name of OperatorNew might have been changed from array to
2446 // non-array by resolveAllocationOverload.
2447 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2448 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2449 ? OO_Array_Delete
2450 : OO_Delete);
2451
Douglas Gregor6642ca22010-02-26 05:06:18 +00002452 // C++ [expr.new]p19:
2453 //
2454 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002455 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002456 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002457 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002458 // the scope of T. If this lookup fails to find the name, or if
2459 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002460 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002461 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002462 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002463 auto *RD =
2464 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002465 LookupQualifiedName(FoundDelete, RD);
2466 }
John McCallfb6f5262010-03-18 08:19:33 +00002467 if (FoundDelete.isAmbiguous())
2468 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002469
Richard Smithb2f0f052016-10-10 18:54:32 +00002470 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002471 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002472 if (DeleteScope == AFS_Class)
2473 return true;
2474
Douglas Gregor6642ca22010-02-26 05:06:18 +00002475 DeclareGlobalNewDelete();
2476 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2477 }
2478
2479 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002480
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002481 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002482
John McCalld3be2c82010-09-14 21:34:24 +00002483 // Whether we're looking for a placement operator delete is dictated
2484 // by whether we selected a placement operator new, not by whether
2485 // we had explicit placement arguments. This matters for things like
2486 // struct A { void *operator new(size_t, int = 0); ... };
2487 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002488 //
2489 // We don't have any definition for what a "placement allocation function"
2490 // is, but we assume it's any allocation function whose
2491 // parameter-declaration-clause is anything other than (size_t).
2492 //
2493 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2494 // This affects whether an exception from the constructor of an overaligned
2495 // type uses the sized or non-sized form of aligned operator delete.
2496 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2497 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002498
2499 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002500 // C++ [expr.new]p20:
2501 // A declaration of a placement deallocation function matches the
2502 // declaration of a placement allocation function if it has the
2503 // same number of parameters and, after parameter transformations
2504 // (8.3.5), all parameter types except the first are
2505 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002506 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002507 // To perform this comparison, we compute the function type that
2508 // the deallocation function should have, and use that type both
2509 // for template argument deduction and for comparison purposes.
2510 QualType ExpectedFunctionType;
2511 {
2512 const FunctionProtoType *Proto
2513 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002514
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002515 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002516 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002517 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2518 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002519
John McCalldb40c7f2010-12-14 08:05:40 +00002520 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002521 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002522 EPI.Variadic = Proto->isVariadic();
2523
Douglas Gregor6642ca22010-02-26 05:06:18 +00002524 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002525 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002526 }
2527
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002528 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002529 DEnd = FoundDelete.end();
2530 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002531 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002532 if (FunctionTemplateDecl *FnTmpl =
2533 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002534 // Perform template argument deduction to try to match the
2535 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002536 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002537 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2538 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002539 continue;
2540 } else
2541 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2542
Richard Smithbaa47832016-12-01 02:11:49 +00002543 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2544 ExpectedFunctionType,
2545 /*AdjustExcpetionSpec*/true),
2546 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002547 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002548 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002549
Richard Smithb2f0f052016-10-10 18:54:32 +00002550 if (getLangOpts().CUDA)
2551 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2552 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002553 // C++1y [expr.new]p22:
2554 // For a non-placement allocation function, the normal deallocation
2555 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002556 //
2557 // Per [expr.delete]p10, this lookup prefers a member operator delete
2558 // without a size_t argument, but prefers a non-member operator delete
2559 // with a size_t where possible (which it always is in this case).
2560 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2561 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2562 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2563 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2564 &BestDeallocFns);
2565 if (Selected)
2566 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2567 else {
2568 // If we failed to select an operator, all remaining functions are viable
2569 // but ambiguous.
2570 for (auto Fn : BestDeallocFns)
2571 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002572 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002573 }
2574
2575 // C++ [expr.new]p20:
2576 // [...] If the lookup finds a single matching deallocation
2577 // function, that function will be called; otherwise, no
2578 // deallocation function will be called.
2579 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002580 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002581
Richard Smithb2f0f052016-10-10 18:54:32 +00002582 // C++1z [expr.new]p23:
2583 // If the lookup finds a usual deallocation function (3.7.4.2)
2584 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002585 // as a placement deallocation function, would have been
2586 // selected as a match for the allocation function, the program
2587 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002588 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002589 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002590 UsualDeallocFnInfo Info(*this,
2591 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002592 // Core issue, per mail to core reflector, 2016-10-09:
2593 // If this is a member operator delete, and there is a corresponding
2594 // non-sized member operator delete, this isn't /really/ a sized
2595 // deallocation function, it just happens to have a size_t parameter.
2596 bool IsSizedDelete = Info.HasSizeT;
2597 if (IsSizedDelete && !FoundGlobalDelete) {
2598 auto NonSizedDelete =
2599 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2600 /*WantAlign*/Info.HasAlignValT);
2601 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2602 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2603 IsSizedDelete = false;
2604 }
2605
2606 if (IsSizedDelete) {
2607 SourceRange R = PlaceArgs.empty()
2608 ? SourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002609 : SourceRange(PlaceArgs.front()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002610 PlaceArgs.back()->getEndLoc());
Richard Smithb2f0f052016-10-10 18:54:32 +00002611 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2612 if (!OperatorDelete->isImplicit())
2613 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2614 << DeleteName;
2615 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002616 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002617
2618 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2619 Matches[0].first);
2620 } else if (!Matches.empty()) {
2621 // We found multiple suitable operators. Per [expr.new]p20, that means we
2622 // call no 'operator delete' function, but we should at least warn the user.
2623 // FIXME: Suppress this warning if the construction cannot throw.
2624 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2625 << DeleteName << AllocElemType;
2626
2627 for (auto &Match : Matches)
2628 Diag(Match.second->getLocation(),
2629 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002630 }
2631
Sebastian Redlfaf68082008-12-03 20:26:15 +00002632 return false;
2633}
2634
2635/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2636/// delete. These are:
2637/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002638/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002639/// void* operator new(std::size_t) throw(std::bad_alloc);
2640/// void* operator new[](std::size_t) throw(std::bad_alloc);
2641/// void operator delete(void *) throw();
2642/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002643/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002644/// void* operator new(std::size_t);
2645/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002646/// void operator delete(void *) noexcept;
2647/// void operator delete[](void *) noexcept;
2648/// // C++1y:
2649/// void* operator new(std::size_t);
2650/// void* operator new[](std::size_t);
2651/// void operator delete(void *) noexcept;
2652/// void operator delete[](void *) noexcept;
2653/// void operator delete(void *, std::size_t) noexcept;
2654/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002655/// @endcode
2656/// Note that the placement and nothrow forms of new are *not* implicitly
2657/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002658void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002659 if (GlobalNewDeleteDeclared)
2660 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661
Anastasia Stulova46b55fa2019-07-18 10:02:35 +00002662 // The implicitly declared new and delete operators
2663 // are not supported in OpenCL.
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002664 if (getLangOpts().OpenCLCPlusPlus)
2665 return;
2666
Douglas Gregor87f54062009-09-15 22:30:29 +00002667 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002668 // [...] The following allocation and deallocation functions (18.4) are
2669 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002670 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002671 //
Sebastian Redl37588092011-03-14 18:08:30 +00002672 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002673 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002674 // void* operator new[](std::size_t) throw(std::bad_alloc);
2675 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002676 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002677 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002678 // void* operator new(std::size_t);
2679 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002680 // void operator delete(void*) noexcept;
2681 // void operator delete[](void*) noexcept;
2682 // C++1y:
2683 // void* operator new(std::size_t);
2684 // void* operator new[](std::size_t);
2685 // void operator delete(void*) noexcept;
2686 // void operator delete[](void*) noexcept;
2687 // void operator delete(void*, std::size_t) noexcept;
2688 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002689 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002690 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002691 // new, operator new[], operator delete, operator delete[].
2692 //
2693 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2694 // "std" or "bad_alloc" as necessary to form the exception specification.
2695 // However, we do not make these implicit declarations visible to name
2696 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002697 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002698 // The "std::bad_alloc" class has not yet been declared, so build it
2699 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002700 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2701 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002702 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002704 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002705 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002706 }
Richard Smith59139022016-09-30 22:41:36 +00002707 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002708 // The "std::align_val_t" enum class has not yet been declared, so build it
2709 // implicitly.
2710 auto *AlignValT = EnumDecl::Create(
2711 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2712 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2713 AlignValT->setIntegerType(Context.getSizeType());
2714 AlignValT->setPromotionType(Context.getSizeType());
2715 AlignValT->setImplicit(true);
2716 StdAlignValT = AlignValT;
2717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002718
Sebastian Redlfaf68082008-12-03 20:26:15 +00002719 GlobalNewDeleteDeclared = true;
2720
2721 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2722 QualType SizeT = Context.getSizeType();
2723
Richard Smith96269c52016-09-29 22:49:46 +00002724 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2725 QualType Return, QualType Param) {
2726 llvm::SmallVector<QualType, 3> Params;
2727 Params.push_back(Param);
2728
2729 // Create up to four variants of the function (sized/aligned).
2730 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2731 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002732 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002733
2734 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2735 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2736 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002737 if (Sized)
2738 Params.push_back(SizeT);
2739
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002740 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002741 if (Aligned)
2742 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2743
2744 DeclareGlobalAllocationFunction(
2745 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2746
2747 if (Aligned)
2748 Params.pop_back();
2749 }
2750 }
2751 };
2752
2753 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2754 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2755 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2756 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002757}
2758
2759/// DeclareGlobalAllocationFunction - Declares a single implicit global
2760/// allocation function if it doesn't already exist.
2761void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002762 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002763 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002764 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2765
2766 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002767 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2768 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2769 Alloc != AllocEnd; ++Alloc) {
2770 // Only look at non-template functions, as it is the predefined,
2771 // non-templated allocation function we are trying to declare here.
2772 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002773 if (Func->getNumParams() == Params.size()) {
2774 llvm::SmallVector<QualType, 3> FuncParams;
2775 for (auto *P : Func->parameters())
2776 FuncParams.push_back(
2777 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2778 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002779 // Make the function visible to name lookup, even if we found it in
2780 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002781 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002782 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002783 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002784 }
Chandler Carruth93538422010-02-03 11:02:14 +00002785 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002786 }
2787 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002788
Erich Keane881e83d2019-03-04 14:54:52 +00002789 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
Erich Keane00022812019-05-23 16:05:21 +00002790 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
Richard Smithc015bc22014-02-07 22:39:53 +00002791
Richard Smithf8b417c2014-02-08 00:42:45 +00002792 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002793 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002794 = (Name.getCXXOverloadedOperator() == OO_New ||
2795 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002796 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002797 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002798 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002799 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002800 EPI.ExceptionSpec.Type = EST_Dynamic;
2801 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002802 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002803 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002804 EPI.ExceptionSpec =
2805 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002806 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002807
Artem Belevich07db5cf2016-10-21 20:34:05 +00002808 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2809 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2810 FunctionDecl *Alloc = FunctionDecl::Create(
2811 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2812 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2813 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002814 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002815 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002816
Petr Hosek821b38f2018-12-04 03:25:25 +00002817 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2818 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2819 ? VisibilityAttr::Hidden
2820 : VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002821
Artem Belevich07db5cf2016-10-21 20:34:05 +00002822 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2823 for (QualType T : Params) {
2824 ParamDecls.push_back(ParmVarDecl::Create(
2825 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2826 /*TInfo=*/nullptr, SC_None, nullptr));
2827 ParamDecls.back()->setImplicit();
2828 }
2829 Alloc->setParams(ParamDecls);
2830 if (ExtraAttr)
2831 Alloc->addAttr(ExtraAttr);
2832 Context.getTranslationUnitDecl()->addDecl(Alloc);
2833 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2834 };
2835
2836 if (!LangOpts.CUDA)
2837 CreateAllocationFunctionDecl(nullptr);
2838 else {
2839 // Host and device get their own declaration so each can be
2840 // defined or re-declared independently.
2841 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2842 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002843 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002844}
2845
Richard Smith1cdec012013-09-29 04:40:38 +00002846FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2847 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002848 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002849 DeclarationName Name) {
2850 DeclareGlobalNewDelete();
2851
2852 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2853 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2854
Richard Smithb2f0f052016-10-10 18:54:32 +00002855 // FIXME: It's possible for this to result in ambiguity, through a
2856 // user-declared variadic operator delete or the enable_if attribute. We
2857 // should probably not consider those cases to be usual deallocation
2858 // functions. But for now we just make an arbitrary choice in that case.
2859 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2860 Overaligned);
2861 assert(Result.FD && "operator delete missing from global scope?");
2862 return Result.FD;
2863}
Richard Smith1cdec012013-09-29 04:40:38 +00002864
Richard Smithb2f0f052016-10-10 18:54:32 +00002865FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2866 CXXRecordDecl *RD) {
2867 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002868
Richard Smithb2f0f052016-10-10 18:54:32 +00002869 FunctionDecl *OperatorDelete = nullptr;
2870 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2871 return nullptr;
2872 if (OperatorDelete)
2873 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002874
Richard Smithb2f0f052016-10-10 18:54:32 +00002875 // If there's no class-specific operator delete, look up the global
2876 // non-array delete.
2877 return FindUsualDeallocationFunction(
2878 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2879 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002880}
2881
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002882bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2883 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002884 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002885 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002886 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002887 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002888
John McCall27b18f82009-11-17 02:14:36 +00002889 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002890 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002891
Chandler Carruthb6f99172010-06-28 00:30:51 +00002892 Found.suppressDiagnostics();
2893
Richard Smithb2f0f052016-10-10 18:54:32 +00002894 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002895
Richard Smithb2f0f052016-10-10 18:54:32 +00002896 // C++17 [expr.delete]p10:
2897 // If the deallocation functions have class scope, the one without a
2898 // parameter of type std::size_t is selected.
2899 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2900 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2901 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002902
Richard Smithb2f0f052016-10-10 18:54:32 +00002903 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002904 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002905 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002906
Richard Smithb2f0f052016-10-10 18:54:32 +00002907 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002908 if (Operator->isDeleted()) {
2909 if (Diagnose) {
2910 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002911 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002912 }
2913 return true;
2914 }
2915
Richard Smith921bd202012-02-26 09:11:52 +00002916 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002917 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002918 return true;
2919
John McCall66a87592010-08-04 00:31:26 +00002920 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002921 }
John McCall66a87592010-08-04 00:31:26 +00002922
Richard Smithb2f0f052016-10-10 18:54:32 +00002923 // We found multiple suitable operators; complain about the ambiguity.
2924 // FIXME: The standard doesn't say to do this; it appears that the intent
2925 // is that this should never happen.
2926 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002927 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002928 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2929 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002930 for (auto &Match : Matches)
2931 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002932 }
John McCall66a87592010-08-04 00:31:26 +00002933 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002934 }
2935
2936 // We did find operator delete/operator delete[] declarations, but
2937 // none of them were suitable.
2938 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002939 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002940 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2941 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002942
Richard Smithb2f0f052016-10-10 18:54:32 +00002943 for (NamedDecl *D : Found)
2944 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002945 diag::note_member_declared_here) << Name;
2946 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002947 return true;
2948 }
2949
Craig Topperc3ec1492014-05-26 06:22:03 +00002950 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002951 return false;
2952}
2953
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002954namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002955/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002956/// initializing deletee have the same array form.
2957class MismatchingNewDeleteDetector {
2958public:
2959 enum MismatchResult {
2960 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2961 NoMismatch,
2962 /// Indicates that variable is initialized with mismatching form of \a new.
2963 VarInitMismatches,
2964 /// Indicates that member is initialized with mismatching form of \a new.
2965 MemberInitMismatches,
2966 /// Indicates that 1 or more constructors' definitions could not been
2967 /// analyzed, and they will be checked again at the end of translation unit.
2968 AnalyzeLater
2969 };
2970
2971 /// \param EndOfTU True, if this is the final analysis at the end of
2972 /// translation unit. False, if this is the initial analysis at the point
2973 /// delete-expression was encountered.
2974 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002975 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002976 HasUndefinedConstructors(false) {}
2977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002978 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002979 /// matching form of new-expression.
2980 ///
2981 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2982 /// point where delete-expression is encountered, then a warning will be
2983 /// issued immediately. If return value is \c AnalyzeLater at the point where
2984 /// delete-expression is seen, then member will be analyzed at the end of
2985 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2986 /// couldn't be analyzed. If at least one constructor initializes the member
2987 /// with matching type of new, the return value is \c NoMismatch.
2988 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002989 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002990 /// \param Field Class member to analyze.
2991 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2992 /// for deleting the \p Field.
2993 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002994 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002995 /// List of mismatching new-expressions used for initialization of the pointee
2996 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2997 /// Indicates whether delete-expression was in array form.
2998 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002999
3000private:
3001 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003002 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003003 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003004 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003005 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00003006 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003007 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003008 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003009 /// \c new either by the member initializer or in-class initialization.
3010 ///
3011 /// If bodies of all constructors are not visible at the end of translation
3012 /// unit or at least one constructor initializes member with the matching
3013 /// form of \c new, mismatch cannot be proven, and this function will return
3014 /// \c NoMismatch.
3015 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003016 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003017 /// \c new.
3018 ///
3019 /// If variable is initialized with matching form of \c new or variable is not
3020 /// initialized with a \c new expression, this function will return true.
3021 /// If variable is initialized with mismatching form of \c new, returns false.
3022 /// \param D Variable to analyze.
3023 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003024 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003025 /// form of \c new.
3026 ///
3027 /// Returns true, if member is initialized with matching form of \c new in
3028 /// member initializer list. Returns false, if member is initialized with the
3029 /// matching form of \c new in this constructor's initializer or given
3030 /// constructor isn't defined at the point where delete-expression is seen, or
3031 /// member isn't initialized by the constructor.
3032 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003033 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003034 /// \c new in member initializer list.
3035 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3036 /// Checks whether member is initialized with mismatching form of \c new by
3037 /// in-class initializer.
3038 MismatchResult analyzeInClassInitializer();
3039};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003040}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003041
3042MismatchingNewDeleteDetector::MismatchResult
3043MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3044 NewExprs.clear();
3045 assert(DE && "Expected delete-expression");
3046 IsArrayForm = DE->isArrayForm();
3047 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3048 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3049 return analyzeMemberExpr(ME);
3050 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3051 if (!hasMatchingVarInit(D))
3052 return VarInitMismatches;
3053 }
3054 return NoMismatch;
3055}
3056
3057const CXXNewExpr *
3058MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3059 assert(E != nullptr && "Expected a valid initializer expression");
3060 E = E->IgnoreParenImpCasts();
3061 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3062 if (ILE->getNumInits() == 1)
3063 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3064 }
3065
3066 return dyn_cast_or_null<const CXXNewExpr>(E);
3067}
3068
3069bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3070 const CXXCtorInitializer *CI) {
3071 const CXXNewExpr *NE = nullptr;
3072 if (Field == CI->getMember() &&
3073 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3074 if (NE->isArray() == IsArrayForm)
3075 return true;
3076 else
3077 NewExprs.push_back(NE);
3078 }
3079 return false;
3080}
3081
3082bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3083 const CXXConstructorDecl *CD) {
3084 if (CD->isImplicit())
3085 return false;
3086 const FunctionDecl *Definition = CD;
3087 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3088 HasUndefinedConstructors = true;
3089 return EndOfTU;
3090 }
3091 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3092 if (hasMatchingNewInCtorInit(CI))
3093 return true;
3094 }
3095 return false;
3096}
3097
3098MismatchingNewDeleteDetector::MismatchResult
3099MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3100 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003101 const Expr *InitExpr = Field->getInClassInitializer();
3102 if (!InitExpr)
3103 return EndOfTU ? NoMismatch : AnalyzeLater;
3104 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003105 if (NE->isArray() != IsArrayForm) {
3106 NewExprs.push_back(NE);
3107 return MemberInitMismatches;
3108 }
3109 }
3110 return NoMismatch;
3111}
3112
3113MismatchingNewDeleteDetector::MismatchResult
3114MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3115 bool DeleteWasArrayForm) {
3116 assert(Field != nullptr && "Analysis requires a valid class member.");
3117 this->Field = Field;
3118 IsArrayForm = DeleteWasArrayForm;
3119 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3120 for (const auto *CD : RD->ctors()) {
3121 if (hasMatchingNewInCtor(CD))
3122 return NoMismatch;
3123 }
3124 if (HasUndefinedConstructors)
3125 return EndOfTU ? NoMismatch : AnalyzeLater;
3126 if (!NewExprs.empty())
3127 return MemberInitMismatches;
3128 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3129 : NoMismatch;
3130}
3131
3132MismatchingNewDeleteDetector::MismatchResult
3133MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3134 assert(ME != nullptr && "Expected a member expression");
3135 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3136 return analyzeField(F, IsArrayForm);
3137 return NoMismatch;
3138}
3139
3140bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3141 const CXXNewExpr *NE = nullptr;
3142 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3143 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3144 NE->isArray() != IsArrayForm) {
3145 NewExprs.push_back(NE);
3146 }
3147 }
3148 return NewExprs.empty();
3149}
3150
3151static void
3152DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3153 const MismatchingNewDeleteDetector &Detector) {
3154 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3155 FixItHint H;
3156 if (!Detector.IsArrayForm)
3157 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3158 else {
3159 SourceLocation RSquare = Lexer::findLocationAfterToken(
3160 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3161 SemaRef.getLangOpts(), true);
3162 if (RSquare.isValid())
3163 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3164 }
3165 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3166 << Detector.IsArrayForm << H;
3167
3168 for (const auto *NE : Detector.NewExprs)
3169 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3170 << Detector.IsArrayForm;
3171}
3172
3173void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3174 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3175 return;
3176 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3177 switch (Detector.analyzeDeleteExpr(DE)) {
3178 case MismatchingNewDeleteDetector::VarInitMismatches:
3179 case MismatchingNewDeleteDetector::MemberInitMismatches: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003180 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003181 break;
3182 }
3183 case MismatchingNewDeleteDetector::AnalyzeLater: {
3184 DeleteExprs[Detector.Field].push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003185 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003186 break;
3187 }
3188 case MismatchingNewDeleteDetector::NoMismatch:
3189 break;
3190 }
3191}
3192
3193void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3194 bool DeleteWasArrayForm) {
3195 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3196 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3197 case MismatchingNewDeleteDetector::VarInitMismatches:
3198 llvm_unreachable("This analysis should have been done for class members.");
3199 case MismatchingNewDeleteDetector::AnalyzeLater:
3200 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3201 "translation unit.");
3202 case MismatchingNewDeleteDetector::MemberInitMismatches:
3203 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3204 break;
3205 case MismatchingNewDeleteDetector::NoMismatch:
3206 break;
3207 }
3208}
3209
Sebastian Redlbd150f42008-11-21 19:14:01 +00003210/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3211/// @code ::delete ptr; @endcode
3212/// or
3213/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003214ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003215Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003216 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003217 // C++ [expr.delete]p1:
3218 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003219 // non-explicit conversion function to a pointer type. The result has type
3220 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003221 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003222 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3223
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003224 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003225 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003226 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003227 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003228
John Wiegley01296292011-04-08 18:41:53 +00003229 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003230 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003231 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003232 if (Ex.isInvalid())
3233 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003234
John Wiegley01296292011-04-08 18:41:53 +00003235 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003236
Richard Smithccc11812013-05-21 19:05:48 +00003237 class DeleteConverter : public ContextualImplicitConverter {
3238 public:
3239 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003240
Craig Toppere14c0f82014-03-12 04:55:44 +00003241 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003242 // FIXME: If we have an operator T* and an operator void*, we must pick
3243 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003244 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003245 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003246 return true;
3247 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003248 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003249
Richard Smithccc11812013-05-21 19:05:48 +00003250 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003251 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003252 return S.Diag(Loc, diag::err_delete_operand) << T;
3253 }
3254
3255 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003256 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003257 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3258 }
3259
3260 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003261 QualType T,
3262 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003263 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3264 }
3265
3266 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003267 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003268 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3269 << ConvTy;
3270 }
3271
3272 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003273 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003274 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3275 }
3276
3277 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003278 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003279 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3280 << ConvTy;
3281 }
3282
3283 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003284 QualType T,
3285 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003286 llvm_unreachable("conversion functions are permitted");
3287 }
3288 } Converter;
3289
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003290 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003291 if (Ex.isInvalid())
3292 return ExprError();
3293 Type = Ex.get()->getType();
3294 if (!Converter.match(Type))
3295 // FIXME: PerformContextualImplicitConversion should return ExprError
3296 // itself in this case.
3297 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003298
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003299 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003300 QualType PointeeElem = Context.getBaseElementType(Pointee);
3301
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003302 if (Pointee.getAddressSpace() != LangAS::Default &&
3303 !getLangOpts().OpenCLCPlusPlus)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003304 return Diag(Ex.get()->getBeginLoc(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003305 diag::err_address_space_qualified_delete)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003306 << Pointee.getUnqualifiedType()
3307 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003308
Craig Topperc3ec1492014-05-26 06:22:03 +00003309 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003310 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003311 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003312 // effectively bans deletion of "void*". However, most compilers support
3313 // this, so we treat it as a warning unless we're in a SFINAE context.
3314 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003315 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003316 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003317 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003318 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003319 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003320 // FIXME: This can result in errors if the definition was imported from a
3321 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003322 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003323 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003324 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3325 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3326 }
3327 }
3328
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003329 if (Pointee->isArrayType() && !ArrayForm) {
3330 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003331 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003332 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003333 ArrayForm = true;
3334 }
3335
Anders Carlssona471db02009-08-16 20:29:29 +00003336 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3337 ArrayForm ? OO_Array_Delete : OO_Delete);
3338
Eli Friedmanae4280f2011-07-26 22:25:31 +00003339 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003340 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003341 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3342 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003343 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003344
John McCall284c48f2011-01-27 09:37:56 +00003345 // If we're allocating an array of records, check whether the
3346 // usual operator delete[] has a size_t parameter.
3347 if (ArrayForm) {
3348 // If the user specifically asked to use the global allocator,
3349 // we'll need to do the lookup into the class.
3350 if (UseGlobal)
3351 UsualArrayDeleteWantsSize =
3352 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3353
3354 // Otherwise, the usual operator delete[] should be the
3355 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003356 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003357 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003358 UsualDeallocFnInfo(*this,
3359 DeclAccessPair::make(OperatorDelete, AS_public))
3360 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003361 }
3362
Richard Smitheec915d62012-02-18 04:13:32 +00003363 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003364 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003365 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003366 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003367 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3368 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003369 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003370
Nico Weber5a9259c2016-01-15 21:45:31 +00003371 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3372 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3373 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3374 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003375 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376
Richard Smithb2f0f052016-10-10 18:54:32 +00003377 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003378 if (getLangOpts().OpenCLCPlusPlus) {
3379 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3380 return ExprError();
3381 }
3382
Richard Smithb2f0f052016-10-10 18:54:32 +00003383 bool IsComplete = isCompleteType(StartLoc, Pointee);
3384 bool CanProvideSize =
3385 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3386 Pointee.isDestructedType());
3387 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3388
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003389 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003390 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3391 Overaligned, DeleteName);
3392 }
Mike Stump11289f42009-09-09 15:08:12 +00003393
Eli Friedmanfa0df832012-02-02 03:46:19 +00003394 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003395
Richard Smith5b349582017-10-13 01:55:36 +00003396 // Check access and ambiguity of destructor if we're going to call it.
3397 // Note that this is required even for a virtual delete.
3398 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003399 if (PointeeRD) {
3400 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003401 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3402 PDiag(diag::err_access_dtor) << PointeeElem);
3403 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003404 }
3405 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003406
Akira Hatanaka71645c22018-12-21 07:05:36 +00003407 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
Richard Smith5b349582017-10-13 01:55:36 +00003408
3409 // Convert the operand to the type of the first parameter of operator
3410 // delete. This is only necessary if we selected a destroying operator
3411 // delete that we are going to call (non-virtually); converting to void*
3412 // is trivial and left to AST consumers to handle.
3413 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3414 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003415 Qualifiers Qs = Pointee.getQualifiers();
3416 if (Qs.hasCVRQualifiers()) {
3417 // Qualifiers are irrelevant to this conversion; we're only looking
3418 // for access and ambiguity.
3419 Qs.removeCVRQualifiers();
3420 QualType Unqual = Context.getPointerType(
3421 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3422 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3423 }
Richard Smith5b349582017-10-13 01:55:36 +00003424 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3425 if (Ex.isInvalid())
3426 return ExprError();
3427 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003428 }
3429
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003430 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003431 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3432 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003433 AnalyzeDeleteExprMismatch(Result);
3434 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003435}
3436
Eric Fiselierfa752f22018-03-21 19:19:48 +00003437static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3438 bool IsDelete,
3439 FunctionDecl *&Operator) {
3440
3441 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3442 IsDelete ? OO_Delete : OO_New);
3443
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003444 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003445 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3446 assert(!R.empty() && "implicitly declared allocation functions not found");
3447 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3448
3449 // We do our own custom access checks below.
3450 R.suppressDiagnostics();
3451
3452 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3453 OverloadCandidateSet Candidates(R.getNameLoc(),
3454 OverloadCandidateSet::CSK_Normal);
3455 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3456 FnOvl != FnOvlEnd; ++FnOvl) {
3457 // Even member operator new/delete are implicitly treated as
3458 // static, so don't use AddMemberCandidate.
3459 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3460
3461 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3462 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3463 /*ExplicitTemplateArgs=*/nullptr, Args,
3464 Candidates,
3465 /*SuppressUserConversions=*/false);
3466 continue;
3467 }
3468
3469 FunctionDecl *Fn = cast<FunctionDecl>(D);
3470 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3471 /*SuppressUserConversions=*/false);
3472 }
3473
3474 SourceRange Range = TheCall->getSourceRange();
3475
3476 // Do the resolution.
3477 OverloadCandidateSet::iterator Best;
3478 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3479 case OR_Success: {
3480 // Got one!
3481 FunctionDecl *FnDecl = Best->Function;
3482 assert(R.getNamingClass() == nullptr &&
3483 "class members should not be considered");
3484
3485 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3486 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3487 << (IsDelete ? 1 : 0) << Range;
3488 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3489 << R.getLookupName() << FnDecl->getSourceRange();
3490 return true;
3491 }
3492
3493 Operator = FnDecl;
3494 return false;
3495 }
3496
3497 case OR_No_Viable_Function:
David Blaikie5e328052019-05-03 00:44:50 +00003498 Candidates.NoteCandidates(
3499 PartialDiagnosticAt(R.getNameLoc(),
3500 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3501 << R.getLookupName() << Range),
3502 S, OCD_AllCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003503 return true;
3504
3505 case OR_Ambiguous:
David Blaikie5e328052019-05-03 00:44:50 +00003506 Candidates.NoteCandidates(
3507 PartialDiagnosticAt(R.getNameLoc(),
3508 S.PDiag(diag::err_ovl_ambiguous_call)
3509 << R.getLookupName() << Range),
3510 S, OCD_ViableCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003511 return true;
3512
3513 case OR_Deleted: {
David Blaikie5e328052019-05-03 00:44:50 +00003514 Candidates.NoteCandidates(
3515 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3516 << R.getLookupName() << Range),
3517 S, OCD_AllCandidates, Args);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003518 return true;
3519 }
3520 }
3521 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3522}
3523
3524ExprResult
3525Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3526 bool IsDelete) {
3527 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3528 if (!getLangOpts().CPlusPlus) {
3529 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3530 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3531 << "C++";
3532 return ExprError();
3533 }
3534 // CodeGen assumes it can find the global new and delete to call,
3535 // so ensure that they are declared.
3536 DeclareGlobalNewDelete();
3537
3538 FunctionDecl *OperatorNewOrDelete = nullptr;
3539 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3540 OperatorNewOrDelete))
3541 return ExprError();
3542 assert(OperatorNewOrDelete && "should be found");
3543
Akira Hatanaka71645c22018-12-21 07:05:36 +00003544 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3545 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3546
Eric Fiselierfa752f22018-03-21 19:19:48 +00003547 TheCall->setType(OperatorNewOrDelete->getReturnType());
3548 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3549 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3550 InitializedEntity Entity =
3551 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3552 ExprResult Arg = PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003553 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
Eric Fiselierfa752f22018-03-21 19:19:48 +00003554 if (Arg.isInvalid())
3555 return ExprError();
3556 TheCall->setArg(i, Arg.get());
3557 }
3558 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3559 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3560 "Callee expected to be implicit cast to a builtin function pointer");
3561 Callee->setType(OperatorNewOrDelete->getType());
3562
3563 return TheCallResult;
3564}
3565
Nico Weber5a9259c2016-01-15 21:45:31 +00003566void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3567 bool IsDelete, bool CallCanBeVirtual,
3568 bool WarnOnNonAbstractTypes,
3569 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003570 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003571 return;
3572
3573 // C++ [expr.delete]p3:
3574 // In the first alternative (delete object), if the static type of the
3575 // object to be deleted is different from its dynamic type, the static
3576 // type shall be a base class of the dynamic type of the object to be
3577 // deleted and the static type shall have a virtual destructor or the
3578 // behavior is undefined.
3579 //
3580 const CXXRecordDecl *PointeeRD = dtor->getParent();
3581 // Note: a final class cannot be derived from, no issue there
3582 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3583 return;
3584
Nico Weberbf2260c2017-08-31 06:17:08 +00003585 // If the superclass is in a system header, there's nothing that can be done.
3586 // The `delete` (where we emit the warning) can be in a system header,
3587 // what matters for this warning is where the deleted type is defined.
3588 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3589 return;
3590
Brian Gesiak5488ab42019-01-11 01:54:53 +00003591 QualType ClassType = dtor->getThisType()->getPointeeType();
Nico Weber5a9259c2016-01-15 21:45:31 +00003592 if (PointeeRD->isAbstract()) {
3593 // If the class is abstract, we warn by default, because we're
3594 // sure the code has undefined behavior.
3595 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3596 << ClassType;
3597 } else if (WarnOnNonAbstractTypes) {
3598 // Otherwise, if this is not an array delete, it's a bit suspect,
3599 // but not necessarily wrong.
3600 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3601 << ClassType;
3602 }
3603 if (!IsDelete) {
3604 std::string TypeStr;
3605 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3606 Diag(DtorLoc, diag::note_delete_non_virtual)
3607 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3608 }
3609}
3610
Richard Smith03a4aa32016-06-23 19:02:52 +00003611Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3612 SourceLocation StmtLoc,
3613 ConditionKind CK) {
3614 ExprResult E =
3615 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3616 if (E.isInvalid())
3617 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003618 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3619 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003620}
3621
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003622/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003623/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003624ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003625 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003626 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003627 if (ConditionVar->isInvalidDecl())
3628 return ExprError();
3629
Douglas Gregor633caca2009-11-23 23:44:04 +00003630 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631
Douglas Gregor633caca2009-11-23 23:44:04 +00003632 // C++ [stmt.select]p2:
3633 // The declarator shall not specify a function or an array.
3634 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003635 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003636 diag::err_invalid_use_of_function_type)
3637 << ConditionVar->getSourceRange());
3638 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003640 diag::err_invalid_use_of_array_type)
3641 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003642
Richard Smith7dcd7332019-06-04 18:30:46 +00003643 ExprResult Condition = BuildDeclRefExpr(
3644 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3645 ConditionVar->getLocation());
Eli Friedman2dfa7932012-01-16 21:00:51 +00003646
Richard Smith03a4aa32016-06-23 19:02:52 +00003647 switch (CK) {
3648 case ConditionKind::Boolean:
3649 return CheckBooleanCondition(StmtLoc, Condition.get());
3650
Richard Smithb130fe72016-06-23 19:16:49 +00003651 case ConditionKind::ConstexprIf:
3652 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3653
Richard Smith03a4aa32016-06-23 19:02:52 +00003654 case ConditionKind::Switch:
3655 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003657
Richard Smith03a4aa32016-06-23 19:02:52 +00003658 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003659}
3660
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003661/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003662ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003663 // C++ 6.4p4:
3664 // The value of a condition that is an initialized declaration in a statement
3665 // other than a switch statement is the value of the declared variable
3666 // implicitly converted to type bool. If that conversion is ill-formed, the
3667 // program is ill-formed.
3668 // The value of a condition that is an expression is the value of the
3669 // expression, implicitly converted to bool.
3670 //
Richard Smithb130fe72016-06-23 19:16:49 +00003671 // FIXME: Return this value to the caller so they don't need to recompute it.
3672 llvm::APSInt Value(/*BitWidth*/1);
3673 return (IsConstexpr && !CondExpr->isValueDependent())
3674 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3675 CCEK_ConstexprIf)
3676 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003677}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003678
3679/// Helper function to determine whether this is the (deprecated) C++
3680/// conversion from a string literal to a pointer to non-const char or
3681/// non-const wchar_t (for narrow and wide string literals,
3682/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003683bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003684Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3685 // Look inside the implicit cast, if it exists.
3686 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3687 From = Cast->getSubExpr();
3688
3689 // A string literal (2.13.4) that is not a wide string literal can
3690 // be converted to an rvalue of type "pointer to char"; a wide
3691 // string literal can be converted to an rvalue of type "pointer
3692 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003693 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003694 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003695 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003696 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003697 // This conversion is considered only when there is an
3698 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003699 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3700 switch (StrLit->getKind()) {
3701 case StringLiteral::UTF8:
3702 case StringLiteral::UTF16:
3703 case StringLiteral::UTF32:
3704 // We don't allow UTF literals to be implicitly converted
3705 break;
3706 case StringLiteral::Ascii:
3707 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3708 ToPointeeType->getKind() == BuiltinType::Char_S);
3709 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003710 return Context.typesAreCompatible(Context.getWideCharType(),
3711 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003712 }
3713 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003714 }
3715
3716 return false;
3717}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003718
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003720 SourceLocation CastLoc,
3721 QualType Ty,
3722 CastKind Kind,
3723 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003724 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003725 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003726 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003727 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003728 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003729 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003730 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003731 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732
Richard Smith72d74052013-07-20 19:41:36 +00003733 if (S.RequireNonAbstractType(CastLoc, Ty,
3734 diag::err_allocation_of_abstract_type))
3735 return ExprError();
3736
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003737 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003738 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003739
Richard Smith5179eb72016-06-28 19:03:57 +00003740 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3741 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003742 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003743 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003744
Richard Smithf8adcdc2014-07-17 05:12:35 +00003745 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003746 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003747 ConstructorArgs, HadMultipleCandidates,
3748 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3749 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003750 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003751 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003753 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
John McCalle3027922010-08-25 11:45:40 +00003756 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003757 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758
Richard Smithd3f2d322015-02-24 21:16:19 +00003759 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003760 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003761 return ExprError();
3762
Douglas Gregora4253922010-04-16 22:17:36 +00003763 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003764 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3765 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003766 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003767 if (Result.isInvalid())
3768 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003769 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003770 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3771 CK_UserDefinedConversion, Result.get(),
3772 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773
Douglas Gregor668443e2011-01-20 00:18:04 +00003774 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003775 }
3776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777}
Douglas Gregora4253922010-04-16 22:17:36 +00003778
Douglas Gregor5fb53972009-01-14 15:45:31 +00003779/// PerformImplicitConversion - Perform an implicit conversion of the
3780/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003781/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003782/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003783/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003784ExprResult
3785Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003786 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003787 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003788 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003789 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3790 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3791 return From;
3792
John McCall0d1da222010-01-12 00:44:57 +00003793 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003794 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003795 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3796 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003797 if (Res.isInvalid())
3798 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003799 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003800 break;
John Wiegley01296292011-04-08 18:41:53 +00003801 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003802
Anders Carlsson110b07b2009-09-15 06:28:28 +00003803 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003804
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003805 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003806 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003807 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003808 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003809 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003810 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003811
Anders Carlsson110b07b2009-09-15 06:28:28 +00003812 // If the user-defined conversion is specified by a conversion function,
3813 // the initial standard conversion sequence converts the source type to
3814 // the implicit object parameter of the conversion function.
3815 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003816 } else {
3817 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003818 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003819 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003820 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003821 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003822 // initial standard conversion sequence converts the source type to
3823 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003824 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3825 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003826 }
Richard Smith72d74052013-07-20 19:41:36 +00003827 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003828 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003829 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003830 PerformImplicitConversion(From, BeforeToType,
3831 ICS.UserDefined.Before, AA_Converting,
3832 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003833 if (Res.isInvalid())
3834 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003835 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003837
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003838 ExprResult CastArg = BuildCXXCastArgument(
3839 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3840 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3841 ICS.UserDefined.HadMultipleCandidates, From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003842
3843 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003844 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003845
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003846 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003847
Richard Smith1ef75542018-06-27 20:30:34 +00003848 // C++ [over.match.oper]p7:
3849 // [...] the second standard conversion sequence of a user-defined
3850 // conversion sequence is not applied.
3851 if (CCK == CCK_ForBuiltinOverloadedOp)
3852 return From;
3853
Richard Smith507840d2011-11-29 22:48:16 +00003854 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3855 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003856 }
John McCall0d1da222010-01-12 00:44:57 +00003857
3858 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003859 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003860 PDiag(diag::err_typecheck_ambiguous_condition)
3861 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003862 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863
Douglas Gregor39c16d42008-10-24 04:54:22 +00003864 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003865 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003866
3867 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003868 bool Diagnosed =
3869 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3870 From->getType(), From, Action);
3871 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003872 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003873 }
3874
3875 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003876 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003877}
3878
Richard Smith507840d2011-11-29 22:48:16 +00003879/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003880/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003881/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003882/// expression. Flavor is the context in which we're performing this
3883/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003884ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003885Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003886 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003887 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003888 CheckedConversionKind CCK) {
3889 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003890
Mike Stump87c57ac2009-05-16 07:39:55 +00003891 // Overall FIXME: we are recomputing too many types here and doing far too
3892 // much extra work. What this means is that we need to keep track of more
3893 // information that is computed when we try the implicit conversion initially,
3894 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003895 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003896
Douglas Gregor2fe98832008-11-03 19:09:14 +00003897 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003898 // FIXME: When can ToType be a reference type?
3899 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003900 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003901 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003902 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003903 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003904 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003905 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003906 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003907 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3908 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003909 ConstructorArgs, /*HadMultipleCandidates*/ false,
3910 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3911 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003912 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003913 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003914 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3915 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003916 From, /*HadMultipleCandidates*/ false,
3917 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3918 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003919 }
3920
Douglas Gregor980fb162010-04-29 18:24:40 +00003921 // Resolve overloaded function references.
3922 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3923 DeclAccessPair Found;
3924 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3925 true, Found);
3926 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003927 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003928
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003929 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00003930 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931
Douglas Gregor980fb162010-04-29 18:24:40 +00003932 From = FixOverloadedFunctionReference(From, Found, Fn);
3933 FromType = From->getType();
3934 }
3935
Richard Smitha23ab512013-05-23 00:30:41 +00003936 // If we're converting to an atomic type, first convert to the corresponding
3937 // non-atomic type.
3938 QualType ToAtomicType;
3939 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3940 ToAtomicType = ToType;
3941 ToType = ToAtomic->getValueType();
3942 }
3943
George Burgess IV8d141e02015-12-14 22:00:49 +00003944 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003945 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003946 switch (SCS.First) {
3947 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003948 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3949 FromType = FromAtomic->getValueType().getUnqualifiedType();
3950 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3951 From, /*BasePath=*/nullptr, VK_RValue);
3952 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003953 break;
3954
Eli Friedman946b7b52012-01-24 22:51:26 +00003955 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003956 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003957 ExprResult FromRes = DefaultLvalueConversion(From);
3958 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003959 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003960 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003961 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003962 }
John McCall34376a62010-12-04 03:47:34 +00003963
Douglas Gregor39c16d42008-10-24 04:54:22 +00003964 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003965 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003966 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003967 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003968 break;
3969
3970 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003971 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003972 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003973 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003974 break;
3975
3976 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003977 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003978 }
3979
Richard Smith507840d2011-11-29 22:48:16 +00003980 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003981 switch (SCS.Second) {
3982 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003983 // C++ [except.spec]p5:
3984 // [For] assignment to and initialization of pointers to functions,
3985 // pointers to member functions, and references to functions: the
3986 // target entity shall allow at least the exceptions allowed by the
3987 // source value in the assignment or initialization.
3988 switch (Action) {
3989 case AA_Assigning:
3990 case AA_Initializing:
3991 // Note, function argument passing and returning are initialization.
3992 case AA_Passing:
3993 case AA_Returning:
3994 case AA_Sending:
3995 case AA_Passing_CFAudited:
3996 if (CheckExceptionSpecCompatibility(From, ToType))
3997 return ExprError();
3998 break;
3999
4000 case AA_Casting:
4001 case AA_Converting:
4002 // Casts and implicit conversions are not initialization, so are not
4003 // checked for exception specification mismatches.
4004 break;
4005 }
Sebastian Redl5d431642009-10-10 12:04:10 +00004006 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004007 break;
4008
4009 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004010 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00004011 if (ToType->isBooleanType()) {
4012 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4013 SCS.Second == ICK_Integral_Promotion &&
4014 "only enums with fixed underlying type can promote to bool");
4015 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004016 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004017 } else {
4018 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004019 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004020 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004021 break;
4022
4023 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004024 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004025 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004026 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004027 break;
4028
4029 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004030 case ICK_Complex_Conversion: {
4031 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4032 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4033 CastKind CK;
4034 if (FromEl->isRealFloatingType()) {
4035 if (ToEl->isRealFloatingType())
4036 CK = CK_FloatingComplexCast;
4037 else
4038 CK = CK_FloatingComplexToIntegralComplex;
4039 } else if (ToEl->isRealFloatingType()) {
4040 CK = CK_IntegralComplexToFloatingComplex;
4041 } else {
4042 CK = CK_IntegralComplexCast;
4043 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004044 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004045 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004046 break;
John McCall8cb679e2010-11-15 09:13:47 +00004047 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004048
Douglas Gregor39c16d42008-10-24 04:54:22 +00004049 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004050 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004051 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004052 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004053 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004054 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004055 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004056 break;
4057
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004058 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004059 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004060 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004061 break;
4062
John McCall31168b02011-06-15 23:02:42 +00004063 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004064 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004065 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004066 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004067 if (Action == AA_Initializing || Action == AA_Assigning)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004068 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004069 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004070 << ToType << From->getType() << Action << From->getSourceRange()
4071 << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004072 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004073 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004074 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004075 << From->getType() << ToType << Action << From->getSourceRange()
4076 << 0;
John McCall31168b02011-06-15 23:02:42 +00004077
Douglas Gregor33823722011-06-11 01:09:30 +00004078 if (From->getType()->isObjCObjectPointerType() &&
4079 ToType->isObjCObjectPointerType())
4080 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004081 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4082 !CheckObjCARCUnavailableWeakConversion(ToType,
4083 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004084 if (Action == AA_Initializing)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004085 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
John McCall9c3467e2011-09-09 06:12:06 +00004086 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004087 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4088 << (Action == AA_Casting) << From->getType() << ToType
4089 << From->getSourceRange();
John McCall9c3467e2011-09-09 06:12:06 +00004090 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004091
Richard Smith354abec2017-12-08 23:29:59 +00004092 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004093 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004094 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004095 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004096
4097 // Make sure we extend blocks if necessary.
4098 // FIXME: doing this here is really ugly.
4099 if (Kind == CK_BlockPointerToObjCPointerCast) {
4100 ExprResult E = From;
4101 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004102 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004103 }
Brian Kelley11352a82017-03-29 18:09:02 +00004104 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4105 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004106 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004107 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004108 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004110
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004111 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004112 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004113 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004114 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004115 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004116 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004117 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004118
4119 // We may not have been able to figure out what this member pointer resolved
4120 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004121 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004122 (void)isCompleteType(From->getExprLoc(), From->getType());
4123 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004124 }
David Majnemerd96b9972014-08-08 00:10:39 +00004125
Richard Smith507840d2011-11-29 22:48:16 +00004126 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004127 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004128 break;
4129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004130
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004131 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004132 // Perform half-to-boolean conversion via float.
4133 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004134 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004135 FromType = Context.FloatTy;
4136 }
4137
Richard Smith507840d2011-11-29 22:48:16 +00004138 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004139 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004140 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004141 break;
4142
Douglas Gregor88d292c2010-05-13 16:44:06 +00004143 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004144 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004145 if (CheckDerivedToBaseConversion(
4146 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4147 From->getSourceRange(), &BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004148 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004149
Richard Smith507840d2011-11-29 22:48:16 +00004150 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4151 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004152 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004153 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004154 }
4155
Douglas Gregor46188682010-05-18 22:42:18 +00004156 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004157 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004158 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004159 break;
4160
George Burgess IVdf1ed002016-01-13 01:52:39 +00004161 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004162 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004163 Expr *Elem = prepareVectorSplat(ToType, From).get();
4164 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4165 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004166 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004167 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004168
Douglas Gregor46188682010-05-18 22:42:18 +00004169 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004170 // Case 1. x -> _Complex y
4171 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4172 QualType ElType = ToComplex->getElementType();
4173 bool isFloatingComplex = ElType->isRealFloatingType();
4174
4175 // x -> y
4176 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4177 // do nothing
4178 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004179 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004180 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004181 } else {
4182 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004183 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004184 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004185 }
4186 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004187 From = ImpCastExprToType(From, ToType,
4188 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004189 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004190
4191 // Case 2. _Complex x -> y
4192 } else {
4193 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4194 assert(FromComplex);
4195
4196 QualType ElType = FromComplex->getElementType();
4197 bool isFloatingComplex = ElType->isRealFloatingType();
4198
4199 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004200 From = ImpCastExprToType(From, ElType,
4201 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004202 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004203 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004204
4205 // x -> y
4206 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4207 // do nothing
4208 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004209 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004210 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004211 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004212 } else {
4213 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004214 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004215 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004216 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004217 }
4218 }
Douglas Gregor46188682010-05-18 22:42:18 +00004219 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004220
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004221 case ICK_Block_Pointer_Conversion: {
Marco Antogninid36e1302019-07-09 15:04:27 +00004222 LangAS AddrSpaceL =
Marco Antognini9eb95902019-07-17 08:52:09 +00004223 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
Marco Antogninid36e1302019-07-09 15:04:27 +00004224 LangAS AddrSpaceR =
Marco Antognini9eb95902019-07-17 08:52:09 +00004225 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4226 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4227 "Invalid cast");
Marco Antogninid36e1302019-07-09 15:04:27 +00004228 CastKind Kind =
4229 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4230 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004231 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004232 break;
4233 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004234
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004235 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004236 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004237 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004238 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4239 if (FromRes.isInvalid())
4240 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004241 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004242 assert ((ConvTy == Sema::Compatible) &&
4243 "Improper transparent union conversion");
4244 (void)ConvTy;
4245 break;
4246 }
4247
Guy Benyei259f9f42013-02-07 16:05:33 +00004248 case ICK_Zero_Event_Conversion:
Egor Churaev89831422016-12-23 14:55:49 +00004249 case ICK_Zero_Queue_Conversion:
4250 From = ImpCastExprToType(From, ToType,
Andrew Savonichevb555b762018-10-23 15:19:20 +00004251 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00004252 From->getValueKind()).get();
4253 break;
4254
Douglas Gregor46188682010-05-18 22:42:18 +00004255 case ICK_Lvalue_To_Rvalue:
4256 case ICK_Array_To_Pointer:
4257 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004258 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004259 case ICK_Qualification:
4260 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004261 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004262 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004263 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004264 }
4265
4266 switch (SCS.Third) {
4267 case ICK_Identity:
4268 // Nothing to do.
4269 break;
4270
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004271 case ICK_Function_Conversion:
4272 // If both sides are functions (or pointers/references to them), there could
4273 // be incompatible exception declarations.
4274 if (CheckExceptionSpecCompatibility(From, ToType))
4275 return ExprError();
4276
4277 From = ImpCastExprToType(From, ToType, CK_NoOp,
4278 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4279 break;
4280
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004281 case ICK_Qualification: {
4282 // The qualification keeps the category of the inner expression, unless the
4283 // target type isn't a reference.
Anastasia Stulova04307942018-11-16 16:22:56 +00004284 ExprValueKind VK =
4285 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4286
4287 CastKind CK = CK_NoOp;
4288
4289 if (ToType->isReferenceType() &&
4290 ToType->getPointeeType().getAddressSpace() !=
4291 From->getType().getAddressSpace())
4292 CK = CK_AddressSpaceConversion;
4293
4294 if (ToType->isPointerType() &&
4295 ToType->getPointeeType().getAddressSpace() !=
4296 From->getType()->getPointeeType().getAddressSpace())
4297 CK = CK_AddressSpaceConversion;
4298
4299 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4300 /*BasePath=*/nullptr, CCK)
4301 .get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004302
Douglas Gregore981bb02011-03-14 16:13:32 +00004303 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004304 !getLangOpts().WritableStrings) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004305 Diag(From->getBeginLoc(),
4306 getLangOpts().CPlusPlus11
4307 ? diag::ext_deprecated_string_literal_conversion
4308 : diag::warn_deprecated_string_literal_conversion)
4309 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004310 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004311
Douglas Gregor39c16d42008-10-24 04:54:22 +00004312 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004313 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004314
Douglas Gregor39c16d42008-10-24 04:54:22 +00004315 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004316 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004317 }
4318
Douglas Gregor298f43d2012-04-12 20:42:30 +00004319 // If this conversion sequence involved a scalar -> atomic conversion, perform
4320 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004321 if (!ToAtomicType.isNull()) {
4322 assert(Context.hasSameType(
4323 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4324 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004325 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004326 }
4327
George Burgess IV8d141e02015-12-14 22:00:49 +00004328 // If this conversion sequence succeeded and involved implicitly converting a
4329 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004330 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004331 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004332 From->getBeginLoc());
George Burgess IV8d141e02015-12-14 22:00:49 +00004333
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004334 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004335}
4336
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004337/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004338///
4339/// If the particular type trait requires a complete type, tries to complete
4340/// it. If completing the type fails, a diagnostic is emitted and false
4341/// returned. If completing the type succeeds or no completion was required,
4342/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004343static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004344 SourceLocation Loc,
4345 QualType ArgTy) {
4346 // C++0x [meta.unary.prop]p3:
4347 // For all of the class templates X declared in this Clause, instantiating
4348 // that template with a template argument that is a class template
4349 // specialization may result in the implicit instantiation of the template
4350 // argument if and only if the semantics of X require that the argument
4351 // must be a complete type.
4352 // We apply this rule to all the type trait expressions used to implement
4353 // these class templates. We also try to follow any GCC documented behavior
4354 // in these expressions to ensure portability of standard libraries.
4355 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004356 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004357 // is_complete_type somewhat obviously cannot require a complete type.
4358 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004359 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004360
4361 // These traits are modeled on the type predicates in C++0x
4362 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4363 // requiring a complete type, as whether or not they return true cannot be
4364 // impacted by the completeness of the type.
4365 case UTT_IsVoid:
4366 case UTT_IsIntegral:
4367 case UTT_IsFloatingPoint:
4368 case UTT_IsArray:
4369 case UTT_IsPointer:
4370 case UTT_IsLvalueReference:
4371 case UTT_IsRvalueReference:
4372 case UTT_IsMemberFunctionPointer:
4373 case UTT_IsMemberObjectPointer:
4374 case UTT_IsEnum:
4375 case UTT_IsUnion:
4376 case UTT_IsClass:
4377 case UTT_IsFunction:
4378 case UTT_IsReference:
4379 case UTT_IsArithmetic:
4380 case UTT_IsFundamental:
4381 case UTT_IsObject:
4382 case UTT_IsScalar:
4383 case UTT_IsCompound:
4384 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004385 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004386
4387 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4388 // which requires some of its traits to have the complete type. However,
4389 // the completeness of the type cannot impact these traits' semantics, and
4390 // so they don't require it. This matches the comments on these traits in
4391 // Table 49.
4392 case UTT_IsConst:
4393 case UTT_IsVolatile:
4394 case UTT_IsSigned:
4395 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004396
4397 // This type trait always returns false, checking the type is moot.
4398 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004399 return true;
4400
David Majnemer213bea32015-11-16 06:58:51 +00004401 // C++14 [meta.unary.prop]:
4402 // If T is a non-union class type, T shall be a complete type.
4403 case UTT_IsEmpty:
4404 case UTT_IsPolymorphic:
4405 case UTT_IsAbstract:
4406 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4407 if (!RD->isUnion())
4408 return !S.RequireCompleteType(
4409 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4410 return true;
4411
4412 // C++14 [meta.unary.prop]:
4413 // If T is a class type, T shall be a complete type.
4414 case UTT_IsFinal:
4415 case UTT_IsSealed:
4416 if (ArgTy->getAsCXXRecordDecl())
4417 return !S.RequireCompleteType(
4418 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4419 return true;
4420
Richard Smithf03e9082017-06-01 00:28:16 +00004421 // C++1z [meta.unary.prop]:
4422 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004423 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004424 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004425 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004426 case UTT_IsStandardLayout:
4427 case UTT_IsPOD:
4428 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004429 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4430 // or an array of unknown bound. But GCC actually imposes the same constraints
4431 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004432 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004433 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004434 case UTT_HasNothrowConstructor:
4435 case UTT_HasNothrowCopy:
4436 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004437 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004438 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004439 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004440 case UTT_HasTrivialCopy:
4441 case UTT_HasTrivialDestructor:
4442 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004443 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4444 LLVM_FALLTHROUGH;
4445
4446 // C++1z [meta.unary.prop]:
4447 // T shall be a complete type, cv void, or an array of unknown bound.
4448 case UTT_IsDestructible:
4449 case UTT_IsNothrowDestructible:
4450 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004451 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004452 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004453 return true;
4454
4455 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004456 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004457 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004458}
4459
Joao Matosc9523d42013-03-27 01:34:16 +00004460static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4461 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004462 bool (CXXRecordDecl::*HasTrivial)() const,
4463 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004464 bool (CXXMethodDecl::*IsDesiredOp)() const)
4465{
4466 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4467 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4468 return true;
4469
4470 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4471 DeclarationNameInfo NameInfo(Name, KeyLoc);
4472 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4473 if (Self.LookupQualifiedName(Res, RD)) {
4474 bool FoundOperator = false;
4475 Res.suppressDiagnostics();
4476 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4477 Op != OpEnd; ++Op) {
4478 if (isa<FunctionTemplateDecl>(*Op))
4479 continue;
4480
4481 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4482 if((Operator->*IsDesiredOp)()) {
4483 FoundOperator = true;
4484 const FunctionProtoType *CPT =
4485 Operator->getType()->getAs<FunctionProtoType>();
4486 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004487 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004488 return false;
4489 }
4490 }
4491 return FoundOperator;
4492 }
4493 return false;
4494}
4495
Alp Toker95e7ff22014-01-01 05:57:51 +00004496static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004497 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004498 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004499
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004500 ASTContext &C = Self.Context;
4501 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004502 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004503 // Type trait expressions corresponding to the primary type category
4504 // predicates in C++0x [meta.unary.cat].
4505 case UTT_IsVoid:
4506 return T->isVoidType();
4507 case UTT_IsIntegral:
4508 return T->isIntegralType(C);
4509 case UTT_IsFloatingPoint:
4510 return T->isFloatingType();
4511 case UTT_IsArray:
4512 return T->isArrayType();
4513 case UTT_IsPointer:
4514 return T->isPointerType();
4515 case UTT_IsLvalueReference:
4516 return T->isLValueReferenceType();
4517 case UTT_IsRvalueReference:
4518 return T->isRValueReferenceType();
4519 case UTT_IsMemberFunctionPointer:
4520 return T->isMemberFunctionPointerType();
4521 case UTT_IsMemberObjectPointer:
4522 return T->isMemberDataPointerType();
4523 case UTT_IsEnum:
4524 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004525 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004526 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004527 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004528 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004529 case UTT_IsFunction:
4530 return T->isFunctionType();
4531
4532 // Type trait expressions which correspond to the convenient composition
4533 // predicates in C++0x [meta.unary.comp].
4534 case UTT_IsReference:
4535 return T->isReferenceType();
4536 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004537 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004538 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004539 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004540 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004541 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004542 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004543 // Note: semantic analysis depends on Objective-C lifetime types to be
4544 // considered scalar types. However, such types do not actually behave
4545 // like scalar types at run time (since they may require retain/release
4546 // operations), so we report them as non-scalar.
4547 if (T->isObjCLifetimeType()) {
4548 switch (T.getObjCLifetime()) {
4549 case Qualifiers::OCL_None:
4550 case Qualifiers::OCL_ExplicitNone:
4551 return true;
4552
4553 case Qualifiers::OCL_Strong:
4554 case Qualifiers::OCL_Weak:
4555 case Qualifiers::OCL_Autoreleasing:
4556 return false;
4557 }
4558 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004559
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004560 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004561 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004562 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004563 case UTT_IsMemberPointer:
4564 return T->isMemberPointerType();
4565
4566 // Type trait expressions which correspond to the type property predicates
4567 // in C++0x [meta.unary.prop].
4568 case UTT_IsConst:
4569 return T.isConstQualified();
4570 case UTT_IsVolatile:
4571 return T.isVolatileQualified();
4572 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004573 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004574 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004575 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004576 case UTT_IsStandardLayout:
4577 return T->isStandardLayoutType();
4578 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004579 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004580 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004581 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004582 case UTT_IsEmpty:
4583 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4584 return !RD->isUnion() && RD->isEmpty();
4585 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004586 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004587 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004588 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004589 return false;
4590 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004591 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004592 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004593 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004594 case UTT_IsAggregate:
4595 // Report vector extensions and complex types as aggregates because they
4596 // support aggregate initialization. GCC mirrors this behavior for vectors
4597 // but not _Complex.
4598 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4599 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004600 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4601 // even then only when it is used with the 'interface struct ...' syntax
4602 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004603 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004604 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004605 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004606 case UTT_IsSealed:
4607 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004608 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004609 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004610 case UTT_IsSigned:
Zoe Carver511dbd82019-09-23 15:41:20 +00004611 // Enum types should always return false.
4612 // Floating points should always return true.
4613 return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType());
John Wiegley65497cc2011-04-27 23:09:49 +00004614 case UTT_IsUnsigned:
4615 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004616
4617 // Type trait expressions which query classes regarding their construction,
4618 // destruction, and copying. Rather than being based directly on the
4619 // related type predicates in the standard, they are specified by both
4620 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4621 // specifications.
4622 //
4623 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4624 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004625 //
4626 // Note that these builtins do not behave as documented in g++: if a class
4627 // has both a trivial and a non-trivial special member of a particular kind,
4628 // they return false! For now, we emulate this behavior.
4629 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4630 // does not correctly compute triviality in the presence of multiple special
4631 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004632 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004633 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4634 // If __is_pod (type) is true then the trait is true, else if type is
4635 // a cv class or union type (or array thereof) with a trivial default
4636 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004637 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004638 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004639 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4640 return RD->hasTrivialDefaultConstructor() &&
4641 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004642 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004643 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004644 // This trait is implemented by MSVC 2012 and needed to parse the
4645 // standard library headers. Specifically this is used as the logic
4646 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004647 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004648 return true;
4649 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4650 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4651 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004652 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004653 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4654 // If __is_pod (type) is true or type is a reference type then
4655 // the trait is true, else if type is a cv class or union type
4656 // with a trivial copy constructor ([class.copy]) then the trait
4657 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004658 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004659 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004660 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4661 return RD->hasTrivialCopyConstructor() &&
4662 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004663 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004664 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004665 // This trait is implemented by MSVC 2012 and needed to parse the
4666 // standard library headers. Specifically it is used as the logic
4667 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004668 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004669 return true;
4670 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4671 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4672 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004673 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004674 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4675 // If type is const qualified or is a reference type then the
4676 // trait is false. Otherwise if __is_pod (type) is true then the
4677 // trait is true, else if type is a cv class or union type with
4678 // a trivial copy assignment ([class.copy]) then the trait is
4679 // true, else it is false.
4680 // Note: the const and reference restrictions are interesting,
4681 // given that const and reference members don't prevent a class
4682 // from having a trivial copy assignment operator (but do cause
4683 // errors if the copy assignment operator is actually used, q.v.
4684 // [class.copy]p12).
4685
Richard Smith92f241f2012-12-08 02:53:02 +00004686 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004687 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004688 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004689 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004690 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4691 return RD->hasTrivialCopyAssignment() &&
4692 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004693 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004694 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004695 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004696 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004697 // C++14 [meta.unary.prop]:
4698 // For reference types, is_destructible<T>::value is true.
4699 if (T->isReferenceType())
4700 return true;
4701
4702 // Objective-C++ ARC: autorelease types don't require destruction.
4703 if (T->isObjCLifetimeType() &&
4704 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4705 return true;
4706
4707 // C++14 [meta.unary.prop]:
4708 // For incomplete types and function types, is_destructible<T>::value is
4709 // false.
4710 if (T->isIncompleteType() || T->isFunctionType())
4711 return false;
4712
Richard Smithf03e9082017-06-01 00:28:16 +00004713 // A type that requires destruction (via a non-trivial destructor or ARC
4714 // lifetime semantics) is not trivially-destructible.
4715 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4716 return false;
4717
David Majnemerac73de92015-08-11 03:03:28 +00004718 // C++14 [meta.unary.prop]:
4719 // For object types and given U equal to remove_all_extents_t<T>, if the
4720 // expression std::declval<U&>().~U() is well-formed when treated as an
4721 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4722 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4723 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4724 if (!Destructor)
4725 return false;
4726 // C++14 [dcl.fct.def.delete]p2:
4727 // A program that refers to a deleted function implicitly or
4728 // explicitly, other than to declare it, is ill-formed.
4729 if (Destructor->isDeleted())
4730 return false;
4731 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4732 return false;
4733 if (UTT == UTT_IsNothrowDestructible) {
4734 const FunctionProtoType *CPT =
4735 Destructor->getType()->getAs<FunctionProtoType>();
4736 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004737 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004738 return false;
4739 }
4740 }
4741 return true;
4742
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004743 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004744 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004745 // If __is_pod (type) is true or type is a reference type
4746 // then the trait is true, else if type is a cv class or union
4747 // type (or array thereof) with a trivial destructor
4748 // ([class.dtor]) then the trait is true, else it is
4749 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004750 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004751 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004752
John McCall31168b02011-06-15 23:02:42 +00004753 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004754 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004755 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4756 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004757
Richard Smith92f241f2012-12-08 02:53:02 +00004758 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4759 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004760 return false;
4761 // TODO: Propagate nothrowness for implicitly declared special members.
4762 case UTT_HasNothrowAssign:
4763 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4764 // If type is const qualified or is a reference type then the
4765 // trait is false. Otherwise if __has_trivial_assign (type)
4766 // is true then the trait is true, else if type is a cv class
4767 // or union type with copy assignment operators that are known
4768 // not to throw an exception then the trait is true, else it is
4769 // false.
4770 if (C.getBaseElementType(T).isConstQualified())
4771 return false;
4772 if (T->isReferenceType())
4773 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004774 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004775 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004776
Joao Matosc9523d42013-03-27 01:34:16 +00004777 if (const RecordType *RT = T->getAs<RecordType>())
4778 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4779 &CXXRecordDecl::hasTrivialCopyAssignment,
4780 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4781 &CXXMethodDecl::isCopyAssignmentOperator);
4782 return false;
4783 case UTT_HasNothrowMoveAssign:
4784 // This trait is implemented by MSVC 2012 and needed to parse the
4785 // standard library headers. Specifically this is used as the logic
4786 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004787 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004788 return true;
4789
4790 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4791 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4792 &CXXRecordDecl::hasTrivialMoveAssignment,
4793 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4794 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004795 return false;
4796 case UTT_HasNothrowCopy:
4797 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4798 // If __has_trivial_copy (type) is true then the trait is true, else
4799 // if type is a cv class or union type with copy constructors that are
4800 // known not to throw an exception then the trait is true, else it is
4801 // false.
John McCall31168b02011-06-15 23:02:42 +00004802 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004803 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004804 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4805 if (RD->hasTrivialCopyConstructor() &&
4806 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004807 return true;
4808
4809 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004810 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004811 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004812 // A template constructor is never a copy constructor.
4813 // FIXME: However, it may actually be selected at the actual overload
4814 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004815 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004816 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004817 // UsingDecl itself is not a constructor
4818 if (isa<UsingDecl>(ND))
4819 continue;
4820 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004821 if (Constructor->isCopyConstructor(FoundTQs)) {
4822 FoundConstructor = true;
4823 const FunctionProtoType *CPT
4824 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004825 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4826 if (!CPT)
4827 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004828 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004829 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004830 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004831 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004832 }
4833 }
4834
Richard Smith938f40b2011-06-11 17:19:42 +00004835 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004836 }
4837 return false;
4838 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004839 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004840 // If __has_trivial_constructor (type) is true then the trait is
4841 // true, else if type is a cv class or union type (or array
4842 // thereof) with a default constructor that is known not to
4843 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004844 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004845 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004846 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4847 if (RD->hasTrivialDefaultConstructor() &&
4848 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004849 return true;
4850
Alp Tokerb4bca412014-01-20 00:23:47 +00004851 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004852 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004853 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004854 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004855 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004856 // UsingDecl itself is not a constructor
4857 if (isa<UsingDecl>(ND))
4858 continue;
4859 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004860 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004861 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004862 const FunctionProtoType *CPT
4863 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004864 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4865 if (!CPT)
4866 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004867 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004868 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004869 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004870 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004871 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004872 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004873 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004874 }
4875 return false;
4876 case UTT_HasVirtualDestructor:
4877 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4878 // If type is a class type with a virtual destructor ([class.dtor])
4879 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004880 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004881 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004882 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004883 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004884
4885 // These type trait expressions are modeled on the specifications for the
4886 // Embarcadero C++0x type trait functions:
4887 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4888 case UTT_IsCompleteType:
4889 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4890 // Returns True if and only if T is a complete type at the point of the
4891 // function call.
4892 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004893 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004894 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004895 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004896}
Sebastian Redl5822f082009-02-07 20:10:22 +00004897
Alp Tokercbb90342013-12-13 20:49:58 +00004898static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4899 QualType RhsT, SourceLocation KeyLoc);
4900
Douglas Gregor29c42f22012-02-24 07:38:34 +00004901static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4902 ArrayRef<TypeSourceInfo *> Args,
4903 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004904 if (Kind <= UTT_Last)
4905 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4906
Eric Fiselier1af6c112018-01-12 00:09:37 +00004907 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4908 // traits to avoid duplication.
4909 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004910 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4911 Args[1]->getType(), RParenLoc);
4912
Douglas Gregor29c42f22012-02-24 07:38:34 +00004913 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004914 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004915 case clang::TT_IsConstructible:
4916 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004917 case clang::TT_IsTriviallyConstructible: {
4918 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004919 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004920 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004921 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004922 // definition for is_constructible, as defined below, is known to call
4923 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004924 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004925 // The predicate condition for a template specialization
4926 // is_constructible<T, Args...> shall be satisfied if and only if the
4927 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004928 // variable t:
4929 //
4930 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004931 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004932
4933 // Precondition: T and all types in the parameter pack Args shall be
4934 // complete types, (possibly cv-qualified) void, or arrays of
4935 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004936 for (const auto *TSI : Args) {
4937 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004938 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004939 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004940
Simon Pilgrim75c26882016-09-30 14:25:09 +00004941 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004942 diag::err_incomplete_type_used_in_type_trait_expr))
4943 return false;
4944 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004945
David Majnemer9658ecc2015-11-13 05:32:43 +00004946 // Make sure the first argument is not incomplete nor a function type.
4947 QualType T = Args[0]->getType();
4948 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004949 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004950
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004951 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004952 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004953 if (RD && RD->isAbstract())
4954 return false;
4955
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004956 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4957 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004958 ArgExprs.reserve(Args.size() - 1);
4959 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004960 QualType ArgTy = Args[I]->getType();
4961 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4962 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004963 OpaqueArgExprs.push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004964 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
David Majnemer9658ecc2015-11-13 05:32:43 +00004965 ArgTy.getNonLValueExprType(S.Context),
4966 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004967 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004968 for (Expr &E : OpaqueArgExprs)
4969 ArgExprs.push_back(&E);
4970
Simon Pilgrim75c26882016-09-30 14:25:09 +00004971 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004972 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004973 EnterExpressionEvaluationContext Unevaluated(
4974 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004975 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4976 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4977 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4978 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4979 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004980 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004981 if (Init.Failed())
4982 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004983
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004984 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004985 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4986 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004987
Alp Toker73287bf2014-01-20 00:24:09 +00004988 if (Kind == clang::TT_IsConstructible)
4989 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004990
Eric Fiselier1af6c112018-01-12 00:09:37 +00004991 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4992 if (!T->isReferenceType())
4993 return false;
4994
4995 return !Init.isDirectReferenceBinding();
4996 }
4997
Alp Toker73287bf2014-01-20 00:24:09 +00004998 if (Kind == clang::TT_IsNothrowConstructible)
4999 return S.canThrow(Result.get()) == CT_Cannot;
5000
5001 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005002 // Under Objective-C ARC and Weak, if the destination has non-trivial
5003 // Objective-C lifetime, this is a non-trivial construction.
5004 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005005 return false;
5006
5007 // The initialization succeeded; now make sure there are no non-trivial
5008 // calls.
5009 return !Result.get()->hasNonTrivialCall(S.Context);
5010 }
5011
5012 llvm_unreachable("unhandled type trait");
5013 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005014 }
Alp Tokercbb90342013-12-13 20:49:58 +00005015 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00005016 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005017
Douglas Gregor29c42f22012-02-24 07:38:34 +00005018 return false;
5019}
5020
Simon Pilgrim75c26882016-09-30 14:25:09 +00005021ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5022 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005023 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00005024 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00005025
Alp Toker95e7ff22014-01-01 05:57:51 +00005026 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5027 *this, Kind, KWLoc, Args[0]->getType()))
5028 return ExprError();
5029
Douglas Gregor29c42f22012-02-24 07:38:34 +00005030 bool Dependent = false;
5031 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5032 if (Args[I]->getType()->isDependentType()) {
5033 Dependent = true;
5034 break;
5035 }
5036 }
Alp Tokercbb90342013-12-13 20:49:58 +00005037
5038 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005039 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005040 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5041
5042 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5043 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005044}
5045
Alp Toker88f64e62013-12-13 21:19:30 +00005046ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5047 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005048 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005049 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005050 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005051
Douglas Gregor29c42f22012-02-24 07:38:34 +00005052 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5053 TypeSourceInfo *TInfo;
5054 QualType T = GetTypeFromParser(Args[I], &TInfo);
5055 if (!TInfo)
5056 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005057
5058 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005059 }
Alp Tokercbb90342013-12-13 20:49:58 +00005060
Douglas Gregor29c42f22012-02-24 07:38:34 +00005061 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5062}
5063
Alp Tokercbb90342013-12-13 20:49:58 +00005064static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5065 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005066 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5067 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005068
5069 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005070 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005071 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005072 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005073 // Base and Derived are not unions and name the same class type without
5074 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005075
John McCall388ef532011-01-28 22:02:36 +00005076 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005077 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005078 if (!rhsRecord || !lhsRecord) {
5079 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5080 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5081 if (!LHSObjTy || !RHSObjTy)
5082 return false;
5083
5084 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5085 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5086 if (!BaseInterface || !DerivedInterface)
5087 return false;
5088
5089 if (Self.RequireCompleteType(
5090 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5091 return false;
5092
5093 return BaseInterface->isSuperClassOf(DerivedInterface);
5094 }
John McCall388ef532011-01-28 22:02:36 +00005095
5096 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5097 == (lhsRecord == rhsRecord));
5098
Marshall Clowce781052019-05-13 19:29:23 +00005099 // Unions are never base classes, and never have base classes.
5100 // It doesn't matter if they are complete or not. See PR#41843
5101 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5102 return false;
5103 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5104 return false;
5105
John McCall388ef532011-01-28 22:02:36 +00005106 if (lhsRecord == rhsRecord)
Marshall Clowce781052019-05-13 19:29:23 +00005107 return true;
John McCall388ef532011-01-28 22:02:36 +00005108
5109 // C++0x [meta.rel]p2:
5110 // If Base and Derived are class types and are different types
5111 // (ignoring possible cv-qualifiers) then Derived shall be a
5112 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005113 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005114 diag::err_incomplete_type_used_in_type_trait_expr))
5115 return false;
5116
5117 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5118 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5119 }
John Wiegley65497cc2011-04-27 23:09:49 +00005120 case BTT_IsSame:
5121 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005122 case BTT_TypeCompatible: {
5123 // GCC ignores cv-qualifiers on arrays for this builtin.
5124 Qualifiers LhsQuals, RhsQuals;
5125 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5126 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5127 return Self.Context.typesAreCompatible(Lhs, Rhs);
5128 }
John Wiegley65497cc2011-04-27 23:09:49 +00005129 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005130 case BTT_IsConvertibleTo: {
5131 // C++0x [meta.rel]p4:
5132 // Given the following function prototype:
5133 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005134 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005135 // typename add_rvalue_reference<T>::type create();
5136 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005137 // the predicate condition for a template specialization
5138 // is_convertible<From, To> shall be satisfied if and only if
5139 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005140 // well-formed, including any implicit conversions to the return
5141 // type of the function:
5142 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005143 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005144 // return create<From>();
5145 // }
5146 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005147 // Access checking is performed as if in a context unrelated to To and
5148 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005149 // of the return-statement (including conversions to the return type)
5150 // is considered.
5151 //
5152 // We model the initialization as a copy-initialization of a temporary
5153 // of the appropriate type, which for this expression is identical to the
5154 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005155
5156 // Functions aren't allowed to return function or array types.
5157 if (RhsT->isFunctionType() || RhsT->isArrayType())
5158 return false;
5159
5160 // A return statement in a void function must have void type.
5161 if (RhsT->isVoidType())
5162 return LhsT->isVoidType();
5163
5164 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005165 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005166 return false;
5167
5168 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005169 if (LhsT->isObjectType() || LhsT->isFunctionType())
5170 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005171
5172 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005173 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005174 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005175 Expr::getValueKindForType(LhsT));
5176 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005177 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005178 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005179
5180 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005181 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005182 EnterExpressionEvaluationContext Unevaluated(
5183 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005184 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5185 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005186 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005187 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005188 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005189
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005190 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005191 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5192 }
Alp Toker73287bf2014-01-20 00:24:09 +00005193
David Majnemerb3d96882016-05-23 17:21:55 +00005194 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005195 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005196 case BTT_IsTriviallyAssignable: {
5197 // C++11 [meta.unary.prop]p3:
5198 // is_trivially_assignable is defined as:
5199 // is_assignable<T, U>::value is true and the assignment, as defined by
5200 // is_assignable, is known to call no operation that is not trivial
5201 //
5202 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005203 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005204 // treated as an unevaluated operand (Clause 5).
5205 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005206 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005207 // void, or arrays of unknown bound.
5208 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005209 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005210 diag::err_incomplete_type_used_in_type_trait_expr))
5211 return false;
5212 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005213 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005214 diag::err_incomplete_type_used_in_type_trait_expr))
5215 return false;
5216
5217 // cv void is never assignable.
5218 if (LhsT->isVoidType() || RhsT->isVoidType())
5219 return false;
5220
Simon Pilgrim75c26882016-09-30 14:25:09 +00005221 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005222 // declval<U>().
5223 if (LhsT->isObjectType() || LhsT->isFunctionType())
5224 LhsT = Self.Context.getRValueReferenceType(LhsT);
5225 if (RhsT->isObjectType() || RhsT->isFunctionType())
5226 RhsT = Self.Context.getRValueReferenceType(RhsT);
5227 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5228 Expr::getValueKindForType(LhsT));
5229 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5230 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005231
5232 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005233 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005234 EnterExpressionEvaluationContext Unevaluated(
5235 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005236 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005237 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005238 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5239 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005240 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5241 return false;
5242
David Majnemerb3d96882016-05-23 17:21:55 +00005243 if (BTT == BTT_IsAssignable)
5244 return true;
5245
Alp Toker73287bf2014-01-20 00:24:09 +00005246 if (BTT == BTT_IsNothrowAssignable)
5247 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005248
Alp Toker73287bf2014-01-20 00:24:09 +00005249 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005250 // Under Objective-C ARC and Weak, if the destination has non-trivial
5251 // Objective-C lifetime, this is a non-trivial assignment.
5252 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005253 return false;
5254
5255 return !Result.get()->hasNonTrivialCall(Self.Context);
5256 }
5257
5258 llvm_unreachable("unhandled type trait");
5259 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005260 }
Alp Tokercbb90342013-12-13 20:49:58 +00005261 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005262 }
5263 llvm_unreachable("Unknown type trait or not implemented");
5264}
5265
John Wiegley6242b6a2011-04-28 00:16:57 +00005266ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5267 SourceLocation KWLoc,
5268 ParsedType Ty,
5269 Expr* DimExpr,
5270 SourceLocation RParen) {
5271 TypeSourceInfo *TSInfo;
5272 QualType T = GetTypeFromParser(Ty, &TSInfo);
5273 if (!TSInfo)
5274 TSInfo = Context.getTrivialTypeSourceInfo(T);
5275
5276 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5277}
5278
5279static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5280 QualType T, Expr *DimExpr,
5281 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005282 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005283
5284 switch(ATT) {
5285 case ATT_ArrayRank:
5286 if (T->isArrayType()) {
5287 unsigned Dim = 0;
5288 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5289 ++Dim;
5290 T = AT->getElementType();
5291 }
5292 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005293 }
John Wiegleyd3522222011-04-28 02:06:46 +00005294 return 0;
5295
John Wiegley6242b6a2011-04-28 00:16:57 +00005296 case ATT_ArrayExtent: {
5297 llvm::APSInt Value;
5298 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005299 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005300 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005301 false).isInvalid())
5302 return 0;
5303 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005304 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5305 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005306 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005307 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005308 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005309
5310 if (T->isArrayType()) {
5311 unsigned D = 0;
5312 bool Matched = false;
5313 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5314 if (Dim == D) {
5315 Matched = true;
5316 break;
5317 }
5318 ++D;
5319 T = AT->getElementType();
5320 }
5321
John Wiegleyd3522222011-04-28 02:06:46 +00005322 if (Matched && T->isArrayType()) {
5323 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5324 return CAT->getSize().getLimitedValue();
5325 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005326 }
John Wiegleyd3522222011-04-28 02:06:46 +00005327 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005328 }
5329 }
5330 llvm_unreachable("Unknown type trait or not implemented");
5331}
5332
5333ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5334 SourceLocation KWLoc,
5335 TypeSourceInfo *TSInfo,
5336 Expr* DimExpr,
5337 SourceLocation RParen) {
5338 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005339
Chandler Carruthc5276e52011-05-01 08:48:21 +00005340 // FIXME: This should likely be tracked as an APInt to remove any host
5341 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005342 uint64_t Value = 0;
5343 if (!T->isDependentType())
5344 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5345
Chandler Carruthc5276e52011-05-01 08:48:21 +00005346 // While the specification for these traits from the Embarcadero C++
5347 // compiler's documentation says the return type is 'unsigned int', Clang
5348 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5349 // compiler, there is no difference. On several other platforms this is an
5350 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005351 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5352 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005353}
5354
John Wiegleyf9f65842011-04-25 06:54:41 +00005355ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005356 SourceLocation KWLoc,
5357 Expr *Queried,
5358 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005359 // If error parsing the expression, ignore.
5360 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005361 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005362
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005363 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005364
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005365 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005366}
5367
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005368static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5369 switch (ET) {
5370 case ET_IsLValueExpr: return E->isLValue();
5371 case ET_IsRValueExpr: return E->isRValue();
5372 }
5373 llvm_unreachable("Expression trait not covered by switch");
5374}
5375
John Wiegleyf9f65842011-04-25 06:54:41 +00005376ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005377 SourceLocation KWLoc,
5378 Expr *Queried,
5379 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005380 if (Queried->isTypeDependent()) {
5381 // Delay type-checking for type-dependent expressions.
5382 } else if (Queried->getType()->isPlaceholderType()) {
5383 ExprResult PE = CheckPlaceholderExpr(Queried);
5384 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005385 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005386 }
5387
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005388 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005389
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005390 return new (Context)
5391 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005392}
5393
Richard Trieu82402a02011-09-15 21:56:47 +00005394QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005395 ExprValueKind &VK,
5396 SourceLocation Loc,
5397 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005398 assert(!LHS.get()->getType()->isPlaceholderType() &&
5399 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005400 "placeholders should have been weeded out by now");
5401
Richard Smith4baaa5a2016-12-03 01:14:32 +00005402 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5403 // temporary materialization conversion otherwise.
5404 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005405 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005406 else if (LHS.get()->isRValue())
5407 LHS = TemporaryMaterializationConversion(LHS.get());
5408 if (LHS.isInvalid())
5409 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005410
5411 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005412 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005413 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005414
Sebastian Redl5822f082009-02-07 20:10:22 +00005415 const char *OpSpelling = isIndirect ? "->*" : ".*";
5416 // C++ 5.5p2
5417 // The binary operator .* [p3: ->*] binds its second operand, which shall
5418 // be of type "pointer to member of T" (where T is a completely-defined
5419 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005420 QualType RHSType = RHS.get()->getType();
5421 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005422 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005423 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005424 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005425 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005426 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005427
Sebastian Redl5822f082009-02-07 20:10:22 +00005428 QualType Class(MemPtr->getClass(), 0);
5429
Douglas Gregord07ba342010-10-13 20:41:14 +00005430 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5431 // member pointer points must be completely-defined. However, there is no
5432 // reason for this semantic distinction, and the rule is not enforced by
5433 // other compilers. Therefore, we do not check this property, as it is
5434 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005435
Sebastian Redl5822f082009-02-07 20:10:22 +00005436 // C++ 5.5p2
5437 // [...] to its first operand, which shall be of class T or of a class of
5438 // which T is an unambiguous and accessible base class. [p3: a pointer to
5439 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005440 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005441 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005442 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5443 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005444 else {
5445 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005446 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005447 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005448 return QualType();
5449 }
5450 }
5451
Richard Trieu82402a02011-09-15 21:56:47 +00005452 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005453 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005454 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5455 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005456 return QualType();
5457 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005458
Richard Smith0f59cb32015-12-18 21:45:41 +00005459 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005460 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005461 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005462 return QualType();
5463 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005464
5465 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005466 if (CheckDerivedToBaseConversion(
5467 LHSType, Class, Loc,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005468 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005469 &BasePath))
Richard Smithdb05cd32013-12-12 03:40:18 +00005470 return QualType();
5471
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005472 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005473 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5474 if (isIndirect)
5475 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005476 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005477 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005478 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005479 }
5480
Richard Trieu82402a02011-09-15 21:56:47 +00005481 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005482 // Diagnose use of pointer-to-member type which when used as
5483 // the functional cast in a pointer-to-member expression.
5484 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5485 return QualType();
5486 }
John McCall7decc9e2010-11-18 06:31:45 +00005487
Sebastian Redl5822f082009-02-07 20:10:22 +00005488 // C++ 5.5p2
5489 // The result is an object or a function of the type specified by the
5490 // second operand.
5491 // The cv qualifiers are the union of those in the pointer and the left side,
5492 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005493 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005494 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005495
Douglas Gregor1d042092011-01-26 16:40:18 +00005496 // C++0x [expr.mptr.oper]p6:
5497 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005498 // ill-formed if the second operand is a pointer to member function with
5499 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5500 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005501 // is a pointer to member function with ref-qualifier &&.
5502 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5503 switch (Proto->getRefQualifier()) {
5504 case RQ_None:
5505 // Do nothing
5506 break;
5507
5508 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005509 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
Nicolas Lesser1ad0e9f2018-07-13 16:27:45 +00005510 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5511 // is (exactly) 'const'.
5512 if (Proto->isConst() && !Proto->isVolatile())
Richard Smith25923272017-08-25 01:47:55 +00005513 Diag(Loc, getLangOpts().CPlusPlus2a
5514 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5515 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5516 else
5517 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5518 << RHSType << 1 << LHS.get()->getSourceRange();
5519 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005520 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005521
Douglas Gregor1d042092011-01-26 16:40:18 +00005522 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005523 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005524 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005525 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005526 break;
5527 }
5528 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005529
John McCall7decc9e2010-11-18 06:31:45 +00005530 // C++ [expr.mptr.oper]p6:
5531 // The result of a .* expression whose second operand is a pointer
5532 // to a data member is of the same value category as its
5533 // first operand. The result of a .* expression whose second
5534 // operand is a pointer to a member function is a prvalue. The
5535 // result of an ->* expression is an lvalue if its second operand
5536 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005537 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005538 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005539 return Context.BoundMemberTy;
5540 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005541 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005542 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005543 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005544 }
John McCall7decc9e2010-11-18 06:31:45 +00005545
Sebastian Redl5822f082009-02-07 20:10:22 +00005546 return Result;
5547}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005548
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005549/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005550///
5551/// This is part of the parameter validation for the ? operator. If either
5552/// value operand is a class type, the two operands are attempted to be
5553/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005554/// It returns true if the program is ill-formed and has already been diagnosed
5555/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005556static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5557 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005558 bool &HaveConversion,
5559 QualType &ToType) {
5560 HaveConversion = false;
5561 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005563 InitializationKind Kind =
5564 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005565 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005566 // The process for determining whether an operand expression E1 of type T1
5567 // can be converted to match an operand expression E2 of type T2 is defined
5568 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005569 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5570 // implicitly converted to type "lvalue reference to T2", subject to the
5571 // constraint that in the conversion the reference must bind directly to
5572 // an lvalue.
5573 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005574 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005575 // the constraint that the reference must bind directly.
5576 if (To->isLValue() || To->isXValue()) {
5577 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5578 : Self.Context.getRValueReferenceType(ToType);
5579
Douglas Gregor838fcc32010-03-26 20:14:36 +00005580 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005582 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005583 if (InitSeq.isDirectReferenceBinding()) {
5584 ToType = T;
5585 HaveConversion = true;
5586 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005587 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005588
Douglas Gregor838fcc32010-03-26 20:14:36 +00005589 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005590 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005591 }
John McCall65eb8792010-02-25 01:37:24 +00005592
Sebastian Redl1a99f442009-04-16 17:51:27 +00005593 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5594 // -- if E1 and E2 have class type, and the underlying class types are
5595 // the same or one is a base class of the other:
5596 QualType FTy = From->getType();
5597 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005598 const RecordType *FRec = FTy->getAs<RecordType>();
5599 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005600 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005601 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5602 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5603 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005604 // E1 can be converted to match E2 if the class of T2 is the
5605 // same type as, or a base class of, the class of T1, and
5606 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005607 if (FRec == TRec || FDerivedFromT) {
5608 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005609 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005610 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005611 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005612 HaveConversion = true;
5613 return false;
5614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005615
Douglas Gregor838fcc32010-03-26 20:14:36 +00005616 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005617 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005618 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005620
Douglas Gregor838fcc32010-03-26 20:14:36 +00005621 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005622 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005623
Douglas Gregor838fcc32010-03-26 20:14:36 +00005624 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5625 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005626 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005627 // an rvalue).
5628 //
5629 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5630 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005631 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005632
Douglas Gregor838fcc32010-03-26 20:14:36 +00005633 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005634 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005635 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005636 ToType = TTy;
5637 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005638 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005639
Sebastian Redl1a99f442009-04-16 17:51:27 +00005640 return false;
5641}
5642
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005643/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005644///
5645/// This is part of the parameter validation for the ? operator. If either
5646/// value operand is a class type, overload resolution is used to find a
5647/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005648static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005649 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005650 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005651 OverloadCandidateSet CandidateSet(QuestionLoc,
5652 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005653 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005654 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005655
5656 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005657 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005658 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005659 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005660 ExprResult LHSRes = Self.PerformImplicitConversion(
5661 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5662 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005663 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005664 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005665 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005666
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005667 ExprResult RHSRes = Self.PerformImplicitConversion(
5668 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5669 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005670 if (RHSRes.isInvalid())
5671 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005672 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005673 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005674 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005675 return false;
John Wiegley01296292011-04-08 18:41:53 +00005676 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005677
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005678 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005679
5680 // Emit a better diagnostic if one of the expressions is a null pointer
5681 // constant and the other is a pointer type. In this case, the user most
5682 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005683 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005684 return true;
5685
5686 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005687 << LHS.get()->getType() << RHS.get()->getType()
5688 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005689 return true;
5690
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005691 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005692 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005693 << LHS.get()->getType() << RHS.get()->getType()
5694 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005695 // FIXME: Print the possible common types by printing the return types of
5696 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005697 break;
5698
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005699 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005700 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005701 }
5702 return true;
5703}
5704
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005705/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005706/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005707static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005708 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005709 InitializationKind Kind =
5710 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005711 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005712 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005713 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005714 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005715 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005716
John Wiegley01296292011-04-08 18:41:53 +00005717 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005718 return false;
5719}
5720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005721/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005722///
5723/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5724/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005725QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5726 ExprResult &RHS, ExprValueKind &VK,
5727 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005728 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005729 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5730 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005731
Richard Smith45edb702012-08-07 22:06:48 +00005732 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005733 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005734 //
5735 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5736 // a is that of a integer vector with the same number of elements and
5737 // size as the vectors of b and c. If one of either b or c is a scalar
5738 // it is implicitly converted to match the type of the vector.
5739 // Otherwise the expression is ill-formed. If both b and c are scalars,
5740 // then b and c are checked and converted to the type of a if possible.
5741 // Unlike the OpenCL ?: operator, the expression is evaluated as
5742 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005743 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005744 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005745 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005746 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005747 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005748 }
5749
John McCall7decc9e2010-11-18 06:31:45 +00005750 // Assume r-value.
5751 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005752 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005753
Sebastian Redl1a99f442009-04-16 17:51:27 +00005754 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005755 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005756 return Context.DependentTy;
5757
Richard Smith45edb702012-08-07 22:06:48 +00005758 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005759 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005760 QualType LTy = LHS.get()->getType();
5761 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005762 bool LVoid = LTy->isVoidType();
5763 bool RVoid = RTy->isVoidType();
5764 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005765 // ... one of the following shall hold:
5766 // -- The second or the third operand (but not both) is a (possibly
5767 // parenthesized) throw-expression; the result is of the type
5768 // and value category of the other.
5769 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5770 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5771 if (LThrow != RThrow) {
5772 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5773 VK = NonThrow->getValueKind();
5774 // DR (no number yet): the result is a bit-field if the
5775 // non-throw-expression operand is a bit-field.
5776 OK = NonThrow->getObjectKind();
5777 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005778 }
5779
Sebastian Redl1a99f442009-04-16 17:51:27 +00005780 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005781 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005782 if (LVoid && RVoid)
5783 return Context.VoidTy;
5784
5785 // Neither holds, error.
5786 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5787 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005788 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005789 return QualType();
5790 }
5791
5792 // Neither is void.
5793
Richard Smithf2b084f2012-08-08 06:13:49 +00005794 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005795 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005796 // either has (cv) class type [...] an attempt is made to convert each of
5797 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005798 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005799 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005800 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005801 QualType L2RType, R2LType;
5802 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005803 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005804 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005805 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005806 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005807
Sebastian Redl1a99f442009-04-16 17:51:27 +00005808 // If both can be converted, [...] the program is ill-formed.
5809 if (HaveL2R && HaveR2L) {
5810 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005811 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005812 return QualType();
5813 }
5814
5815 // If exactly one conversion is possible, that conversion is applied to
5816 // the chosen operand and the converted operands are used in place of the
5817 // original operands for the remainder of this section.
5818 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005819 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005820 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005821 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005822 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005823 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005824 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005825 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005826 }
5827 }
5828
Richard Smithf2b084f2012-08-08 06:13:49 +00005829 // C++11 [expr.cond]p3
5830 // if both are glvalues of the same value category and the same type except
5831 // for cv-qualification, an attempt is made to convert each of those
5832 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005833 // FIXME:
5834 // Resolving a defect in P0012R1: we extend this to cover all cases where
5835 // one of the operands is reference-compatible with the other, in order
5836 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005837 ExprValueKind LVK = LHS.get()->getValueKind();
5838 ExprValueKind RVK = RHS.get()->getValueKind();
5839 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005840 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005841 // DerivedToBase was already handled by the class-specific case above.
5842 // FIXME: Should we allow ObjC conversions here?
5843 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5844 if (CompareReferenceRelationship(
5845 QuestionLoc, LTy, RTy, DerivedToBase,
5846 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005847 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5848 // [...] subject to the constraint that the reference must bind
5849 // directly [...]
5850 !RHS.get()->refersToBitField() &&
5851 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005852 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005853 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005854 } else if (CompareReferenceRelationship(
5855 QuestionLoc, RTy, LTy, DerivedToBase,
5856 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005857 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5858 !LHS.get()->refersToBitField() &&
5859 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005860 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5861 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005862 }
5863 }
5864
5865 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005866 // If the second and third operands are glvalues of the same value
5867 // category and have the same type, the result is of that type and
5868 // value category and it is a bit-field if the second or the third
5869 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005870 // We only extend this to bitfields, not to the crazy other kinds of
5871 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005872 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005873 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005874 LHS.get()->isOrdinaryOrBitFieldObject() &&
5875 RHS.get()->isOrdinaryOrBitFieldObject()) {
5876 VK = LHS.get()->getValueKind();
5877 if (LHS.get()->getObjectKind() == OK_BitField ||
5878 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005879 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005880
5881 // If we have function pointer types, unify them anyway to unify their
5882 // exception specifications, if any.
5883 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5884 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005885 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005886 /*ConvertArgs*/false);
5887 LTy = Context.getQualifiedType(LTy, Qs);
5888
5889 assert(!LTy.isNull() && "failed to find composite pointer type for "
5890 "canonically equivalent function ptr types");
5891 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5892 }
5893
John McCall7decc9e2010-11-18 06:31:45 +00005894 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005895 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005896
Richard Smithf2b084f2012-08-08 06:13:49 +00005897 // C++11 [expr.cond]p5
5898 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005899 // do not have the same type, and either has (cv) class type, ...
5900 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5901 // ... overload resolution is used to determine the conversions (if any)
5902 // to be applied to the operands. If the overload resolution fails, the
5903 // program is ill-formed.
5904 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5905 return QualType();
5906 }
5907
Richard Smithf2b084f2012-08-08 06:13:49 +00005908 // C++11 [expr.cond]p6
5909 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005910 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005911 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5912 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005913 if (LHS.isInvalid() || RHS.isInvalid())
5914 return QualType();
5915 LTy = LHS.get()->getType();
5916 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005917
5918 // After those conversions, one of the following shall hold:
5919 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005920 // is of that type. If the operands have class type, the result
5921 // is a prvalue temporary of the result type, which is
5922 // copy-initialized from either the second operand or the third
5923 // operand depending on the value of the first operand.
5924 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5925 if (LTy->isRecordType()) {
5926 // The operands have class type. Make a temporary copy.
5927 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005928
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5930 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005931 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005932 if (LHSCopy.isInvalid())
5933 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005934
5935 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5936 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005937 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005938 if (RHSCopy.isInvalid())
5939 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005940
John Wiegley01296292011-04-08 18:41:53 +00005941 LHS = LHSCopy;
5942 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005943 }
5944
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005945 // If we have function pointer types, unify them anyway to unify their
5946 // exception specifications, if any.
5947 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5948 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5949 assert(!LTy.isNull() && "failed to find composite pointer type for "
5950 "canonically equivalent function ptr types");
5951 }
5952
Sebastian Redl1a99f442009-04-16 17:51:27 +00005953 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005954 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005955
Douglas Gregor46188682010-05-18 22:42:18 +00005956 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005957 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005958 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5959 /*AllowBothBool*/true,
5960 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005961
Sebastian Redl1a99f442009-04-16 17:51:27 +00005962 // -- The second and third operands have arithmetic or enumeration type;
5963 // the usual arithmetic conversions are performed to bring them to a
5964 // common type, and the result is of that type.
5965 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005966 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005967 if (LHS.isInvalid() || RHS.isInvalid())
5968 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005969 if (ResTy.isNull()) {
5970 Diag(QuestionLoc,
5971 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5972 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5973 return QualType();
5974 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005975
5976 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5977 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5978
5979 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005980 }
5981
5982 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005983 // type and the other is a null pointer constant, or both are null
5984 // pointer constants, at least one of which is non-integral; pointer
5985 // conversions and qualification conversions are performed to bring them
5986 // to their composite pointer type. The result is of the composite
5987 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005988 // -- The second and third operands have pointer to member type, or one has
5989 // pointer to member type and the other is a null pointer constant;
5990 // pointer to member conversions and qualification conversions are
5991 // performed to bring them to a common type, whose cv-qualification
5992 // shall match the cv-qualification of either the second or the third
5993 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005994 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5995 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005996 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005997
Douglas Gregor697a3912010-04-01 22:47:07 +00005998 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005999 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6000 if (!Composite.isNull())
6001 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006002
Chandler Carruth9c9127e2011-02-19 00:13:59 +00006003 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00006004 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00006005 return QualType();
6006
Sebastian Redl1a99f442009-04-16 17:51:27 +00006007 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006008 << LHS.get()->getType() << RHS.get()->getType()
6009 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006010 return QualType();
6011}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006012
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006013static FunctionProtoType::ExceptionSpecInfo
6014mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6015 FunctionProtoType::ExceptionSpecInfo ESI2,
6016 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6017 ExceptionSpecificationType EST1 = ESI1.Type;
6018 ExceptionSpecificationType EST2 = ESI2.Type;
6019
6020 // If either of them can throw anything, that is the result.
6021 if (EST1 == EST_None) return ESI1;
6022 if (EST2 == EST_None) return ESI2;
6023 if (EST1 == EST_MSAny) return ESI1;
6024 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006025 if (EST1 == EST_NoexceptFalse) return ESI1;
6026 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006027
6028 // If either of them is non-throwing, the result is the other.
Erich Keaned02f4a12019-05-30 17:31:54 +00006029 if (EST1 == EST_NoThrow) return ESI2;
6030 if (EST2 == EST_NoThrow) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006031 if (EST1 == EST_DynamicNone) return ESI2;
6032 if (EST2 == EST_DynamicNone) return ESI1;
6033 if (EST1 == EST_BasicNoexcept) return ESI2;
6034 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006035 if (EST1 == EST_NoexceptTrue) return ESI2;
6036 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006037
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006038 // If we're left with value-dependent computed noexcept expressions, we're
6039 // stuck. Before C++17, we can just drop the exception specification entirely,
6040 // since it's not actually part of the canonical type. And this should never
6041 // happen in C++17, because it would mean we were computing the composite
6042 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006043 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006044 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006045 "computing composite pointer type of dependent types");
6046 return FunctionProtoType::ExceptionSpecInfo();
6047 }
6048
6049 // Switch over the possibilities so that people adding new values know to
6050 // update this function.
6051 switch (EST1) {
6052 case EST_None:
6053 case EST_DynamicNone:
6054 case EST_MSAny:
6055 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006056 case EST_DependentNoexcept:
6057 case EST_NoexceptFalse:
6058 case EST_NoexceptTrue:
Erich Keaned02f4a12019-05-30 17:31:54 +00006059 case EST_NoThrow:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006060 llvm_unreachable("handled above");
6061
6062 case EST_Dynamic: {
6063 // This is the fun case: both exception specifications are dynamic. Form
6064 // the union of the two lists.
6065 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6066 llvm::SmallPtrSet<QualType, 8> Found;
6067 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6068 for (QualType E : Exceptions)
6069 if (Found.insert(S.Context.getCanonicalType(E)).second)
6070 ExceptionTypeStorage.push_back(E);
6071
6072 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6073 Result.Exceptions = ExceptionTypeStorage;
6074 return Result;
6075 }
6076
6077 case EST_Unevaluated:
6078 case EST_Uninstantiated:
6079 case EST_Unparsed:
6080 llvm_unreachable("shouldn't see unresolved exception specifications here");
6081 }
6082
6083 llvm_unreachable("invalid ExceptionSpecificationType");
6084}
6085
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006086/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006087///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006088/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006089/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006090/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006091/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006092///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006093/// \param Loc The location of the operator requiring these two expressions to
6094/// be converted to the composite pointer type.
6095///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006096/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006097QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006098 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006099 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006100 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006101
6102 // C++1z [expr]p14:
6103 // The composite pointer type of two operands p1 and p2 having types T1
6104 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006105 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006106
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006107 // where at least one is a pointer or pointer to member type or
6108 // std::nullptr_t is:
6109 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6110 T1->isNullPtrType();
6111 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6112 T2->isNullPtrType();
6113 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006114 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006115
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006116 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6117 // This can't actually happen, following the standard, but we also use this
6118 // to implement the end of [expr.conv], which hits this case.
6119 //
6120 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6121 if (T1IsPointerLike &&
6122 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006123 if (ConvertArgs)
6124 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6125 ? CK_NullToMemberPointer
6126 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006127 return T1;
6128 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006129 if (T2IsPointerLike &&
6130 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006131 if (ConvertArgs)
6132 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6133 ? CK_NullToMemberPointer
6134 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006135 return T2;
6136 }
Mike Stump11289f42009-09-09 15:08:12 +00006137
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006138 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006139 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006140 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006141 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6142 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006143
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006144 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6145 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6146 // the union of cv1 and cv2;
6147 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6148 // "pointer to function", where the function types are otherwise the same,
6149 // "pointer to function";
6150 // FIXME: This rule is defective: it should also permit removing noexcept
6151 // from a pointer to member function. As a Clang extension, we also
6152 // permit removing 'noreturn', so we generalize this rule to;
6153 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6154 // "pointer to member function" and the pointee types can be unified
6155 // by a function pointer conversion, that conversion is applied
6156 // before checking the following rules.
6157 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6158 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6159 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6160 // respectively;
6161 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6162 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6163 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6164 // T1 or the cv-combined type of T1 and T2, respectively;
6165 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6166 // T2;
6167 //
6168 // If looked at in the right way, these bullets all do the same thing.
6169 // What we do here is, we build the two possible cv-combined types, and try
6170 // the conversions in both directions. If only one works, or if the two
6171 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006172 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006173 //
6174 // Note that this will fail to find a composite pointer type for "pointer
6175 // to void" and "pointer to function". We can't actually perform the final
6176 // conversion in this case, even though a composite pointer type formally
6177 // exists.
6178 SmallVector<unsigned, 4> QualifierUnion;
6179 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006180 QualType Composite1 = T1;
6181 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006182 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006183 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006184 const PointerType *Ptr1, *Ptr2;
6185 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6186 (Ptr2 = Composite2->getAs<PointerType>())) {
6187 Composite1 = Ptr1->getPointeeType();
6188 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006189
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006190 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006191 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006192 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006193 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006194
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006195 QualifierUnion.push_back(
6196 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006197 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006198 continue;
6199 }
Mike Stump11289f42009-09-09 15:08:12 +00006200
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006201 const MemberPointerType *MemPtr1, *MemPtr2;
6202 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6203 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6204 Composite1 = MemPtr1->getPointeeType();
6205 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006206
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006207 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006208 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006209 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006210 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006211
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006212 QualifierUnion.push_back(
6213 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6214 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6215 MemPtr2->getClass()));
6216 continue;
6217 }
Mike Stump11289f42009-09-09 15:08:12 +00006218
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006219 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006220
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006221 // Cannot unwrap any more types.
6222 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006223 }
Mike Stump11289f42009-09-09 15:08:12 +00006224
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006225 // Apply the function pointer conversion to unify the types. We've already
6226 // unwrapped down to the function types, and we want to merge rather than
6227 // just convert, so do this ourselves rather than calling
6228 // IsFunctionConversion.
6229 //
6230 // FIXME: In order to match the standard wording as closely as possible, we
6231 // currently only do this under a single level of pointers. Ideally, we would
6232 // allow this in general, and set NeedConstBefore to the relevant depth on
6233 // the side(s) where we changed anything.
6234 if (QualifierUnion.size() == 1) {
6235 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6236 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6237 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6238 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6239
6240 // The result is noreturn if both operands are.
6241 bool Noreturn =
6242 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6243 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6244 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6245
6246 // The result is nothrow if both operands are.
6247 SmallVector<QualType, 8> ExceptionTypeStorage;
6248 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6249 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6250 ExceptionTypeStorage);
6251
6252 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6253 FPT1->getParamTypes(), EPI1);
6254 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6255 FPT2->getParamTypes(), EPI2);
6256 }
6257 }
6258 }
6259
Richard Smith5e9746f2016-10-21 22:00:42 +00006260 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006261 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006262 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006263 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006264 for (unsigned I = 0; I != NeedConstBefore; ++I)
6265 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006266 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006267 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006268
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006269 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006270 auto MOC = MemberOfClass.rbegin();
6271 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6272 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6273 auto Classes = *MOC++;
6274 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006275 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006276 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006277 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006278 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006279 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006280 } else {
6281 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006282 Composite1 =
6283 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6284 Composite2 =
6285 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006286 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006287 }
6288
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006289 struct Conversion {
6290 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006291 Expr *&E1, *&E2;
6292 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006293 InitializedEntity Entity;
6294 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006295 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006296 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006297
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006298 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6299 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006300 : S(S), E1(E1), E2(E2), Composite(Composite),
6301 Entity(InitializedEntity::InitializeTemporary(Composite)),
6302 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6303 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6304 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006305
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006306 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006307 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6308 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006309 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006310 E1 = E1Result.getAs<Expr>();
6311
6312 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6313 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006314 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006315 E2 = E2Result.getAs<Expr>();
6316
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006317 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006318 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006319 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006320
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006321 // Try to convert to each composite pointer type.
6322 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006323 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6324 if (ConvertArgs && C1.perform())
6325 return QualType();
6326 return C1.Composite;
6327 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006328 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006329
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006330 if (C1.Viable == C2.Viable) {
6331 // Either Composite1 and Composite2 are viable and are different, or
6332 // neither is viable.
6333 // FIXME: How both be viable and different?
6334 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006335 }
6336
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006337 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006338 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6339 return QualType();
6340
6341 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006342}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006343
John McCalldadc5752010-08-24 06:29:42 +00006344ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006345 if (!E)
6346 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006347
John McCall31168b02011-06-15 23:02:42 +00006348 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6349
6350 // If the result is a glvalue, we shouldn't bind it.
6351 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006352 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006353
John McCall31168b02011-06-15 23:02:42 +00006354 // In ARC, calls that return a retainable type can return retained,
6355 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006356 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006357 E->getType()->isObjCRetainableType()) {
6358
6359 bool ReturnsRetained;
6360
6361 // For actual calls, we compute this by examining the type of the
6362 // called value.
6363 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6364 Expr *Callee = Call->getCallee()->IgnoreParens();
6365 QualType T = Callee->getType();
6366
6367 if (T == Context.BoundMemberTy) {
6368 // Handle pointer-to-members.
6369 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6370 T = BinOp->getRHS()->getType();
6371 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6372 T = Mem->getMemberDecl()->getType();
6373 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006374
John McCall31168b02011-06-15 23:02:42 +00006375 if (const PointerType *Ptr = T->getAs<PointerType>())
6376 T = Ptr->getPointeeType();
6377 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6378 T = Ptr->getPointeeType();
6379 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6380 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006381
John McCall31168b02011-06-15 23:02:42 +00006382 const FunctionType *FTy = T->getAs<FunctionType>();
6383 assert(FTy && "call to value not of function type?");
6384 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6385
6386 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6387 // type always produce a +1 object.
6388 } else if (isa<StmtExpr>(E)) {
6389 ReturnsRetained = true;
6390
Ted Kremeneke65b0862012-03-06 20:05:56 +00006391 // We hit this case with the lambda conversion-to-block optimization;
6392 // we don't want any extra casts here.
6393 } else if (isa<CastExpr>(E) &&
6394 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006395 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006396
John McCall31168b02011-06-15 23:02:42 +00006397 // For message sends and property references, we try to find an
6398 // actual method. FIXME: we should infer retention by selector in
6399 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006400 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006401 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006402 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6403 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006404 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6405 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006406 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006407 // Don't do reclaims if we're using the zero-element array
6408 // constant.
6409 if (ArrayLit->getNumElements() == 0 &&
6410 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6411 return E;
6412
Ted Kremeneke65b0862012-03-06 20:05:56 +00006413 D = ArrayLit->getArrayWithObjectsMethod();
6414 } else if (ObjCDictionaryLiteral *DictLit
6415 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006416 // Don't do reclaims if we're using the zero-element dictionary
6417 // constant.
6418 if (DictLit->getNumElements() == 0 &&
6419 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6420 return E;
6421
Ted Kremeneke65b0862012-03-06 20:05:56 +00006422 D = DictLit->getDictWithObjectsMethod();
6423 }
John McCall31168b02011-06-15 23:02:42 +00006424
6425 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006426
6427 // Don't do reclaims on performSelector calls; despite their
6428 // return type, the invoked method doesn't necessarily actually
6429 // return an object.
6430 if (!ReturnsRetained &&
6431 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006432 return E;
John McCall31168b02011-06-15 23:02:42 +00006433 }
6434
John McCall16de4d22011-11-14 19:53:16 +00006435 // Don't reclaim an object of Class type.
6436 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006437 return E;
John McCall16de4d22011-11-14 19:53:16 +00006438
Tim Shen4a05bb82016-06-21 20:29:17 +00006439 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006440
John McCall2d637d22011-09-10 06:18:15 +00006441 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6442 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006443 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6444 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006445 }
6446
David Blaikiebbafb8a2012-03-11 07:00:24 +00006447 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006448 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006449
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006450 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6451 // a fast path for the common case that the type is directly a RecordType.
6452 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006453 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006454 while (!RT) {
6455 switch (T->getTypeClass()) {
6456 case Type::Record:
6457 RT = cast<RecordType>(T);
6458 break;
6459 case Type::ConstantArray:
6460 case Type::IncompleteArray:
6461 case Type::VariableArray:
6462 case Type::DependentSizedArray:
6463 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6464 break;
6465 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006466 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006467 }
6468 }
Mike Stump11289f42009-09-09 15:08:12 +00006469
Richard Smithfd555f62012-02-22 02:04:18 +00006470 // That should be enough to guarantee that this type is complete, if we're
6471 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006472 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006473 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006474 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006475
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006476 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6477 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006478 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006479
John McCall31168b02011-06-15 23:02:42 +00006480 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006481 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006482 CheckDestructorAccess(E->getExprLoc(), Destructor,
6483 PDiag(diag::err_access_dtor_temp)
6484 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006485 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6486 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006487
Richard Smithfd555f62012-02-22 02:04:18 +00006488 // If destructor is trivial, we can avoid the extra copy.
6489 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006490 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006491
John McCall28fc7092011-11-10 05:35:25 +00006492 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006493 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006494 }
Richard Smitheec915d62012-02-18 04:13:32 +00006495
6496 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006497 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6498
6499 if (IsDecltype)
6500 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6501
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006502 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006503}
6504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006505ExprResult
John McCall5d413782010-12-06 08:20:24 +00006506Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006507 if (SubExpr.isInvalid())
6508 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006509
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006510 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006511}
6512
John McCall28fc7092011-11-10 05:35:25 +00006513Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006514 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006515
Eli Friedman3bda6b12012-02-02 23:15:15 +00006516 CleanupVarDeclMarking();
6517
John McCall28fc7092011-11-10 05:35:25 +00006518 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6519 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006520 assert(Cleanup.exprNeedsCleanups() ||
6521 ExprCleanupObjects.size() == FirstCleanup);
6522 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006523 return SubExpr;
6524
Craig Topper5fc8fc22014-08-27 06:28:36 +00006525 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6526 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006527
Tim Shen4a05bb82016-06-21 20:29:17 +00006528 auto *E = ExprWithCleanups::Create(
6529 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006530 DiscardCleanupsInEvaluationContext();
6531
6532 return E;
6533}
6534
John McCall5d413782010-12-06 08:20:24 +00006535Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006536 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006537
Eli Friedman3bda6b12012-02-02 23:15:15 +00006538 CleanupVarDeclMarking();
6539
Tim Shen4a05bb82016-06-21 20:29:17 +00006540 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006541 return SubStmt;
6542
6543 // FIXME: In order to attach the temporaries, wrap the statement into
6544 // a StmtExpr; currently this is only used for asm statements.
6545 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6546 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006547 CompoundStmt *CompStmt = CompoundStmt::Create(
6548 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006549 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6550 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006551 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006552}
6553
Richard Smithfd555f62012-02-22 02:04:18 +00006554/// Process the expression contained within a decltype. For such expressions,
6555/// certain semantic checks on temporaries are delayed until this point, and
6556/// are omitted for the 'topmost' call in the decltype expression. If the
6557/// topmost call bound a temporary, strip that temporary off the expression.
6558ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006559 assert(ExprEvalContexts.back().ExprContext ==
6560 ExpressionEvaluationContextRecord::EK_Decltype &&
6561 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006562
Akira Hatanaka0a848562019-01-10 20:12:16 +00006563 ExprResult Result = CheckPlaceholderExpr(E);
6564 if (Result.isInvalid())
6565 return ExprError();
6566 E = Result.get();
6567
Richard Smithfd555f62012-02-22 02:04:18 +00006568 // C++11 [expr.call]p11:
6569 // If a function call is a prvalue of object type,
6570 // -- if the function call is either
6571 // -- the operand of a decltype-specifier, or
6572 // -- the right operand of a comma operator that is the operand of a
6573 // decltype-specifier,
6574 // a temporary object is not introduced for the prvalue.
6575
6576 // Recursively rebuild ParenExprs and comma expressions to strip out the
6577 // outermost CXXBindTemporaryExpr, if any.
6578 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6579 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6580 if (SubExpr.isInvalid())
6581 return ExprError();
6582 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006583 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006584 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006585 }
6586 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6587 if (BO->getOpcode() == BO_Comma) {
6588 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6589 if (RHS.isInvalid())
6590 return ExprError();
6591 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006592 return E;
6593 return new (Context) BinaryOperator(
6594 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006595 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006596 }
6597 }
6598
6599 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006600 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6601 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006602 if (TopCall)
6603 E = TopCall;
6604 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006605 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006606
6607 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006608 ExprEvalContexts.back().ExprContext =
6609 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00006610
Richard Smithf86b0ae2012-07-28 19:54:11 +00006611 // In MS mode, don't perform any extra checking of call return types within a
6612 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006613 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006614 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006615
Richard Smithfd555f62012-02-22 02:04:18 +00006616 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006617 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6618 I != N; ++I) {
6619 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006620 if (Call == TopCall)
6621 continue;
6622
David Majnemerced8bdf2015-02-25 17:36:15 +00006623 if (CheckCallReturnType(Call->getCallReturnType(Context),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006624 Call->getBeginLoc(), Call, Call->getDirectCallee()))
Richard Smithfd555f62012-02-22 02:04:18 +00006625 return ExprError();
6626 }
6627
6628 // Now all relevant types are complete, check the destructors are accessible
6629 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006630 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6631 I != N; ++I) {
6632 CXXBindTemporaryExpr *Bind =
6633 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006634 if (Bind == TopBind)
6635 continue;
6636
6637 CXXTemporary *Temp = Bind->getTemporary();
6638
6639 CXXRecordDecl *RD =
6640 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6641 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6642 Temp->setDestructor(Destructor);
6643
Richard Smith7d847b12012-05-11 22:20:10 +00006644 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6645 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006646 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006647 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006648 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6649 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006650
6651 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006652 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006653 }
6654
6655 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006656 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006657}
6658
Richard Smith79c927b2013-11-06 19:31:51 +00006659/// Note a set of 'operator->' functions that were used for a member access.
6660static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006661 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006662 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6663 // FIXME: Make this configurable?
6664 unsigned Limit = 9;
6665 if (OperatorArrows.size() > Limit) {
6666 // Produce Limit-1 normal notes and one 'skipping' note.
6667 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6668 SkipCount = OperatorArrows.size() - (Limit - 1);
6669 }
6670
6671 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6672 if (I == SkipStart) {
6673 S.Diag(OperatorArrows[I]->getLocation(),
6674 diag::note_operator_arrows_suppressed)
6675 << SkipCount;
6676 I += SkipCount;
6677 } else {
6678 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6679 << OperatorArrows[I]->getCallResultType();
6680 ++I;
6681 }
6682 }
6683}
6684
Nico Weber964d3322015-02-16 22:35:45 +00006685ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6686 SourceLocation OpLoc,
6687 tok::TokenKind OpKind,
6688 ParsedType &ObjectType,
6689 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006690 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006691 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006692 if (Result.isInvalid()) return ExprError();
6693 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006694
John McCall526ab472011-10-25 17:37:35 +00006695 Result = CheckPlaceholderExpr(Base);
6696 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006697 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006698
John McCallb268a282010-08-23 23:25:46 +00006699 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006700 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006701 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006702 // If we have a pointer to a dependent type and are using the -> operator,
6703 // the object type is the type that the pointer points to. We might still
6704 // have enough information about that type to do something useful.
6705 if (OpKind == tok::arrow)
6706 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6707 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006708
John McCallba7bf592010-08-24 05:47:05 +00006709 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006710 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006711 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006712 }
Mike Stump11289f42009-09-09 15:08:12 +00006713
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006714 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006715 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006716 // returned, with the original second operand.
6717 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006718 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006719 bool NoArrowOperatorFound = false;
6720 bool FirstIteration = true;
6721 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006722 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006723 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006724 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006725 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006726
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006727 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006728 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6729 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006730 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006731 noteOperatorArrows(*this, OperatorArrows);
6732 Diag(OpLoc, diag::note_operator_arrow_depth)
6733 << getLangOpts().ArrowDepth;
6734 return ExprError();
6735 }
6736
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006737 Result = BuildOverloadedArrowExpr(
6738 S, Base, OpLoc,
6739 // When in a template specialization and on the first loop iteration,
6740 // potentially give the default diagnostic (with the fixit in a
6741 // separate note) instead of having the error reported back to here
6742 // and giving a diagnostic with a fixit attached to the error itself.
6743 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006744 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006745 : &NoArrowOperatorFound);
6746 if (Result.isInvalid()) {
6747 if (NoArrowOperatorFound) {
6748 if (FirstIteration) {
6749 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006750 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006751 << FixItHint::CreateReplacement(OpLoc, ".");
6752 OpKind = tok::period;
6753 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006754 }
6755 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6756 << BaseType << Base->getSourceRange();
6757 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006758 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006759 Diag(CD->getBeginLoc(),
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006760 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006761 }
6762 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006763 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006764 }
John McCallb268a282010-08-23 23:25:46 +00006765 Base = Result.get();
6766 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006767 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006768 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006769 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006770 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006771 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6772 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006773 return ExprError();
6774 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006775 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006776 }
Mike Stump11289f42009-09-09 15:08:12 +00006777
Richard Smith89009442019-05-09 22:22:48 +00006778 if (OpKind == tok::arrow) {
6779 if (BaseType->isPointerType())
6780 BaseType = BaseType->getPointeeType();
6781 else if (auto *AT = Context.getAsArrayType(BaseType))
6782 BaseType = AT->getElementType();
6783 }
Douglas Gregore4f764f2009-11-20 19:58:21 +00006784 }
Mike Stump11289f42009-09-09 15:08:12 +00006785
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006786 // Objective-C properties allow "." access on Objective-C pointer types,
6787 // so adjust the base type to the object type itself.
6788 if (BaseType->isObjCObjectPointerType())
6789 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006790
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006791 // C++ [basic.lookup.classref]p2:
6792 // [...] If the type of the object expression is of pointer to scalar
6793 // type, the unqualified-id is looked up in the context of the complete
6794 // postfix-expression.
6795 //
6796 // This also indicates that we could be parsing a pseudo-destructor-name.
6797 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006798 // expressions or normal member (ivar or property) access expressions, and
6799 // it's legal for the type to be incomplete if this is a pseudo-destructor
6800 // call. We'll do more incomplete-type checks later in the lookup process,
6801 // so just skip this check for ObjC types.
Richard Smith9e77f522019-08-14 22:57:50 +00006802 if (!BaseType->isRecordType()) {
John McCall9d145df2015-12-14 19:12:54 +00006803 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006804 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006805 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006806 }
Mike Stump11289f42009-09-09 15:08:12 +00006807
Douglas Gregor3024f072012-04-16 07:05:22 +00006808 // The object type must be complete (or dependent), or
6809 // C++11 [expr.prim.general]p3:
6810 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006811 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006812 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006813 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006814 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006815 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006816 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006817
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006818 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006819 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006820 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006821 // type C (or of pointer to a class type C), the unqualified-id is looked
6822 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006823 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006824 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006825}
6826
Simon Pilgrim75c26882016-09-30 14:25:09 +00006827static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006828 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006829 if (Base->hasPlaceholderType()) {
6830 ExprResult result = S.CheckPlaceholderExpr(Base);
6831 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006832 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006833 }
6834 ObjectType = Base->getType();
6835
David Blaikie1d578782011-12-16 16:03:09 +00006836 // C++ [expr.pseudo]p2:
6837 // The left-hand side of the dot operator shall be of scalar type. The
6838 // left-hand side of the arrow operator shall be of pointer to scalar type.
6839 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006840 // Note that this is rather different from the normal handling for the
6841 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006842 if (OpKind == tok::arrow) {
6843 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6844 ObjectType = Ptr->getPointeeType();
6845 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006846 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006847 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6848 << ObjectType << true
6849 << FixItHint::CreateReplacement(OpLoc, ".");
6850 if (S.isSFINAEContext())
6851 return true;
6852
6853 OpKind = tok::period;
6854 }
6855 }
6856
6857 return false;
6858}
6859
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006860/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006861/// pointer objects.
6862static bool
6863canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6864 QualType DestructedType) {
6865 // If this is a record type, check if its destructor is callable.
6866 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
Bruno Ricci4eb701c2019-01-24 13:52:47 +00006867 if (RD->hasDefinition())
6868 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6869 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006870 return false;
6871 }
6872
6873 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6874 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6875 DestructedType->isVectorType();
6876}
6877
John McCalldadc5752010-08-24 06:29:42 +00006878ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006879 SourceLocation OpLoc,
6880 tok::TokenKind OpKind,
6881 const CXXScopeSpec &SS,
6882 TypeSourceInfo *ScopeTypeInfo,
6883 SourceLocation CCLoc,
6884 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006885 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006886 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006887
Eli Friedman0ce4de42012-01-25 04:35:06 +00006888 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006889 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6890 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891
Douglas Gregorc5c57342012-09-10 14:57:06 +00006892 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6893 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006894 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006895 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006896 else {
Nico Weber58829272012-01-23 05:50:57 +00006897 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6898 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006899 return ExprError();
6900 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006901 }
6902
6903 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006904 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006905 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006906 if (DestructedTypeInfo) {
6907 QualType DestructedType = DestructedTypeInfo->getType();
6908 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006909 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006910 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6911 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006912 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6913 // Foo *foo;
6914 // foo.~Foo();
6915 if (OpKind == tok::period && ObjectType->isPointerType() &&
6916 Context.hasSameUnqualifiedType(DestructedType,
6917 ObjectType->getPointeeType())) {
6918 auto Diagnostic =
6919 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6920 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006921
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006922 // Issue a fixit only when the destructor is valid.
6923 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6924 *this, DestructedType))
6925 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6926
6927 // Recover by setting the object type to the destructed type and the
6928 // operator to '->'.
6929 ObjectType = DestructedType;
6930 OpKind = tok::arrow;
6931 } else {
6932 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6933 << ObjectType << DestructedType << Base->getSourceRange()
6934 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6935
6936 // Recover by setting the destructed type to the object type.
6937 DestructedType = ObjectType;
6938 DestructedTypeInfo =
6939 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6940 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6941 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006942 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006943 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006944
John McCall31168b02011-06-15 23:02:42 +00006945 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6946 // Okay: just pretend that the user provided the correctly-qualified
6947 // type.
6948 } else {
6949 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6950 << ObjectType << DestructedType << Base->getSourceRange()
6951 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6952 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006953
John McCall31168b02011-06-15 23:02:42 +00006954 // Recover by setting the destructed type to the object type.
6955 DestructedType = ObjectType;
6956 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6957 DestructedTypeStart);
6958 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6959 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006960 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006963 // C++ [expr.pseudo]p2:
6964 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6965 // form
6966 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006968 //
6969 // shall designate the same scalar type.
6970 if (ScopeTypeInfo) {
6971 QualType ScopeType = ScopeTypeInfo->getType();
6972 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006973 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006974
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006975 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006976 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006977 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006978 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006979
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006980 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006981 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006982 }
6983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006984
John McCallb268a282010-08-23 23:25:46 +00006985 Expr *Result
6986 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6987 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006988 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006989 ScopeTypeInfo,
6990 CCLoc,
6991 TildeLoc,
6992 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006993
David Majnemerced8bdf2015-02-25 17:36:15 +00006994 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006995}
6996
John McCalldadc5752010-08-24 06:29:42 +00006997ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006998 SourceLocation OpLoc,
6999 tok::TokenKind OpKind,
7000 CXXScopeSpec &SS,
7001 UnqualifiedId &FirstTypeName,
7002 SourceLocation CCLoc,
7003 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007004 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007005 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7006 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007007 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00007008 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7009 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007010 "Invalid second type name in pseudo-destructor");
7011
Eli Friedman0ce4de42012-01-25 04:35:06 +00007012 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007013 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7014 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00007015
7016 // Compute the object type that we should use for name lookup purposes. Only
7017 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00007018 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007019 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00007020 if (ObjectType->isRecordType())
7021 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00007022 else if (ObjectType->isDependentType())
7023 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007025
7026 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007027 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007028 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00007029 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007030 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007031 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007032 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007033 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007034 S, &SS, true, false, ObjectTypePtrForLookup,
7035 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007036 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00007037 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7038 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007039 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00007040 // couldn't find anything useful in scope. Just store the identifier and
7041 // it's location, and we'll perform (qualified) name lookup again at
7042 // template instantiation time.
7043 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7044 SecondTypeName.StartLocation);
7045 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007046 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007047 diag::err_pseudo_dtor_destructor_non_type)
7048 << SecondTypeName.Identifier << ObjectType;
7049 if (isSFINAEContext())
7050 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007051
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007052 // Recover by assuming we had the right type all along.
7053 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007054 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007055 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007056 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007057 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007058 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007059 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007060 TemplateId->NumArgs);
Richard Smithb23c5e82019-05-09 03:31:27 +00007061 TypeResult T = ActOnTemplateIdType(S,
7062 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007063 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007064 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007065 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007066 TemplateId->TemplateNameLoc,
7067 TemplateId->LAngleLoc,
7068 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007069 TemplateId->RAngleLoc,
7070 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007071 if (T.isInvalid() || !T.get()) {
7072 // Recover by assuming we had the right type all along.
7073 DestructedType = ObjectType;
7074 } else
7075 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007076 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007077
7078 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007079 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007080 if (!DestructedType.isNull()) {
7081 if (!DestructedTypeInfo)
7082 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007083 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007084 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007086
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007087 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007088 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007089 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007090 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007091 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007092 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007094 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007095 S, &SS, true, false, ObjectTypePtrForLookup,
7096 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007097 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007099 diag::err_pseudo_dtor_destructor_non_type)
7100 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007101
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007102 if (isSFINAEContext())
7103 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007104
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007105 // Just drop this type. It's unnecessary anyway.
7106 ScopeType = QualType();
7107 } else
7108 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007109 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007110 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007111 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007112 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007113 TemplateId->NumArgs);
Richard Smithb23c5e82019-05-09 03:31:27 +00007114 TypeResult T = ActOnTemplateIdType(S,
7115 TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007116 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007117 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007118 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007119 TemplateId->TemplateNameLoc,
7120 TemplateId->LAngleLoc,
7121 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007122 TemplateId->RAngleLoc,
7123 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007124 if (T.isInvalid() || !T.get()) {
7125 // Recover by dropping this type.
7126 ScopeType = QualType();
7127 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007129 }
7130 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007131
Douglas Gregor90ad9222010-02-24 23:02:30 +00007132 if (!ScopeType.isNull() && !ScopeTypeInfo)
7133 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7134 FirstTypeName.StartLocation);
7135
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007136
John McCallb268a282010-08-23 23:25:46 +00007137 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007138 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007139 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007140}
7141
David Blaikie1d578782011-12-16 16:03:09 +00007142ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7143 SourceLocation OpLoc,
7144 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007145 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007146 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007147 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007148 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7149 return ExprError();
7150
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007151 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7152 false);
David Blaikie1d578782011-12-16 16:03:09 +00007153
7154 TypeLocBuilder TLB;
7155 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7156 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7157 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7158 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7159
7160 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007161 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007162 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007163}
7164
John Wiegley01296292011-04-08 18:41:53 +00007165ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007166 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007167 bool HadMultipleCandidates) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00007168 // Convert the expression to match the conversion function's implicit object
7169 // parameter.
7170 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7171 FoundDecl, Method);
7172 if (Exp.isInvalid())
7173 return true;
7174
Eli Friedman98b01ed2012-03-01 04:01:32 +00007175 if (Method->getParent()->isLambda() &&
7176 Method->getConversionType()->isBlockPointerType()) {
Jan Korouse72321f2019-07-23 16:54:11 +00007177 // This is a lambda conversion to block pointer; check if the argument
Richard Smith7ed5fb22018-07-27 17:13:18 +00007178 // was a LambdaExpr.
Eli Friedman98b01ed2012-03-01 04:01:32 +00007179 Expr *SubE = E;
7180 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7181 if (CE && CE->getCastKind() == CK_NoOp)
7182 SubE = CE->getSubExpr();
7183 SubE = SubE->IgnoreParens();
7184 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7185 SubE = BE->getSubExpr();
7186 if (isa<LambdaExpr>(SubE)) {
7187 // For the conversion to block pointer on a lambda expression, we
7188 // construct a special BlockLiteral instead; this doesn't really make
7189 // a difference in ARC, but outside of ARC the resulting block literal
7190 // follows the normal lifetime rules for block literals instead of being
7191 // autoreleased.
7192 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007193 PushExpressionEvaluationContext(
7194 ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith7ed5fb22018-07-27 17:13:18 +00007195 ExprResult BlockExp = BuildBlockForLambdaConversion(
7196 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
Akira Hatanakac482acd2016-05-04 18:07:20 +00007197 PopExpressionEvaluationContext();
7198
Richard Smith7ed5fb22018-07-27 17:13:18 +00007199 if (BlockExp.isInvalid())
7200 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7201 return BlockExp;
Eli Friedman98b01ed2012-03-01 04:01:32 +00007202 }
7203 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007204
Richard Smith84be9982019-06-06 23:24:18 +00007205 MemberExpr *ME =
7206 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
7207 NestedNameSpecifierLoc(), SourceLocation(), Method,
7208 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
7209 HadMultipleCandidates, DeclarationNameInfo(),
7210 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007211
Alp Toker314cc812014-01-25 16:55:45 +00007212 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007213 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7214 ResultType = ResultType.getNonLValueExprType(Context);
7215
Bruno Riccic5885cf2018-12-21 15:20:32 +00007216 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7217 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
George Burgess IVce6284b2017-01-28 02:19:40 +00007218
7219 if (CheckFunctionCall(Method, CE,
7220 Method->getType()->castAs<FunctionProtoType>()))
7221 return ExprError();
7222
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007223 return CE;
7224}
7225
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007226ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7227 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007228 // If the operand is an unresolved lookup expression, the expression is ill-
7229 // formed per [over.over]p1, because overloaded function names cannot be used
7230 // without arguments except in explicit contexts.
7231 ExprResult R = CheckPlaceholderExpr(Operand);
7232 if (R.isInvalid())
7233 return R;
7234
7235 // The operand may have been modified when checking the placeholder type.
7236 Operand = R.get();
7237
Richard Smith51ec0cf2017-02-21 01:17:38 +00007238 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007239 // The expression operand for noexcept is in an unevaluated expression
7240 // context, so side effects could result in unintended consequences.
7241 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7242 }
7243
Richard Smithf623c962012-04-17 00:58:00 +00007244 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007245 return new (Context)
7246 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007247}
7248
7249ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7250 Expr *Operand, SourceLocation RParen) {
7251 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007252}
7253
Eli Friedmanf798f652012-05-24 22:04:19 +00007254static bool IsSpecialDiscardedValue(Expr *E) {
7255 // In C++11, discarded-value expressions of a certain form are special,
7256 // according to [expr]p10:
7257 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7258 // expression is an lvalue of volatile-qualified type and it has
7259 // one of the following forms:
7260 E = E->IgnoreParens();
7261
Eli Friedmanc49c2262012-05-24 22:36:31 +00007262 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007263 if (isa<DeclRefExpr>(E))
7264 return true;
7265
Eli Friedmanc49c2262012-05-24 22:36:31 +00007266 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007267 if (isa<ArraySubscriptExpr>(E))
7268 return true;
7269
Eli Friedmanc49c2262012-05-24 22:36:31 +00007270 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007271 if (isa<MemberExpr>(E))
7272 return true;
7273
Eli Friedmanc49c2262012-05-24 22:36:31 +00007274 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007275 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7276 if (UO->getOpcode() == UO_Deref)
7277 return true;
7278
7279 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007280 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007281 if (BO->isPtrMemOp())
7282 return true;
7283
Eli Friedmanc49c2262012-05-24 22:36:31 +00007284 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007285 if (BO->getOpcode() == BO_Comma)
7286 return IsSpecialDiscardedValue(BO->getRHS());
7287 }
7288
Eli Friedmanc49c2262012-05-24 22:36:31 +00007289 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007290 // operands are one of the above, or
7291 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7292 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7293 IsSpecialDiscardedValue(CO->getFalseExpr());
7294 // The related edge case of "*x ?: *x".
7295 if (BinaryConditionalOperator *BCO =
7296 dyn_cast<BinaryConditionalOperator>(E)) {
7297 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7298 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7299 IsSpecialDiscardedValue(BCO->getFalseExpr());
7300 }
7301
7302 // Objective-C++ extensions to the rule.
7303 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7304 return true;
7305
7306 return false;
7307}
7308
John McCall34376a62010-12-04 03:47:34 +00007309/// Perform the conversions required for an expression used in a
7310/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007311ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007312 if (E->hasPlaceholderType()) {
7313 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007314 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007315 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007316 }
7317
John McCallfee942d2010-12-02 02:07:15 +00007318 // C99 6.3.2.1:
7319 // [Except in specific positions,] an lvalue that does not have
7320 // array type is converted to the value stored in the
7321 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007322 if (E->isRValue()) {
7323 // In C, function designators (i.e. expressions of function type)
7324 // are r-values, but we still want to do function-to-pointer decay
7325 // on them. This is both technically correct and convenient for
7326 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007327 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007328 return DefaultFunctionArrayConversion(E);
7329
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007330 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007331 }
John McCallfee942d2010-12-02 02:07:15 +00007332
Eli Friedmanf798f652012-05-24 22:04:19 +00007333 if (getLangOpts().CPlusPlus) {
7334 // The C++11 standard defines the notion of a discarded-value expression;
7335 // normally, we don't need to do anything to handle it, but if it is a
7336 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7337 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007338 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007339 E->getType().isVolatileQualified() &&
7340 IsSpecialDiscardedValue(E)) {
7341 ExprResult Res = DefaultLvalueConversion(E);
7342 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007343 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007344 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007345 }
Richard Smith122f88d2016-12-06 23:52:28 +00007346
7347 // C++1z:
7348 // If the expression is a prvalue after this optional conversion, the
7349 // temporary materialization conversion is applied.
7350 //
7351 // We skip this step: IR generation is able to synthesize the storage for
7352 // itself in the aggregate case, and adding the extra node to the AST is
7353 // just clutter.
7354 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7355 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007356 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007357 }
John McCall34376a62010-12-04 03:47:34 +00007358
7359 // GCC seems to also exclude expressions of incomplete enum type.
7360 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7361 if (!T->getDecl()->isComplete()) {
7362 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007363 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007364 return E;
John McCall34376a62010-12-04 03:47:34 +00007365 }
7366 }
7367
John Wiegley01296292011-04-08 18:41:53 +00007368 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7369 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007370 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007371 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007372
John McCallca61b652010-12-04 12:29:11 +00007373 if (!E->getType()->isVoidType())
7374 RequireCompleteType(E->getExprLoc(), E->getType(),
7375 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007376 return E;
John McCall34376a62010-12-04 03:47:34 +00007377}
7378
Faisal Valia17d19f2013-11-07 05:17:06 +00007379// If we can unambiguously determine whether Var can never be used
7380// in a constant expression, return true.
7381// - if the variable and its initializer are non-dependent, then
7382// we can unambiguously check if the variable is a constant expression.
7383// - if the initializer is not value dependent - we can determine whether
7384// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007385// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007386// never be a constant expression.
7387// - FXIME: if the initializer is dependent, we can still do some analysis and
7388// identify certain cases unambiguously as non-const by using a Visitor:
7389// - such as those that involve odr-use of a ParmVarDecl, involve a new
7390// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007391static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007392 ASTContext &Context) {
7393 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007394 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007395
7396 // If there is no initializer - this can not be a constant expression.
7397 if (!Var->getAnyInitializer(DefVD)) return true;
7398 assert(DefVD);
7399 if (DefVD->isWeak()) return false;
7400 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007401
Faisal Valia17d19f2013-11-07 05:17:06 +00007402 Expr *Init = cast<Expr>(Eval->Value);
7403
7404 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007405 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7406 // of value-dependent expressions, and use it here to determine whether the
7407 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007408 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007409 }
7410
Richard Smith715f7a12019-06-11 17:50:32 +00007411 return !Var->isUsableInConstantExpressions(Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007412}
7413
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007414/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007415/// that must be captured by any of its enclosing lambdas that are ready to
7416/// capture. If there is a lambda that can capture a nested
7417/// potential-capture, go ahead and do so. Also, check to see if any
7418/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007419/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007420
Faisal Valiab3d6462013-12-07 20:22:44 +00007421static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7422 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7423
Simon Pilgrim75c26882016-09-30 14:25:09 +00007424 assert(!S.isUnevaluatedContext());
7425 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007426#ifndef NDEBUG
7427 DeclContext *DC = S.CurContext;
7428 while (DC && isa<CapturedDecl>(DC))
7429 DC = DC->getParent();
7430 assert(
7431 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007432 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007433#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007434
7435 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7436
Faisal Valiab3d6462013-12-07 20:22:44 +00007437 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007438 // lambda (within a generic outer lambda), must be captured by an
7439 // outer lambda that is enclosed within a non-dependent context.
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007440 CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007441 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007442 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007443 // need to check enclosing lambda's for speculative captures.
7444 // For e.g.:
7445 // Even though 'x' is not odr-used, it should be captured.
7446 // int test() {
7447 // const int x = 10;
7448 // auto L = [=](auto a) {
7449 // (void) +x + a;
7450 // };
7451 // }
7452 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007453 !IsFullExprInstantiationDependent)
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007454 return;
Faisal Valiab3d6462013-12-07 20:22:44 +00007455
7456 // If we have a capture-capable lambda for the variable, go ahead and
7457 // capture the variable in that lambda (and all its enclosing lambdas).
7458 if (const Optional<unsigned> Index =
7459 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Richard Smith94ef6862019-05-28 23:09:42 +00007460 S.FunctionScopes, Var, S))
7461 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
7462 Index.getValue());
Simon Pilgrim75c26882016-09-30 14:25:09 +00007463 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007464 VariableCanNeverBeAConstantExpression(Var, S.Context);
7465 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7466 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007467 // can not be used in a constant expression - which means
7468 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007469 // capture violation early, if the variable is un-captureable.
7470 // This is purely for diagnosing errors early. Otherwise, this
7471 // error would get diagnosed when the lambda becomes capture ready.
7472 QualType CaptureType, DeclRefType;
7473 SourceLocation ExprLoc = VarExpr->getExprLoc();
7474 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007475 /*EllipsisLoc*/ SourceLocation(),
7476 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007477 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007478 // We will never be able to capture this variable, and we need
7479 // to be able to in any and all instantiations, so diagnose it.
7480 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007481 /*EllipsisLoc*/ SourceLocation(),
7482 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007483 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007484 }
7485 }
Richard Smith7bf8f6f2019-06-04 17:17:20 +00007486 });
Faisal Valia17d19f2013-11-07 05:17:06 +00007487
Faisal Valiab3d6462013-12-07 20:22:44 +00007488 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007489 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007490 // If we have a capture-capable lambda for 'this', go ahead and capture
7491 // 'this' in that lambda (and all its enclosing lambdas).
7492 if (const Optional<unsigned> Index =
7493 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007494 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007495 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7496 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7497 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7498 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007499 }
7500 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007501
7502 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007503 CurrentLSI->clearPotentialCaptures();
7504}
7505
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007506static ExprResult attemptRecovery(Sema &SemaRef,
7507 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007508 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007509 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7510 Consumer.getLookupResult().getLookupKind());
7511 const CXXScopeSpec *SS = Consumer.getSS();
7512 CXXScopeSpec NewSS;
7513
7514 // Use an approprate CXXScopeSpec for building the expr.
7515 if (auto *NNS = TC.getCorrectionSpecifier())
7516 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7517 else if (SS && !TC.WillReplaceSpecifier())
7518 NewSS = *SS;
7519
Richard Smithde6d6c42015-12-29 19:43:10 +00007520 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007521 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007522 R.addDecl(ND);
7523 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007524 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007525 CXXRecordDecl *Record = nullptr;
7526 if (auto *NNS = TC.getCorrectionSpecifier())
7527 Record = NNS->getAsType()->getAsCXXRecordDecl();
7528 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007529 Record =
7530 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7531 if (Record)
7532 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007533
7534 // Detect and handle the case where the decl might be an implicit
7535 // member.
7536 bool MightBeImplicitMember;
7537 if (!Consumer.isAddressOfOperand())
7538 MightBeImplicitMember = true;
7539 else if (!NewSS.isEmpty())
7540 MightBeImplicitMember = false;
7541 else if (R.isOverloadedResult())
7542 MightBeImplicitMember = false;
7543 else if (R.isUnresolvableResult())
7544 MightBeImplicitMember = true;
7545 else
7546 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7547 isa<IndirectFieldDecl>(ND) ||
7548 isa<MSPropertyDecl>(ND);
7549
7550 if (MightBeImplicitMember)
7551 return SemaRef.BuildPossibleImplicitMemberExpr(
7552 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007553 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007554 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7555 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7556 Ivar->getIdentifier());
7557 }
7558 }
7559
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007560 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7561 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007562}
7563
Kaelyn Takata6c759512014-10-27 18:07:37 +00007564namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007565class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7566 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7567
7568public:
7569 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7570 : TypoExprs(TypoExprs) {}
7571 bool VisitTypoExpr(TypoExpr *TE) {
7572 TypoExprs.insert(TE);
7573 return true;
7574 }
7575};
7576
Kaelyn Takata6c759512014-10-27 18:07:37 +00007577class TransformTypos : public TreeTransform<TransformTypos> {
7578 typedef TreeTransform<TransformTypos> BaseTransform;
7579
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007580 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7581 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007582 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007583 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007584 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007585 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007586
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007587 /// Emit diagnostics for all of the TypoExprs encountered.
David Goldmanfd4d7772019-08-20 19:03:15 +00007588 ///
Kaelyn Takata6c759512014-10-27 18:07:37 +00007589 /// If the TypoExprs were successfully corrected, then the diagnostics should
7590 /// suggest the corrections. Otherwise the diagnostics will not suggest
7591 /// anything (having been passed an empty TypoCorrection).
David Goldmanfd4d7772019-08-20 19:03:15 +00007592 ///
7593 /// If we've failed to correct due to ambiguous corrections, we need to
7594 /// be sure to pass empty corrections and replacements. Otherwise it's
7595 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
7596 /// and we don't want to report those diagnostics.
7597 void EmitAllDiagnostics(bool IsAmbiguous) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007598 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007599 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007600 if (State.DiagHandler) {
David Goldmanfd4d7772019-08-20 19:03:15 +00007601 TypoCorrection TC = IsAmbiguous
7602 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
7603 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007604
7605 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7606 // TypoCorrection, replacing the existing decls. This ensures the right
7607 // NamedDecl is used in diagnostics e.g. in the case where overload
7608 // resolution was used to select one from several possible decls that
7609 // had been stored in the TypoCorrection.
7610 if (auto *ND = getDeclFromExpr(
7611 Replacement.isInvalid() ? nullptr : Replacement.get()))
7612 TC.setCorrectionDecl(ND);
7613
7614 State.DiagHandler(TC);
7615 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007616 SemaRef.clearDelayedTypo(TE);
7617 }
7618 }
7619
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007620 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007621 /// given combination of the other TypoExprs, retry those corrections against
7622 /// the next combination of substitutions for the other TypoExprs by advancing
7623 /// to the next potential correction of the second TypoExpr. For the second
7624 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7625 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7626 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7627 /// TransformCache). Returns true if there is still any untried combinations
7628 /// of corrections.
7629 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7630 for (auto TE : TypoExprs) {
7631 auto &State = SemaRef.getTypoExprState(TE);
7632 TransformCache.erase(TE);
7633 if (!State.Consumer->finished())
7634 return true;
7635 State.Consumer->resetCorrectionStream();
7636 }
7637 return false;
7638 }
7639
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007640 NamedDecl *getDeclFromExpr(Expr *E) {
7641 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7642 E = OverloadResolution[OE];
7643
7644 if (!E)
7645 return nullptr;
7646 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007647 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007648 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007649 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007650 // FIXME: Add any other expr types that could be be seen by the delayed typo
7651 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007652 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007653 return nullptr;
7654 }
7655
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007656 ExprResult TryTransform(Expr *E) {
7657 Sema::SFINAETrap Trap(SemaRef);
7658 ExprResult Res = TransformExpr(E);
7659 if (Trap.hasErrorOccurred() || Res.isInvalid())
7660 return ExprError();
7661
7662 return ExprFilter(Res.get());
7663 }
7664
David Goldmanfd4d7772019-08-20 19:03:15 +00007665 // Since correcting typos may intoduce new TypoExprs, this function
7666 // checks for new TypoExprs and recurses if it finds any. Note that it will
7667 // only succeed if it is able to correct all typos in the given expression.
7668 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
7669 if (Res.isInvalid()) {
7670 return Res;
7671 }
7672 // Check to see if any new TypoExprs were created. If so, we need to recurse
7673 // to check their validity.
7674 Expr *FixedExpr = Res.get();
7675
7676 auto SavedTypoExprs = std::move(TypoExprs);
7677 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
7678 TypoExprs.clear();
7679 AmbiguousTypoExprs.clear();
7680
7681 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
7682 if (!TypoExprs.empty()) {
7683 // Recurse to handle newly created TypoExprs. If we're not able to
7684 // handle them, discard these TypoExprs.
7685 ExprResult RecurResult =
7686 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
7687 if (RecurResult.isInvalid()) {
7688 Res = ExprError();
7689 // Recursive corrections didn't work, wipe them away and don't add
7690 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
7691 // since we don't want to clear them twice. Note: it's possible the
7692 // TypoExprs were created recursively and thus won't be in our
7693 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
7694 auto &SemaTypoExprs = SemaRef.TypoExprs;
7695 for (auto TE : TypoExprs) {
7696 TransformCache.erase(TE);
7697 SemaRef.clearDelayedTypo(TE);
7698
7699 auto SI = find(SemaTypoExprs, TE);
7700 if (SI != SemaTypoExprs.end()) {
7701 SemaTypoExprs.erase(SI);
7702 }
7703 }
7704 } else {
7705 // TypoExpr is valid: add newly created TypoExprs since we were
7706 // able to correct them.
7707 Res = RecurResult;
7708 SavedTypoExprs.set_union(TypoExprs);
7709 }
7710 }
7711
7712 TypoExprs = std::move(SavedTypoExprs);
7713 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
7714
7715 return Res;
7716 }
7717
7718 // Try to transform the given expression, looping through the correction
7719 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
7720 //
7721 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
7722 // true and this method immediately will return an `ExprError`.
7723 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
7724 ExprResult Res;
7725 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
7726 SemaRef.TypoExprs.clear();
7727
7728 while (true) {
7729 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
7730
7731 // Recursion encountered an ambiguous correction. This means that our
7732 // correction itself is ambiguous, so stop now.
7733 if (IsAmbiguous)
7734 break;
7735
7736 // If the transform is still valid after checking for any new typos,
7737 // it's good to go.
7738 if (!Res.isInvalid())
7739 break;
7740
7741 // The transform was invalid, see if we have any TypoExprs with untried
7742 // correction candidates.
7743 if (!CheckAndAdvanceTypoExprCorrectionStreams())
7744 break;
7745 }
7746
7747 // If we found a valid result, double check to make sure it's not ambiguous.
7748 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
7749 auto SavedTransformCache = std::move(TransformCache);
7750 TransformCache.clear();
7751 // Ensure none of the TypoExprs have multiple typo correction candidates
7752 // with the same edit length that pass all the checks and filters.
7753 while (!AmbiguousTypoExprs.empty()) {
7754 auto TE = AmbiguousTypoExprs.back();
7755
7756 // TryTransform itself can create new Typos, adding them to the TypoExpr map
7757 // and invalidating our TypoExprState, so always fetch it instead of storing.
7758 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
7759
7760 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
7761 TypoCorrection Next;
7762 do {
David Goldman6d186502019-09-13 14:43:24 +00007763 // Fetch the next correction by erasing the typo from the cache and calling
7764 // `TryTransform` which will iterate through corrections in
7765 // `TransformTypoExpr`.
7766 TransformCache.erase(TE);
David Goldmanfd4d7772019-08-20 19:03:15 +00007767 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
7768
7769 if (!AmbigRes.isInvalid() || IsAmbiguous) {
7770 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
7771 SavedTransformCache.erase(TE);
7772 Res = ExprError();
7773 IsAmbiguous = true;
7774 break;
7775 }
7776 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
7777 Next.getEditDistance(false) == TC.getEditDistance(false));
7778
7779 if (IsAmbiguous)
7780 break;
7781
7782 AmbiguousTypoExprs.remove(TE);
7783 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
7784 }
7785 TransformCache = std::move(SavedTransformCache);
7786 }
7787
7788 // Wipe away any newly created TypoExprs that we don't know about. Since we
7789 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
7790 // possible if a `TypoExpr` is created during a transformation but then
7791 // fails before we can discover it.
7792 auto &SemaTypoExprs = SemaRef.TypoExprs;
7793 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
7794 auto TE = *Iterator;
7795 auto FI = find(TypoExprs, TE);
7796 if (FI != TypoExprs.end()) {
7797 Iterator++;
7798 continue;
7799 }
7800 SemaRef.clearDelayedTypo(TE);
7801 Iterator = SemaTypoExprs.erase(Iterator);
7802 }
7803 SemaRef.TypoExprs = std::move(SavedTypoExprs);
7804
7805 return Res;
7806 }
7807
Kaelyn Takata6c759512014-10-27 18:07:37 +00007808public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007809 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7810 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007811
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007812 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7813 MultiExprArg Args,
7814 SourceLocation RParenLoc,
7815 Expr *ExecConfig = nullptr) {
7816 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7817 RParenLoc, ExecConfig);
7818 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007819 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007820 Expr *ResultCall = Result.get();
7821 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7822 ResultCall = BE->getSubExpr();
7823 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7824 OverloadResolution[OE] = CE->getCallee();
7825 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007826 }
7827 return Result;
7828 }
7829
Kaelyn Takata6c759512014-10-27 18:07:37 +00007830 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7831
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007832 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7833
Kaelyn Takata6c759512014-10-27 18:07:37 +00007834 ExprResult Transform(Expr *E) {
David Goldmanfd4d7772019-08-20 19:03:15 +00007835 bool IsAmbiguous = false;
7836 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007837
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007838 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007839 FindTypoExprs(TypoExprs).TraverseStmt(E);
7840
David Goldmanfd4d7772019-08-20 19:03:15 +00007841 EmitAllDiagnostics(IsAmbiguous);
Kaelyn Takata6c759512014-10-27 18:07:37 +00007842
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007843 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007844 }
7845
7846 ExprResult TransformTypoExpr(TypoExpr *E) {
7847 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7848 // cached transformation result if there is one and the TypoExpr isn't the
7849 // first one that was encountered.
7850 auto &CacheEntry = TransformCache[E];
7851 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7852 return CacheEntry;
7853 }
7854
7855 auto &State = SemaRef.getTypoExprState(E);
7856 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7857
7858 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7859 // typo correction and return it.
7860 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007861 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007862 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007863 // FIXME: If we would typo-correct to an invalid declaration, it's
7864 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007865 ExprResult NE = State.RecoveryHandler ?
7866 State.RecoveryHandler(SemaRef, E, TC) :
7867 attemptRecovery(SemaRef, *State.Consumer, TC);
7868 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007869 // Check whether there may be a second viable correction with the same
7870 // edit distance; if so, remember this TypoExpr may have an ambiguous
7871 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007872 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007873 if ((Next = State.Consumer->peekNextCorrection()) &&
7874 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7875 AmbiguousTypoExprs.insert(E);
7876 } else {
7877 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007878 }
7879 assert(!NE.isUnset() &&
7880 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007881 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007882 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007883 }
7884 return CacheEntry = ExprError();
7885 }
7886};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007887}
Faisal Valia17d19f2013-11-07 05:17:06 +00007888
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007889ExprResult
7890Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7891 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007892 // If the current evaluation context indicates there are uncorrected typos
7893 // and the current expression isn't guaranteed to not have typos, try to
7894 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007895 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007896 (E->isTypeDependent() || E->isValueDependent() ||
7897 E->isInstantiationDependent())) {
7898 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007899 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007900 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007901 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007902 ExprEvalContexts.back().NumTypos -= TyposResolved;
7903 return Result;
7904 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007905 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007906 }
7907 return E;
7908}
7909
Richard Smith945f8d32013-01-14 22:39:08 +00007910ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007911 bool DiscardedValue,
Richard Smithb3d203f2018-10-19 19:01:34 +00007912 bool IsConstexpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007913 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007914
7915 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007916 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007917
Richard Smithb3d203f2018-10-19 19:01:34 +00007918 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007919 return ExprError();
7920
Richard Smith945f8d32013-01-14 22:39:08 +00007921 if (DiscardedValue) {
Richard Smithb3d203f2018-10-19 19:01:34 +00007922 // Top-level expressions default to 'id' when we're in a debugger.
7923 if (getLangOpts().DebuggerCastResultToId &&
7924 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7925 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7926 if (FullExpr.isInvalid())
7927 return ExprError();
7928 }
7929
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007930 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007931 if (FullExpr.isInvalid())
7932 return ExprError();
7933
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007934 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007935 if (FullExpr.isInvalid())
7936 return ExprError();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007937
7938 DiagnoseUnusedExprResult(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007939 }
John Wiegley01296292011-04-08 18:41:53 +00007940
Kaelyn Takata49d84322014-11-11 23:26:56 +00007941 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7942 if (FullExpr.isInvalid())
7943 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007944
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007945 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007946
Simon Pilgrim75c26882016-09-30 14:25:09 +00007947 // At the end of this full expression (which could be a deeply nested
7948 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007949 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007950 // Consider the following code:
7951 // void f(int, int);
7952 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007953 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007954 // const int x = 10, y = 20;
7955 // auto L = [=](auto a) {
7956 // auto M = [=](auto b) {
7957 // f(x, b); <-- requires x to be captured by L and M
7958 // f(y, a); <-- requires y to be captured by L, but not all Ms
7959 // };
7960 // };
7961 // }
7962
Simon Pilgrim75c26882016-09-30 14:25:09 +00007963 // FIXME: Also consider what happens for something like this that involves
7964 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007965 // void f() {
7966 // const int n = 0;
7967 // auto L = [&](auto a) {
7968 // +n + ({ 0; a; });
7969 // };
7970 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007971 //
7972 // Here, we see +n, and then the full-expression 0; ends, so we don't
7973 // capture n (and instead remove it from our list of potential captures),
7974 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007975 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007976
Alexey Bataev31939e32016-11-11 12:36:20 +00007977 LambdaScopeInfo *const CurrentLSI =
7978 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007979 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007980 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007981 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007982 // By ensuring we are in the context of a lambda's call operator
7983 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007984 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007985 // PR, a proper fix would entail :
7986 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007987 // - Add to Sema an integer holding the smallest (outermost) scope
7988 // index that we are *lexically* within, and save/restore/set to
7989 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007990 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007991 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007992 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007993 DeclContext *DC = CurContext;
7994 while (DC && isa<CapturedDecl>(DC))
7995 DC = DC->getParent();
7996 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007997 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007998 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007999 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8000 *this);
John McCall5d413782010-12-06 08:20:24 +00008001 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00008002}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00008003
8004StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8005 if (!FullStmt) return StmtError();
8006
John McCall5d413782010-12-06 08:20:24 +00008007 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00008008}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008009
Simon Pilgrim75c26882016-09-30 14:25:09 +00008010Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008011Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8012 CXXScopeSpec &SS,
8013 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008014 DeclarationName TargetName = TargetNameInfo.getName();
8015 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00008016 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008017
Douglas Gregor43edb322011-10-24 22:31:10 +00008018 // If the name itself is dependent, then the result is dependent.
8019 if (TargetName.isDependentName())
8020 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008021
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008022 // Do the redeclaration lookup in the current scope.
8023 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8024 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00008025 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008026 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00008027
Douglas Gregor43edb322011-10-24 22:31:10 +00008028 switch (R.getResultKind()) {
8029 case LookupResult::Found:
8030 case LookupResult::FoundOverloaded:
8031 case LookupResult::FoundUnresolvedValue:
8032 case LookupResult::Ambiguous:
8033 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008034
Douglas Gregor43edb322011-10-24 22:31:10 +00008035 case LookupResult::NotFound:
8036 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008037
Douglas Gregor43edb322011-10-24 22:31:10 +00008038 case LookupResult::NotFoundInCurrentInstantiation:
8039 return IER_Dependent;
8040 }
David Blaikie8a40f702012-01-17 06:56:22 +00008041
8042 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00008043}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008044
Simon Pilgrim75c26882016-09-30 14:25:09 +00008045Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00008046Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8047 bool IsIfExists, CXXScopeSpec &SS,
8048 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008049 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00008050
Richard Smith151c4562016-12-20 21:35:28 +00008051 // Check for an unexpanded parameter pack.
8052 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8053 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8054 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00008055 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00008056
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00008057 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8058}