blob: ee0967455325f1e9fe8b9c1f7796ab8ef9825cf5 [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.
93 if (CurClass->isDependentContext() && !EnteringContext) {
94 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
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000456 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
457 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000458}
459
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000460/// Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000461ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000462 SourceLocation TypeidLoc,
463 Expr *E,
464 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000465 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000466 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000467 if (E->getType()->isPlaceholderType()) {
468 ExprResult result = CheckPlaceholderExpr(E);
469 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000470 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000471 }
472
Douglas Gregor9da64192010-04-26 22:37:10 +0000473 QualType T = E->getType();
474 if (const RecordType *RecordT = T->getAs<RecordType>()) {
475 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
476 // C++ [expr.typeid]p3:
477 // [...] If the type of the expression is a class type, the class
478 // shall be completely-defined.
479 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
480 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000481
Douglas Gregor9da64192010-04-26 22:37:10 +0000482 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000483 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000484 // polymorphic class type [...] [the] expression is an unevaluated
485 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000486 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000487 // The subexpression is potentially evaluated; switch the context
488 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000489 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000490 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000491 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000492
493 // We require a vtable to query the type at run time.
494 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000495 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000496 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000498
Douglas Gregor9da64192010-04-26 22:37:10 +0000499 // C++ [expr.typeid]p4:
500 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501 // cv-qualified type, the result of the typeid expression refers to a
502 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000503 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000504 Qualifiers Quals;
505 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
506 if (!Context.hasSameType(T, UnqualT)) {
507 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000508 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000509 }
510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000511
David Majnemer6f3150a2014-11-21 21:09:12 +0000512 if (E->getType()->isVariablyModifiedType())
513 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
514 << E->getType());
Richard Smith51ec0cf2017-02-21 01:17:38 +0000515 else if (!inTemplateInstantiation() &&
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000516 E->HasSideEffects(Context, WasEvaluated)) {
517 // The expression operand for typeid is in an unevaluated expression
518 // context, so side effects could result in unintended consequences.
519 Diag(E->getExprLoc(), WasEvaluated
520 ? diag::warn_side_effects_typeid
521 : diag::warn_side_effects_unevaluated_context);
522 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000523
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000524 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
525 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000526}
527
528/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000529ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000530Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
531 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Sven van Haastregt2ca6ba12018-05-09 13:16:17 +0000532 // OpenCL C++ 1.0 s2.9: typeid is not supported.
533 if (getLangOpts().OpenCLCPlusPlus) {
534 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
535 << "typeid");
536 }
537
Douglas Gregor9da64192010-04-26 22:37:10 +0000538 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000539 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000540 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000541
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000542 if (!CXXTypeInfoDecl) {
543 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
544 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
545 LookupQualifiedName(R, getStdNamespace());
546 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000547 // Microsoft's typeinfo doesn't have type_info in std but in the global
548 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000549 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000550 LookupQualifiedName(R, Context.getTranslationUnitDecl());
551 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
552 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000553 if (!CXXTypeInfoDecl)
554 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
555 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000556
Nico Weber1b7f39d2012-05-20 01:27:21 +0000557 if (!getLangOpts().RTTI) {
558 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
559 }
560
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000561 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000562
Douglas Gregor9da64192010-04-26 22:37:10 +0000563 if (isType) {
564 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000565 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000566 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
567 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000568 if (T.isNull())
569 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000570
Douglas Gregor9da64192010-04-26 22:37:10 +0000571 if (!TInfo)
572 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000573
Douglas Gregor9da64192010-04-26 22:37:10 +0000574 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000575 }
Mike Stump11289f42009-09-09 15:08:12 +0000576
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000577 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000578 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000579}
580
David Majnemer1dbc7a72016-03-27 04:46:07 +0000581/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
582/// a single GUID.
583static void
584getUuidAttrOfType(Sema &SemaRef, QualType QT,
585 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
586 // Optionally remove one level of pointer, reference or array indirection.
587 const Type *Ty = QT.getTypePtr();
588 if (QT->isPointerType() || QT->isReferenceType())
589 Ty = QT->getPointeeType().getTypePtr();
590 else if (QT->isArrayType())
591 Ty = Ty->getBaseElementTypeUnsafe();
592
Reid Klecknere516eab2016-12-13 18:58:09 +0000593 const auto *TD = Ty->getAsTagDecl();
594 if (!TD)
David Majnemer1dbc7a72016-03-27 04:46:07 +0000595 return;
596
Reid Klecknere516eab2016-12-13 18:58:09 +0000597 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000598 UuidAttrs.insert(Uuid);
599 return;
600 }
601
602 // __uuidof can grab UUIDs from template arguments.
Reid Klecknere516eab2016-12-13 18:58:09 +0000603 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000604 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
605 for (const TemplateArgument &TA : TAL.asArray()) {
606 const UuidAttr *UuidForTA = nullptr;
607 if (TA.getKind() == TemplateArgument::Type)
608 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
609 else if (TA.getKind() == TemplateArgument::Declaration)
610 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
611
612 if (UuidForTA)
613 UuidAttrs.insert(UuidForTA);
614 }
615 }
616}
617
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000618/// Build a Microsoft __uuidof expression with a type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000619ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
620 SourceLocation TypeidLoc,
621 TypeSourceInfo *Operand,
622 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000623 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000624 if (!Operand->getType()->isDependentType()) {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000625 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
626 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
627 if (UuidAttrs.empty())
628 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
629 if (UuidAttrs.size() > 1)
630 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000631 UuidStr = UuidAttrs.back()->getGuid();
Francois Pichetb7577652010-12-27 01:32:00 +0000632 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000633
David Majnemer2041b462016-03-28 03:19:50 +0000634 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000635 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000636}
637
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000638/// Build a Microsoft __uuidof expression with an expression operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000639ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
640 SourceLocation TypeidLoc,
641 Expr *E,
642 SourceLocation RParenLoc) {
David Majnemer2041b462016-03-28 03:19:50 +0000643 StringRef UuidStr;
Francois Pichetb7577652010-12-27 01:32:00 +0000644 if (!E->getType()->isDependentType()) {
David Majnemer2041b462016-03-28 03:19:50 +0000645 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
646 UuidStr = "00000000-0000-0000-0000-000000000000";
647 } else {
David Majnemer1dbc7a72016-03-27 04:46:07 +0000648 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
649 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
650 if (UuidAttrs.empty())
David Majnemer59c0ec22013-09-07 06:59:46 +0000651 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
David Majnemer1dbc7a72016-03-27 04:46:07 +0000652 if (UuidAttrs.size() > 1)
653 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
David Majnemer2041b462016-03-28 03:19:50 +0000654 UuidStr = UuidAttrs.back()->getGuid();
David Majnemer59c0ec22013-09-07 06:59:46 +0000655 }
Francois Pichetb7577652010-12-27 01:32:00 +0000656 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000657
David Majnemer2041b462016-03-28 03:19:50 +0000658 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000659 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000660}
661
662/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
663ExprResult
664Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
665 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000666 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000667 if (!MSVCGuidDecl) {
668 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
669 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
670 LookupQualifiedName(R, Context.getTranslationUnitDecl());
671 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
672 if (!MSVCGuidDecl)
673 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000674 }
675
Francois Pichet9f4f2072010-09-08 12:20:18 +0000676 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000677
Francois Pichet9f4f2072010-09-08 12:20:18 +0000678 if (isType) {
679 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000680 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000681 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
682 &TInfo);
683 if (T.isNull())
684 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685
Francois Pichet9f4f2072010-09-08 12:20:18 +0000686 if (!TInfo)
687 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
688
689 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
690 }
691
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000692 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000693 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
694}
695
Steve Naroff66356bd2007-09-16 14:56:35 +0000696/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000697ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000698Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000699 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000700 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000701 return new (Context)
702 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000703}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000704
Sebastian Redl576fd422009-05-10 18:38:11 +0000705/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000706ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000707Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000708 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000709}
710
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000711/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000712ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000713Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
714 bool IsThrownVarInScope = false;
715 if (Ex) {
716 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000717 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000718 // copy/move construction of a class object [...]
719 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000720 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000721 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000722 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000723 // innermost enclosing try-block (if there is one), the copy/move
724 // operation from the operand to the exception object (15.1) can be
725 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000726 // exception object
727 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
728 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
729 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
730 for( ; S; S = S->getParent()) {
731 if (S->isDeclScope(Var)) {
732 IsThrownVarInScope = true;
733 break;
734 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000735
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000736 if (S->getFlags() &
737 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
738 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
739 Scope::TryScope))
740 break;
741 }
742 }
743 }
744 }
Simon Pilgrim75c26882016-09-30 14:25:09 +0000745
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000746 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
747}
748
Simon Pilgrim75c26882016-09-30 14:25:09 +0000749ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000750 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000751 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000752 if (!getLangOpts().CXXExceptions &&
Alexey Bataev3167b302019-02-22 14:42:48 +0000753 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
Alexey Bataevc416e642019-02-08 18:02:25 +0000754 // Delay error emission for the OpenMP device code.
Alexey Bataev7feae052019-02-20 19:37:17 +0000755 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexey Bataevc416e642019-02-08 18:02:25 +0000756 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000757
Justin Lebar2a8db342016-09-28 22:45:54 +0000758 // Exceptions aren't allowed in CUDA device code.
759 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000760 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
761 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000762
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000763 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
764 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
765
John Wiegley01296292011-04-08 18:41:53 +0000766 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000767 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
768 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000769 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000770
771 // Initialize the exception result. This implicitly weeds out
772 // abstract types or types with inaccessible copy constructors.
773
774 // C++0x [class.copymove]p31:
775 // When certain criteria are met, an implementation is allowed to omit the
776 // copy/move construction of a class object [...]
777 //
778 // - in a throw-expression, when the operand is the name of a
779 // non-volatile automatic object (other than a function or
780 // catch-clause
781 // parameter) whose scope does not extend beyond the end of the
782 // innermost enclosing try-block (if there is one), the copy/move
783 // operation from the operand to the exception object (15.1) can be
784 // omitted by constructing the automatic object directly into the
785 // exception object
786 const VarDecl *NRVOVariable = nullptr;
787 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000788 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000789
790 InitializedEntity Entity = InitializedEntity::InitializeException(
791 OpLoc, ExceptionObjectTy,
792 /*NRVO=*/NRVOVariable != nullptr);
793 ExprResult Res = PerformMoveOrCopyInitialization(
794 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
795 if (Res.isInvalid())
796 return ExprError();
797 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000798 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000799
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000800 return new (Context)
801 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000802}
803
David Majnemere7a818f2015-03-06 18:53:55 +0000804static void
805collectPublicBases(CXXRecordDecl *RD,
806 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
807 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
808 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
809 bool ParentIsPublic) {
810 for (const CXXBaseSpecifier &BS : RD->bases()) {
811 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
812 bool NewSubobject;
813 // Virtual bases constitute the same subobject. Non-virtual bases are
814 // always distinct subobjects.
815 if (BS.isVirtual())
816 NewSubobject = VBases.insert(BaseDecl).second;
817 else
818 NewSubobject = true;
819
820 if (NewSubobject)
821 ++SubobjectsSeen[BaseDecl];
822
823 // Only add subobjects which have public access throughout the entire chain.
824 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
825 if (PublicPath)
826 PublicSubobjectsSeen.insert(BaseDecl);
827
828 // Recurse on to each base subobject.
829 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
830 PublicPath);
831 }
832}
833
834static void getUnambiguousPublicSubobjects(
835 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
836 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
837 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
838 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
839 SubobjectsSeen[RD] = 1;
840 PublicSubobjectsSeen.insert(RD);
841 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
842 /*ParentIsPublic=*/true);
843
844 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
845 // Skip ambiguous objects.
846 if (SubobjectsSeen[PublicSubobject] > 1)
847 continue;
848
849 Objects.push_back(PublicSubobject);
850 }
851}
852
Sebastian Redl4de47b42009-04-27 20:27:31 +0000853/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000854bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
855 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000856 // If the type of the exception would be an incomplete type or a pointer
857 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000858 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000859 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000860 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000861 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000862 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000863 }
864 if (!isPointer || !Ty->isVoidType()) {
865 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000866 isPointer ? diag::err_throw_incomplete_ptr
867 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000868 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000869 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000870
David Majnemerd09a51c2015-03-03 01:50:05 +0000871 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000872 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000873 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000874 }
875
Eli Friedman91a3d272010-06-03 20:39:03 +0000876 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000877 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
878 if (!RD)
879 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000880
Douglas Gregor88d292c2010-05-13 16:44:06 +0000881 // If we are throwing a polymorphic class type or pointer thereof,
882 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000883 MarkVTableUsed(ThrowLoc, RD);
884
Eli Friedman36ebbec2010-10-12 20:32:36 +0000885 // If a pointer is thrown, the referenced object will not be destroyed.
886 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000887 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000888
Richard Smitheec915d62012-02-18 04:13:32 +0000889 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000890 if (!RD->hasIrrelevantDestructor()) {
891 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
892 MarkFunctionReferenced(E->getExprLoc(), Destructor);
893 CheckDestructorAccess(E->getExprLoc(), Destructor,
894 PDiag(diag::err_access_dtor_exception) << Ty);
895 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000896 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000897 }
898 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000899
David Majnemerdfa6d202015-03-11 18:36:39 +0000900 // The MSVC ABI creates a list of all types which can catch the exception
901 // object. This list also references the appropriate copy constructor to call
902 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000903 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000904 // We are only interested in the public, unambiguous bases contained within
905 // the exception object. Bases which are ambiguous or otherwise
906 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000907 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
908 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000909
David Majnemere7a818f2015-03-06 18:53:55 +0000910 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000911 // Attempt to lookup the copy constructor. Various pieces of machinery
912 // will spring into action, like template instantiation, which means this
913 // cannot be a simple walk of the class's decls. Instead, we must perform
914 // lookup and overload resolution.
915 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
916 if (!CD)
917 continue;
918
919 // Mark the constructor referenced as it is used by this throw expression.
920 MarkFunctionReferenced(E->getExprLoc(), CD);
921
922 // Skip this copy constructor if it is trivial, we don't need to record it
923 // in the catchable type data.
924 if (CD->isTrivial())
925 continue;
926
927 // The copy constructor is non-trivial, create a mapping from this class
928 // type to this constructor.
929 // N.B. The selection of copy constructor is not sensitive to this
930 // particular throw-site. Lookup will be performed at the catch-site to
931 // ensure that the copy constructor is, in fact, accessible (via
932 // friendship or any other means).
933 Context.addCopyConstructorForExceptionObject(Subobject, CD);
934
935 // We don't keep the instantiated default argument expressions around so
936 // we must rebuild them here.
937 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000938 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
939 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000940 }
941 }
942 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000943
David Majnemerba3e5ec2015-03-13 18:26:17 +0000944 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000945}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000946
Faisal Vali67b04462016-06-11 16:41:54 +0000947static QualType adjustCVQualifiersForCXXThisWithinLambda(
948 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
949 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
950
951 QualType ClassType = ThisTy->getPointeeType();
952 LambdaScopeInfo *CurLSI = nullptr;
953 DeclContext *CurDC = CurSemaContext;
954
955 // Iterate through the stack of lambdas starting from the innermost lambda to
956 // the outermost lambda, checking if '*this' is ever captured by copy - since
957 // that could change the cv-qualifiers of the '*this' object.
958 // The object referred to by '*this' starts out with the cv-qualifiers of its
959 // member function. We then start with the innermost lambda and iterate
960 // outward checking to see if any lambda performs a by-copy capture of '*this'
961 // - and if so, any nested lambda must respect the 'constness' of that
962 // capturing lamdbda's call operator.
963 //
964
Faisal Vali999f27e2017-05-02 20:56:34 +0000965 // Since the FunctionScopeInfo stack is representative of the lexical
966 // nesting of the lambda expressions during initial parsing (and is the best
967 // place for querying information about captures about lambdas that are
968 // partially processed) and perhaps during instantiation of function templates
969 // that contain lambda expressions that need to be transformed BUT not
970 // necessarily during instantiation of a nested generic lambda's function call
971 // operator (which might even be instantiated at the end of the TU) - at which
972 // time the DeclContext tree is mature enough to query capture information
973 // reliably - we use a two pronged approach to walk through all the lexically
974 // enclosing lambda expressions:
975 //
976 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
977 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
978 // enclosed by the call-operator of the LSI below it on the stack (while
979 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
980 // the stack represents the innermost lambda.
981 //
982 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
983 // represents a lambda's call operator. If it does, we must be instantiating
984 // a generic lambda's call operator (represented by the Current LSI, and
985 // should be the only scenario where an inconsistency between the LSI and the
986 // DeclContext should occur), so climb out the DeclContexts if they
987 // represent lambdas, while querying the corresponding closure types
988 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000989
Faisal Vali999f27e2017-05-02 20:56:34 +0000990 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000991 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000992 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
993 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
994 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000995 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
996 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +0000997
998 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +0000999 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001000
Faisal Vali67b04462016-06-11 16:41:54 +00001001 auto C = CurLSI->getCXXThisCapture();
1002
1003 if (C.isCopyCapture()) {
1004 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1005 if (CurLSI->CallOperator->isConst())
1006 ClassType.addConst();
1007 return ASTCtx.getPointerType(ClassType);
1008 }
1009 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001010
1011 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1012 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001013 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001014 assert(CurLSI && "While computing 'this' capture-type for a generic "
1015 "lambda, we must have a corresponding LambdaScopeInfo");
1016 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1017 "While computing 'this' capture-type for a generic lambda, when we "
1018 "run out of enclosing LSI's, yet the enclosing DC is a "
1019 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1020 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001021 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001022
Faisal Vali67b04462016-06-11 16:41:54 +00001023 auto IsThisCaptured =
1024 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1025 IsConst = false;
1026 IsByCopy = false;
1027 for (auto &&C : Closure->captures()) {
1028 if (C.capturesThis()) {
1029 if (C.getCaptureKind() == LCK_StarThis)
1030 IsByCopy = true;
1031 if (Closure->getLambdaCallOperator()->isConst())
1032 IsConst = true;
1033 return true;
1034 }
1035 }
1036 return false;
1037 };
1038
1039 bool IsByCopyCapture = false;
1040 bool IsConstCapture = false;
1041 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1042 while (Closure &&
1043 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1044 if (IsByCopyCapture) {
1045 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1046 if (IsConstCapture)
1047 ClassType.addConst();
1048 return ASTCtx.getPointerType(ClassType);
1049 }
1050 Closure = isLambdaCallOperator(Closure->getParent())
1051 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1052 : nullptr;
1053 }
1054 }
1055 return ASTCtx.getPointerType(ClassType);
1056}
1057
Eli Friedman73a04092012-01-07 04:59:52 +00001058QualType Sema::getCurrentThisType() {
1059 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001060 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001061
Richard Smith938f40b2011-06-11 17:19:42 +00001062 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1063 if (method && method->isInstance())
Brian Gesiak5488ab42019-01-11 01:54:53 +00001064 ThisTy = method->getThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001065 }
Faisal Validc6b5962016-03-21 09:25:37 +00001066
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001067 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001068 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001069
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001070 assert(isa<CXXRecordDecl>(DC) &&
1071 "Trying to get 'this' type from static method?");
1072
1073 // This is a lambda call operator that is being instantiated as a default
1074 // initializer. DC must point to the enclosing class type, so we can recover
1075 // the 'this' type from it.
1076
1077 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1078 // There are no cv-qualifiers for 'this' within default initializers,
1079 // per [expr.prim.general]p4.
1080 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001081 }
Faisal Vali67b04462016-06-11 16:41:54 +00001082
1083 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1084 // might need to be adjusted if the lambda or any of its enclosing lambda's
1085 // captures '*this' by copy.
1086 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1087 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1088 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001089 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001090}
1091
Simon Pilgrim75c26882016-09-30 14:25:09 +00001092Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001093 Decl *ContextDecl,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001094 Qualifiers CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001095 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001096 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1097{
1098 if (!Enabled || !ContextDecl)
1099 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001100
1101 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001102 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1103 Record = Template->getTemplatedDecl();
1104 else
1105 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001106
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001107 QualType T = S.Context.getRecordType(Record);
1108 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1109
1110 S.CXXThisTypeOverride = S.Context.getPointerType(T);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001111
Douglas Gregor3024f072012-04-16 07:05:22 +00001112 this->Enabled = true;
1113}
1114
1115
1116Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1117 if (Enabled) {
1118 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1119 }
1120}
1121
Faisal Validc6b5962016-03-21 09:25:37 +00001122static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1123 QualType ThisTy, SourceLocation Loc,
1124 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001125
Faisal Vali67b04462016-06-11 16:41:54 +00001126 QualType AdjustedThisTy = ThisTy;
1127 // The type of the corresponding data member (not a 'this' pointer if 'by
1128 // copy').
1129 QualType CaptureThisFieldTy = ThisTy;
1130 if (ByCopy) {
1131 // If we are capturing the object referred to by '*this' by copy, ignore any
1132 // cv qualifiers inherited from the type of the member function for the type
1133 // of the closure-type's corresponding data member and any use of 'this'.
1134 CaptureThisFieldTy = ThisTy->getPointeeType();
1135 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1136 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1137 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001138
Faisal Vali67b04462016-06-11 16:41:54 +00001139 FieldDecl *Field = FieldDecl::Create(
1140 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1141 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1142 ICIS_NoInit);
1143
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001144 Field->setImplicit(true);
1145 Field->setAccess(AS_private);
1146 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001147 Expr *This =
1148 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001149 if (ByCopy) {
1150 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1151 UO_Deref,
1152 This).get();
1153 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001154 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001155 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1156 InitializationSequence Init(S, Entity, InitKind, StarThis);
1157 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1158 if (ER.isInvalid()) return nullptr;
1159 return ER.get();
1160 }
1161 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001162}
1163
Simon Pilgrim75c26882016-09-30 14:25:09 +00001164bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001165 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1166 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001167 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001168 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001169 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001170
Faisal Validc6b5962016-03-21 09:25:37 +00001171 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001172
Reid Kleckner87a31802018-03-12 21:43:02 +00001173 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1174 ? *FunctionScopeIndexToStopAt
1175 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001176
Simon Pilgrim75c26882016-09-30 14:25:09 +00001177 // Check that we can capture the *enclosing object* (referred to by '*this')
1178 // by the capturing-entity/closure (lambda/block/etc) at
1179 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1180
1181 // Note: The *enclosing object* can only be captured by-value by a
1182 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001183 // [*this] { ... }.
1184 // Every other capture of the *enclosing object* results in its by-reference
1185 // capture.
1186
1187 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1188 // stack), we can capture the *enclosing object* only if:
1189 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1190 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001191 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001192 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001193 // -- or, there is some enclosing closure 'E' that has already captured the
1194 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001195 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001196 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001197 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001198
1199
Faisal Validc6b5962016-03-21 09:25:37 +00001200 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001201 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001202 if (CapturingScopeInfo *CSI =
1203 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1204 if (CSI->CXXThisCaptureIndex != 0) {
1205 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001206 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001207 break;
1208 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001209 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1210 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1211 // This context can't implicitly capture 'this'; fail out.
1212 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001213 Diag(Loc, diag::err_this_capture)
1214 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001215 return true;
1216 }
Eli Friedman20139d32012-01-11 02:36:31 +00001217 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001218 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001219 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001220 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001221 (Explicit && idx == MaxFunctionScopesIndex)) {
1222 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1223 // iteration through can be an explicit capture, all enclosing closures,
1224 // if any, must perform implicit captures.
1225
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001226 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001227 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001228 continue;
1229 }
Eli Friedman20139d32012-01-11 02:36:31 +00001230 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001231 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001232 Diag(Loc, diag::err_this_capture)
1233 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001234 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001235 }
Eli Friedman73a04092012-01-07 04:59:52 +00001236 break;
1237 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001238 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001239
1240 // If we got here, then the closure at MaxFunctionScopesIndex on the
1241 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1242 // (including implicit by-reference captures in any enclosing closures).
1243
1244 // In the loop below, respect the ByCopy flag only for the closure requesting
1245 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001246 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001247 // implicitly capturing the *enclosing object* by reference (see loop
1248 // above)).
1249 assert((!ByCopy ||
1250 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1251 "Only a lambda can capture the enclosing object (referred to by "
1252 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001253 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1254 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001255 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001256 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1257 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001258 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001259 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001260
Faisal Validc6b5962016-03-21 09:25:37 +00001261 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1262 // For lambda expressions, build a field and an initializing expression,
1263 // and capture the *enclosing object* by copy only if this is the first
1264 // iteration.
1265 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1266 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001267
Faisal Validc6b5962016-03-21 09:25:37 +00001268 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001269 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001270 ThisExpr =
1271 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1272 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001273
Faisal Validc6b5962016-03-21 09:25:37 +00001274 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001275 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001276 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001277 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001278}
1279
Richard Smith938f40b2011-06-11 17:19:42 +00001280ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001281 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1282 /// is a non-lvalue expression whose value is the address of the object for
1283 /// which the function is called.
1284
Douglas Gregor09deffa2011-10-18 16:47:30 +00001285 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001286 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001287
Eli Friedman73a04092012-01-07 04:59:52 +00001288 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001289 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001290}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001291
Douglas Gregor3024f072012-04-16 07:05:22 +00001292bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1293 // If we're outside the body of a member function, then we'll have a specified
1294 // type for 'this'.
1295 if (CXXThisTypeOverride.isNull())
1296 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001297
Douglas Gregor3024f072012-04-16 07:05:22 +00001298 // Determine whether we're looking into a class that's currently being
1299 // defined.
1300 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1301 return Class && Class->isBeingDefined();
1302}
1303
Vedant Kumara14a1f92018-01-17 18:53:51 +00001304/// Parse construction of a specified type.
1305/// Can be interpreted either as function-style casting ("int(x)")
1306/// or class type construction ("ClassType(x,y,z)")
1307/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001308ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001309Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001310 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001311 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001312 SourceLocation RParenOrBraceLoc,
1313 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001314 if (!TypeRep)
1315 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001316
John McCall97513962010-01-15 18:39:57 +00001317 TypeSourceInfo *TInfo;
1318 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1319 if (!TInfo)
1320 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001321
Vedant Kumara14a1f92018-01-17 18:53:51 +00001322 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1323 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001324 // Avoid creating a non-type-dependent expression that contains typos.
1325 // Non-type-dependent expressions are liable to be discarded without
1326 // checking for embedded typos.
1327 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1328 !Result.get()->isTypeDependent())
1329 Result = CorrectDelayedTyposInExpr(Result.get());
1330 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001331}
1332
Douglas Gregor2b88c112010-09-08 00:15:04 +00001333ExprResult
1334Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001335 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001336 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001337 SourceLocation RParenOrBraceLoc,
1338 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001339 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001340 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001341
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001342 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001343 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1344 // directly. We work around this by dropping the locations of the braces.
1345 SourceRange Locs = ListInitialization
1346 ? SourceRange()
1347 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1348 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1349 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001350 }
1351
Richard Smith600b5262017-01-26 20:40:47 +00001352 assert((!ListInitialization ||
1353 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1354 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001355 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001356
Richard Smith60437622017-02-09 19:17:44 +00001357 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1358 InitializationKind Kind =
1359 Exprs.size()
1360 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001361 ? InitializationKind::CreateDirectList(
1362 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1363 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1364 RParenOrBraceLoc)
1365 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1366 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001367
1368 // C++1z [expr.type.conv]p1:
1369 // If the type is a placeholder for a deduced class type, [...perform class
1370 // template argument deduction...]
1371 DeducedType *Deduced = Ty->getContainedDeducedType();
1372 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1373 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1374 Kind, Exprs);
1375 if (Ty.isNull())
1376 return ExprError();
1377 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1378 }
1379
Douglas Gregordd04d332009-01-16 18:33:17 +00001380 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001381 // If the expression list is a parenthesized single expression, the type
1382 // conversion expression is equivalent (in definedness, and if defined in
1383 // meaning) to the corresponding cast expression.
1384 if (Exprs.size() == 1 && !ListInitialization &&
1385 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001386 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001387 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1388 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001389 }
1390
Richard Smith49a6b6e2017-03-24 01:14:25 +00001391 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001392 QualType ElemTy = Ty;
1393 if (Ty->isArrayType()) {
1394 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001395 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1396 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001397 ElemTy = Context.getBaseElementType(Ty);
1398 }
1399
Richard Smith49a6b6e2017-03-24 01:14:25 +00001400 // There doesn't seem to be an explicit rule against this but sanity demands
1401 // we only construct objects with object types.
1402 if (Ty->isFunctionType())
1403 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1404 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001405
Richard Smith49a6b6e2017-03-24 01:14:25 +00001406 // C++17 [expr.type.conv]p2:
1407 // If the type is cv void and the initializer is (), the expression is a
1408 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001409 if (!Ty->isVoidType() &&
1410 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001411 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001412 return ExprError();
1413
Richard Smith49a6b6e2017-03-24 01:14:25 +00001414 // Otherwise, the expression is a prvalue of the specified type whose
1415 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001416 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1417 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001418
Richard Smith49a6b6e2017-03-24 01:14:25 +00001419 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001420 return Result;
1421
1422 Expr *Inner = Result.get();
1423 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1424 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001425 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1426 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001427 // If we created a CXXTemporaryObjectExpr, that node also represents the
1428 // functional cast. Otherwise, create an explicit cast to represent
1429 // the syntactic form of a functional-style cast that was used here.
1430 //
1431 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1432 // would give a more consistent AST representation than using a
1433 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1434 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001435 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001436 SourceRange Locs = ListInitialization
1437 ? SourceRange()
1438 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001439 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001440 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1441 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001442 }
1443
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001444 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001445}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001446
Artem Belevich78929ef2018-09-21 17:29:33 +00001447bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1448 // [CUDA] Ignore this function, if we can't call it.
1449 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1450 if (getLangOpts().CUDA &&
1451 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1452 return false;
1453
1454 SmallVector<const FunctionDecl*, 4> PreventedBy;
1455 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1456
1457 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1458 return Result;
1459
1460 // In case of CUDA, return true if none of the 1-argument deallocator
1461 // functions are actually callable.
1462 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1463 assert(FD->getNumParams() == 1 &&
1464 "Only single-operand functions should be in PreventedBy");
1465 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1466 });
1467}
1468
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001469/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001470/// deallocation function.
1471static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001472 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
Artem Belevich78929ef2018-09-21 17:29:33 +00001473 return S.isUsualDeallocationFunction(Method);
Richard Smithb2f0f052016-10-10 18:54:32 +00001474
1475 if (FD->getOverloadedOperator() != OO_Delete &&
1476 FD->getOverloadedOperator() != OO_Array_Delete)
1477 return false;
1478
1479 unsigned UsualParams = 1;
1480
1481 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1482 S.Context.hasSameUnqualifiedType(
1483 FD->getParamDecl(UsualParams)->getType(),
1484 S.Context.getSizeType()))
1485 ++UsualParams;
1486
1487 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1488 S.Context.hasSameUnqualifiedType(
1489 FD->getParamDecl(UsualParams)->getType(),
1490 S.Context.getTypeDeclType(S.getStdAlignValT())))
1491 ++UsualParams;
1492
1493 return UsualParams == FD->getNumParams();
1494}
1495
1496namespace {
1497 struct UsualDeallocFnInfo {
1498 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001499 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001500 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001501 Destroying(false), HasSizeT(false), HasAlignValT(false),
1502 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001503 // A function template declaration is never a usual deallocation function.
1504 if (!FD)
1505 return;
Richard Smith5b349582017-10-13 01:55:36 +00001506 unsigned NumBaseParams = 1;
1507 if (FD->isDestroyingOperatorDelete()) {
1508 Destroying = true;
1509 ++NumBaseParams;
1510 }
Eric Fiselier8e920502019-01-16 02:34:36 +00001511
1512 if (NumBaseParams < FD->getNumParams() &&
1513 S.Context.hasSameUnqualifiedType(
1514 FD->getParamDecl(NumBaseParams)->getType(),
1515 S.Context.getSizeType())) {
1516 ++NumBaseParams;
1517 HasSizeT = true;
1518 }
1519
1520 if (NumBaseParams < FD->getNumParams() &&
1521 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1522 ++NumBaseParams;
1523 HasAlignValT = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001524 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001525
1526 // In CUDA, determine how much we'd like / dislike to call this.
1527 if (S.getLangOpts().CUDA)
1528 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1529 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001530 }
1531
Eric Fiselierfa752f22018-03-21 19:19:48 +00001532 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001533
Richard Smithf75dcbe2016-10-11 00:21:10 +00001534 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1535 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001536 // C++ P0722:
1537 // A destroying operator delete is preferred over a non-destroying
1538 // operator delete.
1539 if (Destroying != Other.Destroying)
1540 return Destroying;
1541
Richard Smithf75dcbe2016-10-11 00:21:10 +00001542 // C++17 [expr.delete]p10:
1543 // If the type has new-extended alignment, a function with a parameter
1544 // of type std::align_val_t is preferred; otherwise a function without
1545 // such a parameter is preferred
1546 if (HasAlignValT != Other.HasAlignValT)
1547 return HasAlignValT == WantAlign;
1548
1549 if (HasSizeT != Other.HasSizeT)
1550 return HasSizeT == WantSize;
1551
1552 // Use CUDA call preference as a tiebreaker.
1553 return CUDAPref > Other.CUDAPref;
1554 }
1555
Richard Smithb2f0f052016-10-10 18:54:32 +00001556 DeclAccessPair Found;
1557 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001558 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001559 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001560 };
1561}
1562
1563/// Determine whether a type has new-extended alignment. This may be called when
1564/// the type is incomplete (for a delete-expression with an incomplete pointee
1565/// type), in which case it will conservatively return false if the alignment is
1566/// not known.
1567static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1568 return S.getLangOpts().AlignedAllocation &&
1569 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1570 S.getASTContext().getTargetInfo().getNewAlign();
1571}
1572
1573/// Select the correct "usual" deallocation function to use from a selection of
1574/// deallocation functions (either global or class-scope).
1575static UsualDeallocFnInfo resolveDeallocationOverload(
1576 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1577 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1578 UsualDeallocFnInfo Best;
1579
Richard Smithb2f0f052016-10-10 18:54:32 +00001580 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001581 UsualDeallocFnInfo Info(S, I.getPair());
1582 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1583 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001584 continue;
1585
1586 if (!Best) {
1587 Best = Info;
1588 if (BestFns)
1589 BestFns->push_back(Info);
1590 continue;
1591 }
1592
Richard Smithf75dcbe2016-10-11 00:21:10 +00001593 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001594 continue;
1595
1596 // If more than one preferred function is found, all non-preferred
1597 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001598 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001599 BestFns->clear();
1600
1601 Best = Info;
1602 if (BestFns)
1603 BestFns->push_back(Info);
1604 }
1605
1606 return Best;
1607}
1608
1609/// Determine whether a given type is a class for which 'delete[]' would call
1610/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1611/// we need to store the array size (even if the type is
1612/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001613static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1614 QualType allocType) {
1615 const RecordType *record =
1616 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1617 if (!record) return false;
1618
1619 // Try to find an operator delete[] in class scope.
1620
1621 DeclarationName deleteName =
1622 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1623 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1624 S.LookupQualifiedName(ops, record->getDecl());
1625
1626 // We're just doing this for information.
1627 ops.suppressDiagnostics();
1628
1629 // Very likely: there's no operator delete[].
1630 if (ops.empty()) return false;
1631
1632 // If it's ambiguous, it should be illegal to call operator delete[]
1633 // on this thing, so it doesn't matter if we allocate extra space or not.
1634 if (ops.isAmbiguous()) return false;
1635
Richard Smithb2f0f052016-10-10 18:54:32 +00001636 // C++17 [expr.delete]p10:
1637 // If the deallocation functions have class scope, the one without a
1638 // parameter of type std::size_t is selected.
1639 auto Best = resolveDeallocationOverload(
1640 S, ops, /*WantSize*/false,
1641 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1642 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001643}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001644
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001645/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001646///
Sebastian Redld74dd492012-02-12 18:41:05 +00001647/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001648/// @code new (memory) int[size][4] @endcode
1649/// or
1650/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001651///
1652/// \param StartLoc The first location of the expression.
1653/// \param UseGlobal True if 'new' was prefixed with '::'.
1654/// \param PlacementLParen Opening paren of the placement arguments.
1655/// \param PlacementArgs Placement new arguments.
1656/// \param PlacementRParen Closing paren of the placement arguments.
1657/// \param TypeIdParens If the type is in parens, the source range.
1658/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001659/// \param Initializer The initializing expression or initializer-list, or null
1660/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001661ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001662Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001663 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001664 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001665 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001666 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001667 // If the specified type is an array, unwrap it and save the expression.
1668 if (D.getNumTypeObjects() > 0 &&
1669 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001670 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001671 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001672 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1673 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001674 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001675 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1676 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001677 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001678 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1679 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001680
Sebastian Redl351bb782008-12-02 14:43:59 +00001681 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001682 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001683 }
1684
Douglas Gregor73341c42009-09-11 00:18:58 +00001685 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001686 if (ArraySize) {
1687 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001688 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1689 break;
1690
1691 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1692 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001693 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001694 if (getLangOpts().CPlusPlus14) {
Fangrui Song99337e22018-07-20 08:19:20 +00001695 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1696 // shall be a converted constant expression (5.19) of type std::size_t
1697 // and shall evaluate to a strictly positive value.
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001698 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1699 assert(IntWidth && "Builtin type of size 0?");
1700 llvm::APSInt Value(IntWidth);
1701 Array.NumElts
1702 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1703 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001704 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001705 } else {
1706 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001707 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001708 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001709 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001710 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001711 if (!Array.NumElts)
1712 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001713 }
1714 }
1715 }
1716 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001717
Craig Topperc3ec1492014-05-26 06:22:03 +00001718 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001719 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001720 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001721 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001722
Sebastian Redl6047f072012-02-16 12:22:20 +00001723 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001724 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001725 DirectInitRange = List->getSourceRange();
1726
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001727 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1728 PlacementLParen, PlacementArgs, PlacementRParen,
1729 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001730 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001731}
1732
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001733static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1734 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001735 if (!Init)
1736 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001737 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1738 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001739 if (isa<ImplicitValueInitExpr>(Init))
1740 return true;
1741 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1742 return !CCE->isListInitialization() &&
1743 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001744 else if (Style == CXXNewExpr::ListInit) {
1745 assert(isa<InitListExpr>(Init) &&
1746 "Shouldn't create list CXXConstructExprs for arrays.");
1747 return true;
1748 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001749 return false;
1750}
1751
Akira Hatanaka71645c22018-12-21 07:05:36 +00001752bool
1753Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1754 if (!getLangOpts().AlignedAllocationUnavailable)
1755 return false;
1756 if (FD.isDefined())
1757 return false;
1758 bool IsAligned = false;
1759 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1760 return true;
1761 return false;
1762}
1763
Akira Hatanakacae83f72017-06-29 18:48:40 +00001764// Emit a diagnostic if an aligned allocation/deallocation function that is not
1765// implemented in the standard library is selected.
Akira Hatanaka71645c22018-12-21 07:05:36 +00001766void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1767 SourceLocation Loc) {
1768 if (isUnavailableAlignedAllocationFunction(FD)) {
1769 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001770 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
Akira Hatanaka71645c22018-12-21 07:05:36 +00001771 getASTContext().getTargetInfo().getPlatformName());
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001772
Akira Hatanaka71645c22018-12-21 07:05:36 +00001773 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1774 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1775 Diag(Loc, diag::err_aligned_allocation_unavailable)
Volodymyr Sapsaie5015ab2018-08-03 23:12:37 +00001776 << IsDelete << FD.getType().getAsString() << OSName
1777 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanaka71645c22018-12-21 07:05:36 +00001778 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
Akira Hatanakacae83f72017-06-29 18:48:40 +00001779 }
1780}
1781
John McCalldadc5752010-08-24 06:29:42 +00001782ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001783Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001784 SourceLocation PlacementLParen,
1785 MultiExprArg PlacementArgs,
1786 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001787 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001788 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001789 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001790 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001791 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001792 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001793 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001794 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001795
Sebastian Redl6047f072012-02-16 12:22:20 +00001796 CXXNewExpr::InitializationStyle initStyle;
1797 if (DirectInitRange.isValid()) {
1798 assert(Initializer && "Have parens but no initializer.");
1799 initStyle = CXXNewExpr::CallInit;
1800 } else if (Initializer && isa<InitListExpr>(Initializer))
1801 initStyle = CXXNewExpr::ListInit;
1802 else {
1803 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1804 isa<CXXConstructExpr>(Initializer)) &&
1805 "Initializer expression that cannot have been implicitly created.");
1806 initStyle = CXXNewExpr::NoInit;
1807 }
1808
1809 Expr **Inits = &Initializer;
1810 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001811 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1812 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1813 Inits = List->getExprs();
1814 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001815 }
1816
Richard Smith60437622017-02-09 19:17:44 +00001817 // C++11 [expr.new]p15:
1818 // A new-expression that creates an object of type T initializes that
1819 // object as follows:
1820 InitializationKind Kind
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001821 // - If the new-initializer is omitted, the object is default-
1822 // initialized (8.5); if no initialization is performed,
1823 // the object has indeterminate value
1824 = initStyle == CXXNewExpr::NoInit
1825 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1826 // - Otherwise, the new-initializer is interpreted according to
1827 // the
1828 // initialization rules of 8.5 for direct-initialization.
1829 : initStyle == CXXNewExpr::ListInit
1830 ? InitializationKind::CreateDirectList(
1831 TypeRange.getBegin(), Initializer->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001832 Initializer->getEndLoc())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001833 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1834 DirectInitRange.getBegin(),
1835 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001836
Richard Smith60437622017-02-09 19:17:44 +00001837 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1838 auto *Deduced = AllocType->getContainedDeducedType();
1839 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1840 if (ArraySize)
1841 return ExprError(Diag(ArraySize->getExprLoc(),
1842 diag::err_deduced_class_template_compound_type)
1843 << /*array*/ 2 << ArraySize->getSourceRange());
1844
1845 InitializedEntity Entity
1846 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1847 AllocType = DeduceTemplateSpecializationFromInitializer(
1848 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1849 if (AllocType.isNull())
1850 return ExprError();
1851 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001852 bool Braced = (initStyle == CXXNewExpr::ListInit);
1853 if (NumInits == 1) {
1854 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1855 Inits = p->getInits();
1856 NumInits = p->getNumInits();
1857 Braced = true;
1858 }
1859 }
1860
Sebastian Redl6047f072012-02-16 12:22:20 +00001861 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001862 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1863 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001864 if (NumInits > 1) {
1865 Expr *FirstBad = Inits[1];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001866 return ExprError(Diag(FirstBad->getBeginLoc(),
Richard Smith30482bc2011-02-20 03:19:35 +00001867 diag::err_auto_new_ctor_multiple_expressions)
1868 << AllocType << TypeRange);
1869 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001870 if (Braced && !getLangOpts().CPlusPlus17)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001871 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001872 << AllocType << TypeRange;
Richard Smith061f1e22013-04-30 21:23:01 +00001873 QualType DeducedType;
Akira Hatanakad458ced2019-01-11 04:57:34 +00001874 if (DeduceAutoType(AllocTypeInfo, Inits[0], DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001875 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Akira Hatanakad458ced2019-01-11 04:57:34 +00001876 << AllocType << Inits[0]->getType()
1877 << TypeRange << Inits[0]->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001878 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001879 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001880 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001881 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001882
Douglas Gregorcda95f42010-05-16 16:01:03 +00001883 // Per C++0x [expr.new]p5, the type being constructed may be a
1884 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001885 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001886 if (const ConstantArrayType *Array
1887 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001888 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1889 Context.getSizeType(),
1890 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001891 AllocType = Array->getElementType();
1892 }
1893 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001894
Douglas Gregor3999e152010-10-06 16:00:31 +00001895 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1896 return ExprError();
1897
Simon Pilgrim75c26882016-09-30 14:25:09 +00001898 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001899 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001900 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1901 AllocType->isObjCLifetimeType()) {
1902 AllocType = Context.getLifetimeQualifiedType(AllocType,
1903 AllocType->getObjCARCImplicitLifetime());
1904 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001905
John McCall31168b02011-06-15 23:02:42 +00001906 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001907
John McCall5e77d762013-04-16 07:28:30 +00001908 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1909 ExprResult result = CheckPlaceholderExpr(ArraySize);
1910 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001911 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001912 }
Richard Smith8dd34252012-02-04 07:07:42 +00001913 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1914 // integral or enumeration type with a non-negative value."
1915 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1916 // enumeration type, or a class type for which a single non-explicit
1917 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001918 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001919 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001920 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001921 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001922 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001923 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001924 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1925
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001926 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
Fangrui Song99337e22018-07-20 08:19:20 +00001927 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001928
Simon Pilgrim75c26882016-09-30 14:25:09 +00001929 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001930 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001931 // Diagnose the compatibility of this conversion.
1932 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1933 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001934 } else {
1935 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1936 protected:
1937 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001938
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001939 public:
1940 SizeConvertDiagnoser(Expr *ArraySize)
1941 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1942 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001943
1944 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1945 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001946 return S.Diag(Loc, diag::err_array_size_not_integral)
1947 << S.getLangOpts().CPlusPlus11 << T;
1948 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001949
1950 SemaDiagnosticBuilder diagnoseIncomplete(
1951 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001952 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1953 << T << ArraySize->getSourceRange();
1954 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001955
1956 SemaDiagnosticBuilder diagnoseExplicitConv(
1957 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001958 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1959 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001960
1961 SemaDiagnosticBuilder noteExplicitConv(
1962 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001963 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1964 << ConvTy->isEnumeralType() << ConvTy;
1965 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001966
1967 SemaDiagnosticBuilder diagnoseAmbiguous(
1968 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001969 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1970 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001971
1972 SemaDiagnosticBuilder noteAmbiguous(
1973 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001974 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1975 << ConvTy->isEnumeralType() << ConvTy;
1976 }
Richard Smithccc11812013-05-21 19:05:48 +00001977
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001978 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1979 QualType T,
1980 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001981 return S.Diag(Loc,
1982 S.getLangOpts().CPlusPlus11
1983 ? diag::warn_cxx98_compat_array_size_conversion
1984 : diag::ext_array_size_conversion)
1985 << T << ConvTy->isEnumeralType() << ConvTy;
1986 }
1987 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001988
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001989 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1990 SizeDiagnoser);
1991 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001992 if (ConvertedSize.isInvalid())
1993 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001994
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001995 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001996 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001997
Douglas Gregor0bf31402010-10-08 23:50:27 +00001998 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001999 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002000
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002001 // C++98 [expr.new]p7:
2002 // The expression in a direct-new-declarator shall have integral type
2003 // with a non-negative value.
2004 //
Richard Smith0511d232016-10-05 22:41:02 +00002005 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2006 // per CWG1464. Otherwise, if it's not a constant, we must have an
2007 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002008 if (!ArraySize->isValueDependent()) {
2009 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00002010 // We've already performed any required implicit conversion to integer or
2011 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00002012 // FIXME: Per CWG1464, we are required to check the value prior to
2013 // converting to size_t. This will never find a negative array size in
2014 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002015 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00002016 if (Value.isSigned() && Value.isNegative()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002017 return ExprError(Diag(ArraySize->getBeginLoc(),
Richard Smith0511d232016-10-05 22:41:02 +00002018 diag::err_typecheck_negative_array_size)
2019 << ArraySize->getSourceRange());
2020 }
2021
2022 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002023 unsigned ActiveSizeBits =
2024 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002025 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002026 return ExprError(
2027 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2028 << Value.toString(10) << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002029 }
Richard Smith0511d232016-10-05 22:41:02 +00002030
2031 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002032 } else if (TypeIdParens.isValid()) {
2033 // Can't have dynamic array size when the type-id is in parentheses.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002034 Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2035 << ArraySize->getSourceRange()
2036 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2037 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002038
Douglas Gregorf2753b32010-07-13 15:54:32 +00002039 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002040 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002042
John McCall036f2f62011-05-15 07:14:44 +00002043 // Note that we do *not* convert the argument in any way. It can
2044 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002045 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002046
Craig Topperc3ec1492014-05-26 06:22:03 +00002047 FunctionDecl *OperatorNew = nullptr;
2048 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002049 unsigned Alignment =
2050 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2051 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2052 bool PassAlignment = getLangOpts().AlignedAllocation &&
2053 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054
Brian Gesiakcb024022018-04-01 22:59:22 +00002055 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002056 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002057 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002058 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002059 SourceRange(PlacementLParen, PlacementRParen),
Brian Gesiakcb024022018-04-01 22:59:22 +00002060 Scope, Scope, AllocType, ArraySize, PassAlignment,
Richard Smithb2f0f052016-10-10 18:54:32 +00002061 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002062 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002063
2064 // If this is an array allocation, compute whether the usual array
2065 // deallocation function for the type has a size_t parameter.
2066 bool UsualArrayDeleteWantsSize = false;
2067 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002068 UsualArrayDeleteWantsSize =
2069 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002070
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002071 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002072 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002073 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002074 OperatorNew->getType()->getAs<FunctionProtoType>();
2075 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2076 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077
Richard Smithd6f9e732014-05-13 19:56:21 +00002078 // We've already converted the placement args, just fill in any default
2079 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002080 // argument. Skip the second parameter too if we're passing in the
2081 // alignment; we've already filled it in.
2082 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2083 PassAlignment ? 2 : 1, PlacementArgs,
2084 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002085 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002087 if (!AllPlaceArgs.empty())
2088 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002089
Richard Smithd6f9e732014-05-13 19:56:21 +00002090 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002091 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002092
2093 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002094
Richard Smithb2f0f052016-10-10 18:54:32 +00002095 // Warn if the type is over-aligned and is being allocated by (unaligned)
2096 // global operator new.
2097 if (PlacementArgs.empty() && !PassAlignment &&
2098 (OperatorNew->isImplicit() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002099 (OperatorNew->getBeginLoc().isValid() &&
2100 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002101 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002102 Diag(StartLoc, diag::warn_overaligned_type)
2103 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002104 << unsigned(Alignment / Context.getCharWidth())
2105 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002106 }
2107 }
2108
Sebastian Redl6047f072012-02-16 12:22:20 +00002109 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002110 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2111 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002112 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002113 SourceRange InitRange(Inits[0]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002114 Inits[NumInits - 1]->getEndLoc());
Richard Smith0511d232016-10-05 22:41:02 +00002115 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2116 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002117 }
2118
Richard Smithdd2ca572012-11-26 08:32:48 +00002119 // If we can perform the initialization, and we've not already done so,
2120 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002121 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002122 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002123 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002124 // The type we initialize is the complete type, including the array bound.
2125 QualType InitType;
2126 if (KnownArraySize)
2127 InitType = Context.getConstantArrayType(
2128 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2129 *KnownArraySize),
2130 ArrayType::Normal, 0);
2131 else if (ArraySize)
2132 InitType =
2133 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2134 else
2135 InitType = AllocType;
2136
Douglas Gregor85dabae2009-12-16 01:38:02 +00002137 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002138 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002139 InitializationSequence InitSeq(*this, Entity, Kind,
2140 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002141 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002142 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002143 if (FullInit.isInvalid())
2144 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002145
Sebastian Redl6047f072012-02-16 12:22:20 +00002146 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2147 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002148 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002149 if (CXXBindTemporaryExpr *Binder =
2150 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002151 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002152
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002153 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002154 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002155
Douglas Gregor6642ca22010-02-26 05:06:18 +00002156 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002157 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002158 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2159 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002160 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00002161 }
2162 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002163 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2164 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002165 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00002166 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002167
John McCall928a2572011-07-13 20:12:57 +00002168 // C++0x [expr.new]p17:
2169 // If the new expression creates an array of objects of class type,
2170 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002171 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2172 if (ArraySize && !BaseAllocType->isDependentType()) {
2173 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2174 if (CXXDestructorDecl *dtor = LookupDestructor(
2175 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2176 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002177 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002178 PDiag(diag::err_access_dtor)
2179 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002180 if (DiagnoseUseOfDecl(dtor, StartLoc))
2181 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002182 }
John McCall928a2572011-07-13 20:12:57 +00002183 }
2184 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002185
Bruno Ricci9b6dfac2019-01-07 15:04:45 +00002186 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2187 PassAlignment, UsualArrayDeleteWantsSize,
2188 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2189 Initializer, ResultType, AllocTypeInfo, Range,
2190 DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002191}
2192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002193/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002194/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002195bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002196 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002197 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2198 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002199 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002200 return Diag(Loc, diag::err_bad_new_type)
2201 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002202 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002203 return Diag(Loc, diag::err_bad_new_type)
2204 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002205 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002206 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002207 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002208 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002209 diag::err_allocation_of_abstract_type))
2210 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002211 else if (AllocType->isVariablyModifiedType())
2212 return Diag(Loc, diag::err_variably_modified_new_type)
2213 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002214 else if (AllocType.getAddressSpace() != LangAS::Default &&
2215 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002216 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002217 << AllocType.getUnqualifiedType()
2218 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002219 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002220 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2221 QualType BaseAllocType = Context.getBaseElementType(AT);
2222 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2223 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002224 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002225 << BaseAllocType;
2226 }
2227 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002228
Sebastian Redlbd150f42008-11-21 19:14:01 +00002229 return false;
2230}
2231
Brian Gesiak87412d92018-02-15 20:09:25 +00002232static bool resolveAllocationOverload(
2233 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2234 bool &PassAlignment, FunctionDecl *&Operator,
2235 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002236 OverloadCandidateSet Candidates(R.getNameLoc(),
2237 OverloadCandidateSet::CSK_Normal);
2238 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2239 Alloc != AllocEnd; ++Alloc) {
2240 // Even member operator new/delete are implicitly treated as
2241 // static, so don't use AddMemberCandidate.
2242 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2243
2244 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2245 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2246 /*ExplicitTemplateArgs=*/nullptr, Args,
2247 Candidates,
2248 /*SuppressUserConversions=*/false);
2249 continue;
2250 }
2251
2252 FunctionDecl *Fn = cast<FunctionDecl>(D);
2253 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2254 /*SuppressUserConversions=*/false);
2255 }
2256
2257 // Do the resolution.
2258 OverloadCandidateSet::iterator Best;
2259 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2260 case OR_Success: {
2261 // Got one!
2262 FunctionDecl *FnDecl = Best->Function;
2263 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2264 Best->FoundDecl) == Sema::AR_inaccessible)
2265 return true;
2266
2267 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002268 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002269 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002270
Richard Smithb2f0f052016-10-10 18:54:32 +00002271 case OR_No_Viable_Function:
2272 // C++17 [expr.new]p13:
2273 // If no matching function is found and the allocated object type has
2274 // new-extended alignment, the alignment argument is removed from the
2275 // argument list, and overload resolution is performed again.
2276 if (PassAlignment) {
2277 PassAlignment = false;
2278 AlignArg = Args[1];
2279 Args.erase(Args.begin() + 1);
2280 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002281 Operator, &Candidates, AlignArg,
2282 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002283 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002284
Richard Smithb2f0f052016-10-10 18:54:32 +00002285 // MSVC will fall back on trying to find a matching global operator new
2286 // if operator new[] cannot be found. Also, MSVC will leak by not
2287 // generating a call to operator delete or operator delete[], but we
2288 // will not replicate that bug.
2289 // FIXME: Find out how this interacts with the std::align_val_t fallback
2290 // once MSVC implements it.
2291 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2292 S.Context.getLangOpts().MSVCCompat) {
2293 R.clear();
2294 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2295 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2296 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2297 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002298 Operator, /*Candidates=*/nullptr,
2299 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002300 }
Richard Smith1cdec012013-09-29 04:40:38 +00002301
Brian Gesiak87412d92018-02-15 20:09:25 +00002302 if (Diagnose) {
2303 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2304 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002305
Brian Gesiak87412d92018-02-15 20:09:25 +00002306 // If we have aligned candidates, only note the align_val_t candidates
2307 // from AlignedCandidates and the non-align_val_t candidates from
2308 // Candidates.
2309 if (AlignedCandidates) {
2310 auto IsAligned = [](OverloadCandidate &C) {
2311 return C.Function->getNumParams() > 1 &&
2312 C.Function->getParamDecl(1)->getType()->isAlignValT();
2313 };
2314 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002315
Brian Gesiak87412d92018-02-15 20:09:25 +00002316 // This was an overaligned allocation, so list the aligned candidates
2317 // first.
2318 Args.insert(Args.begin() + 1, AlignArg);
2319 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2320 R.getNameLoc(), IsAligned);
2321 Args.erase(Args.begin() + 1);
2322 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2323 IsUnaligned);
2324 } else {
2325 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2326 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002327 }
Richard Smith1cdec012013-09-29 04:40:38 +00002328 return true;
2329
Richard Smithb2f0f052016-10-10 18:54:32 +00002330 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002331 if (Diagnose) {
2332 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2333 << R.getLookupName() << Range;
2334 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2335 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002336 return true;
2337
2338 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002339 if (Diagnose) {
2340 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
Erik Pilkington13ee62f2019-03-20 19:26:33 +00002341 << R.getLookupName() << Range;
Brian Gesiak87412d92018-02-15 20:09:25 +00002342 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2343 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002344 return true;
2345 }
2346 }
2347 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002348}
2349
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002350bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002351 AllocationFunctionScope NewScope,
2352 AllocationFunctionScope DeleteScope,
2353 QualType AllocType, bool IsArray,
2354 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002355 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002356 FunctionDecl *&OperatorDelete,
2357 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002358 // --- Choosing an allocation function ---
2359 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002360 // 1) If looking in AFS_Global scope for allocation functions, only look in
2361 // the global scope. Else, if AFS_Class, only look in the scope of the
2362 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002363 // 2) If an array size is given, look for operator new[], else look for
2364 // operator new.
2365 // 3) The first argument is always size_t. Append the arguments from the
2366 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002367
Richard Smithb2f0f052016-10-10 18:54:32 +00002368 SmallVector<Expr*, 8> AllocArgs;
2369 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2370
2371 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002372 // FIXME: Should the Sema create the expression and embed it in the syntax
2373 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002374 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002375 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002376 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002377 Context.getSizeType(),
2378 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002379 AllocArgs.push_back(&Size);
2380
2381 QualType AlignValT = Context.VoidTy;
2382 if (PassAlignment) {
2383 DeclareGlobalNewDelete();
2384 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2385 }
2386 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2387 if (PassAlignment)
2388 AllocArgs.push_back(&Align);
2389
2390 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002391
Douglas Gregor6642ca22010-02-26 05:06:18 +00002392 // C++ [expr.new]p8:
2393 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002394 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002395 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002396 // type, the allocation function's name is operator new[] and the
2397 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002398 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002399 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002400
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002401 QualType AllocElemType = Context.getBaseElementType(AllocType);
2402
Richard Smithb2f0f052016-10-10 18:54:32 +00002403 // Find the allocation function.
2404 {
2405 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2406
2407 // C++1z [expr.new]p9:
2408 // If the new-expression begins with a unary :: operator, the allocation
2409 // function's name is looked up in the global scope. Otherwise, if the
2410 // allocated type is a class type T or array thereof, the allocation
2411 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002412 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002413 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2414
2415 // We can see ambiguity here if the allocation function is found in
2416 // multiple base classes.
2417 if (R.isAmbiguous())
2418 return true;
2419
2420 // If this lookup fails to find the name, or if the allocated type is not
2421 // a class type, the allocation function's name is looked up in the
2422 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002423 if (R.empty()) {
2424 if (NewScope == AFS_Class)
2425 return true;
2426
Richard Smithb2f0f052016-10-10 18:54:32 +00002427 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002428 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002429
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002430 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2431 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2432 return true;
2433 }
2434
Richard Smithb2f0f052016-10-10 18:54:32 +00002435 assert(!R.empty() && "implicitly declared allocation functions not found");
2436 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2437
2438 // We do our own custom access checks below.
2439 R.suppressDiagnostics();
2440
2441 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002442 OperatorNew, /*Candidates=*/nullptr,
2443 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002444 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002445 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002446
Richard Smithb2f0f052016-10-10 18:54:32 +00002447 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002448 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002449 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002450 return false;
2451 }
2452
Richard Smithb2f0f052016-10-10 18:54:32 +00002453 // Note, the name of OperatorNew might have been changed from array to
2454 // non-array by resolveAllocationOverload.
2455 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2456 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2457 ? OO_Array_Delete
2458 : OO_Delete);
2459
Douglas Gregor6642ca22010-02-26 05:06:18 +00002460 // C++ [expr.new]p19:
2461 //
2462 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002463 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002464 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002465 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002466 // the scope of T. If this lookup fails to find the name, or if
2467 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002468 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002469 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002470 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002471 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002472 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002473 LookupQualifiedName(FoundDelete, RD);
2474 }
John McCallfb6f5262010-03-18 08:19:33 +00002475 if (FoundDelete.isAmbiguous())
2476 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002477
Richard Smithb2f0f052016-10-10 18:54:32 +00002478 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002479 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002480 if (DeleteScope == AFS_Class)
2481 return true;
2482
Douglas Gregor6642ca22010-02-26 05:06:18 +00002483 DeclareGlobalNewDelete();
2484 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2485 }
2486
2487 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002488
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002489 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002490
John McCalld3be2c82010-09-14 21:34:24 +00002491 // Whether we're looking for a placement operator delete is dictated
2492 // by whether we selected a placement operator new, not by whether
2493 // we had explicit placement arguments. This matters for things like
2494 // struct A { void *operator new(size_t, int = 0); ... };
2495 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002496 //
2497 // We don't have any definition for what a "placement allocation function"
2498 // is, but we assume it's any allocation function whose
2499 // parameter-declaration-clause is anything other than (size_t).
2500 //
2501 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2502 // This affects whether an exception from the constructor of an overaligned
2503 // type uses the sized or non-sized form of aligned operator delete.
2504 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2505 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002506
2507 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002508 // C++ [expr.new]p20:
2509 // A declaration of a placement deallocation function matches the
2510 // declaration of a placement allocation function if it has the
2511 // same number of parameters and, after parameter transformations
2512 // (8.3.5), all parameter types except the first are
2513 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002514 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002515 // To perform this comparison, we compute the function type that
2516 // the deallocation function should have, and use that type both
2517 // for template argument deduction and for comparison purposes.
2518 QualType ExpectedFunctionType;
2519 {
2520 const FunctionProtoType *Proto
2521 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002522
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002523 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002525 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2526 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002527
John McCalldb40c7f2010-12-14 08:05:40 +00002528 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002529 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002530 EPI.Variadic = Proto->isVariadic();
2531
Douglas Gregor6642ca22010-02-26 05:06:18 +00002532 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002533 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002534 }
2535
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002536 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002537 DEnd = FoundDelete.end();
2538 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002539 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002540 if (FunctionTemplateDecl *FnTmpl =
2541 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002542 // Perform template argument deduction to try to match the
2543 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002544 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002545 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2546 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002547 continue;
2548 } else
2549 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2550
Richard Smithbaa47832016-12-01 02:11:49 +00002551 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2552 ExpectedFunctionType,
2553 /*AdjustExcpetionSpec*/true),
2554 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002555 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002556 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002557
Richard Smithb2f0f052016-10-10 18:54:32 +00002558 if (getLangOpts().CUDA)
2559 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2560 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002561 // C++1y [expr.new]p22:
2562 // For a non-placement allocation function, the normal deallocation
2563 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002564 //
2565 // Per [expr.delete]p10, this lookup prefers a member operator delete
2566 // without a size_t argument, but prefers a non-member operator delete
2567 // with a size_t where possible (which it always is in this case).
2568 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2569 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2570 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2571 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2572 &BestDeallocFns);
2573 if (Selected)
2574 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2575 else {
2576 // If we failed to select an operator, all remaining functions are viable
2577 // but ambiguous.
2578 for (auto Fn : BestDeallocFns)
2579 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002580 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002581 }
2582
2583 // C++ [expr.new]p20:
2584 // [...] If the lookup finds a single matching deallocation
2585 // function, that function will be called; otherwise, no
2586 // deallocation function will be called.
2587 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002588 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002589
Richard Smithb2f0f052016-10-10 18:54:32 +00002590 // C++1z [expr.new]p23:
2591 // If the lookup finds a usual deallocation function (3.7.4.2)
2592 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002593 // as a placement deallocation function, would have been
2594 // selected as a match for the allocation function, the program
2595 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002596 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002597 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002598 UsualDeallocFnInfo Info(*this,
2599 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002600 // Core issue, per mail to core reflector, 2016-10-09:
2601 // If this is a member operator delete, and there is a corresponding
2602 // non-sized member operator delete, this isn't /really/ a sized
2603 // deallocation function, it just happens to have a size_t parameter.
2604 bool IsSizedDelete = Info.HasSizeT;
2605 if (IsSizedDelete && !FoundGlobalDelete) {
2606 auto NonSizedDelete =
2607 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2608 /*WantAlign*/Info.HasAlignValT);
2609 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2610 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2611 IsSizedDelete = false;
2612 }
2613
2614 if (IsSizedDelete) {
2615 SourceRange R = PlaceArgs.empty()
2616 ? SourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002617 : SourceRange(PlaceArgs.front()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002618 PlaceArgs.back()->getEndLoc());
Richard Smithb2f0f052016-10-10 18:54:32 +00002619 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2620 if (!OperatorDelete->isImplicit())
2621 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2622 << DeleteName;
2623 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002624 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002625
2626 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2627 Matches[0].first);
2628 } else if (!Matches.empty()) {
2629 // We found multiple suitable operators. Per [expr.new]p20, that means we
2630 // call no 'operator delete' function, but we should at least warn the user.
2631 // FIXME: Suppress this warning if the construction cannot throw.
2632 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2633 << DeleteName << AllocElemType;
2634
2635 for (auto &Match : Matches)
2636 Diag(Match.second->getLocation(),
2637 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002638 }
2639
Sebastian Redlfaf68082008-12-03 20:26:15 +00002640 return false;
2641}
2642
2643/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2644/// delete. These are:
2645/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002646/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002647/// void* operator new(std::size_t) throw(std::bad_alloc);
2648/// void* operator new[](std::size_t) throw(std::bad_alloc);
2649/// void operator delete(void *) throw();
2650/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002651/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002652/// void* operator new(std::size_t);
2653/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002654/// void operator delete(void *) noexcept;
2655/// void operator delete[](void *) noexcept;
2656/// // C++1y:
2657/// void* operator new(std::size_t);
2658/// void* operator new[](std::size_t);
2659/// void operator delete(void *) noexcept;
2660/// void operator delete[](void *) noexcept;
2661/// void operator delete(void *, std::size_t) noexcept;
2662/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002663/// @endcode
2664/// Note that the placement and nothrow forms of new are *not* implicitly
2665/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002666void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002667 if (GlobalNewDeleteDeclared)
2668 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002669
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002670 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2671 // are not supported.
2672 if (getLangOpts().OpenCLCPlusPlus)
2673 return;
2674
Douglas Gregor87f54062009-09-15 22:30:29 +00002675 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002676 // [...] The following allocation and deallocation functions (18.4) are
2677 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002678 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002679 //
Sebastian Redl37588092011-03-14 18:08:30 +00002680 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002681 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002682 // void* operator new[](std::size_t) throw(std::bad_alloc);
2683 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002684 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002685 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002686 // void* operator new(std::size_t);
2687 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002688 // void operator delete(void*) noexcept;
2689 // void operator delete[](void*) noexcept;
2690 // C++1y:
2691 // void* operator new(std::size_t);
2692 // void* operator new[](std::size_t);
2693 // void operator delete(void*) noexcept;
2694 // void operator delete[](void*) noexcept;
2695 // void operator delete(void*, std::size_t) noexcept;
2696 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002697 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002698 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002699 // new, operator new[], operator delete, operator delete[].
2700 //
2701 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2702 // "std" or "bad_alloc" as necessary to form the exception specification.
2703 // However, we do not make these implicit declarations visible to name
2704 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002705 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002706 // The "std::bad_alloc" class has not yet been declared, so build it
2707 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002708 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2709 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002710 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002711 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002712 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002713 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002714 }
Richard Smith59139022016-09-30 22:41:36 +00002715 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002716 // The "std::align_val_t" enum class has not yet been declared, so build it
2717 // implicitly.
2718 auto *AlignValT = EnumDecl::Create(
2719 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2720 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2721 AlignValT->setIntegerType(Context.getSizeType());
2722 AlignValT->setPromotionType(Context.getSizeType());
2723 AlignValT->setImplicit(true);
2724 StdAlignValT = AlignValT;
2725 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002726
Sebastian Redlfaf68082008-12-03 20:26:15 +00002727 GlobalNewDeleteDeclared = true;
2728
2729 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2730 QualType SizeT = Context.getSizeType();
2731
Richard Smith96269c52016-09-29 22:49:46 +00002732 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2733 QualType Return, QualType Param) {
2734 llvm::SmallVector<QualType, 3> Params;
2735 Params.push_back(Param);
2736
2737 // Create up to four variants of the function (sized/aligned).
2738 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2739 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002740 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002741
2742 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2743 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2744 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002745 if (Sized)
2746 Params.push_back(SizeT);
2747
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002748 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002749 if (Aligned)
2750 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2751
2752 DeclareGlobalAllocationFunction(
2753 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2754
2755 if (Aligned)
2756 Params.pop_back();
2757 }
2758 }
2759 };
2760
2761 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2762 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2763 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2764 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002765}
2766
2767/// DeclareGlobalAllocationFunction - Declares a single implicit global
2768/// allocation function if it doesn't already exist.
2769void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002770 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002771 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002772 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2773
2774 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002775 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2776 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2777 Alloc != AllocEnd; ++Alloc) {
2778 // Only look at non-template functions, as it is the predefined,
2779 // non-templated allocation function we are trying to declare here.
2780 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002781 if (Func->getNumParams() == Params.size()) {
2782 llvm::SmallVector<QualType, 3> FuncParams;
2783 for (auto *P : Func->parameters())
2784 FuncParams.push_back(
2785 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2786 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002787 // Make the function visible to name lookup, even if we found it in
2788 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002789 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002790 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002791 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002792 }
Chandler Carruth93538422010-02-03 11:02:14 +00002793 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002794 }
2795 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002796
Erich Keane881e83d2019-03-04 14:54:52 +00002797 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2798 /*IsVariadic=*/false, /*IsCXXMethod=*/false));
Richard Smithc015bc22014-02-07 22:39:53 +00002799
Richard Smithf8b417c2014-02-08 00:42:45 +00002800 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002801 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002802 = (Name.getCXXOverloadedOperator() == OO_New ||
2803 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002804 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002805 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002806 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002807 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002808 EPI.ExceptionSpec.Type = EST_Dynamic;
2809 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002810 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002811 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002812 EPI.ExceptionSpec =
2813 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002815
Artem Belevich07db5cf2016-10-21 20:34:05 +00002816 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2817 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2818 FunctionDecl *Alloc = FunctionDecl::Create(
2819 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2820 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2821 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002822 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002823 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002824
Petr Hosek821b38f2018-12-04 03:25:25 +00002825 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2826 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2827 ? VisibilityAttr::Hidden
2828 : VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829
Artem Belevich07db5cf2016-10-21 20:34:05 +00002830 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2831 for (QualType T : Params) {
2832 ParamDecls.push_back(ParmVarDecl::Create(
2833 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2834 /*TInfo=*/nullptr, SC_None, nullptr));
2835 ParamDecls.back()->setImplicit();
2836 }
2837 Alloc->setParams(ParamDecls);
2838 if (ExtraAttr)
2839 Alloc->addAttr(ExtraAttr);
2840 Context.getTranslationUnitDecl()->addDecl(Alloc);
2841 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2842 };
2843
2844 if (!LangOpts.CUDA)
2845 CreateAllocationFunctionDecl(nullptr);
2846 else {
2847 // Host and device get their own declaration so each can be
2848 // defined or re-declared independently.
2849 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2850 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002851 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002852}
2853
Richard Smith1cdec012013-09-29 04:40:38 +00002854FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2855 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002856 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002857 DeclarationName Name) {
2858 DeclareGlobalNewDelete();
2859
2860 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2861 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2862
Richard Smithb2f0f052016-10-10 18:54:32 +00002863 // FIXME: It's possible for this to result in ambiguity, through a
2864 // user-declared variadic operator delete or the enable_if attribute. We
2865 // should probably not consider those cases to be usual deallocation
2866 // functions. But for now we just make an arbitrary choice in that case.
2867 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2868 Overaligned);
2869 assert(Result.FD && "operator delete missing from global scope?");
2870 return Result.FD;
2871}
Richard Smith1cdec012013-09-29 04:40:38 +00002872
Richard Smithb2f0f052016-10-10 18:54:32 +00002873FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2874 CXXRecordDecl *RD) {
2875 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002876
Richard Smithb2f0f052016-10-10 18:54:32 +00002877 FunctionDecl *OperatorDelete = nullptr;
2878 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2879 return nullptr;
2880 if (OperatorDelete)
2881 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002882
Richard Smithb2f0f052016-10-10 18:54:32 +00002883 // If there's no class-specific operator delete, look up the global
2884 // non-array delete.
2885 return FindUsualDeallocationFunction(
2886 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2887 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002888}
2889
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002890bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2891 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002892 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002893 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002894 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002895 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002896
John McCall27b18f82009-11-17 02:14:36 +00002897 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002898 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002899
Chandler Carruthb6f99172010-06-28 00:30:51 +00002900 Found.suppressDiagnostics();
2901
Richard Smithb2f0f052016-10-10 18:54:32 +00002902 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002903
Richard Smithb2f0f052016-10-10 18:54:32 +00002904 // C++17 [expr.delete]p10:
2905 // If the deallocation functions have class scope, the one without a
2906 // parameter of type std::size_t is selected.
2907 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2908 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2909 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002910
Richard Smithb2f0f052016-10-10 18:54:32 +00002911 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002912 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002913 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002914
Richard Smithb2f0f052016-10-10 18:54:32 +00002915 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002916 if (Operator->isDeleted()) {
2917 if (Diagnose) {
2918 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002919 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002920 }
2921 return true;
2922 }
2923
Richard Smith921bd202012-02-26 09:11:52 +00002924 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002925 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002926 return true;
2927
John McCall66a87592010-08-04 00:31:26 +00002928 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002929 }
John McCall66a87592010-08-04 00:31:26 +00002930
Richard Smithb2f0f052016-10-10 18:54:32 +00002931 // We found multiple suitable operators; complain about the ambiguity.
2932 // FIXME: The standard doesn't say to do this; it appears that the intent
2933 // is that this should never happen.
2934 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002935 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002936 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2937 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002938 for (auto &Match : Matches)
2939 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002940 }
John McCall66a87592010-08-04 00:31:26 +00002941 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002942 }
2943
2944 // We did find operator delete/operator delete[] declarations, but
2945 // none of them were suitable.
2946 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002947 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002948 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2949 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002950
Richard Smithb2f0f052016-10-10 18:54:32 +00002951 for (NamedDecl *D : Found)
2952 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002953 diag::note_member_declared_here) << Name;
2954 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002955 return true;
2956 }
2957
Craig Topperc3ec1492014-05-26 06:22:03 +00002958 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002959 return false;
2960}
2961
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002962namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002963/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002964/// initializing deletee have the same array form.
2965class MismatchingNewDeleteDetector {
2966public:
2967 enum MismatchResult {
2968 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2969 NoMismatch,
2970 /// Indicates that variable is initialized with mismatching form of \a new.
2971 VarInitMismatches,
2972 /// Indicates that member is initialized with mismatching form of \a new.
2973 MemberInitMismatches,
2974 /// Indicates that 1 or more constructors' definitions could not been
2975 /// analyzed, and they will be checked again at the end of translation unit.
2976 AnalyzeLater
2977 };
2978
2979 /// \param EndOfTU True, if this is the final analysis at the end of
2980 /// translation unit. False, if this is the initial analysis at the point
2981 /// delete-expression was encountered.
2982 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002983 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002984 HasUndefinedConstructors(false) {}
2985
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002986 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002987 /// matching form of new-expression.
2988 ///
2989 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2990 /// point where delete-expression is encountered, then a warning will be
2991 /// issued immediately. If return value is \c AnalyzeLater at the point where
2992 /// delete-expression is seen, then member will be analyzed at the end of
2993 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2994 /// couldn't be analyzed. If at least one constructor initializes the member
2995 /// with matching type of new, the return value is \c NoMismatch.
2996 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002997 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002998 /// \param Field Class member to analyze.
2999 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3000 /// for deleting the \p Field.
3001 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00003002 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003003 /// List of mismatching new-expressions used for initialization of the pointee
3004 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3005 /// Indicates whether delete-expression was in array form.
3006 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003007
3008private:
3009 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003010 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003011 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003012 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003013 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00003014 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003015 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003016 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003017 /// \c new either by the member initializer or in-class initialization.
3018 ///
3019 /// If bodies of all constructors are not visible at the end of translation
3020 /// unit or at least one constructor initializes member with the matching
3021 /// form of \c new, mismatch cannot be proven, and this function will return
3022 /// \c NoMismatch.
3023 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003024 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003025 /// \c new.
3026 ///
3027 /// If variable is initialized with matching form of \c new or variable is not
3028 /// initialized with a \c new expression, this function will return true.
3029 /// If variable is initialized with mismatching form of \c new, returns false.
3030 /// \param D Variable to analyze.
3031 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003032 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003033 /// form of \c new.
3034 ///
3035 /// Returns true, if member is initialized with matching form of \c new in
3036 /// member initializer list. Returns false, if member is initialized with the
3037 /// matching form of \c new in this constructor's initializer or given
3038 /// constructor isn't defined at the point where delete-expression is seen, or
3039 /// member isn't initialized by the constructor.
3040 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003041 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003042 /// \c new in member initializer list.
3043 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3044 /// Checks whether member is initialized with mismatching form of \c new by
3045 /// in-class initializer.
3046 MismatchResult analyzeInClassInitializer();
3047};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003048}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003049
3050MismatchingNewDeleteDetector::MismatchResult
3051MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3052 NewExprs.clear();
3053 assert(DE && "Expected delete-expression");
3054 IsArrayForm = DE->isArrayForm();
3055 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3056 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3057 return analyzeMemberExpr(ME);
3058 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3059 if (!hasMatchingVarInit(D))
3060 return VarInitMismatches;
3061 }
3062 return NoMismatch;
3063}
3064
3065const CXXNewExpr *
3066MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3067 assert(E != nullptr && "Expected a valid initializer expression");
3068 E = E->IgnoreParenImpCasts();
3069 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3070 if (ILE->getNumInits() == 1)
3071 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3072 }
3073
3074 return dyn_cast_or_null<const CXXNewExpr>(E);
3075}
3076
3077bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3078 const CXXCtorInitializer *CI) {
3079 const CXXNewExpr *NE = nullptr;
3080 if (Field == CI->getMember() &&
3081 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3082 if (NE->isArray() == IsArrayForm)
3083 return true;
3084 else
3085 NewExprs.push_back(NE);
3086 }
3087 return false;
3088}
3089
3090bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3091 const CXXConstructorDecl *CD) {
3092 if (CD->isImplicit())
3093 return false;
3094 const FunctionDecl *Definition = CD;
3095 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3096 HasUndefinedConstructors = true;
3097 return EndOfTU;
3098 }
3099 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3100 if (hasMatchingNewInCtorInit(CI))
3101 return true;
3102 }
3103 return false;
3104}
3105
3106MismatchingNewDeleteDetector::MismatchResult
3107MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3108 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003109 const Expr *InitExpr = Field->getInClassInitializer();
3110 if (!InitExpr)
3111 return EndOfTU ? NoMismatch : AnalyzeLater;
3112 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003113 if (NE->isArray() != IsArrayForm) {
3114 NewExprs.push_back(NE);
3115 return MemberInitMismatches;
3116 }
3117 }
3118 return NoMismatch;
3119}
3120
3121MismatchingNewDeleteDetector::MismatchResult
3122MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3123 bool DeleteWasArrayForm) {
3124 assert(Field != nullptr && "Analysis requires a valid class member.");
3125 this->Field = Field;
3126 IsArrayForm = DeleteWasArrayForm;
3127 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3128 for (const auto *CD : RD->ctors()) {
3129 if (hasMatchingNewInCtor(CD))
3130 return NoMismatch;
3131 }
3132 if (HasUndefinedConstructors)
3133 return EndOfTU ? NoMismatch : AnalyzeLater;
3134 if (!NewExprs.empty())
3135 return MemberInitMismatches;
3136 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3137 : NoMismatch;
3138}
3139
3140MismatchingNewDeleteDetector::MismatchResult
3141MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3142 assert(ME != nullptr && "Expected a member expression");
3143 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3144 return analyzeField(F, IsArrayForm);
3145 return NoMismatch;
3146}
3147
3148bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3149 const CXXNewExpr *NE = nullptr;
3150 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3151 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3152 NE->isArray() != IsArrayForm) {
3153 NewExprs.push_back(NE);
3154 }
3155 }
3156 return NewExprs.empty();
3157}
3158
3159static void
3160DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3161 const MismatchingNewDeleteDetector &Detector) {
3162 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3163 FixItHint H;
3164 if (!Detector.IsArrayForm)
3165 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3166 else {
3167 SourceLocation RSquare = Lexer::findLocationAfterToken(
3168 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3169 SemaRef.getLangOpts(), true);
3170 if (RSquare.isValid())
3171 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3172 }
3173 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3174 << Detector.IsArrayForm << H;
3175
3176 for (const auto *NE : Detector.NewExprs)
3177 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3178 << Detector.IsArrayForm;
3179}
3180
3181void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3182 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3183 return;
3184 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3185 switch (Detector.analyzeDeleteExpr(DE)) {
3186 case MismatchingNewDeleteDetector::VarInitMismatches:
3187 case MismatchingNewDeleteDetector::MemberInitMismatches: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003188 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003189 break;
3190 }
3191 case MismatchingNewDeleteDetector::AnalyzeLater: {
3192 DeleteExprs[Detector.Field].push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003193 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003194 break;
3195 }
3196 case MismatchingNewDeleteDetector::NoMismatch:
3197 break;
3198 }
3199}
3200
3201void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3202 bool DeleteWasArrayForm) {
3203 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3204 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3205 case MismatchingNewDeleteDetector::VarInitMismatches:
3206 llvm_unreachable("This analysis should have been done for class members.");
3207 case MismatchingNewDeleteDetector::AnalyzeLater:
3208 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3209 "translation unit.");
3210 case MismatchingNewDeleteDetector::MemberInitMismatches:
3211 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3212 break;
3213 case MismatchingNewDeleteDetector::NoMismatch:
3214 break;
3215 }
3216}
3217
Sebastian Redlbd150f42008-11-21 19:14:01 +00003218/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3219/// @code ::delete ptr; @endcode
3220/// or
3221/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003222ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003223Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003224 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003225 // C++ [expr.delete]p1:
3226 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003227 // non-explicit conversion function to a pointer type. The result has type
3228 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003229 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003230 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3231
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003232 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003233 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003234 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003235 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003236
John Wiegley01296292011-04-08 18:41:53 +00003237 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003238 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003239 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003240 if (Ex.isInvalid())
3241 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003242
John Wiegley01296292011-04-08 18:41:53 +00003243 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003244
Richard Smithccc11812013-05-21 19:05:48 +00003245 class DeleteConverter : public ContextualImplicitConverter {
3246 public:
3247 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248
Craig Toppere14c0f82014-03-12 04:55:44 +00003249 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003250 // FIXME: If we have an operator T* and an operator void*, we must pick
3251 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003252 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003253 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003254 return true;
3255 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003256 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003257
Richard Smithccc11812013-05-21 19:05:48 +00003258 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003259 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003260 return S.Diag(Loc, diag::err_delete_operand) << T;
3261 }
3262
3263 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003264 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003265 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3266 }
3267
3268 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003269 QualType T,
3270 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003271 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3272 }
3273
3274 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003275 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003276 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3277 << ConvTy;
3278 }
3279
3280 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003281 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003282 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3283 }
3284
3285 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003286 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003287 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3288 << ConvTy;
3289 }
3290
3291 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003292 QualType T,
3293 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003294 llvm_unreachable("conversion functions are permitted");
3295 }
3296 } Converter;
3297
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003298 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003299 if (Ex.isInvalid())
3300 return ExprError();
3301 Type = Ex.get()->getType();
3302 if (!Converter.match(Type))
3303 // FIXME: PerformContextualImplicitConversion should return ExprError
3304 // itself in this case.
3305 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003306
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003307 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003308 QualType PointeeElem = Context.getBaseElementType(Pointee);
3309
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003310 if (Pointee.getAddressSpace() != LangAS::Default &&
3311 !getLangOpts().OpenCLCPlusPlus)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003312 return Diag(Ex.get()->getBeginLoc(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003313 diag::err_address_space_qualified_delete)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003314 << Pointee.getUnqualifiedType()
3315 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003316
Craig Topperc3ec1492014-05-26 06:22:03 +00003317 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003318 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003319 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003320 // effectively bans deletion of "void*". However, most compilers support
3321 // this, so we treat it as a warning unless we're in a SFINAE context.
3322 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003323 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003324 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003325 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003326 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003327 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003328 // FIXME: This can result in errors if the definition was imported from a
3329 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003330 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003331 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003332 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3333 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3334 }
3335 }
3336
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003337 if (Pointee->isArrayType() && !ArrayForm) {
3338 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003339 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003340 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003341 ArrayForm = true;
3342 }
3343
Anders Carlssona471db02009-08-16 20:29:29 +00003344 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3345 ArrayForm ? OO_Array_Delete : OO_Delete);
3346
Eli Friedmanae4280f2011-07-26 22:25:31 +00003347 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003348 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003349 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3350 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003351 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003352
John McCall284c48f2011-01-27 09:37:56 +00003353 // If we're allocating an array of records, check whether the
3354 // usual operator delete[] has a size_t parameter.
3355 if (ArrayForm) {
3356 // If the user specifically asked to use the global allocator,
3357 // we'll need to do the lookup into the class.
3358 if (UseGlobal)
3359 UsualArrayDeleteWantsSize =
3360 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3361
3362 // Otherwise, the usual operator delete[] should be the
3363 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003364 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003365 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003366 UsualDeallocFnInfo(*this,
3367 DeclAccessPair::make(OperatorDelete, AS_public))
3368 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003369 }
3370
Richard Smitheec915d62012-02-18 04:13:32 +00003371 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003372 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003373 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003374 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003375 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3376 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003377 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003378
Nico Weber5a9259c2016-01-15 21:45:31 +00003379 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3380 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3381 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3382 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384
Richard Smithb2f0f052016-10-10 18:54:32 +00003385 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003386 if (getLangOpts().OpenCLCPlusPlus) {
3387 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3388 return ExprError();
3389 }
3390
Richard Smithb2f0f052016-10-10 18:54:32 +00003391 bool IsComplete = isCompleteType(StartLoc, Pointee);
3392 bool CanProvideSize =
3393 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3394 Pointee.isDestructedType());
3395 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3396
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003397 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003398 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3399 Overaligned, DeleteName);
3400 }
Mike Stump11289f42009-09-09 15:08:12 +00003401
Eli Friedmanfa0df832012-02-02 03:46:19 +00003402 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003403
Richard Smith5b349582017-10-13 01:55:36 +00003404 // Check access and ambiguity of destructor if we're going to call it.
3405 // Note that this is required even for a virtual delete.
3406 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003407 if (PointeeRD) {
3408 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003409 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3410 PDiag(diag::err_access_dtor) << PointeeElem);
3411 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003412 }
3413 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003414
Akira Hatanaka71645c22018-12-21 07:05:36 +00003415 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
Richard Smith5b349582017-10-13 01:55:36 +00003416
3417 // Convert the operand to the type of the first parameter of operator
3418 // delete. This is only necessary if we selected a destroying operator
3419 // delete that we are going to call (non-virtually); converting to void*
3420 // is trivial and left to AST consumers to handle.
3421 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3422 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003423 Qualifiers Qs = Pointee.getQualifiers();
3424 if (Qs.hasCVRQualifiers()) {
3425 // Qualifiers are irrelevant to this conversion; we're only looking
3426 // for access and ambiguity.
3427 Qs.removeCVRQualifiers();
3428 QualType Unqual = Context.getPointerType(
3429 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3430 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3431 }
Richard Smith5b349582017-10-13 01:55:36 +00003432 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3433 if (Ex.isInvalid())
3434 return ExprError();
3435 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003436 }
3437
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003438 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003439 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3440 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003441 AnalyzeDeleteExprMismatch(Result);
3442 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003443}
3444
Eric Fiselierfa752f22018-03-21 19:19:48 +00003445static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3446 bool IsDelete,
3447 FunctionDecl *&Operator) {
3448
3449 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3450 IsDelete ? OO_Delete : OO_New);
3451
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003452 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003453 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3454 assert(!R.empty() && "implicitly declared allocation functions not found");
3455 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3456
3457 // We do our own custom access checks below.
3458 R.suppressDiagnostics();
3459
3460 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3461 OverloadCandidateSet Candidates(R.getNameLoc(),
3462 OverloadCandidateSet::CSK_Normal);
3463 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3464 FnOvl != FnOvlEnd; ++FnOvl) {
3465 // Even member operator new/delete are implicitly treated as
3466 // static, so don't use AddMemberCandidate.
3467 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3468
3469 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3470 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3471 /*ExplicitTemplateArgs=*/nullptr, Args,
3472 Candidates,
3473 /*SuppressUserConversions=*/false);
3474 continue;
3475 }
3476
3477 FunctionDecl *Fn = cast<FunctionDecl>(D);
3478 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3479 /*SuppressUserConversions=*/false);
3480 }
3481
3482 SourceRange Range = TheCall->getSourceRange();
3483
3484 // Do the resolution.
3485 OverloadCandidateSet::iterator Best;
3486 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3487 case OR_Success: {
3488 // Got one!
3489 FunctionDecl *FnDecl = Best->Function;
3490 assert(R.getNamingClass() == nullptr &&
3491 "class members should not be considered");
3492
3493 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3494 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3495 << (IsDelete ? 1 : 0) << Range;
3496 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3497 << R.getLookupName() << FnDecl->getSourceRange();
3498 return true;
3499 }
3500
3501 Operator = FnDecl;
3502 return false;
3503 }
3504
3505 case OR_No_Viable_Function:
3506 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3507 << R.getLookupName() << Range;
3508 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3509 return true;
3510
3511 case OR_Ambiguous:
3512 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3513 << R.getLookupName() << Range;
3514 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3515 return true;
3516
3517 case OR_Deleted: {
3518 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
Erik Pilkington13ee62f2019-03-20 19:26:33 +00003519 << R.getLookupName() << Range;
Eric Fiselierfa752f22018-03-21 19:19:48 +00003520 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3521 return true;
3522 }
3523 }
3524 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3525}
3526
3527ExprResult
3528Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3529 bool IsDelete) {
3530 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3531 if (!getLangOpts().CPlusPlus) {
3532 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3533 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3534 << "C++";
3535 return ExprError();
3536 }
3537 // CodeGen assumes it can find the global new and delete to call,
3538 // so ensure that they are declared.
3539 DeclareGlobalNewDelete();
3540
3541 FunctionDecl *OperatorNewOrDelete = nullptr;
3542 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3543 OperatorNewOrDelete))
3544 return ExprError();
3545 assert(OperatorNewOrDelete && "should be found");
3546
Akira Hatanaka71645c22018-12-21 07:05:36 +00003547 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3548 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3549
Eric Fiselierfa752f22018-03-21 19:19:48 +00003550 TheCall->setType(OperatorNewOrDelete->getReturnType());
3551 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3552 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3553 InitializedEntity Entity =
3554 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3555 ExprResult Arg = PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003556 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
Eric Fiselierfa752f22018-03-21 19:19:48 +00003557 if (Arg.isInvalid())
3558 return ExprError();
3559 TheCall->setArg(i, Arg.get());
3560 }
3561 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3562 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3563 "Callee expected to be implicit cast to a builtin function pointer");
3564 Callee->setType(OperatorNewOrDelete->getType());
3565
3566 return TheCallResult;
3567}
3568
Nico Weber5a9259c2016-01-15 21:45:31 +00003569void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3570 bool IsDelete, bool CallCanBeVirtual,
3571 bool WarnOnNonAbstractTypes,
3572 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003573 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003574 return;
3575
3576 // C++ [expr.delete]p3:
3577 // In the first alternative (delete object), if the static type of the
3578 // object to be deleted is different from its dynamic type, the static
3579 // type shall be a base class of the dynamic type of the object to be
3580 // deleted and the static type shall have a virtual destructor or the
3581 // behavior is undefined.
3582 //
3583 const CXXRecordDecl *PointeeRD = dtor->getParent();
3584 // Note: a final class cannot be derived from, no issue there
3585 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3586 return;
3587
Nico Weberbf2260c2017-08-31 06:17:08 +00003588 // If the superclass is in a system header, there's nothing that can be done.
3589 // The `delete` (where we emit the warning) can be in a system header,
3590 // what matters for this warning is where the deleted type is defined.
3591 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3592 return;
3593
Brian Gesiak5488ab42019-01-11 01:54:53 +00003594 QualType ClassType = dtor->getThisType()->getPointeeType();
Nico Weber5a9259c2016-01-15 21:45:31 +00003595 if (PointeeRD->isAbstract()) {
3596 // If the class is abstract, we warn by default, because we're
3597 // sure the code has undefined behavior.
3598 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3599 << ClassType;
3600 } else if (WarnOnNonAbstractTypes) {
3601 // Otherwise, if this is not an array delete, it's a bit suspect,
3602 // but not necessarily wrong.
3603 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3604 << ClassType;
3605 }
3606 if (!IsDelete) {
3607 std::string TypeStr;
3608 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3609 Diag(DtorLoc, diag::note_delete_non_virtual)
3610 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3611 }
3612}
3613
Richard Smith03a4aa32016-06-23 19:02:52 +00003614Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3615 SourceLocation StmtLoc,
3616 ConditionKind CK) {
3617 ExprResult E =
3618 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3619 if (E.isInvalid())
3620 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003621 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3622 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003623}
3624
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003625/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003626/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003627ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003628 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003629 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003630 if (ConditionVar->isInvalidDecl())
3631 return ExprError();
3632
Douglas Gregor633caca2009-11-23 23:44:04 +00003633 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003634
Douglas Gregor633caca2009-11-23 23:44:04 +00003635 // C++ [stmt.select]p2:
3636 // The declarator shall not specify a function or an array.
3637 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003639 diag::err_invalid_use_of_function_type)
3640 << ConditionVar->getSourceRange());
3641 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003642 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003643 diag::err_invalid_use_of_array_type)
3644 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003645
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003646 ExprResult Condition = DeclRefExpr::Create(
3647 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3648 /*enclosing*/ false, ConditionVar->getLocation(),
3649 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003650
Eli Friedmanfa0df832012-02-02 03:46:19 +00003651 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003652
Richard Smith03a4aa32016-06-23 19:02:52 +00003653 switch (CK) {
3654 case ConditionKind::Boolean:
3655 return CheckBooleanCondition(StmtLoc, Condition.get());
3656
Richard Smithb130fe72016-06-23 19:16:49 +00003657 case ConditionKind::ConstexprIf:
3658 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3659
Richard Smith03a4aa32016-06-23 19:02:52 +00003660 case ConditionKind::Switch:
3661 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663
Richard Smith03a4aa32016-06-23 19:02:52 +00003664 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003665}
3666
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003667/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003668ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003669 // C++ 6.4p4:
3670 // The value of a condition that is an initialized declaration in a statement
3671 // other than a switch statement is the value of the declared variable
3672 // implicitly converted to type bool. If that conversion is ill-formed, the
3673 // program is ill-formed.
3674 // The value of a condition that is an expression is the value of the
3675 // expression, implicitly converted to bool.
3676 //
Richard Smithb130fe72016-06-23 19:16:49 +00003677 // FIXME: Return this value to the caller so they don't need to recompute it.
3678 llvm::APSInt Value(/*BitWidth*/1);
3679 return (IsConstexpr && !CondExpr->isValueDependent())
3680 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3681 CCEK_ConstexprIf)
3682 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003683}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003684
3685/// Helper function to determine whether this is the (deprecated) C++
3686/// conversion from a string literal to a pointer to non-const char or
3687/// non-const wchar_t (for narrow and wide string literals,
3688/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003689bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003690Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3691 // Look inside the implicit cast, if it exists.
3692 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3693 From = Cast->getSubExpr();
3694
3695 // A string literal (2.13.4) that is not a wide string literal can
3696 // be converted to an rvalue of type "pointer to char"; a wide
3697 // string literal can be converted to an rvalue of type "pointer
3698 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003699 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003700 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003701 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003702 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003703 // This conversion is considered only when there is an
3704 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003705 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3706 switch (StrLit->getKind()) {
3707 case StringLiteral::UTF8:
3708 case StringLiteral::UTF16:
3709 case StringLiteral::UTF32:
3710 // We don't allow UTF literals to be implicitly converted
3711 break;
3712 case StringLiteral::Ascii:
3713 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3714 ToPointeeType->getKind() == BuiltinType::Char_S);
3715 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003716 return Context.typesAreCompatible(Context.getWideCharType(),
3717 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003718 }
3719 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003720 }
3721
3722 return false;
3723}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003724
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003726 SourceLocation CastLoc,
3727 QualType Ty,
3728 CastKind Kind,
3729 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003730 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003731 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003732 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003733 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003734 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003735 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003736 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003737 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003738
Richard Smith72d74052013-07-20 19:41:36 +00003739 if (S.RequireNonAbstractType(CastLoc, Ty,
3740 diag::err_allocation_of_abstract_type))
3741 return ExprError();
3742
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003743 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003744 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003745
Richard Smith5179eb72016-06-28 19:03:57 +00003746 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3747 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003748 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003749 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003750
Richard Smithf8adcdc2014-07-17 05:12:35 +00003751 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003752 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003753 ConstructorArgs, HadMultipleCandidates,
3754 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3755 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003756 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003757 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003759 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003760 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761
John McCalle3027922010-08-25 11:45:40 +00003762 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003763 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764
Richard Smithd3f2d322015-02-24 21:16:19 +00003765 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003766 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003767 return ExprError();
3768
Douglas Gregora4253922010-04-16 22:17:36 +00003769 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003770 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3771 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003772 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003773 if (Result.isInvalid())
3774 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003775 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003776 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3777 CK_UserDefinedConversion, Result.get(),
3778 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003779
Douglas Gregor668443e2011-01-20 00:18:04 +00003780 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003781 }
3782 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003783}
Douglas Gregora4253922010-04-16 22:17:36 +00003784
Douglas Gregor5fb53972009-01-14 15:45:31 +00003785/// PerformImplicitConversion - Perform an implicit conversion of the
3786/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003787/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003788/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003789/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003790ExprResult
3791Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003792 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003793 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003794 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003795 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3796 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3797 return From;
3798
John McCall0d1da222010-01-12 00:44:57 +00003799 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003800 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003801 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3802 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003803 if (Res.isInvalid())
3804 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003805 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003806 break;
John Wiegley01296292011-04-08 18:41:53 +00003807 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003808
Anders Carlsson110b07b2009-09-15 06:28:28 +00003809 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003810
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003811 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003812 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003813 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003814 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003815 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003816 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817
Anders Carlsson110b07b2009-09-15 06:28:28 +00003818 // If the user-defined conversion is specified by a conversion function,
3819 // the initial standard conversion sequence converts the source type to
3820 // the implicit object parameter of the conversion function.
3821 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003822 } else {
3823 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003824 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003825 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003826 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003827 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003828 // initial standard conversion sequence converts the source type to
3829 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003830 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832 }
Richard Smith72d74052013-07-20 19:41:36 +00003833 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003834 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003835 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003836 PerformImplicitConversion(From, BeforeToType,
3837 ICS.UserDefined.Before, AA_Converting,
3838 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003839 if (Res.isInvalid())
3840 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003841 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003844 ExprResult CastArg = BuildCXXCastArgument(
3845 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3846 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3847 ICS.UserDefined.HadMultipleCandidates, From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003848
3849 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003850 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003851
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003852 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003853
Richard Smith1ef75542018-06-27 20:30:34 +00003854 // C++ [over.match.oper]p7:
3855 // [...] the second standard conversion sequence of a user-defined
3856 // conversion sequence is not applied.
3857 if (CCK == CCK_ForBuiltinOverloadedOp)
3858 return From;
3859
Richard Smith507840d2011-11-29 22:48:16 +00003860 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3861 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003862 }
John McCall0d1da222010-01-12 00:44:57 +00003863
3864 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003865 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003866 PDiag(diag::err_typecheck_ambiguous_condition)
3867 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003868 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003869
Douglas Gregor39c16d42008-10-24 04:54:22 +00003870 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003871 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003872
3873 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003874 bool Diagnosed =
3875 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3876 From->getType(), From, Action);
3877 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003878 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003879 }
3880
3881 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003882 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003883}
3884
Richard Smith507840d2011-11-29 22:48:16 +00003885/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003886/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003887/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003888/// expression. Flavor is the context in which we're performing this
3889/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003890ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003891Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003892 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003893 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003894 CheckedConversionKind CCK) {
3895 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003896
Mike Stump87c57ac2009-05-16 07:39:55 +00003897 // Overall FIXME: we are recomputing too many types here and doing far too
3898 // much extra work. What this means is that we need to keep track of more
3899 // information that is computed when we try the implicit conversion initially,
3900 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003901 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003902
Douglas Gregor2fe98832008-11-03 19:09:14 +00003903 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003904 // FIXME: When can ToType be a reference type?
3905 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003906 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003907 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003908 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003909 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003910 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003911 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003912 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003913 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3914 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003915 ConstructorArgs, /*HadMultipleCandidates*/ false,
3916 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3917 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003918 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003919 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003920 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3921 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003922 From, /*HadMultipleCandidates*/ false,
3923 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3924 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003925 }
3926
Douglas Gregor980fb162010-04-29 18:24:40 +00003927 // Resolve overloaded function references.
3928 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3929 DeclAccessPair Found;
3930 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3931 true, Found);
3932 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003933 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003934
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003935 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00003936 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003937
Douglas Gregor980fb162010-04-29 18:24:40 +00003938 From = FixOverloadedFunctionReference(From, Found, Fn);
3939 FromType = From->getType();
3940 }
3941
Richard Smitha23ab512013-05-23 00:30:41 +00003942 // If we're converting to an atomic type, first convert to the corresponding
3943 // non-atomic type.
3944 QualType ToAtomicType;
3945 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3946 ToAtomicType = ToType;
3947 ToType = ToAtomic->getValueType();
3948 }
3949
George Burgess IV8d141e02015-12-14 22:00:49 +00003950 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003951 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003952 switch (SCS.First) {
3953 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003954 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3955 FromType = FromAtomic->getValueType().getUnqualifiedType();
3956 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3957 From, /*BasePath=*/nullptr, VK_RValue);
3958 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003959 break;
3960
Eli Friedman946b7b52012-01-24 22:51:26 +00003961 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003962 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003963 ExprResult FromRes = DefaultLvalueConversion(From);
3964 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003965 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003966 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003967 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003968 }
John McCall34376a62010-12-04 03:47:34 +00003969
Douglas Gregor39c16d42008-10-24 04:54:22 +00003970 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003971 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003972 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003973 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003974 break;
3975
3976 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003977 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003978 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003979 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003980 break;
3981
3982 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003983 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003984 }
3985
Richard Smith507840d2011-11-29 22:48:16 +00003986 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003987 switch (SCS.Second) {
3988 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003989 // C++ [except.spec]p5:
3990 // [For] assignment to and initialization of pointers to functions,
3991 // pointers to member functions, and references to functions: the
3992 // target entity shall allow at least the exceptions allowed by the
3993 // source value in the assignment or initialization.
3994 switch (Action) {
3995 case AA_Assigning:
3996 case AA_Initializing:
3997 // Note, function argument passing and returning are initialization.
3998 case AA_Passing:
3999 case AA_Returning:
4000 case AA_Sending:
4001 case AA_Passing_CFAudited:
4002 if (CheckExceptionSpecCompatibility(From, ToType))
4003 return ExprError();
4004 break;
4005
4006 case AA_Casting:
4007 case AA_Converting:
4008 // Casts and implicit conversions are not initialization, so are not
4009 // checked for exception specification mismatches.
4010 break;
4011 }
Sebastian Redl5d431642009-10-10 12:04:10 +00004012 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004013 break;
4014
4015 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004016 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00004017 if (ToType->isBooleanType()) {
4018 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4019 SCS.Second == ICK_Integral_Promotion &&
4020 "only enums with fixed underlying type can promote to bool");
4021 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004022 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004023 } else {
4024 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004025 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004026 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004027 break;
4028
4029 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004030 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004031 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004032 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004033 break;
4034
4035 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004036 case ICK_Complex_Conversion: {
4037 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4038 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4039 CastKind CK;
4040 if (FromEl->isRealFloatingType()) {
4041 if (ToEl->isRealFloatingType())
4042 CK = CK_FloatingComplexCast;
4043 else
4044 CK = CK_FloatingComplexToIntegralComplex;
4045 } else if (ToEl->isRealFloatingType()) {
4046 CK = CK_IntegralComplexToFloatingComplex;
4047 } else {
4048 CK = CK_IntegralComplexCast;
4049 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004050 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004051 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004052 break;
John McCall8cb679e2010-11-15 09:13:47 +00004053 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004054
Douglas Gregor39c16d42008-10-24 04:54:22 +00004055 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004056 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004057 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004058 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004059 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004060 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004061 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004062 break;
4063
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004064 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004065 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004066 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004067 break;
4068
John McCall31168b02011-06-15 23:02:42 +00004069 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004070 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004071 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004072 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004073 if (Action == AA_Initializing || Action == AA_Assigning)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004074 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004075 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004076 << ToType << From->getType() << Action << From->getSourceRange()
4077 << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004078 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004079 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004080 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004081 << From->getType() << ToType << Action << From->getSourceRange()
4082 << 0;
John McCall31168b02011-06-15 23:02:42 +00004083
Douglas Gregor33823722011-06-11 01:09:30 +00004084 if (From->getType()->isObjCObjectPointerType() &&
4085 ToType->isObjCObjectPointerType())
4086 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004087 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4088 !CheckObjCARCUnavailableWeakConversion(ToType,
4089 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004090 if (Action == AA_Initializing)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004091 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
John McCall9c3467e2011-09-09 06:12:06 +00004092 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004093 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4094 << (Action == AA_Casting) << From->getType() << ToType
4095 << From->getSourceRange();
John McCall9c3467e2011-09-09 06:12:06 +00004096 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004097
Richard Smith354abec2017-12-08 23:29:59 +00004098 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004099 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004100 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004101 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004102
4103 // Make sure we extend blocks if necessary.
4104 // FIXME: doing this here is really ugly.
4105 if (Kind == CK_BlockPointerToObjCPointerCast) {
4106 ExprResult E = From;
4107 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004108 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004109 }
Brian Kelley11352a82017-03-29 18:09:02 +00004110 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4111 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004112 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004113 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004114 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004117 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004118 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004119 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004120 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004121 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004122 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004123 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004124
4125 // We may not have been able to figure out what this member pointer resolved
4126 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004127 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004128 (void)isCompleteType(From->getExprLoc(), From->getType());
4129 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004130 }
David Majnemerd96b9972014-08-08 00:10:39 +00004131
Richard Smith507840d2011-11-29 22:48:16 +00004132 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004133 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004134 break;
4135 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004136
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004137 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004138 // Perform half-to-boolean conversion via float.
4139 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004140 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004141 FromType = Context.FloatTy;
4142 }
4143
Richard Smith507840d2011-11-29 22:48:16 +00004144 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004145 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004146 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004147 break;
4148
Douglas Gregor88d292c2010-05-13 16:44:06 +00004149 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004150 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004151 if (CheckDerivedToBaseConversion(
4152 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4153 From->getSourceRange(), &BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004154 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004155
Richard Smith507840d2011-11-29 22:48:16 +00004156 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4157 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004158 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004159 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004160 }
4161
Douglas Gregor46188682010-05-18 22:42:18 +00004162 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004163 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004164 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004165 break;
4166
George Burgess IVdf1ed002016-01-13 01:52:39 +00004167 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004168 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004169 Expr *Elem = prepareVectorSplat(ToType, From).get();
4170 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4171 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004172 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004174
Douglas Gregor46188682010-05-18 22:42:18 +00004175 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004176 // Case 1. x -> _Complex y
4177 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4178 QualType ElType = ToComplex->getElementType();
4179 bool isFloatingComplex = ElType->isRealFloatingType();
4180
4181 // x -> y
4182 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4183 // do nothing
4184 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004185 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004186 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004187 } else {
4188 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004189 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004190 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004191 }
4192 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004193 From = ImpCastExprToType(From, ToType,
4194 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004195 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004196
4197 // Case 2. _Complex x -> y
4198 } else {
4199 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4200 assert(FromComplex);
4201
4202 QualType ElType = FromComplex->getElementType();
4203 bool isFloatingComplex = ElType->isRealFloatingType();
4204
4205 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004206 From = ImpCastExprToType(From, ElType,
4207 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004208 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004209 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004210
4211 // x -> y
4212 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4213 // do nothing
4214 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004215 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004216 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004217 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004218 } else {
4219 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004220 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004221 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004222 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004223 }
4224 }
Douglas Gregor46188682010-05-18 22:42:18 +00004225 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004226
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004227 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004228 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004229 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004230 break;
4231 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004232
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004233 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004234 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004235 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004236 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4237 if (FromRes.isInvalid())
4238 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004239 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004240 assert ((ConvTy == Sema::Compatible) &&
4241 "Improper transparent union conversion");
4242 (void)ConvTy;
4243 break;
4244 }
4245
Guy Benyei259f9f42013-02-07 16:05:33 +00004246 case ICK_Zero_Event_Conversion:
Egor Churaev89831422016-12-23 14:55:49 +00004247 case ICK_Zero_Queue_Conversion:
4248 From = ImpCastExprToType(From, ToType,
Andrew Savonichevb555b762018-10-23 15:19:20 +00004249 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00004250 From->getValueKind()).get();
4251 break;
4252
Douglas Gregor46188682010-05-18 22:42:18 +00004253 case ICK_Lvalue_To_Rvalue:
4254 case ICK_Array_To_Pointer:
4255 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004256 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004257 case ICK_Qualification:
4258 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004259 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004260 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004261 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004262 }
4263
4264 switch (SCS.Third) {
4265 case ICK_Identity:
4266 // Nothing to do.
4267 break;
4268
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004269 case ICK_Function_Conversion:
4270 // If both sides are functions (or pointers/references to them), there could
4271 // be incompatible exception declarations.
4272 if (CheckExceptionSpecCompatibility(From, ToType))
4273 return ExprError();
4274
4275 From = ImpCastExprToType(From, ToType, CK_NoOp,
4276 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4277 break;
4278
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004279 case ICK_Qualification: {
4280 // The qualification keeps the category of the inner expression, unless the
4281 // target type isn't a reference.
Anastasia Stulova04307942018-11-16 16:22:56 +00004282 ExprValueKind VK =
4283 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4284
4285 CastKind CK = CK_NoOp;
4286
4287 if (ToType->isReferenceType() &&
4288 ToType->getPointeeType().getAddressSpace() !=
4289 From->getType().getAddressSpace())
4290 CK = CK_AddressSpaceConversion;
4291
4292 if (ToType->isPointerType() &&
4293 ToType->getPointeeType().getAddressSpace() !=
4294 From->getType()->getPointeeType().getAddressSpace())
4295 CK = CK_AddressSpaceConversion;
4296
4297 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4298 /*BasePath=*/nullptr, CCK)
4299 .get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004300
Douglas Gregore981bb02011-03-14 16:13:32 +00004301 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004302 !getLangOpts().WritableStrings) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004303 Diag(From->getBeginLoc(),
4304 getLangOpts().CPlusPlus11
4305 ? diag::ext_deprecated_string_literal_conversion
4306 : diag::warn_deprecated_string_literal_conversion)
4307 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004308 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004309
Douglas Gregor39c16d42008-10-24 04:54:22 +00004310 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004311 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004312
Douglas Gregor39c16d42008-10-24 04:54:22 +00004313 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004314 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004315 }
4316
Douglas Gregor298f43d2012-04-12 20:42:30 +00004317 // If this conversion sequence involved a scalar -> atomic conversion, perform
4318 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004319 if (!ToAtomicType.isNull()) {
4320 assert(Context.hasSameType(
4321 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4322 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004323 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004324 }
4325
George Burgess IV8d141e02015-12-14 22:00:49 +00004326 // If this conversion sequence succeeded and involved implicitly converting a
4327 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004328 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004329 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004330 From->getBeginLoc());
George Burgess IV8d141e02015-12-14 22:00:49 +00004331
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004332 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004333}
4334
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004335/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004336///
4337/// If the particular type trait requires a complete type, tries to complete
4338/// it. If completing the type fails, a diagnostic is emitted and false
4339/// returned. If completing the type succeeds or no completion was required,
4340/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004341static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004342 SourceLocation Loc,
4343 QualType ArgTy) {
4344 // C++0x [meta.unary.prop]p3:
4345 // For all of the class templates X declared in this Clause, instantiating
4346 // that template with a template argument that is a class template
4347 // specialization may result in the implicit instantiation of the template
4348 // argument if and only if the semantics of X require that the argument
4349 // must be a complete type.
4350 // We apply this rule to all the type trait expressions used to implement
4351 // these class templates. We also try to follow any GCC documented behavior
4352 // in these expressions to ensure portability of standard libraries.
4353 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004354 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004355 // is_complete_type somewhat obviously cannot require a complete type.
4356 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004357 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004358
4359 // These traits are modeled on the type predicates in C++0x
4360 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4361 // requiring a complete type, as whether or not they return true cannot be
4362 // impacted by the completeness of the type.
4363 case UTT_IsVoid:
4364 case UTT_IsIntegral:
4365 case UTT_IsFloatingPoint:
4366 case UTT_IsArray:
4367 case UTT_IsPointer:
4368 case UTT_IsLvalueReference:
4369 case UTT_IsRvalueReference:
4370 case UTT_IsMemberFunctionPointer:
4371 case UTT_IsMemberObjectPointer:
4372 case UTT_IsEnum:
4373 case UTT_IsUnion:
4374 case UTT_IsClass:
4375 case UTT_IsFunction:
4376 case UTT_IsReference:
4377 case UTT_IsArithmetic:
4378 case UTT_IsFundamental:
4379 case UTT_IsObject:
4380 case UTT_IsScalar:
4381 case UTT_IsCompound:
4382 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004383 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004384
4385 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4386 // which requires some of its traits to have the complete type. However,
4387 // the completeness of the type cannot impact these traits' semantics, and
4388 // so they don't require it. This matches the comments on these traits in
4389 // Table 49.
4390 case UTT_IsConst:
4391 case UTT_IsVolatile:
4392 case UTT_IsSigned:
4393 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004394
4395 // This type trait always returns false, checking the type is moot.
4396 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004397 return true;
4398
David Majnemer213bea32015-11-16 06:58:51 +00004399 // C++14 [meta.unary.prop]:
4400 // If T is a non-union class type, T shall be a complete type.
4401 case UTT_IsEmpty:
4402 case UTT_IsPolymorphic:
4403 case UTT_IsAbstract:
4404 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4405 if (!RD->isUnion())
4406 return !S.RequireCompleteType(
4407 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4408 return true;
4409
4410 // C++14 [meta.unary.prop]:
4411 // If T is a class type, T shall be a complete type.
4412 case UTT_IsFinal:
4413 case UTT_IsSealed:
4414 if (ArgTy->getAsCXXRecordDecl())
4415 return !S.RequireCompleteType(
4416 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4417 return true;
4418
Richard Smithf03e9082017-06-01 00:28:16 +00004419 // C++1z [meta.unary.prop]:
4420 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004421 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004422 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004423 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004424 case UTT_IsStandardLayout:
4425 case UTT_IsPOD:
4426 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004427 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4428 // or an array of unknown bound. But GCC actually imposes the same constraints
4429 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004430 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004431 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004432 case UTT_HasNothrowConstructor:
4433 case UTT_HasNothrowCopy:
4434 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004435 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004436 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004437 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004438 case UTT_HasTrivialCopy:
4439 case UTT_HasTrivialDestructor:
4440 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004441 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4442 LLVM_FALLTHROUGH;
4443
4444 // C++1z [meta.unary.prop]:
4445 // T shall be a complete type, cv void, or an array of unknown bound.
4446 case UTT_IsDestructible:
4447 case UTT_IsNothrowDestructible:
4448 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004449 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004450 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004451 return true;
4452
4453 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004454 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004455 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004456}
4457
Joao Matosc9523d42013-03-27 01:34:16 +00004458static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4459 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004460 bool (CXXRecordDecl::*HasTrivial)() const,
4461 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004462 bool (CXXMethodDecl::*IsDesiredOp)() const)
4463{
4464 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4465 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4466 return true;
4467
4468 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4469 DeclarationNameInfo NameInfo(Name, KeyLoc);
4470 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4471 if (Self.LookupQualifiedName(Res, RD)) {
4472 bool FoundOperator = false;
4473 Res.suppressDiagnostics();
4474 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4475 Op != OpEnd; ++Op) {
4476 if (isa<FunctionTemplateDecl>(*Op))
4477 continue;
4478
4479 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4480 if((Operator->*IsDesiredOp)()) {
4481 FoundOperator = true;
4482 const FunctionProtoType *CPT =
4483 Operator->getType()->getAs<FunctionProtoType>();
4484 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004485 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004486 return false;
4487 }
4488 }
4489 return FoundOperator;
4490 }
4491 return false;
4492}
4493
Alp Toker95e7ff22014-01-01 05:57:51 +00004494static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004495 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004496 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004497
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004498 ASTContext &C = Self.Context;
4499 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004500 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004501 // Type trait expressions corresponding to the primary type category
4502 // predicates in C++0x [meta.unary.cat].
4503 case UTT_IsVoid:
4504 return T->isVoidType();
4505 case UTT_IsIntegral:
4506 return T->isIntegralType(C);
4507 case UTT_IsFloatingPoint:
4508 return T->isFloatingType();
4509 case UTT_IsArray:
4510 return T->isArrayType();
4511 case UTT_IsPointer:
4512 return T->isPointerType();
4513 case UTT_IsLvalueReference:
4514 return T->isLValueReferenceType();
4515 case UTT_IsRvalueReference:
4516 return T->isRValueReferenceType();
4517 case UTT_IsMemberFunctionPointer:
4518 return T->isMemberFunctionPointerType();
4519 case UTT_IsMemberObjectPointer:
4520 return T->isMemberDataPointerType();
4521 case UTT_IsEnum:
4522 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004523 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004524 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004525 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004526 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004527 case UTT_IsFunction:
4528 return T->isFunctionType();
4529
4530 // Type trait expressions which correspond to the convenient composition
4531 // predicates in C++0x [meta.unary.comp].
4532 case UTT_IsReference:
4533 return T->isReferenceType();
4534 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004535 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004536 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004537 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004538 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004539 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004540 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004541 // Note: semantic analysis depends on Objective-C lifetime types to be
4542 // considered scalar types. However, such types do not actually behave
4543 // like scalar types at run time (since they may require retain/release
4544 // operations), so we report them as non-scalar.
4545 if (T->isObjCLifetimeType()) {
4546 switch (T.getObjCLifetime()) {
4547 case Qualifiers::OCL_None:
4548 case Qualifiers::OCL_ExplicitNone:
4549 return true;
4550
4551 case Qualifiers::OCL_Strong:
4552 case Qualifiers::OCL_Weak:
4553 case Qualifiers::OCL_Autoreleasing:
4554 return false;
4555 }
4556 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004557
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004558 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004559 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004560 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004561 case UTT_IsMemberPointer:
4562 return T->isMemberPointerType();
4563
4564 // Type trait expressions which correspond to the type property predicates
4565 // in C++0x [meta.unary.prop].
4566 case UTT_IsConst:
4567 return T.isConstQualified();
4568 case UTT_IsVolatile:
4569 return T.isVolatileQualified();
4570 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004571 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004572 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004573 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004574 case UTT_IsStandardLayout:
4575 return T->isStandardLayoutType();
4576 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004577 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004578 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004579 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004580 case UTT_IsEmpty:
4581 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4582 return !RD->isUnion() && RD->isEmpty();
4583 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004584 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004585 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004586 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004587 return false;
4588 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004589 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004590 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004591 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004592 case UTT_IsAggregate:
4593 // Report vector extensions and complex types as aggregates because they
4594 // support aggregate initialization. GCC mirrors this behavior for vectors
4595 // but not _Complex.
4596 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4597 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004598 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4599 // even then only when it is used with the 'interface struct ...' syntax
4600 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004601 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004602 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004603 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004604 case UTT_IsSealed:
4605 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004606 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004607 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004608 case UTT_IsSigned:
4609 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004610 case UTT_IsUnsigned:
4611 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004612
4613 // Type trait expressions which query classes regarding their construction,
4614 // destruction, and copying. Rather than being based directly on the
4615 // related type predicates in the standard, they are specified by both
4616 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4617 // specifications.
4618 //
4619 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4620 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004621 //
4622 // Note that these builtins do not behave as documented in g++: if a class
4623 // has both a trivial and a non-trivial special member of a particular kind,
4624 // they return false! For now, we emulate this behavior.
4625 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4626 // does not correctly compute triviality in the presence of multiple special
4627 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004628 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004629 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4630 // If __is_pod (type) is true then the trait is true, else if type is
4631 // a cv class or union type (or array thereof) with a trivial default
4632 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004633 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004634 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004635 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4636 return RD->hasTrivialDefaultConstructor() &&
4637 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004638 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004639 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004640 // This trait is implemented by MSVC 2012 and needed to parse the
4641 // standard library headers. Specifically this is used as the logic
4642 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004643 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004644 return true;
4645 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4646 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4647 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004648 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004649 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4650 // If __is_pod (type) is true or type is a reference type then
4651 // the trait is true, else if type is a cv class or union type
4652 // with a trivial copy constructor ([class.copy]) then the trait
4653 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004654 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004655 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004656 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4657 return RD->hasTrivialCopyConstructor() &&
4658 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004659 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004660 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004661 // This trait is implemented by MSVC 2012 and needed to parse the
4662 // standard library headers. Specifically it is used as the logic
4663 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004664 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004665 return true;
4666 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4667 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4668 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004669 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004670 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4671 // If type is const qualified or is a reference type then the
4672 // trait is false. Otherwise if __is_pod (type) is true then the
4673 // trait is true, else if type is a cv class or union type with
4674 // a trivial copy assignment ([class.copy]) then the trait is
4675 // true, else it is false.
4676 // Note: the const and reference restrictions are interesting,
4677 // given that const and reference members don't prevent a class
4678 // from having a trivial copy assignment operator (but do cause
4679 // errors if the copy assignment operator is actually used, q.v.
4680 // [class.copy]p12).
4681
Richard Smith92f241f2012-12-08 02:53:02 +00004682 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004683 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004684 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004685 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004686 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4687 return RD->hasTrivialCopyAssignment() &&
4688 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004689 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004690 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004691 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004692 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004693 // C++14 [meta.unary.prop]:
4694 // For reference types, is_destructible<T>::value is true.
4695 if (T->isReferenceType())
4696 return true;
4697
4698 // Objective-C++ ARC: autorelease types don't require destruction.
4699 if (T->isObjCLifetimeType() &&
4700 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4701 return true;
4702
4703 // C++14 [meta.unary.prop]:
4704 // For incomplete types and function types, is_destructible<T>::value is
4705 // false.
4706 if (T->isIncompleteType() || T->isFunctionType())
4707 return false;
4708
Richard Smithf03e9082017-06-01 00:28:16 +00004709 // A type that requires destruction (via a non-trivial destructor or ARC
4710 // lifetime semantics) is not trivially-destructible.
4711 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4712 return false;
4713
David Majnemerac73de92015-08-11 03:03:28 +00004714 // C++14 [meta.unary.prop]:
4715 // For object types and given U equal to remove_all_extents_t<T>, if the
4716 // expression std::declval<U&>().~U() is well-formed when treated as an
4717 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4718 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4719 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4720 if (!Destructor)
4721 return false;
4722 // C++14 [dcl.fct.def.delete]p2:
4723 // A program that refers to a deleted function implicitly or
4724 // explicitly, other than to declare it, is ill-formed.
4725 if (Destructor->isDeleted())
4726 return false;
4727 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4728 return false;
4729 if (UTT == UTT_IsNothrowDestructible) {
4730 const FunctionProtoType *CPT =
4731 Destructor->getType()->getAs<FunctionProtoType>();
4732 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004733 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004734 return false;
4735 }
4736 }
4737 return true;
4738
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004739 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004740 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004741 // If __is_pod (type) is true or type is a reference type
4742 // then the trait is true, else if type is a cv class or union
4743 // type (or array thereof) with a trivial destructor
4744 // ([class.dtor]) then the trait is true, else it is
4745 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004746 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004747 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004748
John McCall31168b02011-06-15 23:02:42 +00004749 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004750 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004751 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4752 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004753
Richard Smith92f241f2012-12-08 02:53:02 +00004754 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4755 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004756 return false;
4757 // TODO: Propagate nothrowness for implicitly declared special members.
4758 case UTT_HasNothrowAssign:
4759 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4760 // If type is const qualified or is a reference type then the
4761 // trait is false. Otherwise if __has_trivial_assign (type)
4762 // is true then the trait is true, else if type is a cv class
4763 // or union type with copy assignment operators that are known
4764 // not to throw an exception then the trait is true, else it is
4765 // false.
4766 if (C.getBaseElementType(T).isConstQualified())
4767 return false;
4768 if (T->isReferenceType())
4769 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004770 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004771 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004772
Joao Matosc9523d42013-03-27 01:34:16 +00004773 if (const RecordType *RT = T->getAs<RecordType>())
4774 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4775 &CXXRecordDecl::hasTrivialCopyAssignment,
4776 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4777 &CXXMethodDecl::isCopyAssignmentOperator);
4778 return false;
4779 case UTT_HasNothrowMoveAssign:
4780 // This trait is implemented by MSVC 2012 and needed to parse the
4781 // standard library headers. Specifically this is used as the logic
4782 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004783 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004784 return true;
4785
4786 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4787 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4788 &CXXRecordDecl::hasTrivialMoveAssignment,
4789 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4790 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004791 return false;
4792 case UTT_HasNothrowCopy:
4793 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4794 // If __has_trivial_copy (type) is true then the trait is true, else
4795 // if type is a cv class or union type with copy constructors that are
4796 // known not to throw an exception then the trait is true, else it is
4797 // false.
John McCall31168b02011-06-15 23:02:42 +00004798 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004799 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004800 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4801 if (RD->hasTrivialCopyConstructor() &&
4802 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004803 return true;
4804
4805 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004806 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004807 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004808 // A template constructor is never a copy constructor.
4809 // FIXME: However, it may actually be selected at the actual overload
4810 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004811 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004812 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004813 // UsingDecl itself is not a constructor
4814 if (isa<UsingDecl>(ND))
4815 continue;
4816 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004817 if (Constructor->isCopyConstructor(FoundTQs)) {
4818 FoundConstructor = true;
4819 const FunctionProtoType *CPT
4820 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004821 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4822 if (!CPT)
4823 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004824 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004825 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004826 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004827 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004828 }
4829 }
4830
Richard Smith938f40b2011-06-11 17:19:42 +00004831 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004832 }
4833 return false;
4834 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004835 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004836 // If __has_trivial_constructor (type) is true then the trait is
4837 // true, else if type is a cv class or union type (or array
4838 // thereof) with a default constructor that is known not to
4839 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004840 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004841 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004842 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4843 if (RD->hasTrivialDefaultConstructor() &&
4844 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004845 return true;
4846
Alp Tokerb4bca412014-01-20 00:23:47 +00004847 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004848 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004849 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004850 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004851 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004852 // UsingDecl itself is not a constructor
4853 if (isa<UsingDecl>(ND))
4854 continue;
4855 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004856 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004857 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004858 const FunctionProtoType *CPT
4859 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004860 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4861 if (!CPT)
4862 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004863 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004864 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004865 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004866 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004867 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004868 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004869 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004870 }
4871 return false;
4872 case UTT_HasVirtualDestructor:
4873 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4874 // If type is a class type with a virtual destructor ([class.dtor])
4875 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004876 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004877 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004878 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004879 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004880
4881 // These type trait expressions are modeled on the specifications for the
4882 // Embarcadero C++0x type trait functions:
4883 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4884 case UTT_IsCompleteType:
4885 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4886 // Returns True if and only if T is a complete type at the point of the
4887 // function call.
4888 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004889 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004890 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004891 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004892}
Sebastian Redl5822f082009-02-07 20:10:22 +00004893
Alp Tokercbb90342013-12-13 20:49:58 +00004894static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4895 QualType RhsT, SourceLocation KeyLoc);
4896
Douglas Gregor29c42f22012-02-24 07:38:34 +00004897static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4898 ArrayRef<TypeSourceInfo *> Args,
4899 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004900 if (Kind <= UTT_Last)
4901 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4902
Eric Fiselier1af6c112018-01-12 00:09:37 +00004903 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4904 // traits to avoid duplication.
4905 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004906 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4907 Args[1]->getType(), RParenLoc);
4908
Douglas Gregor29c42f22012-02-24 07:38:34 +00004909 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004910 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004911 case clang::TT_IsConstructible:
4912 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004913 case clang::TT_IsTriviallyConstructible: {
4914 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004915 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004916 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004917 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004918 // definition for is_constructible, as defined below, is known to call
4919 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004920 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004921 // The predicate condition for a template specialization
4922 // is_constructible<T, Args...> shall be satisfied if and only if the
4923 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004924 // variable t:
4925 //
4926 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004927 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004928
4929 // Precondition: T and all types in the parameter pack Args shall be
4930 // complete types, (possibly cv-qualified) void, or arrays of
4931 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004932 for (const auto *TSI : Args) {
4933 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004934 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004935 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004936
Simon Pilgrim75c26882016-09-30 14:25:09 +00004937 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004938 diag::err_incomplete_type_used_in_type_trait_expr))
4939 return false;
4940 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004941
David Majnemer9658ecc2015-11-13 05:32:43 +00004942 // Make sure the first argument is not incomplete nor a function type.
4943 QualType T = Args[0]->getType();
4944 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004945 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004946
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004947 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004948 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004949 if (RD && RD->isAbstract())
4950 return false;
4951
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004952 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4953 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004954 ArgExprs.reserve(Args.size() - 1);
4955 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004956 QualType ArgTy = Args[I]->getType();
4957 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4958 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004959 OpaqueArgExprs.push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004960 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
David Majnemer9658ecc2015-11-13 05:32:43 +00004961 ArgTy.getNonLValueExprType(S.Context),
4962 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004963 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004964 for (Expr &E : OpaqueArgExprs)
4965 ArgExprs.push_back(&E);
4966
Simon Pilgrim75c26882016-09-30 14:25:09 +00004967 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004968 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004969 EnterExpressionEvaluationContext Unevaluated(
4970 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004971 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4972 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4973 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4974 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4975 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004976 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004977 if (Init.Failed())
4978 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004979
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004980 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004981 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4982 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004983
Alp Toker73287bf2014-01-20 00:24:09 +00004984 if (Kind == clang::TT_IsConstructible)
4985 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004986
Eric Fiselier1af6c112018-01-12 00:09:37 +00004987 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4988 if (!T->isReferenceType())
4989 return false;
4990
4991 return !Init.isDirectReferenceBinding();
4992 }
4993
Alp Toker73287bf2014-01-20 00:24:09 +00004994 if (Kind == clang::TT_IsNothrowConstructible)
4995 return S.canThrow(Result.get()) == CT_Cannot;
4996
4997 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00004998 // Under Objective-C ARC and Weak, if the destination has non-trivial
4999 // Objective-C lifetime, this is a non-trivial construction.
5000 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005001 return false;
5002
5003 // The initialization succeeded; now make sure there are no non-trivial
5004 // calls.
5005 return !Result.get()->hasNonTrivialCall(S.Context);
5006 }
5007
5008 llvm_unreachable("unhandled type trait");
5009 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005010 }
Alp Tokercbb90342013-12-13 20:49:58 +00005011 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00005012 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005013
Douglas Gregor29c42f22012-02-24 07:38:34 +00005014 return false;
5015}
5016
Simon Pilgrim75c26882016-09-30 14:25:09 +00005017ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5018 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005019 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00005020 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00005021
Alp Toker95e7ff22014-01-01 05:57:51 +00005022 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5023 *this, Kind, KWLoc, Args[0]->getType()))
5024 return ExprError();
5025
Douglas Gregor29c42f22012-02-24 07:38:34 +00005026 bool Dependent = false;
5027 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5028 if (Args[I]->getType()->isDependentType()) {
5029 Dependent = true;
5030 break;
5031 }
5032 }
Alp Tokercbb90342013-12-13 20:49:58 +00005033
5034 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005035 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005036 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5037
5038 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5039 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005040}
5041
Alp Toker88f64e62013-12-13 21:19:30 +00005042ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5043 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005044 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005045 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005046 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005047
Douglas Gregor29c42f22012-02-24 07:38:34 +00005048 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5049 TypeSourceInfo *TInfo;
5050 QualType T = GetTypeFromParser(Args[I], &TInfo);
5051 if (!TInfo)
5052 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005053
5054 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005055 }
Alp Tokercbb90342013-12-13 20:49:58 +00005056
Douglas Gregor29c42f22012-02-24 07:38:34 +00005057 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5058}
5059
Alp Tokercbb90342013-12-13 20:49:58 +00005060static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5061 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005062 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5063 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005064
5065 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005066 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005067 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005068 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005069 // Base and Derived are not unions and name the same class type without
5070 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005071
John McCall388ef532011-01-28 22:02:36 +00005072 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005073 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005074 if (!rhsRecord || !lhsRecord) {
5075 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5076 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5077 if (!LHSObjTy || !RHSObjTy)
5078 return false;
5079
5080 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5081 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5082 if (!BaseInterface || !DerivedInterface)
5083 return false;
5084
5085 if (Self.RequireCompleteType(
5086 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5087 return false;
5088
5089 return BaseInterface->isSuperClassOf(DerivedInterface);
5090 }
John McCall388ef532011-01-28 22:02:36 +00005091
5092 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5093 == (lhsRecord == rhsRecord));
5094
5095 if (lhsRecord == rhsRecord)
5096 return !lhsRecord->getDecl()->isUnion();
5097
5098 // C++0x [meta.rel]p2:
5099 // If Base and Derived are class types and are different types
5100 // (ignoring possible cv-qualifiers) then Derived shall be a
5101 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005102 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005103 diag::err_incomplete_type_used_in_type_trait_expr))
5104 return false;
5105
5106 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5107 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5108 }
John Wiegley65497cc2011-04-27 23:09:49 +00005109 case BTT_IsSame:
5110 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005111 case BTT_TypeCompatible: {
5112 // GCC ignores cv-qualifiers on arrays for this builtin.
5113 Qualifiers LhsQuals, RhsQuals;
5114 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5115 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5116 return Self.Context.typesAreCompatible(Lhs, Rhs);
5117 }
John Wiegley65497cc2011-04-27 23:09:49 +00005118 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005119 case BTT_IsConvertibleTo: {
5120 // C++0x [meta.rel]p4:
5121 // Given the following function prototype:
5122 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005123 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005124 // typename add_rvalue_reference<T>::type create();
5125 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005126 // the predicate condition for a template specialization
5127 // is_convertible<From, To> shall be satisfied if and only if
5128 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005129 // well-formed, including any implicit conversions to the return
5130 // type of the function:
5131 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005132 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005133 // return create<From>();
5134 // }
5135 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005136 // Access checking is performed as if in a context unrelated to To and
5137 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005138 // of the return-statement (including conversions to the return type)
5139 // is considered.
5140 //
5141 // We model the initialization as a copy-initialization of a temporary
5142 // of the appropriate type, which for this expression is identical to the
5143 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005144
5145 // Functions aren't allowed to return function or array types.
5146 if (RhsT->isFunctionType() || RhsT->isArrayType())
5147 return false;
5148
5149 // A return statement in a void function must have void type.
5150 if (RhsT->isVoidType())
5151 return LhsT->isVoidType();
5152
5153 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005154 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005155 return false;
5156
5157 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005158 if (LhsT->isObjectType() || LhsT->isFunctionType())
5159 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005160
5161 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005162 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005163 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005164 Expr::getValueKindForType(LhsT));
5165 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005166 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005167 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005168
5169 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005170 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005171 EnterExpressionEvaluationContext Unevaluated(
5172 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005173 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5174 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005175 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005176 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005177 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005178
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005179 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005180 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5181 }
Alp Toker73287bf2014-01-20 00:24:09 +00005182
David Majnemerb3d96882016-05-23 17:21:55 +00005183 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005184 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005185 case BTT_IsTriviallyAssignable: {
5186 // C++11 [meta.unary.prop]p3:
5187 // is_trivially_assignable is defined as:
5188 // is_assignable<T, U>::value is true and the assignment, as defined by
5189 // is_assignable, is known to call no operation that is not trivial
5190 //
5191 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005192 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005193 // treated as an unevaluated operand (Clause 5).
5194 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005195 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005196 // void, or arrays of unknown bound.
5197 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005198 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005199 diag::err_incomplete_type_used_in_type_trait_expr))
5200 return false;
5201 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005202 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005203 diag::err_incomplete_type_used_in_type_trait_expr))
5204 return false;
5205
5206 // cv void is never assignable.
5207 if (LhsT->isVoidType() || RhsT->isVoidType())
5208 return false;
5209
Simon Pilgrim75c26882016-09-30 14:25:09 +00005210 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005211 // declval<U>().
5212 if (LhsT->isObjectType() || LhsT->isFunctionType())
5213 LhsT = Self.Context.getRValueReferenceType(LhsT);
5214 if (RhsT->isObjectType() || RhsT->isFunctionType())
5215 RhsT = Self.Context.getRValueReferenceType(RhsT);
5216 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5217 Expr::getValueKindForType(LhsT));
5218 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5219 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005220
5221 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005222 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005223 EnterExpressionEvaluationContext Unevaluated(
5224 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005225 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005226 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005227 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5228 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005229 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5230 return false;
5231
David Majnemerb3d96882016-05-23 17:21:55 +00005232 if (BTT == BTT_IsAssignable)
5233 return true;
5234
Alp Toker73287bf2014-01-20 00:24:09 +00005235 if (BTT == BTT_IsNothrowAssignable)
5236 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005237
Alp Toker73287bf2014-01-20 00:24:09 +00005238 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005239 // Under Objective-C ARC and Weak, if the destination has non-trivial
5240 // Objective-C lifetime, this is a non-trivial assignment.
5241 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005242 return false;
5243
5244 return !Result.get()->hasNonTrivialCall(Self.Context);
5245 }
5246
5247 llvm_unreachable("unhandled type trait");
5248 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005249 }
Alp Tokercbb90342013-12-13 20:49:58 +00005250 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005251 }
5252 llvm_unreachable("Unknown type trait or not implemented");
5253}
5254
John Wiegley6242b6a2011-04-28 00:16:57 +00005255ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5256 SourceLocation KWLoc,
5257 ParsedType Ty,
5258 Expr* DimExpr,
5259 SourceLocation RParen) {
5260 TypeSourceInfo *TSInfo;
5261 QualType T = GetTypeFromParser(Ty, &TSInfo);
5262 if (!TSInfo)
5263 TSInfo = Context.getTrivialTypeSourceInfo(T);
5264
5265 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5266}
5267
5268static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5269 QualType T, Expr *DimExpr,
5270 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005271 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005272
5273 switch(ATT) {
5274 case ATT_ArrayRank:
5275 if (T->isArrayType()) {
5276 unsigned Dim = 0;
5277 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5278 ++Dim;
5279 T = AT->getElementType();
5280 }
5281 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005282 }
John Wiegleyd3522222011-04-28 02:06:46 +00005283 return 0;
5284
John Wiegley6242b6a2011-04-28 00:16:57 +00005285 case ATT_ArrayExtent: {
5286 llvm::APSInt Value;
5287 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005288 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005289 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005290 false).isInvalid())
5291 return 0;
5292 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005293 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5294 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005295 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005296 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005297 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005298
5299 if (T->isArrayType()) {
5300 unsigned D = 0;
5301 bool Matched = false;
5302 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5303 if (Dim == D) {
5304 Matched = true;
5305 break;
5306 }
5307 ++D;
5308 T = AT->getElementType();
5309 }
5310
John Wiegleyd3522222011-04-28 02:06:46 +00005311 if (Matched && T->isArrayType()) {
5312 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5313 return CAT->getSize().getLimitedValue();
5314 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005315 }
John Wiegleyd3522222011-04-28 02:06:46 +00005316 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005317 }
5318 }
5319 llvm_unreachable("Unknown type trait or not implemented");
5320}
5321
5322ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5323 SourceLocation KWLoc,
5324 TypeSourceInfo *TSInfo,
5325 Expr* DimExpr,
5326 SourceLocation RParen) {
5327 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005328
Chandler Carruthc5276e52011-05-01 08:48:21 +00005329 // FIXME: This should likely be tracked as an APInt to remove any host
5330 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005331 uint64_t Value = 0;
5332 if (!T->isDependentType())
5333 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5334
Chandler Carruthc5276e52011-05-01 08:48:21 +00005335 // While the specification for these traits from the Embarcadero C++
5336 // compiler's documentation says the return type is 'unsigned int', Clang
5337 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5338 // compiler, there is no difference. On several other platforms this is an
5339 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005340 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5341 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005342}
5343
John Wiegleyf9f65842011-04-25 06:54:41 +00005344ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005345 SourceLocation KWLoc,
5346 Expr *Queried,
5347 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005348 // If error parsing the expression, ignore.
5349 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005350 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005351
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005352 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005353
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005354 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005355}
5356
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005357static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5358 switch (ET) {
5359 case ET_IsLValueExpr: return E->isLValue();
5360 case ET_IsRValueExpr: return E->isRValue();
5361 }
5362 llvm_unreachable("Expression trait not covered by switch");
5363}
5364
John Wiegleyf9f65842011-04-25 06:54:41 +00005365ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005366 SourceLocation KWLoc,
5367 Expr *Queried,
5368 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005369 if (Queried->isTypeDependent()) {
5370 // Delay type-checking for type-dependent expressions.
5371 } else if (Queried->getType()->isPlaceholderType()) {
5372 ExprResult PE = CheckPlaceholderExpr(Queried);
5373 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005374 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005375 }
5376
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005377 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005378
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005379 return new (Context)
5380 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005381}
5382
Richard Trieu82402a02011-09-15 21:56:47 +00005383QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005384 ExprValueKind &VK,
5385 SourceLocation Loc,
5386 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005387 assert(!LHS.get()->getType()->isPlaceholderType() &&
5388 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005389 "placeholders should have been weeded out by now");
5390
Richard Smith4baaa5a2016-12-03 01:14:32 +00005391 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5392 // temporary materialization conversion otherwise.
5393 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005394 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005395 else if (LHS.get()->isRValue())
5396 LHS = TemporaryMaterializationConversion(LHS.get());
5397 if (LHS.isInvalid())
5398 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005399
5400 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005401 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005402 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005403
Sebastian Redl5822f082009-02-07 20:10:22 +00005404 const char *OpSpelling = isIndirect ? "->*" : ".*";
5405 // C++ 5.5p2
5406 // The binary operator .* [p3: ->*] binds its second operand, which shall
5407 // be of type "pointer to member of T" (where T is a completely-defined
5408 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005409 QualType RHSType = RHS.get()->getType();
5410 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005411 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005412 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005413 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005414 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005415 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005416
Sebastian Redl5822f082009-02-07 20:10:22 +00005417 QualType Class(MemPtr->getClass(), 0);
5418
Douglas Gregord07ba342010-10-13 20:41:14 +00005419 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5420 // member pointer points must be completely-defined. However, there is no
5421 // reason for this semantic distinction, and the rule is not enforced by
5422 // other compilers. Therefore, we do not check this property, as it is
5423 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005424
Sebastian Redl5822f082009-02-07 20:10:22 +00005425 // C++ 5.5p2
5426 // [...] to its first operand, which shall be of class T or of a class of
5427 // which T is an unambiguous and accessible base class. [p3: a pointer to
5428 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005429 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005430 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005431 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5432 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005433 else {
5434 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005435 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005436 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005437 return QualType();
5438 }
5439 }
5440
Richard Trieu82402a02011-09-15 21:56:47 +00005441 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005442 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005443 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5444 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005445 return QualType();
5446 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005447
Richard Smith0f59cb32015-12-18 21:45:41 +00005448 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005449 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005450 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005451 return QualType();
5452 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005453
5454 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005455 if (CheckDerivedToBaseConversion(
5456 LHSType, Class, Loc,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005457 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005458 &BasePath))
Richard Smithdb05cd32013-12-12 03:40:18 +00005459 return QualType();
5460
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005461 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005462 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5463 if (isIndirect)
5464 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005465 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005466 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005467 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005468 }
5469
Richard Trieu82402a02011-09-15 21:56:47 +00005470 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005471 // Diagnose use of pointer-to-member type which when used as
5472 // the functional cast in a pointer-to-member expression.
5473 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5474 return QualType();
5475 }
John McCall7decc9e2010-11-18 06:31:45 +00005476
Sebastian Redl5822f082009-02-07 20:10:22 +00005477 // C++ 5.5p2
5478 // The result is an object or a function of the type specified by the
5479 // second operand.
5480 // The cv qualifiers are the union of those in the pointer and the left side,
5481 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005482 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005483 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005484
Douglas Gregor1d042092011-01-26 16:40:18 +00005485 // C++0x [expr.mptr.oper]p6:
5486 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005487 // ill-formed if the second operand is a pointer to member function with
5488 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5489 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005490 // is a pointer to member function with ref-qualifier &&.
5491 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5492 switch (Proto->getRefQualifier()) {
5493 case RQ_None:
5494 // Do nothing
5495 break;
5496
5497 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005498 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
Nicolas Lesser1ad0e9f2018-07-13 16:27:45 +00005499 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5500 // is (exactly) 'const'.
5501 if (Proto->isConst() && !Proto->isVolatile())
Richard Smith25923272017-08-25 01:47:55 +00005502 Diag(Loc, getLangOpts().CPlusPlus2a
5503 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5504 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5505 else
5506 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5507 << RHSType << 1 << LHS.get()->getSourceRange();
5508 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005509 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005510
Douglas Gregor1d042092011-01-26 16:40:18 +00005511 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005512 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005513 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005514 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005515 break;
5516 }
5517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518
John McCall7decc9e2010-11-18 06:31:45 +00005519 // C++ [expr.mptr.oper]p6:
5520 // The result of a .* expression whose second operand is a pointer
5521 // to a data member is of the same value category as its
5522 // first operand. The result of a .* expression whose second
5523 // operand is a pointer to a member function is a prvalue. The
5524 // result of an ->* expression is an lvalue if its second operand
5525 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005526 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005527 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005528 return Context.BoundMemberTy;
5529 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005530 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005531 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005532 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005533 }
John McCall7decc9e2010-11-18 06:31:45 +00005534
Sebastian Redl5822f082009-02-07 20:10:22 +00005535 return Result;
5536}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005537
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005538/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005539///
5540/// This is part of the parameter validation for the ? operator. If either
5541/// value operand is a class type, the two operands are attempted to be
5542/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005543/// It returns true if the program is ill-formed and has already been diagnosed
5544/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005545static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5546 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005547 bool &HaveConversion,
5548 QualType &ToType) {
5549 HaveConversion = false;
5550 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005551
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005552 InitializationKind Kind =
5553 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005554 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005555 // The process for determining whether an operand expression E1 of type T1
5556 // can be converted to match an operand expression E2 of type T2 is defined
5557 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005558 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5559 // implicitly converted to type "lvalue reference to T2", subject to the
5560 // constraint that in the conversion the reference must bind directly to
5561 // an lvalue.
5562 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005563 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005564 // the constraint that the reference must bind directly.
5565 if (To->isLValue() || To->isXValue()) {
5566 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5567 : Self.Context.getRValueReferenceType(ToType);
5568
Douglas Gregor838fcc32010-03-26 20:14:36 +00005569 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005570
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005571 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005572 if (InitSeq.isDirectReferenceBinding()) {
5573 ToType = T;
5574 HaveConversion = true;
5575 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005576 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577
Douglas Gregor838fcc32010-03-26 20:14:36 +00005578 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005579 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005580 }
John McCall65eb8792010-02-25 01:37:24 +00005581
Sebastian Redl1a99f442009-04-16 17:51:27 +00005582 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5583 // -- if E1 and E2 have class type, and the underlying class types are
5584 // the same or one is a base class of the other:
5585 QualType FTy = From->getType();
5586 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005587 const RecordType *FRec = FTy->getAs<RecordType>();
5588 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005589 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005590 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5591 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5592 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005593 // E1 can be converted to match E2 if the class of T2 is the
5594 // same type as, or a base class of, the class of T1, and
5595 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005596 if (FRec == TRec || FDerivedFromT) {
5597 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005598 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005599 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005600 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005601 HaveConversion = true;
5602 return false;
5603 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005604
Douglas Gregor838fcc32010-03-26 20:14:36 +00005605 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005606 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005607 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005609
Douglas Gregor838fcc32010-03-26 20:14:36 +00005610 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005612
Douglas Gregor838fcc32010-03-26 20:14:36 +00005613 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5614 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005615 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005616 // an rvalue).
5617 //
5618 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5619 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005620 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005621
Douglas Gregor838fcc32010-03-26 20:14:36 +00005622 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005623 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005624 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005625 ToType = TTy;
5626 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005627 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005628
Sebastian Redl1a99f442009-04-16 17:51:27 +00005629 return false;
5630}
5631
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005632/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005633///
5634/// This is part of the parameter validation for the ? operator. If either
5635/// value operand is a class type, overload resolution is used to find a
5636/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005637static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005638 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005639 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005640 OverloadCandidateSet CandidateSet(QuestionLoc,
5641 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005642 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005643 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005644
5645 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005646 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005647 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005648 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005649 ExprResult LHSRes = Self.PerformImplicitConversion(
5650 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5651 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005652 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005653 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005654 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005655
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005656 ExprResult RHSRes = Self.PerformImplicitConversion(
5657 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5658 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005659 if (RHSRes.isInvalid())
5660 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005661 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005662 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005663 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005664 return false;
John Wiegley01296292011-04-08 18:41:53 +00005665 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005666
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005667 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005668
5669 // Emit a better diagnostic if one of the expressions is a null pointer
5670 // constant and the other is a pointer type. In this case, the user most
5671 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005672 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005673 return true;
5674
5675 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005676 << LHS.get()->getType() << RHS.get()->getType()
5677 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005678 return true;
5679
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005680 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005681 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005682 << LHS.get()->getType() << RHS.get()->getType()
5683 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005684 // FIXME: Print the possible common types by printing the return types of
5685 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005686 break;
5687
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005688 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005689 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005690 }
5691 return true;
5692}
5693
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005694/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005695/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005696static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005697 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005698 InitializationKind Kind =
5699 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005700 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005701 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005702 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005703 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005704 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005705
John Wiegley01296292011-04-08 18:41:53 +00005706 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005707 return false;
5708}
5709
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005710/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005711///
5712/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5713/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005714QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5715 ExprResult &RHS, ExprValueKind &VK,
5716 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005717 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005718 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5719 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005720
Richard Smith45edb702012-08-07 22:06:48 +00005721 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005722 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005723 //
5724 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5725 // a is that of a integer vector with the same number of elements and
5726 // size as the vectors of b and c. If one of either b or c is a scalar
5727 // it is implicitly converted to match the type of the vector.
5728 // Otherwise the expression is ill-formed. If both b and c are scalars,
5729 // then b and c are checked and converted to the type of a if possible.
5730 // Unlike the OpenCL ?: operator, the expression is evaluated as
5731 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005732 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005733 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005734 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005735 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005736 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005737 }
5738
John McCall7decc9e2010-11-18 06:31:45 +00005739 // Assume r-value.
5740 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005741 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005742
Sebastian Redl1a99f442009-04-16 17:51:27 +00005743 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005744 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005745 return Context.DependentTy;
5746
Richard Smith45edb702012-08-07 22:06:48 +00005747 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005748 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005749 QualType LTy = LHS.get()->getType();
5750 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005751 bool LVoid = LTy->isVoidType();
5752 bool RVoid = RTy->isVoidType();
5753 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005754 // ... one of the following shall hold:
5755 // -- The second or the third operand (but not both) is a (possibly
5756 // parenthesized) throw-expression; the result is of the type
5757 // and value category of the other.
5758 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5759 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5760 if (LThrow != RThrow) {
5761 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5762 VK = NonThrow->getValueKind();
5763 // DR (no number yet): the result is a bit-field if the
5764 // non-throw-expression operand is a bit-field.
5765 OK = NonThrow->getObjectKind();
5766 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005767 }
5768
Sebastian Redl1a99f442009-04-16 17:51:27 +00005769 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005770 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005771 if (LVoid && RVoid)
5772 return Context.VoidTy;
5773
5774 // Neither holds, error.
5775 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5776 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005777 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005778 return QualType();
5779 }
5780
5781 // Neither is void.
5782
Richard Smithf2b084f2012-08-08 06:13:49 +00005783 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005784 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005785 // either has (cv) class type [...] an attempt is made to convert each of
5786 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005787 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005788 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005789 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005790 QualType L2RType, R2LType;
5791 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005792 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005793 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005794 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005795 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005796
Sebastian Redl1a99f442009-04-16 17:51:27 +00005797 // If both can be converted, [...] the program is ill-formed.
5798 if (HaveL2R && HaveR2L) {
5799 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005800 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005801 return QualType();
5802 }
5803
5804 // If exactly one conversion is possible, that conversion is applied to
5805 // the chosen operand and the converted operands are used in place of the
5806 // original operands for the remainder of this section.
5807 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005808 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005809 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005810 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005811 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005812 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005813 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005814 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005815 }
5816 }
5817
Richard Smithf2b084f2012-08-08 06:13:49 +00005818 // C++11 [expr.cond]p3
5819 // if both are glvalues of the same value category and the same type except
5820 // for cv-qualification, an attempt is made to convert each of those
5821 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005822 // FIXME:
5823 // Resolving a defect in P0012R1: we extend this to cover all cases where
5824 // one of the operands is reference-compatible with the other, in order
5825 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005826 ExprValueKind LVK = LHS.get()->getValueKind();
5827 ExprValueKind RVK = RHS.get()->getValueKind();
5828 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005829 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005830 // DerivedToBase was already handled by the class-specific case above.
5831 // FIXME: Should we allow ObjC conversions here?
5832 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5833 if (CompareReferenceRelationship(
5834 QuestionLoc, LTy, RTy, DerivedToBase,
5835 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005836 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5837 // [...] subject to the constraint that the reference must bind
5838 // directly [...]
5839 !RHS.get()->refersToBitField() &&
5840 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005841 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005842 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005843 } else if (CompareReferenceRelationship(
5844 QuestionLoc, RTy, LTy, DerivedToBase,
5845 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005846 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5847 !LHS.get()->refersToBitField() &&
5848 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005849 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5850 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005851 }
5852 }
5853
5854 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005855 // If the second and third operands are glvalues of the same value
5856 // category and have the same type, the result is of that type and
5857 // value category and it is a bit-field if the second or the third
5858 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005859 // We only extend this to bitfields, not to the crazy other kinds of
5860 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005861 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005862 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005863 LHS.get()->isOrdinaryOrBitFieldObject() &&
5864 RHS.get()->isOrdinaryOrBitFieldObject()) {
5865 VK = LHS.get()->getValueKind();
5866 if (LHS.get()->getObjectKind() == OK_BitField ||
5867 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005868 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005869
5870 // If we have function pointer types, unify them anyway to unify their
5871 // exception specifications, if any.
5872 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5873 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005874 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005875 /*ConvertArgs*/false);
5876 LTy = Context.getQualifiedType(LTy, Qs);
5877
5878 assert(!LTy.isNull() && "failed to find composite pointer type for "
5879 "canonically equivalent function ptr types");
5880 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5881 }
5882
John McCall7decc9e2010-11-18 06:31:45 +00005883 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005884 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005885
Richard Smithf2b084f2012-08-08 06:13:49 +00005886 // C++11 [expr.cond]p5
5887 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005888 // do not have the same type, and either has (cv) class type, ...
5889 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5890 // ... overload resolution is used to determine the conversions (if any)
5891 // to be applied to the operands. If the overload resolution fails, the
5892 // program is ill-formed.
5893 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5894 return QualType();
5895 }
5896
Richard Smithf2b084f2012-08-08 06:13:49 +00005897 // C++11 [expr.cond]p6
5898 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005899 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005900 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5901 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005902 if (LHS.isInvalid() || RHS.isInvalid())
5903 return QualType();
5904 LTy = LHS.get()->getType();
5905 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005906
5907 // After those conversions, one of the following shall hold:
5908 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005909 // is of that type. If the operands have class type, the result
5910 // is a prvalue temporary of the result type, which is
5911 // copy-initialized from either the second operand or the third
5912 // operand depending on the value of the first operand.
5913 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5914 if (LTy->isRecordType()) {
5915 // The operands have class type. Make a temporary copy.
5916 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005917
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005918 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5919 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005920 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005921 if (LHSCopy.isInvalid())
5922 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005923
5924 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5925 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005926 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005927 if (RHSCopy.isInvalid())
5928 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929
John Wiegley01296292011-04-08 18:41:53 +00005930 LHS = LHSCopy;
5931 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005932 }
5933
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005934 // If we have function pointer types, unify them anyway to unify their
5935 // exception specifications, if any.
5936 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5937 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5938 assert(!LTy.isNull() && "failed to find composite pointer type for "
5939 "canonically equivalent function ptr types");
5940 }
5941
Sebastian Redl1a99f442009-04-16 17:51:27 +00005942 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005943 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005944
Douglas Gregor46188682010-05-18 22:42:18 +00005945 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005946 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005947 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5948 /*AllowBothBool*/true,
5949 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005950
Sebastian Redl1a99f442009-04-16 17:51:27 +00005951 // -- The second and third operands have arithmetic or enumeration type;
5952 // the usual arithmetic conversions are performed to bring them to a
5953 // common type, and the result is of that type.
5954 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005955 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005956 if (LHS.isInvalid() || RHS.isInvalid())
5957 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005958 if (ResTy.isNull()) {
5959 Diag(QuestionLoc,
5960 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5961 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5962 return QualType();
5963 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005964
5965 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5966 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5967
5968 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005969 }
5970
5971 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005972 // type and the other is a null pointer constant, or both are null
5973 // pointer constants, at least one of which is non-integral; pointer
5974 // conversions and qualification conversions are performed to bring them
5975 // to their composite pointer type. The result is of the composite
5976 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005977 // -- The second and third operands have pointer to member type, or one has
5978 // pointer to member type and the other is a null pointer constant;
5979 // pointer to member conversions and qualification conversions are
5980 // performed to bring them to a common type, whose cv-qualification
5981 // shall match the cv-qualification of either the second or the third
5982 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005983 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5984 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005985 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005986
Douglas Gregor697a3912010-04-01 22:47:07 +00005987 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005988 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5989 if (!Composite.isNull())
5990 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005991
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005992 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005993 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005994 return QualType();
5995
Sebastian Redl1a99f442009-04-16 17:51:27 +00005996 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005997 << LHS.get()->getType() << RHS.get()->getType()
5998 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005999 return QualType();
6000}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006001
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006002static FunctionProtoType::ExceptionSpecInfo
6003mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6004 FunctionProtoType::ExceptionSpecInfo ESI2,
6005 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6006 ExceptionSpecificationType EST1 = ESI1.Type;
6007 ExceptionSpecificationType EST2 = ESI2.Type;
6008
6009 // If either of them can throw anything, that is the result.
6010 if (EST1 == EST_None) return ESI1;
6011 if (EST2 == EST_None) return ESI2;
6012 if (EST1 == EST_MSAny) return ESI1;
6013 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006014 if (EST1 == EST_NoexceptFalse) return ESI1;
6015 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006016
6017 // If either of them is non-throwing, the result is the other.
6018 if (EST1 == EST_DynamicNone) return ESI2;
6019 if (EST2 == EST_DynamicNone) return ESI1;
6020 if (EST1 == EST_BasicNoexcept) return ESI2;
6021 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006022 if (EST1 == EST_NoexceptTrue) return ESI2;
6023 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006024
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006025 // If we're left with value-dependent computed noexcept expressions, we're
6026 // stuck. Before C++17, we can just drop the exception specification entirely,
6027 // since it's not actually part of the canonical type. And this should never
6028 // happen in C++17, because it would mean we were computing the composite
6029 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006030 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006031 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006032 "computing composite pointer type of dependent types");
6033 return FunctionProtoType::ExceptionSpecInfo();
6034 }
6035
6036 // Switch over the possibilities so that people adding new values know to
6037 // update this function.
6038 switch (EST1) {
6039 case EST_None:
6040 case EST_DynamicNone:
6041 case EST_MSAny:
6042 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006043 case EST_DependentNoexcept:
6044 case EST_NoexceptFalse:
6045 case EST_NoexceptTrue:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006046 llvm_unreachable("handled above");
6047
6048 case EST_Dynamic: {
6049 // This is the fun case: both exception specifications are dynamic. Form
6050 // the union of the two lists.
6051 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6052 llvm::SmallPtrSet<QualType, 8> Found;
6053 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6054 for (QualType E : Exceptions)
6055 if (Found.insert(S.Context.getCanonicalType(E)).second)
6056 ExceptionTypeStorage.push_back(E);
6057
6058 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6059 Result.Exceptions = ExceptionTypeStorage;
6060 return Result;
6061 }
6062
6063 case EST_Unevaluated:
6064 case EST_Uninstantiated:
6065 case EST_Unparsed:
6066 llvm_unreachable("shouldn't see unresolved exception specifications here");
6067 }
6068
6069 llvm_unreachable("invalid ExceptionSpecificationType");
6070}
6071
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006072/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006073///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006074/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006075/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006076/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006077/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006078///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006079/// \param Loc The location of the operator requiring these two expressions to
6080/// be converted to the composite pointer type.
6081///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006082/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006083QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006084 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006085 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006086 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006087
6088 // C++1z [expr]p14:
6089 // The composite pointer type of two operands p1 and p2 having types T1
6090 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006091 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006092
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006093 // where at least one is a pointer or pointer to member type or
6094 // std::nullptr_t is:
6095 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6096 T1->isNullPtrType();
6097 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6098 T2->isNullPtrType();
6099 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006100 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006101
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006102 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6103 // This can't actually happen, following the standard, but we also use this
6104 // to implement the end of [expr.conv], which hits this case.
6105 //
6106 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6107 if (T1IsPointerLike &&
6108 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006109 if (ConvertArgs)
6110 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6111 ? CK_NullToMemberPointer
6112 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006113 return T1;
6114 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006115 if (T2IsPointerLike &&
6116 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006117 if (ConvertArgs)
6118 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6119 ? CK_NullToMemberPointer
6120 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006121 return T2;
6122 }
Mike Stump11289f42009-09-09 15:08:12 +00006123
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006124 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006125 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006126 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006127 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6128 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006129
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006130 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6131 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6132 // the union of cv1 and cv2;
6133 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6134 // "pointer to function", where the function types are otherwise the same,
6135 // "pointer to function";
6136 // FIXME: This rule is defective: it should also permit removing noexcept
6137 // from a pointer to member function. As a Clang extension, we also
6138 // permit removing 'noreturn', so we generalize this rule to;
6139 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6140 // "pointer to member function" and the pointee types can be unified
6141 // by a function pointer conversion, that conversion is applied
6142 // before checking the following rules.
6143 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6144 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6145 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6146 // respectively;
6147 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6148 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6149 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6150 // T1 or the cv-combined type of T1 and T2, respectively;
6151 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6152 // T2;
6153 //
6154 // If looked at in the right way, these bullets all do the same thing.
6155 // What we do here is, we build the two possible cv-combined types, and try
6156 // the conversions in both directions. If only one works, or if the two
6157 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006158 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006159 //
6160 // Note that this will fail to find a composite pointer type for "pointer
6161 // to void" and "pointer to function". We can't actually perform the final
6162 // conversion in this case, even though a composite pointer type formally
6163 // exists.
6164 SmallVector<unsigned, 4> QualifierUnion;
6165 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006166 QualType Composite1 = T1;
6167 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006168 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006169 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006170 const PointerType *Ptr1, *Ptr2;
6171 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6172 (Ptr2 = Composite2->getAs<PointerType>())) {
6173 Composite1 = Ptr1->getPointeeType();
6174 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006175
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006176 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006177 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006178 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006179 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006180
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006181 QualifierUnion.push_back(
6182 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006183 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006184 continue;
6185 }
Mike Stump11289f42009-09-09 15:08:12 +00006186
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006187 const MemberPointerType *MemPtr1, *MemPtr2;
6188 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6189 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6190 Composite1 = MemPtr1->getPointeeType();
6191 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006192
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006193 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006194 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006195 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006196 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006197
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006198 QualifierUnion.push_back(
6199 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6200 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6201 MemPtr2->getClass()));
6202 continue;
6203 }
Mike Stump11289f42009-09-09 15:08:12 +00006204
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006205 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006206
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006207 // Cannot unwrap any more types.
6208 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006209 }
Mike Stump11289f42009-09-09 15:08:12 +00006210
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006211 // Apply the function pointer conversion to unify the types. We've already
6212 // unwrapped down to the function types, and we want to merge rather than
6213 // just convert, so do this ourselves rather than calling
6214 // IsFunctionConversion.
6215 //
6216 // FIXME: In order to match the standard wording as closely as possible, we
6217 // currently only do this under a single level of pointers. Ideally, we would
6218 // allow this in general, and set NeedConstBefore to the relevant depth on
6219 // the side(s) where we changed anything.
6220 if (QualifierUnion.size() == 1) {
6221 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6222 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6223 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6224 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6225
6226 // The result is noreturn if both operands are.
6227 bool Noreturn =
6228 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6229 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6230 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6231
6232 // The result is nothrow if both operands are.
6233 SmallVector<QualType, 8> ExceptionTypeStorage;
6234 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6235 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6236 ExceptionTypeStorage);
6237
6238 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6239 FPT1->getParamTypes(), EPI1);
6240 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6241 FPT2->getParamTypes(), EPI2);
6242 }
6243 }
6244 }
6245
Richard Smith5e9746f2016-10-21 22:00:42 +00006246 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006247 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006248 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006249 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006250 for (unsigned I = 0; I != NeedConstBefore; ++I)
6251 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006252 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006253 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006254
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006255 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006256 auto MOC = MemberOfClass.rbegin();
6257 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6258 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6259 auto Classes = *MOC++;
6260 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006261 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006262 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006263 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006264 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006265 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006266 } else {
6267 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006268 Composite1 =
6269 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6270 Composite2 =
6271 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006272 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006273 }
6274
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006275 struct Conversion {
6276 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006277 Expr *&E1, *&E2;
6278 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006279 InitializedEntity Entity;
6280 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006281 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006282 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006283
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006284 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6285 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006286 : S(S), E1(E1), E2(E2), Composite(Composite),
6287 Entity(InitializedEntity::InitializeTemporary(Composite)),
6288 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6289 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6290 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006291
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006292 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006293 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6294 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006295 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006296 E1 = E1Result.getAs<Expr>();
6297
6298 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6299 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006300 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006301 E2 = E2Result.getAs<Expr>();
6302
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006303 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006304 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006305 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006306
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006307 // Try to convert to each composite pointer type.
6308 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006309 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6310 if (ConvertArgs && C1.perform())
6311 return QualType();
6312 return C1.Composite;
6313 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006314 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006315
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006316 if (C1.Viable == C2.Viable) {
6317 // Either Composite1 and Composite2 are viable and are different, or
6318 // neither is viable.
6319 // FIXME: How both be viable and different?
6320 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006321 }
6322
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006323 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006324 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6325 return QualType();
6326
6327 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006328}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006329
John McCalldadc5752010-08-24 06:29:42 +00006330ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006331 if (!E)
6332 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006333
John McCall31168b02011-06-15 23:02:42 +00006334 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6335
6336 // If the result is a glvalue, we shouldn't bind it.
6337 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006338 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006339
John McCall31168b02011-06-15 23:02:42 +00006340 // In ARC, calls that return a retainable type can return retained,
6341 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006342 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006343 E->getType()->isObjCRetainableType()) {
6344
6345 bool ReturnsRetained;
6346
6347 // For actual calls, we compute this by examining the type of the
6348 // called value.
6349 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6350 Expr *Callee = Call->getCallee()->IgnoreParens();
6351 QualType T = Callee->getType();
6352
6353 if (T == Context.BoundMemberTy) {
6354 // Handle pointer-to-members.
6355 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6356 T = BinOp->getRHS()->getType();
6357 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6358 T = Mem->getMemberDecl()->getType();
6359 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006360
John McCall31168b02011-06-15 23:02:42 +00006361 if (const PointerType *Ptr = T->getAs<PointerType>())
6362 T = Ptr->getPointeeType();
6363 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6364 T = Ptr->getPointeeType();
6365 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6366 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006367
John McCall31168b02011-06-15 23:02:42 +00006368 const FunctionType *FTy = T->getAs<FunctionType>();
6369 assert(FTy && "call to value not of function type?");
6370 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6371
6372 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6373 // type always produce a +1 object.
6374 } else if (isa<StmtExpr>(E)) {
6375 ReturnsRetained = true;
6376
Ted Kremeneke65b0862012-03-06 20:05:56 +00006377 // We hit this case with the lambda conversion-to-block optimization;
6378 // we don't want any extra casts here.
6379 } else if (isa<CastExpr>(E) &&
6380 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006381 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006382
John McCall31168b02011-06-15 23:02:42 +00006383 // For message sends and property references, we try to find an
6384 // actual method. FIXME: we should infer retention by selector in
6385 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006386 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006387 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006388 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6389 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006390 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6391 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006392 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006393 // Don't do reclaims if we're using the zero-element array
6394 // constant.
6395 if (ArrayLit->getNumElements() == 0 &&
6396 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6397 return E;
6398
Ted Kremeneke65b0862012-03-06 20:05:56 +00006399 D = ArrayLit->getArrayWithObjectsMethod();
6400 } else if (ObjCDictionaryLiteral *DictLit
6401 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006402 // Don't do reclaims if we're using the zero-element dictionary
6403 // constant.
6404 if (DictLit->getNumElements() == 0 &&
6405 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6406 return E;
6407
Ted Kremeneke65b0862012-03-06 20:05:56 +00006408 D = DictLit->getDictWithObjectsMethod();
6409 }
John McCall31168b02011-06-15 23:02:42 +00006410
6411 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006412
6413 // Don't do reclaims on performSelector calls; despite their
6414 // return type, the invoked method doesn't necessarily actually
6415 // return an object.
6416 if (!ReturnsRetained &&
6417 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006418 return E;
John McCall31168b02011-06-15 23:02:42 +00006419 }
6420
John McCall16de4d22011-11-14 19:53:16 +00006421 // Don't reclaim an object of Class type.
6422 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006423 return E;
John McCall16de4d22011-11-14 19:53:16 +00006424
Tim Shen4a05bb82016-06-21 20:29:17 +00006425 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006426
John McCall2d637d22011-09-10 06:18:15 +00006427 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6428 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006429 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6430 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006431 }
6432
David Blaikiebbafb8a2012-03-11 07:00:24 +00006433 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006434 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006435
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006436 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6437 // a fast path for the common case that the type is directly a RecordType.
6438 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006439 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006440 while (!RT) {
6441 switch (T->getTypeClass()) {
6442 case Type::Record:
6443 RT = cast<RecordType>(T);
6444 break;
6445 case Type::ConstantArray:
6446 case Type::IncompleteArray:
6447 case Type::VariableArray:
6448 case Type::DependentSizedArray:
6449 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6450 break;
6451 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006452 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006453 }
6454 }
Mike Stump11289f42009-09-09 15:08:12 +00006455
Richard Smithfd555f62012-02-22 02:04:18 +00006456 // That should be enough to guarantee that this type is complete, if we're
6457 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006458 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006459 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006460 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006461
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006462 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6463 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006464 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006465
John McCall31168b02011-06-15 23:02:42 +00006466 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006467 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006468 CheckDestructorAccess(E->getExprLoc(), Destructor,
6469 PDiag(diag::err_access_dtor_temp)
6470 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006471 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6472 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006473
Richard Smithfd555f62012-02-22 02:04:18 +00006474 // If destructor is trivial, we can avoid the extra copy.
6475 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006476 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006477
John McCall28fc7092011-11-10 05:35:25 +00006478 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006479 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006480 }
Richard Smitheec915d62012-02-18 04:13:32 +00006481
6482 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006483 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6484
6485 if (IsDecltype)
6486 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6487
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006488 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006489}
6490
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006491ExprResult
John McCall5d413782010-12-06 08:20:24 +00006492Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006493 if (SubExpr.isInvalid())
6494 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006495
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006496 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006497}
6498
John McCall28fc7092011-11-10 05:35:25 +00006499Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006500 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006501
Eli Friedman3bda6b12012-02-02 23:15:15 +00006502 CleanupVarDeclMarking();
6503
John McCall28fc7092011-11-10 05:35:25 +00006504 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6505 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006506 assert(Cleanup.exprNeedsCleanups() ||
6507 ExprCleanupObjects.size() == FirstCleanup);
6508 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006509 return SubExpr;
6510
Craig Topper5fc8fc22014-08-27 06:28:36 +00006511 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6512 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006513
Tim Shen4a05bb82016-06-21 20:29:17 +00006514 auto *E = ExprWithCleanups::Create(
6515 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006516 DiscardCleanupsInEvaluationContext();
6517
6518 return E;
6519}
6520
John McCall5d413782010-12-06 08:20:24 +00006521Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006522 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006523
Eli Friedman3bda6b12012-02-02 23:15:15 +00006524 CleanupVarDeclMarking();
6525
Tim Shen4a05bb82016-06-21 20:29:17 +00006526 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006527 return SubStmt;
6528
6529 // FIXME: In order to attach the temporaries, wrap the statement into
6530 // a StmtExpr; currently this is only used for asm statements.
6531 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6532 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006533 CompoundStmt *CompStmt = CompoundStmt::Create(
6534 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006535 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6536 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006537 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006538}
6539
Richard Smithfd555f62012-02-22 02:04:18 +00006540/// Process the expression contained within a decltype. For such expressions,
6541/// certain semantic checks on temporaries are delayed until this point, and
6542/// are omitted for the 'topmost' call in the decltype expression. If the
6543/// topmost call bound a temporary, strip that temporary off the expression.
6544ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006545 assert(ExprEvalContexts.back().ExprContext ==
6546 ExpressionEvaluationContextRecord::EK_Decltype &&
6547 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006548
Akira Hatanaka0a848562019-01-10 20:12:16 +00006549 ExprResult Result = CheckPlaceholderExpr(E);
6550 if (Result.isInvalid())
6551 return ExprError();
6552 E = Result.get();
6553
Richard Smithfd555f62012-02-22 02:04:18 +00006554 // C++11 [expr.call]p11:
6555 // If a function call is a prvalue of object type,
6556 // -- if the function call is either
6557 // -- the operand of a decltype-specifier, or
6558 // -- the right operand of a comma operator that is the operand of a
6559 // decltype-specifier,
6560 // a temporary object is not introduced for the prvalue.
6561
6562 // Recursively rebuild ParenExprs and comma expressions to strip out the
6563 // outermost CXXBindTemporaryExpr, if any.
6564 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6565 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6566 if (SubExpr.isInvalid())
6567 return ExprError();
6568 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006569 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006570 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006571 }
6572 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6573 if (BO->getOpcode() == BO_Comma) {
6574 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6575 if (RHS.isInvalid())
6576 return ExprError();
6577 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006578 return E;
6579 return new (Context) BinaryOperator(
6580 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006581 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006582 }
6583 }
6584
6585 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006586 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6587 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006588 if (TopCall)
6589 E = TopCall;
6590 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006591 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006592
6593 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006594 ExprEvalContexts.back().ExprContext =
6595 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00006596
Richard Smithf86b0ae2012-07-28 19:54:11 +00006597 // In MS mode, don't perform any extra checking of call return types within a
6598 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006599 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006600 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006601
Richard Smithfd555f62012-02-22 02:04:18 +00006602 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006603 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6604 I != N; ++I) {
6605 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006606 if (Call == TopCall)
6607 continue;
6608
David Majnemerced8bdf2015-02-25 17:36:15 +00006609 if (CheckCallReturnType(Call->getCallReturnType(Context),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006610 Call->getBeginLoc(), Call, Call->getDirectCallee()))
Richard Smithfd555f62012-02-22 02:04:18 +00006611 return ExprError();
6612 }
6613
6614 // Now all relevant types are complete, check the destructors are accessible
6615 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006616 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6617 I != N; ++I) {
6618 CXXBindTemporaryExpr *Bind =
6619 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006620 if (Bind == TopBind)
6621 continue;
6622
6623 CXXTemporary *Temp = Bind->getTemporary();
6624
6625 CXXRecordDecl *RD =
6626 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6627 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6628 Temp->setDestructor(Destructor);
6629
Richard Smith7d847b12012-05-11 22:20:10 +00006630 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6631 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006632 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006633 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006634 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6635 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006636
6637 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006638 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006639 }
6640
6641 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006642 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006643}
6644
Richard Smith79c927b2013-11-06 19:31:51 +00006645/// Note a set of 'operator->' functions that were used for a member access.
6646static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006647 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006648 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6649 // FIXME: Make this configurable?
6650 unsigned Limit = 9;
6651 if (OperatorArrows.size() > Limit) {
6652 // Produce Limit-1 normal notes and one 'skipping' note.
6653 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6654 SkipCount = OperatorArrows.size() - (Limit - 1);
6655 }
6656
6657 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6658 if (I == SkipStart) {
6659 S.Diag(OperatorArrows[I]->getLocation(),
6660 diag::note_operator_arrows_suppressed)
6661 << SkipCount;
6662 I += SkipCount;
6663 } else {
6664 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6665 << OperatorArrows[I]->getCallResultType();
6666 ++I;
6667 }
6668 }
6669}
6670
Nico Weber964d3322015-02-16 22:35:45 +00006671ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6672 SourceLocation OpLoc,
6673 tok::TokenKind OpKind,
6674 ParsedType &ObjectType,
6675 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006676 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006677 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006678 if (Result.isInvalid()) return ExprError();
6679 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006680
John McCall526ab472011-10-25 17:37:35 +00006681 Result = CheckPlaceholderExpr(Base);
6682 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006683 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006684
John McCallb268a282010-08-23 23:25:46 +00006685 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006686 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006687 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006688 // If we have a pointer to a dependent type and are using the -> operator,
6689 // the object type is the type that the pointer points to. We might still
6690 // have enough information about that type to do something useful.
6691 if (OpKind == tok::arrow)
6692 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6693 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006694
John McCallba7bf592010-08-24 05:47:05 +00006695 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006696 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006697 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006698 }
Mike Stump11289f42009-09-09 15:08:12 +00006699
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006700 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006701 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006702 // returned, with the original second operand.
6703 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006704 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006705 bool NoArrowOperatorFound = false;
6706 bool FirstIteration = true;
6707 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006708 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006709 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006710 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006711 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006713 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006714 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6715 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006716 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006717 noteOperatorArrows(*this, OperatorArrows);
6718 Diag(OpLoc, diag::note_operator_arrow_depth)
6719 << getLangOpts().ArrowDepth;
6720 return ExprError();
6721 }
6722
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006723 Result = BuildOverloadedArrowExpr(
6724 S, Base, OpLoc,
6725 // When in a template specialization and on the first loop iteration,
6726 // potentially give the default diagnostic (with the fixit in a
6727 // separate note) instead of having the error reported back to here
6728 // and giving a diagnostic with a fixit attached to the error itself.
6729 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006730 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006731 : &NoArrowOperatorFound);
6732 if (Result.isInvalid()) {
6733 if (NoArrowOperatorFound) {
6734 if (FirstIteration) {
6735 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006736 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006737 << FixItHint::CreateReplacement(OpLoc, ".");
6738 OpKind = tok::period;
6739 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006740 }
6741 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6742 << BaseType << Base->getSourceRange();
6743 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006744 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006745 Diag(CD->getBeginLoc(),
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006746 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006747 }
6748 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006749 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006750 }
John McCallb268a282010-08-23 23:25:46 +00006751 Base = Result.get();
6752 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006753 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006754 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006755 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006756 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006757 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6758 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006759 return ExprError();
6760 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006761 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006762 }
Mike Stump11289f42009-09-09 15:08:12 +00006763
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006764 if (OpKind == tok::arrow &&
6765 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006766 BaseType = BaseType->getPointeeType();
6767 }
Mike Stump11289f42009-09-09 15:08:12 +00006768
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006769 // Objective-C properties allow "." access on Objective-C pointer types,
6770 // so adjust the base type to the object type itself.
6771 if (BaseType->isObjCObjectPointerType())
6772 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006773
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006774 // C++ [basic.lookup.classref]p2:
6775 // [...] If the type of the object expression is of pointer to scalar
6776 // type, the unqualified-id is looked up in the context of the complete
6777 // postfix-expression.
6778 //
6779 // This also indicates that we could be parsing a pseudo-destructor-name.
6780 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006781 // expressions or normal member (ivar or property) access expressions, and
6782 // it's legal for the type to be incomplete if this is a pseudo-destructor
6783 // call. We'll do more incomplete-type checks later in the lookup process,
6784 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006785 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006786 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006787 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006788 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006789 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006790 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006791 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006792 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006793 }
Mike Stump11289f42009-09-09 15:08:12 +00006794
Douglas Gregor3024f072012-04-16 07:05:22 +00006795 // The object type must be complete (or dependent), or
6796 // C++11 [expr.prim.general]p3:
6797 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006798 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006799 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006800 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006801 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006802 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006803 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006804
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006805 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006806 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006807 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006808 // type C (or of pointer to a class type C), the unqualified-id is looked
6809 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006810 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006811 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006812}
6813
Simon Pilgrim75c26882016-09-30 14:25:09 +00006814static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006815 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006816 if (Base->hasPlaceholderType()) {
6817 ExprResult result = S.CheckPlaceholderExpr(Base);
6818 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006819 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006820 }
6821 ObjectType = Base->getType();
6822
David Blaikie1d578782011-12-16 16:03:09 +00006823 // C++ [expr.pseudo]p2:
6824 // The left-hand side of the dot operator shall be of scalar type. The
6825 // left-hand side of the arrow operator shall be of pointer to scalar type.
6826 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006827 // Note that this is rather different from the normal handling for the
6828 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006829 if (OpKind == tok::arrow) {
6830 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6831 ObjectType = Ptr->getPointeeType();
6832 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006833 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006834 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6835 << ObjectType << true
6836 << FixItHint::CreateReplacement(OpLoc, ".");
6837 if (S.isSFINAEContext())
6838 return true;
6839
6840 OpKind = tok::period;
6841 }
6842 }
6843
6844 return false;
6845}
6846
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006847/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006848/// pointer objects.
6849static bool
6850canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6851 QualType DestructedType) {
6852 // If this is a record type, check if its destructor is callable.
6853 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
Bruno Ricci4eb701c2019-01-24 13:52:47 +00006854 if (RD->hasDefinition())
6855 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6856 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006857 return false;
6858 }
6859
6860 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6861 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6862 DestructedType->isVectorType();
6863}
6864
John McCalldadc5752010-08-24 06:29:42 +00006865ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006866 SourceLocation OpLoc,
6867 tok::TokenKind OpKind,
6868 const CXXScopeSpec &SS,
6869 TypeSourceInfo *ScopeTypeInfo,
6870 SourceLocation CCLoc,
6871 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006872 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006873 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006874
Eli Friedman0ce4de42012-01-25 04:35:06 +00006875 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006876 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6877 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878
Douglas Gregorc5c57342012-09-10 14:57:06 +00006879 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6880 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006881 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006882 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006883 else {
Nico Weber58829272012-01-23 05:50:57 +00006884 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6885 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006886 return ExprError();
6887 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006888 }
6889
6890 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006891 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006892 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006893 if (DestructedTypeInfo) {
6894 QualType DestructedType = DestructedTypeInfo->getType();
6895 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006896 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006897 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6898 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006899 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6900 // Foo *foo;
6901 // foo.~Foo();
6902 if (OpKind == tok::period && ObjectType->isPointerType() &&
6903 Context.hasSameUnqualifiedType(DestructedType,
6904 ObjectType->getPointeeType())) {
6905 auto Diagnostic =
6906 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6907 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006908
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006909 // Issue a fixit only when the destructor is valid.
6910 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6911 *this, DestructedType))
6912 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6913
6914 // Recover by setting the object type to the destructed type and the
6915 // operator to '->'.
6916 ObjectType = DestructedType;
6917 OpKind = tok::arrow;
6918 } else {
6919 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6920 << ObjectType << DestructedType << Base->getSourceRange()
6921 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6922
6923 // Recover by setting the destructed type to the object type.
6924 DestructedType = ObjectType;
6925 DestructedTypeInfo =
6926 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6927 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6928 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006929 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006930 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006931
John McCall31168b02011-06-15 23:02:42 +00006932 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6933 // Okay: just pretend that the user provided the correctly-qualified
6934 // type.
6935 } else {
6936 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6937 << ObjectType << DestructedType << Base->getSourceRange()
6938 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6939 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006940
John McCall31168b02011-06-15 23:02:42 +00006941 // Recover by setting the destructed type to the object type.
6942 DestructedType = ObjectType;
6943 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6944 DestructedTypeStart);
6945 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6946 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006947 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006948 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006949
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006950 // C++ [expr.pseudo]p2:
6951 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6952 // form
6953 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006954 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006955 //
6956 // shall designate the same scalar type.
6957 if (ScopeTypeInfo) {
6958 QualType ScopeType = ScopeTypeInfo->getType();
6959 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006960 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006961
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006962 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006963 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006964 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006965 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006966
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006967 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006968 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006969 }
6970 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006971
John McCallb268a282010-08-23 23:25:46 +00006972 Expr *Result
6973 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6974 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006975 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006976 ScopeTypeInfo,
6977 CCLoc,
6978 TildeLoc,
6979 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006980
David Majnemerced8bdf2015-02-25 17:36:15 +00006981 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006982}
6983
John McCalldadc5752010-08-24 06:29:42 +00006984ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006985 SourceLocation OpLoc,
6986 tok::TokenKind OpKind,
6987 CXXScopeSpec &SS,
6988 UnqualifiedId &FirstTypeName,
6989 SourceLocation CCLoc,
6990 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006991 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006992 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6993 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006994 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006995 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6996 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006997 "Invalid second type name in pseudo-destructor");
6998
Eli Friedman0ce4de42012-01-25 04:35:06 +00006999 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007000 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7001 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00007002
7003 // Compute the object type that we should use for name lookup purposes. Only
7004 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00007005 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007006 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00007007 if (ObjectType->isRecordType())
7008 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00007009 else if (ObjectType->isDependentType())
7010 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007011 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007012
7013 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007014 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007015 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00007016 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007017 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007018 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007019 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007020 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007021 S, &SS, true, false, ObjectTypePtrForLookup,
7022 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007023 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00007024 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7025 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007026 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00007027 // couldn't find anything useful in scope. Just store the identifier and
7028 // it's location, and we'll perform (qualified) name lookup again at
7029 // template instantiation time.
7030 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7031 SecondTypeName.StartLocation);
7032 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007033 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007034 diag::err_pseudo_dtor_destructor_non_type)
7035 << SecondTypeName.Identifier << ObjectType;
7036 if (isSFINAEContext())
7037 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007038
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007039 // Recover by assuming we had the right type all along.
7040 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007041 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007042 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007043 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007044 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007045 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007046 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007047 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007048 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007049 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007050 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007051 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007052 TemplateId->TemplateNameLoc,
7053 TemplateId->LAngleLoc,
7054 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007055 TemplateId->RAngleLoc,
7056 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007057 if (T.isInvalid() || !T.get()) {
7058 // Recover by assuming we had the right type all along.
7059 DestructedType = ObjectType;
7060 } else
7061 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007063
7064 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007065 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007066 if (!DestructedType.isNull()) {
7067 if (!DestructedTypeInfo)
7068 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007069 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007070 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7071 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007072
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007073 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007074 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007075 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007076 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007077 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007078 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007079 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007080 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007081 S, &SS, true, false, ObjectTypePtrForLookup,
7082 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007083 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007084 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007085 diag::err_pseudo_dtor_destructor_non_type)
7086 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007087
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007088 if (isSFINAEContext())
7089 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007090
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007091 // Just drop this type. It's unnecessary anyway.
7092 ScopeType = QualType();
7093 } else
7094 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007095 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007096 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007097 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007098 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007099 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007100 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007101 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007102 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007103 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007104 TemplateId->TemplateNameLoc,
7105 TemplateId->LAngleLoc,
7106 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007107 TemplateId->RAngleLoc,
7108 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007109 if (T.isInvalid() || !T.get()) {
7110 // Recover by dropping this type.
7111 ScopeType = QualType();
7112 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007113 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007114 }
7115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007116
Douglas Gregor90ad9222010-02-24 23:02:30 +00007117 if (!ScopeType.isNull() && !ScopeTypeInfo)
7118 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7119 FirstTypeName.StartLocation);
7120
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007121
John McCallb268a282010-08-23 23:25:46 +00007122 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007123 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007124 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007125}
7126
David Blaikie1d578782011-12-16 16:03:09 +00007127ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7128 SourceLocation OpLoc,
7129 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007130 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007131 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007132 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007133 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7134 return ExprError();
7135
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007136 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7137 false);
David Blaikie1d578782011-12-16 16:03:09 +00007138
7139 TypeLocBuilder TLB;
7140 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7141 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7142 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7143 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7144
7145 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007146 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007147 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007148}
7149
John Wiegley01296292011-04-08 18:41:53 +00007150ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007151 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007152 bool HadMultipleCandidates) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00007153 // Convert the expression to match the conversion function's implicit object
7154 // parameter.
7155 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7156 FoundDecl, Method);
7157 if (Exp.isInvalid())
7158 return true;
7159
Eli Friedman98b01ed2012-03-01 04:01:32 +00007160 if (Method->getParent()->isLambda() &&
7161 Method->getConversionType()->isBlockPointerType()) {
7162 // This is a lambda coversion to block pointer; check if the argument
Richard Smith7ed5fb22018-07-27 17:13:18 +00007163 // was a LambdaExpr.
Eli Friedman98b01ed2012-03-01 04:01:32 +00007164 Expr *SubE = E;
7165 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7166 if (CE && CE->getCastKind() == CK_NoOp)
7167 SubE = CE->getSubExpr();
7168 SubE = SubE->IgnoreParens();
7169 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7170 SubE = BE->getSubExpr();
7171 if (isa<LambdaExpr>(SubE)) {
7172 // For the conversion to block pointer on a lambda expression, we
7173 // construct a special BlockLiteral instead; this doesn't really make
7174 // a difference in ARC, but outside of ARC the resulting block literal
7175 // follows the normal lifetime rules for block literals instead of being
7176 // autoreleased.
7177 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007178 PushExpressionEvaluationContext(
7179 ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith7ed5fb22018-07-27 17:13:18 +00007180 ExprResult BlockExp = BuildBlockForLambdaConversion(
7181 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
Akira Hatanakac482acd2016-05-04 18:07:20 +00007182 PopExpressionEvaluationContext();
7183
Richard Smith7ed5fb22018-07-27 17:13:18 +00007184 if (BlockExp.isInvalid())
7185 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7186 return BlockExp;
Eli Friedman98b01ed2012-03-01 04:01:32 +00007187 }
7188 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007189
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00007190 MemberExpr *ME = new (Context) MemberExpr(
7191 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7192 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007193 if (HadMultipleCandidates)
7194 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00007195 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007196
Alp Toker314cc812014-01-25 16:55:45 +00007197 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007198 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7199 ResultType = ResultType.getNonLValueExprType(Context);
7200
Bruno Riccic5885cf2018-12-21 15:20:32 +00007201 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7202 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
George Burgess IVce6284b2017-01-28 02:19:40 +00007203
7204 if (CheckFunctionCall(Method, CE,
7205 Method->getType()->castAs<FunctionProtoType>()))
7206 return ExprError();
7207
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007208 return CE;
7209}
7210
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007211ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7212 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007213 // If the operand is an unresolved lookup expression, the expression is ill-
7214 // formed per [over.over]p1, because overloaded function names cannot be used
7215 // without arguments except in explicit contexts.
7216 ExprResult R = CheckPlaceholderExpr(Operand);
7217 if (R.isInvalid())
7218 return R;
7219
7220 // The operand may have been modified when checking the placeholder type.
7221 Operand = R.get();
7222
Richard Smith51ec0cf2017-02-21 01:17:38 +00007223 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007224 // The expression operand for noexcept is in an unevaluated expression
7225 // context, so side effects could result in unintended consequences.
7226 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7227 }
7228
Richard Smithf623c962012-04-17 00:58:00 +00007229 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007230 return new (Context)
7231 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007232}
7233
7234ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7235 Expr *Operand, SourceLocation RParen) {
7236 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007237}
7238
Eli Friedmanf798f652012-05-24 22:04:19 +00007239static bool IsSpecialDiscardedValue(Expr *E) {
7240 // In C++11, discarded-value expressions of a certain form are special,
7241 // according to [expr]p10:
7242 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7243 // expression is an lvalue of volatile-qualified type and it has
7244 // one of the following forms:
7245 E = E->IgnoreParens();
7246
Eli Friedmanc49c2262012-05-24 22:36:31 +00007247 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007248 if (isa<DeclRefExpr>(E))
7249 return true;
7250
Eli Friedmanc49c2262012-05-24 22:36:31 +00007251 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007252 if (isa<ArraySubscriptExpr>(E))
7253 return true;
7254
Eli Friedmanc49c2262012-05-24 22:36:31 +00007255 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007256 if (isa<MemberExpr>(E))
7257 return true;
7258
Eli Friedmanc49c2262012-05-24 22:36:31 +00007259 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007260 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7261 if (UO->getOpcode() == UO_Deref)
7262 return true;
7263
7264 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007265 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007266 if (BO->isPtrMemOp())
7267 return true;
7268
Eli Friedmanc49c2262012-05-24 22:36:31 +00007269 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007270 if (BO->getOpcode() == BO_Comma)
7271 return IsSpecialDiscardedValue(BO->getRHS());
7272 }
7273
Eli Friedmanc49c2262012-05-24 22:36:31 +00007274 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007275 // operands are one of the above, or
7276 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7277 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7278 IsSpecialDiscardedValue(CO->getFalseExpr());
7279 // The related edge case of "*x ?: *x".
7280 if (BinaryConditionalOperator *BCO =
7281 dyn_cast<BinaryConditionalOperator>(E)) {
7282 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7283 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7284 IsSpecialDiscardedValue(BCO->getFalseExpr());
7285 }
7286
7287 // Objective-C++ extensions to the rule.
7288 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7289 return true;
7290
7291 return false;
7292}
7293
John McCall34376a62010-12-04 03:47:34 +00007294/// Perform the conversions required for an expression used in a
7295/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007296ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007297 if (E->hasPlaceholderType()) {
7298 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007299 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007300 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007301 }
7302
John McCallfee942d2010-12-02 02:07:15 +00007303 // C99 6.3.2.1:
7304 // [Except in specific positions,] an lvalue that does not have
7305 // array type is converted to the value stored in the
7306 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007307 if (E->isRValue()) {
7308 // In C, function designators (i.e. expressions of function type)
7309 // are r-values, but we still want to do function-to-pointer decay
7310 // on them. This is both technically correct and convenient for
7311 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007312 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007313 return DefaultFunctionArrayConversion(E);
7314
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007315 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007316 }
John McCallfee942d2010-12-02 02:07:15 +00007317
Eli Friedmanf798f652012-05-24 22:04:19 +00007318 if (getLangOpts().CPlusPlus) {
7319 // The C++11 standard defines the notion of a discarded-value expression;
7320 // normally, we don't need to do anything to handle it, but if it is a
7321 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7322 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007323 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007324 E->getType().isVolatileQualified() &&
7325 IsSpecialDiscardedValue(E)) {
7326 ExprResult Res = DefaultLvalueConversion(E);
7327 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007328 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007329 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007330 }
Richard Smith122f88d2016-12-06 23:52:28 +00007331
7332 // C++1z:
7333 // If the expression is a prvalue after this optional conversion, the
7334 // temporary materialization conversion is applied.
7335 //
7336 // We skip this step: IR generation is able to synthesize the storage for
7337 // itself in the aggregate case, and adding the extra node to the AST is
7338 // just clutter.
7339 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7340 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007341 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007342 }
John McCall34376a62010-12-04 03:47:34 +00007343
7344 // GCC seems to also exclude expressions of incomplete enum type.
7345 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7346 if (!T->getDecl()->isComplete()) {
7347 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007348 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007349 return E;
John McCall34376a62010-12-04 03:47:34 +00007350 }
7351 }
7352
John Wiegley01296292011-04-08 18:41:53 +00007353 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7354 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007355 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007356 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007357
John McCallca61b652010-12-04 12:29:11 +00007358 if (!E->getType()->isVoidType())
7359 RequireCompleteType(E->getExprLoc(), E->getType(),
7360 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007361 return E;
John McCall34376a62010-12-04 03:47:34 +00007362}
7363
Faisal Valia17d19f2013-11-07 05:17:06 +00007364// If we can unambiguously determine whether Var can never be used
7365// in a constant expression, return true.
7366// - if the variable and its initializer are non-dependent, then
7367// we can unambiguously check if the variable is a constant expression.
7368// - if the initializer is not value dependent - we can determine whether
7369// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007370// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007371// never be a constant expression.
7372// - FXIME: if the initializer is dependent, we can still do some analysis and
7373// identify certain cases unambiguously as non-const by using a Visitor:
7374// - such as those that involve odr-use of a ParmVarDecl, involve a new
7375// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007376static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007377 ASTContext &Context) {
7378 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007379 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007380
7381 // If there is no initializer - this can not be a constant expression.
7382 if (!Var->getAnyInitializer(DefVD)) return true;
7383 assert(DefVD);
7384 if (DefVD->isWeak()) return false;
7385 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007386
Faisal Valia17d19f2013-11-07 05:17:06 +00007387 Expr *Init = cast<Expr>(Eval->Value);
7388
7389 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007390 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7391 // of value-dependent expressions, and use it here to determine whether the
7392 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007393 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007394 }
7395
Simon Pilgrim75c26882016-09-30 14:25:09 +00007396 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007397}
7398
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007399/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007400/// that must be captured by any of its enclosing lambdas that are ready to
7401/// capture. If there is a lambda that can capture a nested
7402/// potential-capture, go ahead and do so. Also, check to see if any
7403/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007404/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007405
Faisal Valiab3d6462013-12-07 20:22:44 +00007406static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7407 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7408
Simon Pilgrim75c26882016-09-30 14:25:09 +00007409 assert(!S.isUnevaluatedContext());
7410 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007411#ifndef NDEBUG
7412 DeclContext *DC = S.CurContext;
7413 while (DC && isa<CapturedDecl>(DC))
7414 DC = DC->getParent();
7415 assert(
7416 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007417 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007418#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007419
7420 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7421
Faisal Valiab3d6462013-12-07 20:22:44 +00007422 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007423 // lambda (within a generic outer lambda), must be captured by an
7424 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007425 const unsigned NumPotentialCaptures =
7426 CurrentLSI->getNumPotentialVariableCaptures();
7427 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007428 Expr *VarExpr = nullptr;
7429 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007430 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007431 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007432 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007433 // need to check enclosing lambda's for speculative captures.
7434 // For e.g.:
7435 // Even though 'x' is not odr-used, it should be captured.
7436 // int test() {
7437 // const int x = 10;
7438 // auto L = [=](auto a) {
7439 // (void) +x + a;
7440 // };
7441 // }
7442 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007443 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007444 continue;
7445
7446 // If we have a capture-capable lambda for the variable, go ahead and
7447 // capture the variable in that lambda (and all its enclosing lambdas).
7448 if (const Optional<unsigned> Index =
7449 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007450 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007451 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7452 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7453 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007454 }
7455 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007456 VariableCanNeverBeAConstantExpression(Var, S.Context);
7457 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7458 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007459 // can not be used in a constant expression - which means
7460 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007461 // capture violation early, if the variable is un-captureable.
7462 // This is purely for diagnosing errors early. Otherwise, this
7463 // error would get diagnosed when the lambda becomes capture ready.
7464 QualType CaptureType, DeclRefType;
7465 SourceLocation ExprLoc = VarExpr->getExprLoc();
7466 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007467 /*EllipsisLoc*/ SourceLocation(),
7468 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007469 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007470 // We will never be able to capture this variable, and we need
7471 // to be able to in any and all instantiations, so diagnose it.
7472 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007473 /*EllipsisLoc*/ SourceLocation(),
7474 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007475 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007476 }
7477 }
7478 }
7479
Faisal Valiab3d6462013-12-07 20:22:44 +00007480 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007481 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007482 // If we have a capture-capable lambda for 'this', go ahead and capture
7483 // 'this' in that lambda (and all its enclosing lambdas).
7484 if (const Optional<unsigned> Index =
7485 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007486 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007487 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7488 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7489 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7490 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007491 }
7492 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007493
7494 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007495 CurrentLSI->clearPotentialCaptures();
7496}
7497
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007498static ExprResult attemptRecovery(Sema &SemaRef,
7499 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007500 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007501 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7502 Consumer.getLookupResult().getLookupKind());
7503 const CXXScopeSpec *SS = Consumer.getSS();
7504 CXXScopeSpec NewSS;
7505
7506 // Use an approprate CXXScopeSpec for building the expr.
7507 if (auto *NNS = TC.getCorrectionSpecifier())
7508 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7509 else if (SS && !TC.WillReplaceSpecifier())
7510 NewSS = *SS;
7511
Richard Smithde6d6c42015-12-29 19:43:10 +00007512 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007513 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007514 R.addDecl(ND);
7515 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007516 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007517 CXXRecordDecl *Record = nullptr;
7518 if (auto *NNS = TC.getCorrectionSpecifier())
7519 Record = NNS->getAsType()->getAsCXXRecordDecl();
7520 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007521 Record =
7522 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7523 if (Record)
7524 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007525
7526 // Detect and handle the case where the decl might be an implicit
7527 // member.
7528 bool MightBeImplicitMember;
7529 if (!Consumer.isAddressOfOperand())
7530 MightBeImplicitMember = true;
7531 else if (!NewSS.isEmpty())
7532 MightBeImplicitMember = false;
7533 else if (R.isOverloadedResult())
7534 MightBeImplicitMember = false;
7535 else if (R.isUnresolvableResult())
7536 MightBeImplicitMember = true;
7537 else
7538 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7539 isa<IndirectFieldDecl>(ND) ||
7540 isa<MSPropertyDecl>(ND);
7541
7542 if (MightBeImplicitMember)
7543 return SemaRef.BuildPossibleImplicitMemberExpr(
7544 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007545 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007546 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7547 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7548 Ivar->getIdentifier());
7549 }
7550 }
7551
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007552 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7553 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007554}
7555
Kaelyn Takata6c759512014-10-27 18:07:37 +00007556namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007557class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7558 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7559
7560public:
7561 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7562 : TypoExprs(TypoExprs) {}
7563 bool VisitTypoExpr(TypoExpr *TE) {
7564 TypoExprs.insert(TE);
7565 return true;
7566 }
7567};
7568
Kaelyn Takata6c759512014-10-27 18:07:37 +00007569class TransformTypos : public TreeTransform<TransformTypos> {
7570 typedef TreeTransform<TransformTypos> BaseTransform;
7571
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007572 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7573 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007574 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007575 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007576 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007577 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007578
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007579 /// Emit diagnostics for all of the TypoExprs encountered.
Kaelyn Takata6c759512014-10-27 18:07:37 +00007580 /// If the TypoExprs were successfully corrected, then the diagnostics should
7581 /// suggest the corrections. Otherwise the diagnostics will not suggest
7582 /// anything (having been passed an empty TypoCorrection).
7583 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007584 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007585 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007586 if (State.DiagHandler) {
7587 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7588 ExprResult Replacement = TransformCache[TE];
7589
7590 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7591 // TypoCorrection, replacing the existing decls. This ensures the right
7592 // NamedDecl is used in diagnostics e.g. in the case where overload
7593 // resolution was used to select one from several possible decls that
7594 // had been stored in the TypoCorrection.
7595 if (auto *ND = getDeclFromExpr(
7596 Replacement.isInvalid() ? nullptr : Replacement.get()))
7597 TC.setCorrectionDecl(ND);
7598
7599 State.DiagHandler(TC);
7600 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007601 SemaRef.clearDelayedTypo(TE);
7602 }
7603 }
7604
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007605 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007606 /// given combination of the other TypoExprs, retry those corrections against
7607 /// the next combination of substitutions for the other TypoExprs by advancing
7608 /// to the next potential correction of the second TypoExpr. For the second
7609 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7610 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7611 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7612 /// TransformCache). Returns true if there is still any untried combinations
7613 /// of corrections.
7614 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7615 for (auto TE : TypoExprs) {
7616 auto &State = SemaRef.getTypoExprState(TE);
7617 TransformCache.erase(TE);
7618 if (!State.Consumer->finished())
7619 return true;
7620 State.Consumer->resetCorrectionStream();
7621 }
7622 return false;
7623 }
7624
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007625 NamedDecl *getDeclFromExpr(Expr *E) {
7626 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7627 E = OverloadResolution[OE];
7628
7629 if (!E)
7630 return nullptr;
7631 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007632 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007633 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007634 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007635 // FIXME: Add any other expr types that could be be seen by the delayed typo
7636 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007637 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007638 return nullptr;
7639 }
7640
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007641 ExprResult TryTransform(Expr *E) {
7642 Sema::SFINAETrap Trap(SemaRef);
7643 ExprResult Res = TransformExpr(E);
7644 if (Trap.hasErrorOccurred() || Res.isInvalid())
7645 return ExprError();
7646
7647 return ExprFilter(Res.get());
7648 }
7649
Kaelyn Takata6c759512014-10-27 18:07:37 +00007650public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007651 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7652 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007653
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007654 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7655 MultiExprArg Args,
7656 SourceLocation RParenLoc,
7657 Expr *ExecConfig = nullptr) {
7658 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7659 RParenLoc, ExecConfig);
7660 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007661 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007662 Expr *ResultCall = Result.get();
7663 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7664 ResultCall = BE->getSubExpr();
7665 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7666 OverloadResolution[OE] = CE->getCallee();
7667 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007668 }
7669 return Result;
7670 }
7671
Kaelyn Takata6c759512014-10-27 18:07:37 +00007672 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7673
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007674 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7675
Kaelyn Takata6c759512014-10-27 18:07:37 +00007676 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007677 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007678 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007679 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007680
Kaelyn Takata6c759512014-10-27 18:07:37 +00007681 // Exit if either the transform was valid or if there were no TypoExprs
7682 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007683 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007684 !CheckAndAdvanceTypoExprCorrectionStreams())
7685 break;
7686 }
7687
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007688 // Ensure none of the TypoExprs have multiple typo correction candidates
7689 // with the same edit length that pass all the checks and filters.
7690 // TODO: Properly handle various permutations of possible corrections when
7691 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007692 // Also, disable typo correction while attempting the transform when
7693 // handling potentially ambiguous typo corrections as any new TypoExprs will
7694 // have been introduced by the application of one of the correction
7695 // candidates and add little to no value if corrected.
7696 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007697 while (!AmbiguousTypoExprs.empty()) {
7698 auto TE = AmbiguousTypoExprs.back();
7699 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007700 auto &State = SemaRef.getTypoExprState(TE);
7701 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007702 TransformCache.erase(TE);
7703 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007704 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007705 TransformCache.erase(TE);
7706 Res = ExprError();
7707 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007708 }
7709 AmbiguousTypoExprs.remove(TE);
7710 State.Consumer->restoreSavedPosition();
7711 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007712 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007713 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007714
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007715 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007716 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007717 FindTypoExprs(TypoExprs).TraverseStmt(E);
7718
Kaelyn Takata6c759512014-10-27 18:07:37 +00007719 EmitAllDiagnostics();
7720
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007721 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007722 }
7723
7724 ExprResult TransformTypoExpr(TypoExpr *E) {
7725 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7726 // cached transformation result if there is one and the TypoExpr isn't the
7727 // first one that was encountered.
7728 auto &CacheEntry = TransformCache[E];
7729 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7730 return CacheEntry;
7731 }
7732
7733 auto &State = SemaRef.getTypoExprState(E);
7734 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7735
7736 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7737 // typo correction and return it.
7738 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007739 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007740 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007741 // FIXME: If we would typo-correct to an invalid declaration, it's
7742 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007743 ExprResult NE = State.RecoveryHandler ?
7744 State.RecoveryHandler(SemaRef, E, TC) :
7745 attemptRecovery(SemaRef, *State.Consumer, TC);
7746 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007747 // Check whether there may be a second viable correction with the same
7748 // edit distance; if so, remember this TypoExpr may have an ambiguous
7749 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007750 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007751 if ((Next = State.Consumer->peekNextCorrection()) &&
7752 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7753 AmbiguousTypoExprs.insert(E);
7754 } else {
7755 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007756 }
7757 assert(!NE.isUnset() &&
7758 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007759 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007760 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007761 }
7762 return CacheEntry = ExprError();
7763 }
7764};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007765}
Faisal Valia17d19f2013-11-07 05:17:06 +00007766
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007767ExprResult
7768Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7769 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007770 // If the current evaluation context indicates there are uncorrected typos
7771 // and the current expression isn't guaranteed to not have typos, try to
7772 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007773 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007774 (E->isTypeDependent() || E->isValueDependent() ||
7775 E->isInstantiationDependent())) {
7776 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007777 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007778 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007779 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007780 ExprEvalContexts.back().NumTypos -= TyposResolved;
7781 return Result;
7782 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007783 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007784 }
7785 return E;
7786}
7787
Richard Smith945f8d32013-01-14 22:39:08 +00007788ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007789 bool DiscardedValue,
Richard Smithb3d203f2018-10-19 19:01:34 +00007790 bool IsConstexpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007791 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007792
7793 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007794 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007795
Richard Smithb3d203f2018-10-19 19:01:34 +00007796 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007797 return ExprError();
7798
Richard Smith945f8d32013-01-14 22:39:08 +00007799 if (DiscardedValue) {
Richard Smithb3d203f2018-10-19 19:01:34 +00007800 // Top-level expressions default to 'id' when we're in a debugger.
7801 if (getLangOpts().DebuggerCastResultToId &&
7802 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7803 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7804 if (FullExpr.isInvalid())
7805 return ExprError();
7806 }
7807
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007808 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007809 if (FullExpr.isInvalid())
7810 return ExprError();
7811
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007812 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007813 if (FullExpr.isInvalid())
7814 return ExprError();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007815
7816 DiagnoseUnusedExprResult(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007817 }
John Wiegley01296292011-04-08 18:41:53 +00007818
Kaelyn Takata49d84322014-11-11 23:26:56 +00007819 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7820 if (FullExpr.isInvalid())
7821 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007822
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007823 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007824
Simon Pilgrim75c26882016-09-30 14:25:09 +00007825 // At the end of this full expression (which could be a deeply nested
7826 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007827 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007828 // Consider the following code:
7829 // void f(int, int);
7830 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007831 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007832 // const int x = 10, y = 20;
7833 // auto L = [=](auto a) {
7834 // auto M = [=](auto b) {
7835 // f(x, b); <-- requires x to be captured by L and M
7836 // f(y, a); <-- requires y to be captured by L, but not all Ms
7837 // };
7838 // };
7839 // }
7840
Simon Pilgrim75c26882016-09-30 14:25:09 +00007841 // FIXME: Also consider what happens for something like this that involves
7842 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007843 // void f() {
7844 // const int n = 0;
7845 // auto L = [&](auto a) {
7846 // +n + ({ 0; a; });
7847 // };
7848 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007849 //
7850 // Here, we see +n, and then the full-expression 0; ends, so we don't
7851 // capture n (and instead remove it from our list of potential captures),
7852 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007853 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007854
Alexey Bataev31939e32016-11-11 12:36:20 +00007855 LambdaScopeInfo *const CurrentLSI =
7856 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007857 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007858 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007859 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007860 // By ensuring we are in the context of a lambda's call operator
7861 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007862 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007863 // PR, a proper fix would entail :
7864 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007865 // - Add to Sema an integer holding the smallest (outermost) scope
7866 // index that we are *lexically* within, and save/restore/set to
7867 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007868 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007869 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007870 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007871 DeclContext *DC = CurContext;
7872 while (DC && isa<CapturedDecl>(DC))
7873 DC = DC->getParent();
7874 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007875 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007876 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007877 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7878 *this);
John McCall5d413782010-12-06 08:20:24 +00007879 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007880}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007881
7882StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7883 if (!FullStmt) return StmtError();
7884
John McCall5d413782010-12-06 08:20:24 +00007885 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007886}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007887
Simon Pilgrim75c26882016-09-30 14:25:09 +00007888Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007889Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7890 CXXScopeSpec &SS,
7891 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007892 DeclarationName TargetName = TargetNameInfo.getName();
7893 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007894 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007895
Douglas Gregor43edb322011-10-24 22:31:10 +00007896 // If the name itself is dependent, then the result is dependent.
7897 if (TargetName.isDependentName())
7898 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007899
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007900 // Do the redeclaration lookup in the current scope.
7901 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7902 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007903 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007904 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007905
Douglas Gregor43edb322011-10-24 22:31:10 +00007906 switch (R.getResultKind()) {
7907 case LookupResult::Found:
7908 case LookupResult::FoundOverloaded:
7909 case LookupResult::FoundUnresolvedValue:
7910 case LookupResult::Ambiguous:
7911 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007912
Douglas Gregor43edb322011-10-24 22:31:10 +00007913 case LookupResult::NotFound:
7914 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007915
Douglas Gregor43edb322011-10-24 22:31:10 +00007916 case LookupResult::NotFoundInCurrentInstantiation:
7917 return IER_Dependent;
7918 }
David Blaikie8a40f702012-01-17 06:56:22 +00007919
7920 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007921}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007922
Simon Pilgrim75c26882016-09-30 14:25:09 +00007923Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007924Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7925 bool IsIfExists, CXXScopeSpec &SS,
7926 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007927 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007928
Richard Smith151c4562016-12-20 21:35:28 +00007929 // Check for an unexpanded parameter pack.
7930 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7931 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7932 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007933 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007934
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007935 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7936}