blob: b8431ce36ec6a58da73975adef1508954c28e9ec [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 Bataevc416e642019-02-08 18:02:25 +0000753 !getSourceManager().isInSystemHeader(OpLoc)) {
754 // Delay error emission for the OpenMP device code.
755 if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
756 diagIfOpenMPDeviceCode(OpLoc, diag::err_exceptions_disabled) << "throw";
757 else
758 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
759 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000760
Justin Lebar2a8db342016-09-28 22:45:54 +0000761 // Exceptions aren't allowed in CUDA device code.
762 if (getLangOpts().CUDA)
Justin Lebar179bdce2016-10-13 18:45:08 +0000763 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
764 << "throw" << CurrentCUDATarget();
Justin Lebar2a8db342016-09-28 22:45:54 +0000765
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000766 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
767 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
768
John Wiegley01296292011-04-08 18:41:53 +0000769 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000770 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
771 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000772 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000773
774 // Initialize the exception result. This implicitly weeds out
775 // abstract types or types with inaccessible copy constructors.
776
777 // C++0x [class.copymove]p31:
778 // When certain criteria are met, an implementation is allowed to omit the
779 // copy/move construction of a class object [...]
780 //
781 // - in a throw-expression, when the operand is the name of a
782 // non-volatile automatic object (other than a function or
783 // catch-clause
784 // parameter) whose scope does not extend beyond the end of the
785 // innermost enclosing try-block (if there is one), the copy/move
786 // operation from the operand to the exception object (15.1) can be
787 // omitted by constructing the automatic object directly into the
788 // exception object
789 const VarDecl *NRVOVariable = nullptr;
790 if (IsThrownVarInScope)
Richard Trieu09c163b2018-03-15 03:00:55 +0000791 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
David Majnemerba3e5ec2015-03-13 18:26:17 +0000792
793 InitializedEntity Entity = InitializedEntity::InitializeException(
794 OpLoc, ExceptionObjectTy,
795 /*NRVO=*/NRVOVariable != nullptr);
796 ExprResult Res = PerformMoveOrCopyInitialization(
797 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
798 if (Res.isInvalid())
799 return ExprError();
800 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000801 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000802
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000803 return new (Context)
804 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000805}
806
David Majnemere7a818f2015-03-06 18:53:55 +0000807static void
808collectPublicBases(CXXRecordDecl *RD,
809 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
810 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
811 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
812 bool ParentIsPublic) {
813 for (const CXXBaseSpecifier &BS : RD->bases()) {
814 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
815 bool NewSubobject;
816 // Virtual bases constitute the same subobject. Non-virtual bases are
817 // always distinct subobjects.
818 if (BS.isVirtual())
819 NewSubobject = VBases.insert(BaseDecl).second;
820 else
821 NewSubobject = true;
822
823 if (NewSubobject)
824 ++SubobjectsSeen[BaseDecl];
825
826 // Only add subobjects which have public access throughout the entire chain.
827 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
828 if (PublicPath)
829 PublicSubobjectsSeen.insert(BaseDecl);
830
831 // Recurse on to each base subobject.
832 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
833 PublicPath);
834 }
835}
836
837static void getUnambiguousPublicSubobjects(
838 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
839 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
840 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
841 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
842 SubobjectsSeen[RD] = 1;
843 PublicSubobjectsSeen.insert(RD);
844 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
845 /*ParentIsPublic=*/true);
846
847 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
848 // Skip ambiguous objects.
849 if (SubobjectsSeen[PublicSubobject] > 1)
850 continue;
851
852 Objects.push_back(PublicSubobject);
853 }
854}
855
Sebastian Redl4de47b42009-04-27 20:27:31 +0000856/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000857bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
858 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000859 // If the type of the exception would be an incomplete type or a pointer
860 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000861 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000862 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000863 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000864 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000865 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000866 }
867 if (!isPointer || !Ty->isVoidType()) {
868 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000869 isPointer ? diag::err_throw_incomplete_ptr
870 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000871 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000872 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000873
David Majnemerd09a51c2015-03-03 01:50:05 +0000874 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000875 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000876 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000877 }
878
Eli Friedman91a3d272010-06-03 20:39:03 +0000879 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000880 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
881 if (!RD)
882 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000883
Douglas Gregor88d292c2010-05-13 16:44:06 +0000884 // If we are throwing a polymorphic class type or pointer thereof,
885 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000886 MarkVTableUsed(ThrowLoc, RD);
887
Eli Friedman36ebbec2010-10-12 20:32:36 +0000888 // If a pointer is thrown, the referenced object will not be destroyed.
889 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000890 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000891
Richard Smitheec915d62012-02-18 04:13:32 +0000892 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000893 if (!RD->hasIrrelevantDestructor()) {
894 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
895 MarkFunctionReferenced(E->getExprLoc(), Destructor);
896 CheckDestructorAccess(E->getExprLoc(), Destructor,
897 PDiag(diag::err_access_dtor_exception) << Ty);
898 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000899 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000900 }
901 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000902
David Majnemerdfa6d202015-03-11 18:36:39 +0000903 // The MSVC ABI creates a list of all types which can catch the exception
904 // object. This list also references the appropriate copy constructor to call
905 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000906 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000907 // We are only interested in the public, unambiguous bases contained within
908 // the exception object. Bases which are ambiguous or otherwise
909 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000910 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
911 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000912
David Majnemere7a818f2015-03-06 18:53:55 +0000913 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000914 // Attempt to lookup the copy constructor. Various pieces of machinery
915 // will spring into action, like template instantiation, which means this
916 // cannot be a simple walk of the class's decls. Instead, we must perform
917 // lookup and overload resolution.
918 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
919 if (!CD)
920 continue;
921
922 // Mark the constructor referenced as it is used by this throw expression.
923 MarkFunctionReferenced(E->getExprLoc(), CD);
924
925 // Skip this copy constructor if it is trivial, we don't need to record it
926 // in the catchable type data.
927 if (CD->isTrivial())
928 continue;
929
930 // The copy constructor is non-trivial, create a mapping from this class
931 // type to this constructor.
932 // N.B. The selection of copy constructor is not sensitive to this
933 // particular throw-site. Lookup will be performed at the catch-site to
934 // ensure that the copy constructor is, in fact, accessible (via
935 // friendship or any other means).
936 Context.addCopyConstructorForExceptionObject(Subobject, CD);
937
938 // We don't keep the instantiated default argument expressions around so
939 // we must rebuild them here.
940 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
Reid Klecknerc01ee752016-11-23 16:51:30 +0000941 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
942 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000943 }
944 }
945 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000946
David Majnemerba3e5ec2015-03-13 18:26:17 +0000947 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000948}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000949
Faisal Vali67b04462016-06-11 16:41:54 +0000950static QualType adjustCVQualifiersForCXXThisWithinLambda(
951 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
952 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
953
954 QualType ClassType = ThisTy->getPointeeType();
955 LambdaScopeInfo *CurLSI = nullptr;
956 DeclContext *CurDC = CurSemaContext;
957
958 // Iterate through the stack of lambdas starting from the innermost lambda to
959 // the outermost lambda, checking if '*this' is ever captured by copy - since
960 // that could change the cv-qualifiers of the '*this' object.
961 // The object referred to by '*this' starts out with the cv-qualifiers of its
962 // member function. We then start with the innermost lambda and iterate
963 // outward checking to see if any lambda performs a by-copy capture of '*this'
964 // - and if so, any nested lambda must respect the 'constness' of that
965 // capturing lamdbda's call operator.
966 //
967
Faisal Vali999f27e2017-05-02 20:56:34 +0000968 // Since the FunctionScopeInfo stack is representative of the lexical
969 // nesting of the lambda expressions during initial parsing (and is the best
970 // place for querying information about captures about lambdas that are
971 // partially processed) and perhaps during instantiation of function templates
972 // that contain lambda expressions that need to be transformed BUT not
973 // necessarily during instantiation of a nested generic lambda's function call
974 // operator (which might even be instantiated at the end of the TU) - at which
975 // time the DeclContext tree is mature enough to query capture information
976 // reliably - we use a two pronged approach to walk through all the lexically
977 // enclosing lambda expressions:
978 //
979 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
980 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
981 // enclosed by the call-operator of the LSI below it on the stack (while
982 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
983 // the stack represents the innermost lambda.
984 //
985 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
986 // represents a lambda's call operator. If it does, we must be instantiating
987 // a generic lambda's call operator (represented by the Current LSI, and
988 // should be the only scenario where an inconsistency between the LSI and the
989 // DeclContext should occur), so climb out the DeclContexts if they
990 // represent lambdas, while querying the corresponding closure types
991 // regarding capture information.
Faisal Vali67b04462016-06-11 16:41:54 +0000992
Faisal Vali999f27e2017-05-02 20:56:34 +0000993 // 1) Climb down the function scope info stack.
Faisal Vali67b04462016-06-11 16:41:54 +0000994 for (int I = FunctionScopes.size();
Faisal Vali999f27e2017-05-02 20:56:34 +0000995 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
996 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
997 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
Faisal Vali67b04462016-06-11 16:41:54 +0000998 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
999 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001000
1001 if (!CurLSI->isCXXThisCaptured())
Faisal Vali67b04462016-06-11 16:41:54 +00001002 continue;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001003
Faisal Vali67b04462016-06-11 16:41:54 +00001004 auto C = CurLSI->getCXXThisCapture();
1005
1006 if (C.isCopyCapture()) {
1007 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1008 if (CurLSI->CallOperator->isConst())
1009 ClassType.addConst();
1010 return ASTCtx.getPointerType(ClassType);
1011 }
1012 }
Faisal Vali999f27e2017-05-02 20:56:34 +00001013
1014 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1015 // happen during instantiation of its nested generic lambda call operator)
Faisal Vali67b04462016-06-11 16:41:54 +00001016 if (isLambdaCallOperator(CurDC)) {
Faisal Vali999f27e2017-05-02 20:56:34 +00001017 assert(CurLSI && "While computing 'this' capture-type for a generic "
1018 "lambda, we must have a corresponding LambdaScopeInfo");
1019 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1020 "While computing 'this' capture-type for a generic lambda, when we "
1021 "run out of enclosing LSI's, yet the enclosing DC is a "
1022 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1023 "lambda call oeprator");
Faisal Vali67b04462016-06-11 16:41:54 +00001024 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
Simon Pilgrim75c26882016-09-30 14:25:09 +00001025
Faisal Vali67b04462016-06-11 16:41:54 +00001026 auto IsThisCaptured =
1027 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1028 IsConst = false;
1029 IsByCopy = false;
1030 for (auto &&C : Closure->captures()) {
1031 if (C.capturesThis()) {
1032 if (C.getCaptureKind() == LCK_StarThis)
1033 IsByCopy = true;
1034 if (Closure->getLambdaCallOperator()->isConst())
1035 IsConst = true;
1036 return true;
1037 }
1038 }
1039 return false;
1040 };
1041
1042 bool IsByCopyCapture = false;
1043 bool IsConstCapture = false;
1044 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1045 while (Closure &&
1046 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1047 if (IsByCopyCapture) {
1048 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1049 if (IsConstCapture)
1050 ClassType.addConst();
1051 return ASTCtx.getPointerType(ClassType);
1052 }
1053 Closure = isLambdaCallOperator(Closure->getParent())
1054 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1055 : nullptr;
1056 }
1057 }
1058 return ASTCtx.getPointerType(ClassType);
1059}
1060
Eli Friedman73a04092012-01-07 04:59:52 +00001061QualType Sema::getCurrentThisType() {
1062 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +00001063 QualType ThisTy = CXXThisTypeOverride;
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001064
Richard Smith938f40b2011-06-11 17:19:42 +00001065 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1066 if (method && method->isInstance())
Brian Gesiak5488ab42019-01-11 01:54:53 +00001067 ThisTy = method->getThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001068 }
Faisal Validc6b5962016-03-21 09:25:37 +00001069
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001070 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
Richard Smith51ec0cf2017-02-21 01:17:38 +00001071 inTemplateInstantiation()) {
Faisal Validc6b5962016-03-21 09:25:37 +00001072
Erik Pilkington3cdc3172016-07-27 18:25:10 +00001073 assert(isa<CXXRecordDecl>(DC) &&
1074 "Trying to get 'this' type from static method?");
1075
1076 // This is a lambda call operator that is being instantiated as a default
1077 // initializer. DC must point to the enclosing class type, so we can recover
1078 // the 'this' type from it.
1079
1080 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1081 // There are no cv-qualifiers for 'this' within default initializers,
1082 // per [expr.prim.general]p4.
1083 ThisTy = Context.getPointerType(ClassTy);
Faisal Validc6b5962016-03-21 09:25:37 +00001084 }
Faisal Vali67b04462016-06-11 16:41:54 +00001085
1086 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1087 // might need to be adjusted if the lambda or any of its enclosing lambda's
1088 // captures '*this' by copy.
1089 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1090 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1091 CurContext, Context);
Richard Smith938f40b2011-06-11 17:19:42 +00001092 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +00001093}
1094
Simon Pilgrim75c26882016-09-30 14:25:09 +00001095Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
Douglas Gregor3024f072012-04-16 07:05:22 +00001096 Decl *ContextDecl,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001097 Qualifiers CXXThisTypeQuals,
Simon Pilgrim75c26882016-09-30 14:25:09 +00001098 bool Enabled)
Douglas Gregor3024f072012-04-16 07:05:22 +00001099 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1100{
1101 if (!Enabled || !ContextDecl)
1102 return;
Craig Topperc3ec1492014-05-26 06:22:03 +00001103
1104 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00001105 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1106 Record = Template->getTemplatedDecl();
1107 else
1108 Record = cast<CXXRecordDecl>(ContextDecl);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001109
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001110 QualType T = S.Context.getRecordType(Record);
1111 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1112
1113 S.CXXThisTypeOverride = S.Context.getPointerType(T);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001114
Douglas Gregor3024f072012-04-16 07:05:22 +00001115 this->Enabled = true;
1116}
1117
1118
1119Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1120 if (Enabled) {
1121 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1122 }
1123}
1124
Faisal Validc6b5962016-03-21 09:25:37 +00001125static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1126 QualType ThisTy, SourceLocation Loc,
1127 const bool ByCopy) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00001128
Faisal Vali67b04462016-06-11 16:41:54 +00001129 QualType AdjustedThisTy = ThisTy;
1130 // The type of the corresponding data member (not a 'this' pointer if 'by
1131 // copy').
1132 QualType CaptureThisFieldTy = ThisTy;
1133 if (ByCopy) {
1134 // If we are capturing the object referred to by '*this' by copy, ignore any
1135 // cv qualifiers inherited from the type of the member function for the type
1136 // of the closure-type's corresponding data member and any use of 'this'.
1137 CaptureThisFieldTy = ThisTy->getPointeeType();
1138 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1139 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1140 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00001141
Faisal Vali67b04462016-06-11 16:41:54 +00001142 FieldDecl *Field = FieldDecl::Create(
1143 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1144 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1145 ICIS_NoInit);
1146
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001147 Field->setImplicit(true);
1148 Field->setAccess(AS_private);
1149 RD->addDecl(Field);
Faisal Vali67b04462016-06-11 16:41:54 +00001150 Expr *This =
1151 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
Faisal Validc6b5962016-03-21 09:25:37 +00001152 if (ByCopy) {
1153 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1154 UO_Deref,
1155 This).get();
1156 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
Faisal Vali67b04462016-06-11 16:41:54 +00001157 nullptr, CaptureThisFieldTy, Loc);
Faisal Validc6b5962016-03-21 09:25:37 +00001158 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1159 InitializationSequence Init(S, Entity, InitKind, StarThis);
1160 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1161 if (ER.isInvalid()) return nullptr;
1162 return ER.get();
1163 }
1164 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001165}
1166
Simon Pilgrim75c26882016-09-30 14:25:09 +00001167bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
Faisal Validc6b5962016-03-21 09:25:37 +00001168 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1169 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +00001170 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +00001171 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +00001172 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001173
Faisal Validc6b5962016-03-21 09:25:37 +00001174 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +00001175
Reid Kleckner87a31802018-03-12 21:43:02 +00001176 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1177 ? *FunctionScopeIndexToStopAt
1178 : FunctionScopes.size() - 1;
Faisal Validc6b5962016-03-21 09:25:37 +00001179
Simon Pilgrim75c26882016-09-30 14:25:09 +00001180 // Check that we can capture the *enclosing object* (referred to by '*this')
1181 // by the capturing-entity/closure (lambda/block/etc) at
1182 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1183
1184 // Note: The *enclosing object* can only be captured by-value by a
1185 // closure that is a lambda, using the explicit notation:
Faisal Validc6b5962016-03-21 09:25:37 +00001186 // [*this] { ... }.
1187 // Every other capture of the *enclosing object* results in its by-reference
1188 // capture.
1189
1190 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1191 // stack), we can capture the *enclosing object* only if:
1192 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1193 // - or, 'L' has an implicit capture.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001194 // AND
Faisal Validc6b5962016-03-21 09:25:37 +00001195 // -- there is no enclosing closure
Simon Pilgrim75c26882016-09-30 14:25:09 +00001196 // -- or, there is some enclosing closure 'E' that has already captured the
1197 // *enclosing object*, and every intervening closure (if any) between 'E'
Faisal Validc6b5962016-03-21 09:25:37 +00001198 // and 'L' can implicitly capture the *enclosing object*.
Simon Pilgrim75c26882016-09-30 14:25:09 +00001199 // -- or, every enclosing closure can implicitly capture the
Faisal Validc6b5962016-03-21 09:25:37 +00001200 // *enclosing object*
Simon Pilgrim75c26882016-09-30 14:25:09 +00001201
1202
Faisal Validc6b5962016-03-21 09:25:37 +00001203 unsigned NumCapturingClosures = 0;
Reid Kleckner87a31802018-03-12 21:43:02 +00001204 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +00001205 if (CapturingScopeInfo *CSI =
1206 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1207 if (CSI->CXXThisCaptureIndex != 0) {
1208 // 'this' is already being captured; there isn't anything more to do.
Malcolm Parsons87a03622017-01-13 15:01:06 +00001209 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
Eli Friedman73a04092012-01-07 04:59:52 +00001210 break;
1211 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001212 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1213 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1214 // This context can't implicitly capture 'this'; fail out.
1215 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001216 Diag(Loc, diag::err_this_capture)
1217 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001218 return true;
1219 }
Eli Friedman20139d32012-01-11 02:36:31 +00001220 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +00001221 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001222 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001223 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +00001224 (Explicit && idx == MaxFunctionScopesIndex)) {
1225 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1226 // iteration through can be an explicit capture, all enclosing closures,
1227 // if any, must perform implicit captures.
1228
Douglas Gregorcdd11d42012-02-01 17:04:21 +00001229 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +00001230 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001231 continue;
1232 }
Eli Friedman20139d32012-01-11 02:36:31 +00001233 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001234 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001235 Diag(Loc, diag::err_this_capture)
1236 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001237 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001238 }
Eli Friedman73a04092012-01-07 04:59:52 +00001239 break;
1240 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001241 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001242
1243 // If we got here, then the closure at MaxFunctionScopesIndex on the
1244 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1245 // (including implicit by-reference captures in any enclosing closures).
1246
1247 // In the loop below, respect the ByCopy flag only for the closure requesting
1248 // the capture (i.e. first iteration through the loop below). Ignore it for
Simon Pilgrimb17efcb2016-11-15 18:28:07 +00001249 // all enclosing closure's up to NumCapturingClosures (since they must be
Faisal Validc6b5962016-03-21 09:25:37 +00001250 // implicitly capturing the *enclosing object* by reference (see loop
1251 // above)).
1252 assert((!ByCopy ||
1253 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1254 "Only a lambda can capture the enclosing object (referred to by "
1255 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001256 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1257 // contexts.
Faisal Vali67b04462016-06-11 16:41:54 +00001258 QualType ThisTy = getCurrentThisType();
Reid Kleckner87a31802018-03-12 21:43:02 +00001259 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1260 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001261 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001262 Expr *ThisExpr = nullptr;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001263
Faisal Validc6b5962016-03-21 09:25:37 +00001264 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1265 // For lambda expressions, build a field and an initializing expression,
1266 // and capture the *enclosing object* by copy only if this is the first
1267 // iteration.
1268 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1269 ByCopy && idx == MaxFunctionScopesIndex);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001270
Faisal Validc6b5962016-03-21 09:25:37 +00001271 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001272 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001273 ThisExpr =
1274 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1275 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001276
Faisal Validc6b5962016-03-21 09:25:37 +00001277 bool isNested = NumCapturingClosures > 1;
Faisal Vali67b04462016-06-11 16:41:54 +00001278 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001279 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001280 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001281}
1282
Richard Smith938f40b2011-06-11 17:19:42 +00001283ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001284 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1285 /// is a non-lvalue expression whose value is the address of the object for
1286 /// which the function is called.
1287
Douglas Gregor09deffa2011-10-18 16:47:30 +00001288 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001289 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001290
Eli Friedman73a04092012-01-07 04:59:52 +00001291 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001292 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001293}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001294
Douglas Gregor3024f072012-04-16 07:05:22 +00001295bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1296 // If we're outside the body of a member function, then we'll have a specified
1297 // type for 'this'.
1298 if (CXXThisTypeOverride.isNull())
1299 return false;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001300
Douglas Gregor3024f072012-04-16 07:05:22 +00001301 // Determine whether we're looking into a class that's currently being
1302 // defined.
1303 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1304 return Class && Class->isBeingDefined();
1305}
1306
Vedant Kumara14a1f92018-01-17 18:53:51 +00001307/// Parse construction of a specified type.
1308/// Can be interpreted either as function-style casting ("int(x)")
1309/// or class type construction ("ClassType(x,y,z)")
1310/// or creation of a value-initialized type ("int()").
John McCalldadc5752010-08-24 06:29:42 +00001311ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001312Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001313 SourceLocation LParenOrBraceLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001314 MultiExprArg exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001315 SourceLocation RParenOrBraceLoc,
1316 bool ListInitialization) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001317 if (!TypeRep)
1318 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319
John McCall97513962010-01-15 18:39:57 +00001320 TypeSourceInfo *TInfo;
1321 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1322 if (!TInfo)
1323 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001324
Vedant Kumara14a1f92018-01-17 18:53:51 +00001325 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1326 RParenOrBraceLoc, ListInitialization);
Richard Smithb8c414c2016-06-30 20:24:30 +00001327 // Avoid creating a non-type-dependent expression that contains typos.
1328 // Non-type-dependent expressions are liable to be discarded without
1329 // checking for embedded typos.
1330 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1331 !Result.get()->isTypeDependent())
1332 Result = CorrectDelayedTyposInExpr(Result.get());
1333 return Result;
Douglas Gregor2b88c112010-09-08 00:15:04 +00001334}
1335
Douglas Gregor2b88c112010-09-08 00:15:04 +00001336ExprResult
1337Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001338 SourceLocation LParenOrBraceLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001339 MultiExprArg Exprs,
Vedant Kumara14a1f92018-01-17 18:53:51 +00001340 SourceLocation RParenOrBraceLoc,
1341 bool ListInitialization) {
Douglas Gregor2b88c112010-09-08 00:15:04 +00001342 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001343 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001344
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001345 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Vedant Kumara14a1f92018-01-17 18:53:51 +00001346 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1347 // directly. We work around this by dropping the locations of the braces.
1348 SourceRange Locs = ListInitialization
1349 ? SourceRange()
1350 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1351 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1352 Exprs, Locs.getEnd());
Douglas Gregor0950e412009-03-13 21:01:28 +00001353 }
1354
Richard Smith600b5262017-01-26 20:40:47 +00001355 assert((!ListInitialization ||
1356 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1357 "List initialization must have initializer list as expression.");
Vedant Kumara14a1f92018-01-17 18:53:51 +00001358 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
Sebastian Redld74dd492012-02-12 18:41:05 +00001359
Richard Smith60437622017-02-09 19:17:44 +00001360 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1361 InitializationKind Kind =
1362 Exprs.size()
1363 ? ListInitialization
Vedant Kumara14a1f92018-01-17 18:53:51 +00001364 ? InitializationKind::CreateDirectList(
1365 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1366 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1367 RParenOrBraceLoc)
1368 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1369 RParenOrBraceLoc);
Richard Smith60437622017-02-09 19:17:44 +00001370
1371 // C++1z [expr.type.conv]p1:
1372 // If the type is a placeholder for a deduced class type, [...perform class
1373 // template argument deduction...]
1374 DeducedType *Deduced = Ty->getContainedDeducedType();
1375 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1376 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1377 Kind, Exprs);
1378 if (Ty.isNull())
1379 return ExprError();
1380 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1381 }
1382
Douglas Gregordd04d332009-01-16 18:33:17 +00001383 // C++ [expr.type.conv]p1:
Richard Smith49a6b6e2017-03-24 01:14:25 +00001384 // If the expression list is a parenthesized single expression, the type
1385 // conversion expression is equivalent (in definedness, and if defined in
1386 // meaning) to the corresponding cast expression.
1387 if (Exprs.size() == 1 && !ListInitialization &&
1388 !isa<InitListExpr>(Exprs[0])) {
John McCallb50451a2011-10-05 07:41:44 +00001389 Expr *Arg = Exprs[0];
Vedant Kumara14a1f92018-01-17 18:53:51 +00001390 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1391 RParenOrBraceLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001392 }
1393
Richard Smith49a6b6e2017-03-24 01:14:25 +00001394 // For an expression of the form T(), T shall not be an array type.
Eli Friedman576cbd02012-02-29 00:00:28 +00001395 QualType ElemTy = Ty;
1396 if (Ty->isArrayType()) {
1397 if (!ListInitialization)
Richard Smith49a6b6e2017-03-24 01:14:25 +00001398 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1399 << FullRange);
Eli Friedman576cbd02012-02-29 00:00:28 +00001400 ElemTy = Context.getBaseElementType(Ty);
1401 }
1402
Richard Smith49a6b6e2017-03-24 01:14:25 +00001403 // There doesn't seem to be an explicit rule against this but sanity demands
1404 // we only construct objects with object types.
1405 if (Ty->isFunctionType())
1406 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1407 << Ty << FullRange);
David Majnemer7eddcff2015-09-14 07:05:00 +00001408
Richard Smith49a6b6e2017-03-24 01:14:25 +00001409 // C++17 [expr.type.conv]p2:
1410 // If the type is cv void and the initializer is (), the expression is a
1411 // prvalue of the specified type that performs no initialization.
Eli Friedman576cbd02012-02-29 00:00:28 +00001412 if (!Ty->isVoidType() &&
1413 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001414 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001415 return ExprError();
1416
Richard Smith49a6b6e2017-03-24 01:14:25 +00001417 // Otherwise, the expression is a prvalue of the specified type whose
1418 // result object is direct-initialized (11.6) with the initializer.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001419 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1420 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001421
Richard Smith49a6b6e2017-03-24 01:14:25 +00001422 if (Result.isInvalid())
Richard Smith90061902013-09-23 02:20:00 +00001423 return Result;
1424
1425 Expr *Inner = Result.get();
1426 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1427 Inner = BTE->getSubExpr();
Richard Smith49a6b6e2017-03-24 01:14:25 +00001428 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1429 !isa<CXXScalarValueInitExpr>(Inner)) {
Richard Smith1ae689c2015-01-28 22:06:01 +00001430 // If we created a CXXTemporaryObjectExpr, that node also represents the
1431 // functional cast. Otherwise, create an explicit cast to represent
1432 // the syntactic form of a functional-style cast that was used here.
1433 //
1434 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1435 // would give a more consistent AST representation than using a
1436 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1437 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001438 QualType ResultType = Result.get()->getType();
Vedant Kumara14a1f92018-01-17 18:53:51 +00001439 SourceRange Locs = ListInitialization
1440 ? SourceRange()
1441 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001442 Result = CXXFunctionalCastExpr::Create(
Vedant Kumara14a1f92018-01-17 18:53:51 +00001443 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1444 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
Sebastian Redl2b80af42012-02-13 19:55:43 +00001445 }
1446
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001447 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001448}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001449
Artem Belevich78929ef2018-09-21 17:29:33 +00001450bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1451 // [CUDA] Ignore this function, if we can't call it.
1452 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1453 if (getLangOpts().CUDA &&
1454 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1455 return false;
1456
1457 SmallVector<const FunctionDecl*, 4> PreventedBy;
1458 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1459
1460 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1461 return Result;
1462
1463 // In case of CUDA, return true if none of the 1-argument deallocator
1464 // functions are actually callable.
1465 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1466 assert(FD->getNumParams() == 1 &&
1467 "Only single-operand functions should be in PreventedBy");
1468 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1469 });
1470}
1471
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001472/// Determine whether the given function is a non-placement
Richard Smithb2f0f052016-10-10 18:54:32 +00001473/// deallocation function.
1474static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001475 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
Artem Belevich78929ef2018-09-21 17:29:33 +00001476 return S.isUsualDeallocationFunction(Method);
Richard Smithb2f0f052016-10-10 18:54:32 +00001477
1478 if (FD->getOverloadedOperator() != OO_Delete &&
1479 FD->getOverloadedOperator() != OO_Array_Delete)
1480 return false;
1481
1482 unsigned UsualParams = 1;
1483
1484 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1485 S.Context.hasSameUnqualifiedType(
1486 FD->getParamDecl(UsualParams)->getType(),
1487 S.Context.getSizeType()))
1488 ++UsualParams;
1489
1490 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1491 S.Context.hasSameUnqualifiedType(
1492 FD->getParamDecl(UsualParams)->getType(),
1493 S.Context.getTypeDeclType(S.getStdAlignValT())))
1494 ++UsualParams;
1495
1496 return UsualParams == FD->getNumParams();
1497}
1498
1499namespace {
1500 struct UsualDeallocFnInfo {
1501 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
Richard Smithf75dcbe2016-10-11 00:21:10 +00001502 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
Richard Smithb2f0f052016-10-10 18:54:32 +00001503 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
Richard Smith5b349582017-10-13 01:55:36 +00001504 Destroying(false), HasSizeT(false), HasAlignValT(false),
1505 CUDAPref(Sema::CFP_Native) {
Richard Smithb2f0f052016-10-10 18:54:32 +00001506 // A function template declaration is never a usual deallocation function.
1507 if (!FD)
1508 return;
Richard Smith5b349582017-10-13 01:55:36 +00001509 unsigned NumBaseParams = 1;
1510 if (FD->isDestroyingOperatorDelete()) {
1511 Destroying = true;
1512 ++NumBaseParams;
1513 }
Eric Fiselier8e920502019-01-16 02:34:36 +00001514
1515 if (NumBaseParams < FD->getNumParams() &&
1516 S.Context.hasSameUnqualifiedType(
1517 FD->getParamDecl(NumBaseParams)->getType(),
1518 S.Context.getSizeType())) {
1519 ++NumBaseParams;
1520 HasSizeT = true;
1521 }
1522
1523 if (NumBaseParams < FD->getNumParams() &&
1524 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1525 ++NumBaseParams;
1526 HasAlignValT = true;
Richard Smithb2f0f052016-10-10 18:54:32 +00001527 }
Richard Smithf75dcbe2016-10-11 00:21:10 +00001528
1529 // In CUDA, determine how much we'd like / dislike to call this.
1530 if (S.getLangOpts().CUDA)
1531 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1532 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
Richard Smithb2f0f052016-10-10 18:54:32 +00001533 }
1534
Eric Fiselierfa752f22018-03-21 19:19:48 +00001535 explicit operator bool() const { return FD; }
Richard Smithb2f0f052016-10-10 18:54:32 +00001536
Richard Smithf75dcbe2016-10-11 00:21:10 +00001537 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1538 bool WantAlign) const {
Richard Smith5b349582017-10-13 01:55:36 +00001539 // C++ P0722:
1540 // A destroying operator delete is preferred over a non-destroying
1541 // operator delete.
1542 if (Destroying != Other.Destroying)
1543 return Destroying;
1544
Richard Smithf75dcbe2016-10-11 00:21:10 +00001545 // C++17 [expr.delete]p10:
1546 // If the type has new-extended alignment, a function with a parameter
1547 // of type std::align_val_t is preferred; otherwise a function without
1548 // such a parameter is preferred
1549 if (HasAlignValT != Other.HasAlignValT)
1550 return HasAlignValT == WantAlign;
1551
1552 if (HasSizeT != Other.HasSizeT)
1553 return HasSizeT == WantSize;
1554
1555 // Use CUDA call preference as a tiebreaker.
1556 return CUDAPref > Other.CUDAPref;
1557 }
1558
Richard Smithb2f0f052016-10-10 18:54:32 +00001559 DeclAccessPair Found;
1560 FunctionDecl *FD;
Richard Smith5b349582017-10-13 01:55:36 +00001561 bool Destroying, HasSizeT, HasAlignValT;
Richard Smithf75dcbe2016-10-11 00:21:10 +00001562 Sema::CUDAFunctionPreference CUDAPref;
Richard Smithb2f0f052016-10-10 18:54:32 +00001563 };
1564}
1565
1566/// Determine whether a type has new-extended alignment. This may be called when
1567/// the type is incomplete (for a delete-expression with an incomplete pointee
1568/// type), in which case it will conservatively return false if the alignment is
1569/// not known.
1570static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1571 return S.getLangOpts().AlignedAllocation &&
1572 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1573 S.getASTContext().getTargetInfo().getNewAlign();
1574}
1575
1576/// Select the correct "usual" deallocation function to use from a selection of
1577/// deallocation functions (either global or class-scope).
1578static UsualDeallocFnInfo resolveDeallocationOverload(
1579 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1580 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1581 UsualDeallocFnInfo Best;
1582
Richard Smithb2f0f052016-10-10 18:54:32 +00001583 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00001584 UsualDeallocFnInfo Info(S, I.getPair());
1585 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1586 Info.CUDAPref == Sema::CFP_Never)
Richard Smithb2f0f052016-10-10 18:54:32 +00001587 continue;
1588
1589 if (!Best) {
1590 Best = Info;
1591 if (BestFns)
1592 BestFns->push_back(Info);
1593 continue;
1594 }
1595
Richard Smithf75dcbe2016-10-11 00:21:10 +00001596 if (Best.isBetterThan(Info, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001597 continue;
1598
1599 // If more than one preferred function is found, all non-preferred
1600 // functions are eliminated from further consideration.
Richard Smithf75dcbe2016-10-11 00:21:10 +00001601 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
Richard Smithb2f0f052016-10-10 18:54:32 +00001602 BestFns->clear();
1603
1604 Best = Info;
1605 if (BestFns)
1606 BestFns->push_back(Info);
1607 }
1608
1609 return Best;
1610}
1611
1612/// Determine whether a given type is a class for which 'delete[]' would call
1613/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1614/// we need to store the array size (even if the type is
1615/// trivially-destructible).
John McCall284c48f2011-01-27 09:37:56 +00001616static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1617 QualType allocType) {
1618 const RecordType *record =
1619 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1620 if (!record) return false;
1621
1622 // Try to find an operator delete[] in class scope.
1623
1624 DeclarationName deleteName =
1625 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1626 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1627 S.LookupQualifiedName(ops, record->getDecl());
1628
1629 // We're just doing this for information.
1630 ops.suppressDiagnostics();
1631
1632 // Very likely: there's no operator delete[].
1633 if (ops.empty()) return false;
1634
1635 // If it's ambiguous, it should be illegal to call operator delete[]
1636 // on this thing, so it doesn't matter if we allocate extra space or not.
1637 if (ops.isAmbiguous()) return false;
1638
Richard Smithb2f0f052016-10-10 18:54:32 +00001639 // C++17 [expr.delete]p10:
1640 // If the deallocation functions have class scope, the one without a
1641 // parameter of type std::size_t is selected.
1642 auto Best = resolveDeallocationOverload(
1643 S, ops, /*WantSize*/false,
1644 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1645 return Best && Best.HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00001646}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001647
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001648/// Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001649///
Sebastian Redld74dd492012-02-12 18:41:05 +00001650/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001651/// @code new (memory) int[size][4] @endcode
1652/// or
1653/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001654///
1655/// \param StartLoc The first location of the expression.
1656/// \param UseGlobal True if 'new' was prefixed with '::'.
1657/// \param PlacementLParen Opening paren of the placement arguments.
1658/// \param PlacementArgs Placement new arguments.
1659/// \param PlacementRParen Closing paren of the placement arguments.
1660/// \param TypeIdParens If the type is in parens, the source range.
1661/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001662/// \param Initializer The initializing expression or initializer-list, or null
1663/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001664ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001665Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001666 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001667 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001668 Declarator &D, Expr *Initializer) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001669 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001670 // If the specified type is an array, unwrap it and save the expression.
1671 if (D.getNumTypeObjects() > 0 &&
1672 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
Richard Smith3beb7c62017-01-12 02:27:38 +00001673 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smithbfbff072017-02-10 22:35:37 +00001674 if (D.getDeclSpec().hasAutoTypeSpec())
Richard Smith30482bc2011-02-20 03:19:35 +00001675 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1676 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001677 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001678 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1679 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001680 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001681 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1682 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001683
Sebastian Redl351bb782008-12-02 14:43:59 +00001684 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001685 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001686 }
1687
Douglas Gregor73341c42009-09-11 00:18:58 +00001688 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001689 if (ArraySize) {
1690 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001691 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1692 break;
1693
1694 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1695 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001696 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001697 if (getLangOpts().CPlusPlus14) {
Fangrui Song99337e22018-07-20 08:19:20 +00001698 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1699 // shall be a converted constant expression (5.19) of type std::size_t
1700 // and shall evaluate to a strictly positive value.
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001701 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1702 assert(IntWidth && "Builtin type of size 0?");
1703 llvm::APSInt Value(IntWidth);
1704 Array.NumElts
1705 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1706 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001707 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001708 } else {
1709 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001710 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001711 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001712 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001713 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001714 if (!Array.NumElts)
1715 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001716 }
1717 }
1718 }
1719 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001720
Craig Topperc3ec1492014-05-26 06:22:03 +00001721 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001722 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001723 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001724 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001725
Sebastian Redl6047f072012-02-16 12:22:20 +00001726 SourceRange DirectInitRange;
Richard Smith49a6b6e2017-03-24 01:14:25 +00001727 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
Sebastian Redl6047f072012-02-16 12:22:20 +00001728 DirectInitRange = List->getSourceRange();
1729
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001730 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1731 PlacementLParen, PlacementArgs, PlacementRParen,
1732 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001733 Initializer);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001734}
1735
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001736static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1737 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001738 if (!Init)
1739 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001740 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1741 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001742 if (isa<ImplicitValueInitExpr>(Init))
1743 return true;
1744 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1745 return !CCE->isListInitialization() &&
1746 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001747 else if (Style == CXXNewExpr::ListInit) {
1748 assert(isa<InitListExpr>(Init) &&
1749 "Shouldn't create list CXXConstructExprs for arrays.");
1750 return true;
1751 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001752 return false;
1753}
1754
Akira Hatanaka71645c22018-12-21 07:05:36 +00001755bool
1756Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1757 if (!getLangOpts().AlignedAllocationUnavailable)
1758 return false;
1759 if (FD.isDefined())
1760 return false;
1761 bool IsAligned = false;
1762 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1763 return true;
1764 return false;
1765}
1766
Akira Hatanakacae83f72017-06-29 18:48:40 +00001767// Emit a diagnostic if an aligned allocation/deallocation function that is not
1768// implemented in the standard library is selected.
Akira Hatanaka71645c22018-12-21 07:05:36 +00001769void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1770 SourceLocation Loc) {
1771 if (isUnavailableAlignedAllocationFunction(FD)) {
1772 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001773 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
Akira Hatanaka71645c22018-12-21 07:05:36 +00001774 getASTContext().getTargetInfo().getPlatformName());
Akira Hatanaka3e40c302017-07-19 17:17:50 +00001775
Akira Hatanaka71645c22018-12-21 07:05:36 +00001776 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1777 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1778 Diag(Loc, diag::err_aligned_allocation_unavailable)
Volodymyr Sapsaie5015ab2018-08-03 23:12:37 +00001779 << IsDelete << FD.getType().getAsString() << OSName
1780 << alignedAllocMinVersion(T.getOS()).getAsString();
Akira Hatanaka71645c22018-12-21 07:05:36 +00001781 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
Akira Hatanakacae83f72017-06-29 18:48:40 +00001782 }
1783}
1784
John McCalldadc5752010-08-24 06:29:42 +00001785ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001786Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001787 SourceLocation PlacementLParen,
1788 MultiExprArg PlacementArgs,
1789 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001790 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001791 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001792 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001793 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001794 SourceRange DirectInitRange,
Richard Smith3beb7c62017-01-12 02:27:38 +00001795 Expr *Initializer) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001796 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001797 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001798
Sebastian Redl6047f072012-02-16 12:22:20 +00001799 CXXNewExpr::InitializationStyle initStyle;
1800 if (DirectInitRange.isValid()) {
1801 assert(Initializer && "Have parens but no initializer.");
1802 initStyle = CXXNewExpr::CallInit;
1803 } else if (Initializer && isa<InitListExpr>(Initializer))
1804 initStyle = CXXNewExpr::ListInit;
1805 else {
1806 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1807 isa<CXXConstructExpr>(Initializer)) &&
1808 "Initializer expression that cannot have been implicitly created.");
1809 initStyle = CXXNewExpr::NoInit;
1810 }
1811
1812 Expr **Inits = &Initializer;
1813 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001814 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1815 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1816 Inits = List->getExprs();
1817 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001818 }
1819
Richard Smith60437622017-02-09 19:17:44 +00001820 // C++11 [expr.new]p15:
1821 // A new-expression that creates an object of type T initializes that
1822 // object as follows:
1823 InitializationKind Kind
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001824 // - If the new-initializer is omitted, the object is default-
1825 // initialized (8.5); if no initialization is performed,
1826 // the object has indeterminate value
1827 = initStyle == CXXNewExpr::NoInit
1828 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1829 // - Otherwise, the new-initializer is interpreted according to
1830 // the
1831 // initialization rules of 8.5 for direct-initialization.
1832 : initStyle == CXXNewExpr::ListInit
1833 ? InitializationKind::CreateDirectList(
1834 TypeRange.getBegin(), Initializer->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001835 Initializer->getEndLoc())
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001836 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1837 DirectInitRange.getBegin(),
1838 DirectInitRange.getEnd());
Richard Smith600b5262017-01-26 20:40:47 +00001839
Richard Smith60437622017-02-09 19:17:44 +00001840 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1841 auto *Deduced = AllocType->getContainedDeducedType();
1842 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1843 if (ArraySize)
1844 return ExprError(Diag(ArraySize->getExprLoc(),
1845 diag::err_deduced_class_template_compound_type)
1846 << /*array*/ 2 << ArraySize->getSourceRange());
1847
1848 InitializedEntity Entity
1849 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1850 AllocType = DeduceTemplateSpecializationFromInitializer(
1851 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1852 if (AllocType.isNull())
1853 return ExprError();
1854 } else if (Deduced) {
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001855 bool Braced = (initStyle == CXXNewExpr::ListInit);
1856 if (NumInits == 1) {
1857 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1858 Inits = p->getInits();
1859 NumInits = p->getNumInits();
1860 Braced = true;
1861 }
1862 }
1863
Sebastian Redl6047f072012-02-16 12:22:20 +00001864 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001865 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1866 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001867 if (NumInits > 1) {
1868 Expr *FirstBad = Inits[1];
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001869 return ExprError(Diag(FirstBad->getBeginLoc(),
Richard Smith30482bc2011-02-20 03:19:35 +00001870 diag::err_auto_new_ctor_multiple_expressions)
1871 << AllocType << TypeRange);
1872 }
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001873 if (Braced && !getLangOpts().CPlusPlus17)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001874 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
Zhihao Yuan00c9dfd2017-12-11 18:29:54 +00001875 << AllocType << TypeRange;
Richard Smith061f1e22013-04-30 21:23:01 +00001876 QualType DeducedType;
Akira Hatanakad458ced2019-01-11 04:57:34 +00001877 if (DeduceAutoType(AllocTypeInfo, Inits[0], DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001878 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Akira Hatanakad458ced2019-01-11 04:57:34 +00001879 << AllocType << Inits[0]->getType()
1880 << TypeRange << Inits[0]->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001881 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001882 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001883 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001884 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001885
Douglas Gregorcda95f42010-05-16 16:01:03 +00001886 // Per C++0x [expr.new]p5, the type being constructed may be a
1887 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001888 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001889 if (const ConstantArrayType *Array
1890 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001891 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1892 Context.getSizeType(),
1893 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001894 AllocType = Array->getElementType();
1895 }
1896 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001897
Douglas Gregor3999e152010-10-06 16:00:31 +00001898 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1899 return ExprError();
1900
Simon Pilgrim75c26882016-09-30 14:25:09 +00001901 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001902 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001903 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1904 AllocType->isObjCLifetimeType()) {
1905 AllocType = Context.getLifetimeQualifiedType(AllocType,
1906 AllocType->getObjCARCImplicitLifetime());
1907 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001908
John McCall31168b02011-06-15 23:02:42 +00001909 QualType ResultType = Context.getPointerType(AllocType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00001910
John McCall5e77d762013-04-16 07:28:30 +00001911 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1912 ExprResult result = CheckPlaceholderExpr(ArraySize);
1913 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001914 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001915 }
Richard Smith8dd34252012-02-04 07:07:42 +00001916 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1917 // integral or enumeration type with a non-negative value."
1918 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1919 // enumeration type, or a class type for which a single non-explicit
1920 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001921 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001922 // std::size_t.
Richard Smith0511d232016-10-05 22:41:02 +00001923 llvm::Optional<uint64_t> KnownArraySize;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001924 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001925 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001926 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001927 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1928
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001929 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
Fangrui Song99337e22018-07-20 08:19:20 +00001930 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001931
Simon Pilgrim75c26882016-09-30 14:25:09 +00001932 if (!ConvertedSize.isInvalid() &&
Larisse Voufobf4aa572013-06-18 03:08:53 +00001933 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001934 // Diagnose the compatibility of this conversion.
1935 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1936 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001937 } else {
1938 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1939 protected:
1940 Expr *ArraySize;
Simon Pilgrim75c26882016-09-30 14:25:09 +00001941
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001942 public:
1943 SizeConvertDiagnoser(Expr *ArraySize)
1944 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1945 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001946
1947 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1948 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001949 return S.Diag(Loc, diag::err_array_size_not_integral)
1950 << S.getLangOpts().CPlusPlus11 << T;
1951 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001952
1953 SemaDiagnosticBuilder diagnoseIncomplete(
1954 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001955 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1956 << T << ArraySize->getSourceRange();
1957 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001958
1959 SemaDiagnosticBuilder diagnoseExplicitConv(
1960 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001961 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1962 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001963
1964 SemaDiagnosticBuilder noteExplicitConv(
1965 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001966 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1967 << ConvTy->isEnumeralType() << ConvTy;
1968 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001969
1970 SemaDiagnosticBuilder diagnoseAmbiguous(
1971 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001972 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1973 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001974
1975 SemaDiagnosticBuilder noteAmbiguous(
1976 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001977 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1978 << ConvTy->isEnumeralType() << ConvTy;
1979 }
Richard Smithccc11812013-05-21 19:05:48 +00001980
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001981 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1982 QualType T,
1983 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001984 return S.Diag(Loc,
1985 S.getLangOpts().CPlusPlus11
1986 ? diag::warn_cxx98_compat_array_size_conversion
1987 : diag::ext_array_size_conversion)
1988 << T << ConvTy->isEnumeralType() << ConvTy;
1989 }
1990 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001991
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001992 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1993 SizeDiagnoser);
1994 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001995 if (ConvertedSize.isInvalid())
1996 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001997
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001998 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001999 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00002000
Douglas Gregor0bf31402010-10-08 23:50:27 +00002001 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00002002 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002003
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002004 // C++98 [expr.new]p7:
2005 // The expression in a direct-new-declarator shall have integral type
2006 // with a non-negative value.
2007 //
Richard Smith0511d232016-10-05 22:41:02 +00002008 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2009 // per CWG1464. Otherwise, if it's not a constant, we must have an
2010 // unparenthesized array type.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002011 if (!ArraySize->isValueDependent()) {
2012 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00002013 // We've already performed any required implicit conversion to integer or
2014 // unscoped enumeration type.
Richard Smith0511d232016-10-05 22:41:02 +00002015 // FIXME: Per CWG1464, we are required to check the value prior to
2016 // converting to size_t. This will never find a negative array size in
2017 // C++14 onwards, because Value is always unsigned here!
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002018 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Richard Smith0511d232016-10-05 22:41:02 +00002019 if (Value.isSigned() && Value.isNegative()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002020 return ExprError(Diag(ArraySize->getBeginLoc(),
Richard Smith0511d232016-10-05 22:41:02 +00002021 diag::err_typecheck_negative_array_size)
2022 << ArraySize->getSourceRange());
2023 }
2024
2025 if (!AllocType->isDependentType()) {
Richard Smithbcc9bcb2012-02-04 05:35:53 +00002026 unsigned ActiveSizeBits =
2027 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
Richard Smith0511d232016-10-05 22:41:02 +00002028 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002029 return ExprError(
2030 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2031 << Value.toString(10) << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00002032 }
Richard Smith0511d232016-10-05 22:41:02 +00002033
2034 KnownArraySize = Value.getZExtValue();
Douglas Gregorf2753b32010-07-13 15:54:32 +00002035 } else if (TypeIdParens.isValid()) {
2036 // Can't have dynamic array size when the type-id is in parentheses.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002037 Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2038 << ArraySize->getSourceRange()
2039 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2040 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002041
Douglas Gregorf2753b32010-07-13 15:54:32 +00002042 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002043 }
Sebastian Redl351bb782008-12-02 14:43:59 +00002044 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002045
John McCall036f2f62011-05-15 07:14:44 +00002046 // Note that we do *not* convert the argument in any way. It can
2047 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00002048 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002049
Craig Topperc3ec1492014-05-26 06:22:03 +00002050 FunctionDecl *OperatorNew = nullptr;
2051 FunctionDecl *OperatorDelete = nullptr;
Richard Smithb2f0f052016-10-10 18:54:32 +00002052 unsigned Alignment =
2053 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2054 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2055 bool PassAlignment = getLangOpts().AlignedAllocation &&
2056 Alignment > NewAlignment;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002057
Brian Gesiakcb024022018-04-01 22:59:22 +00002058 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002059 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002060 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002061 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002062 SourceRange(PlacementLParen, PlacementRParen),
Brian Gesiakcb024022018-04-01 22:59:22 +00002063 Scope, Scope, AllocType, ArraySize, PassAlignment,
Richard Smithb2f0f052016-10-10 18:54:32 +00002064 PlacementArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002065 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00002066
2067 // If this is an array allocation, compute whether the usual array
2068 // deallocation function for the type has a size_t parameter.
2069 bool UsualArrayDeleteWantsSize = false;
2070 if (ArraySize && !AllocType->isDependentType())
Richard Smithb2f0f052016-10-10 18:54:32 +00002071 UsualArrayDeleteWantsSize =
2072 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
John McCall284c48f2011-01-27 09:37:56 +00002073
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002074 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00002075 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002076 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00002077 OperatorNew->getType()->getAs<FunctionProtoType>();
2078 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2079 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002080
Richard Smithd6f9e732014-05-13 19:56:21 +00002081 // We've already converted the placement args, just fill in any default
2082 // arguments. Skip the first parameter because we don't have a corresponding
Richard Smithb2f0f052016-10-10 18:54:32 +00002083 // argument. Skip the second parameter too if we're passing in the
2084 // alignment; we've already filled it in.
2085 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2086 PassAlignment ? 2 : 1, PlacementArgs,
2087 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00002088 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002089
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002090 if (!AllPlaceArgs.empty())
2091 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00002092
Richard Smithd6f9e732014-05-13 19:56:21 +00002093 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002094 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00002095
2096 // FIXME: Missing call to CheckFunctionCall or equivalent
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002097
Richard Smithb2f0f052016-10-10 18:54:32 +00002098 // Warn if the type is over-aligned and is being allocated by (unaligned)
2099 // global operator new.
2100 if (PlacementArgs.empty() && !PassAlignment &&
2101 (OperatorNew->isImplicit() ||
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002102 (OperatorNew->getBeginLoc().isValid() &&
2103 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002104 if (Alignment > NewAlignment)
Nick Lewycky411fc652012-01-24 21:15:41 +00002105 Diag(StartLoc, diag::warn_overaligned_type)
2106 << AllocType
Richard Smithb2f0f052016-10-10 18:54:32 +00002107 << unsigned(Alignment / Context.getCharWidth())
2108 << unsigned(NewAlignment / Context.getCharWidth());
Nick Lewycky411fc652012-01-24 21:15:41 +00002109 }
2110 }
2111
Sebastian Redl6047f072012-02-16 12:22:20 +00002112 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002113 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2114 // dialect distinction.
Richard Smith0511d232016-10-05 22:41:02 +00002115 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002116 SourceRange InitRange(Inits[0]->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002117 Inits[NumInits - 1]->getEndLoc());
Richard Smith0511d232016-10-05 22:41:02 +00002118 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2119 return ExprError();
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00002120 }
2121
Richard Smithdd2ca572012-11-26 08:32:48 +00002122 // If we can perform the initialization, and we've not already done so,
2123 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00002124 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002125 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00002126 llvm::makeArrayRef(Inits, NumInits))) {
Richard Smith0511d232016-10-05 22:41:02 +00002127 // The type we initialize is the complete type, including the array bound.
2128 QualType InitType;
2129 if (KnownArraySize)
2130 InitType = Context.getConstantArrayType(
2131 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2132 *KnownArraySize),
2133 ArrayType::Normal, 0);
2134 else if (ArraySize)
2135 InitType =
2136 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2137 else
2138 InitType = AllocType;
2139
Douglas Gregor85dabae2009-12-16 01:38:02 +00002140 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00002141 = InitializedEntity::InitializeNew(StartLoc, InitType);
Richard Smith0511d232016-10-05 22:41:02 +00002142 InitializationSequence InitSeq(*this, Entity, Kind,
2143 MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002144 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00002145 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00002146 if (FullInit.isInvalid())
2147 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002148
Sebastian Redl6047f072012-02-16 12:22:20 +00002149 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2150 // we don't want the initialized object to be destructed.
Richard Smith0511d232016-10-05 22:41:02 +00002151 // FIXME: We should not create these in the first place.
Sebastian Redl6047f072012-02-16 12:22:20 +00002152 if (CXXBindTemporaryExpr *Binder =
2153 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002154 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002155
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002156 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002157 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002158
Douglas Gregor6642ca22010-02-26 05:06:18 +00002159 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00002160 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00002161 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2162 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002163 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00002164 }
2165 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00002166 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2167 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00002168 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00002169 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002170
John McCall928a2572011-07-13 20:12:57 +00002171 // C++0x [expr.new]p17:
2172 // If the new expression creates an array of objects of class type,
2173 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00002174 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2175 if (ArraySize && !BaseAllocType->isDependentType()) {
2176 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2177 if (CXXDestructorDecl *dtor = LookupDestructor(
2178 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2179 MarkFunctionReferenced(StartLoc, dtor);
Simon Pilgrim75c26882016-09-30 14:25:09 +00002180 CheckDestructorAccess(StartLoc, dtor,
David Blaikie631a4862012-03-10 23:40:02 +00002181 PDiag(diag::err_access_dtor)
2182 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00002183 if (DiagnoseUseOfDecl(dtor, StartLoc))
2184 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00002185 }
John McCall928a2572011-07-13 20:12:57 +00002186 }
2187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188
Bruno Ricci9b6dfac2019-01-07 15:04:45 +00002189 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2190 PassAlignment, UsualArrayDeleteWantsSize,
2191 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2192 Initializer, ResultType, AllocTypeInfo, Range,
2193 DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00002194}
2195
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002196/// Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00002197/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00002198bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00002199 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00002200 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2201 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00002202 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002203 return Diag(Loc, diag::err_bad_new_type)
2204 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002205 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00002206 return Diag(Loc, diag::err_bad_new_type)
2207 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00002208 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002209 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00002210 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00002211 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00002212 diag::err_allocation_of_abstract_type))
2213 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00002214 else if (AllocType->isVariablyModifiedType())
2215 return Diag(Loc, diag::err_variably_modified_new_type)
2216 << AllocType;
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002217 else if (AllocType.getAddressSpace() != LangAS::Default &&
2218 !getLangOpts().OpenCLCPlusPlus)
Douglas Gregor39d1a092011-04-15 19:46:20 +00002219 return Diag(Loc, diag::err_address_space_qualified_new)
Yaxun Liub34ec822017-04-11 17:24:23 +00002220 << AllocType.getUnqualifiedType()
2221 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002222 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002223 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2224 QualType BaseAllocType = Context.getBaseElementType(AT);
2225 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2226 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00002227 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00002228 << BaseAllocType;
2229 }
2230 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00002231
Sebastian Redlbd150f42008-11-21 19:14:01 +00002232 return false;
2233}
2234
Brian Gesiak87412d92018-02-15 20:09:25 +00002235static bool resolveAllocationOverload(
2236 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2237 bool &PassAlignment, FunctionDecl *&Operator,
2238 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002239 OverloadCandidateSet Candidates(R.getNameLoc(),
2240 OverloadCandidateSet::CSK_Normal);
2241 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2242 Alloc != AllocEnd; ++Alloc) {
2243 // Even member operator new/delete are implicitly treated as
2244 // static, so don't use AddMemberCandidate.
2245 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2246
2247 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2248 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2249 /*ExplicitTemplateArgs=*/nullptr, Args,
2250 Candidates,
2251 /*SuppressUserConversions=*/false);
2252 continue;
2253 }
2254
2255 FunctionDecl *Fn = cast<FunctionDecl>(D);
2256 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2257 /*SuppressUserConversions=*/false);
2258 }
2259
2260 // Do the resolution.
2261 OverloadCandidateSet::iterator Best;
2262 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2263 case OR_Success: {
2264 // Got one!
2265 FunctionDecl *FnDecl = Best->Function;
2266 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2267 Best->FoundDecl) == Sema::AR_inaccessible)
2268 return true;
2269
2270 Operator = FnDecl;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002271 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002272 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002273
Richard Smithb2f0f052016-10-10 18:54:32 +00002274 case OR_No_Viable_Function:
2275 // C++17 [expr.new]p13:
2276 // If no matching function is found and the allocated object type has
2277 // new-extended alignment, the alignment argument is removed from the
2278 // argument list, and overload resolution is performed again.
2279 if (PassAlignment) {
2280 PassAlignment = false;
2281 AlignArg = Args[1];
2282 Args.erase(Args.begin() + 1);
2283 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002284 Operator, &Candidates, AlignArg,
2285 Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002286 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002287
Richard Smithb2f0f052016-10-10 18:54:32 +00002288 // MSVC will fall back on trying to find a matching global operator new
2289 // if operator new[] cannot be found. Also, MSVC will leak by not
2290 // generating a call to operator delete or operator delete[], but we
2291 // will not replicate that bug.
2292 // FIXME: Find out how this interacts with the std::align_val_t fallback
2293 // once MSVC implements it.
2294 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2295 S.Context.getLangOpts().MSVCCompat) {
2296 R.clear();
2297 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2298 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2299 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2300 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002301 Operator, /*Candidates=*/nullptr,
2302 /*AlignArg=*/nullptr, Diagnose);
Richard Smithb2f0f052016-10-10 18:54:32 +00002303 }
Richard Smith1cdec012013-09-29 04:40:38 +00002304
Brian Gesiak87412d92018-02-15 20:09:25 +00002305 if (Diagnose) {
2306 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2307 << R.getLookupName() << Range;
Richard Smithb2f0f052016-10-10 18:54:32 +00002308
Brian Gesiak87412d92018-02-15 20:09:25 +00002309 // If we have aligned candidates, only note the align_val_t candidates
2310 // from AlignedCandidates and the non-align_val_t candidates from
2311 // Candidates.
2312 if (AlignedCandidates) {
2313 auto IsAligned = [](OverloadCandidate &C) {
2314 return C.Function->getNumParams() > 1 &&
2315 C.Function->getParamDecl(1)->getType()->isAlignValT();
2316 };
2317 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
Richard Smithb2f0f052016-10-10 18:54:32 +00002318
Brian Gesiak87412d92018-02-15 20:09:25 +00002319 // This was an overaligned allocation, so list the aligned candidates
2320 // first.
2321 Args.insert(Args.begin() + 1, AlignArg);
2322 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2323 R.getNameLoc(), IsAligned);
2324 Args.erase(Args.begin() + 1);
2325 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2326 IsUnaligned);
2327 } else {
2328 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2329 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002330 }
Richard Smith1cdec012013-09-29 04:40:38 +00002331 return true;
2332
Richard Smithb2f0f052016-10-10 18:54:32 +00002333 case OR_Ambiguous:
Brian Gesiak87412d92018-02-15 20:09:25 +00002334 if (Diagnose) {
2335 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2336 << R.getLookupName() << Range;
2337 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2338 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002339 return true;
2340
2341 case OR_Deleted: {
Brian Gesiak87412d92018-02-15 20:09:25 +00002342 if (Diagnose) {
2343 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2344 << Best->Function->isDeleted() << R.getLookupName()
2345 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2346 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2347 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002348 return true;
2349 }
2350 }
2351 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Douglas Gregor6642ca22010-02-26 05:06:18 +00002352}
2353
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002354bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
Brian Gesiakcb024022018-04-01 22:59:22 +00002355 AllocationFunctionScope NewScope,
2356 AllocationFunctionScope DeleteScope,
2357 QualType AllocType, bool IsArray,
2358 bool &PassAlignment, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00002359 FunctionDecl *&OperatorNew,
Brian Gesiak87412d92018-02-15 20:09:25 +00002360 FunctionDecl *&OperatorDelete,
2361 bool Diagnose) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002362 // --- Choosing an allocation function ---
2363 // C++ 5.3.4p8 - 14 & 18
Brian Gesiakcb024022018-04-01 22:59:22 +00002364 // 1) If looking in AFS_Global scope for allocation functions, only look in
2365 // the global scope. Else, if AFS_Class, only look in the scope of the
2366 // allocated class. If AFS_Both, look in both.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002367 // 2) If an array size is given, look for operator new[], else look for
2368 // operator new.
2369 // 3) The first argument is always size_t. Append the arguments from the
2370 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002371
Richard Smithb2f0f052016-10-10 18:54:32 +00002372 SmallVector<Expr*, 8> AllocArgs;
2373 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2374
2375 // We don't care about the actual value of these arguments.
Sebastian Redlfaf68082008-12-03 20:26:15 +00002376 // FIXME: Should the Sema create the expression and embed it in the syntax
2377 // tree? Or should the consumer just recalculate the value?
Richard Smithb2f0f052016-10-10 18:54:32 +00002378 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002379 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002380 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00002381 Context.getSizeType(),
2382 SourceLocation());
Richard Smithb2f0f052016-10-10 18:54:32 +00002383 AllocArgs.push_back(&Size);
2384
2385 QualType AlignValT = Context.VoidTy;
2386 if (PassAlignment) {
2387 DeclareGlobalNewDelete();
2388 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2389 }
2390 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2391 if (PassAlignment)
2392 AllocArgs.push_back(&Align);
2393
2394 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
Sebastian Redlfaf68082008-12-03 20:26:15 +00002395
Douglas Gregor6642ca22010-02-26 05:06:18 +00002396 // C++ [expr.new]p8:
2397 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002398 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00002399 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002400 // type, the allocation function's name is operator new[] and the
2401 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00002402 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
Richard Smithb2f0f052016-10-10 18:54:32 +00002403 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002404
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002405 QualType AllocElemType = Context.getBaseElementType(AllocType);
2406
Richard Smithb2f0f052016-10-10 18:54:32 +00002407 // Find the allocation function.
2408 {
2409 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2410
2411 // C++1z [expr.new]p9:
2412 // If the new-expression begins with a unary :: operator, the allocation
2413 // function's name is looked up in the global scope. Otherwise, if the
2414 // allocated type is a class type T or array thereof, the allocation
2415 // function's name is looked up in the scope of T.
Brian Gesiakcb024022018-04-01 22:59:22 +00002416 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
Richard Smithb2f0f052016-10-10 18:54:32 +00002417 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2418
2419 // We can see ambiguity here if the allocation function is found in
2420 // multiple base classes.
2421 if (R.isAmbiguous())
2422 return true;
2423
2424 // If this lookup fails to find the name, or if the allocated type is not
2425 // a class type, the allocation function's name is looked up in the
2426 // global scope.
Brian Gesiakcb024022018-04-01 22:59:22 +00002427 if (R.empty()) {
2428 if (NewScope == AFS_Class)
2429 return true;
2430
Richard Smithb2f0f052016-10-10 18:54:32 +00002431 LookupQualifiedName(R, Context.getTranslationUnitDecl());
Brian Gesiakcb024022018-04-01 22:59:22 +00002432 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002433
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002434 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2435 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2436 return true;
2437 }
2438
Richard Smithb2f0f052016-10-10 18:54:32 +00002439 assert(!R.empty() && "implicitly declared allocation functions not found");
2440 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2441
2442 // We do our own custom access checks below.
2443 R.suppressDiagnostics();
2444
2445 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
Brian Gesiak87412d92018-02-15 20:09:25 +00002446 OperatorNew, /*Candidates=*/nullptr,
2447 /*AlignArg=*/nullptr, Diagnose))
Sebastian Redlfaf68082008-12-03 20:26:15 +00002448 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002449 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00002450
Richard Smithb2f0f052016-10-10 18:54:32 +00002451 // We don't need an operator delete if we're running under -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002452 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002453 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00002454 return false;
2455 }
2456
Richard Smithb2f0f052016-10-10 18:54:32 +00002457 // Note, the name of OperatorNew might have been changed from array to
2458 // non-array by resolveAllocationOverload.
2459 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2460 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2461 ? OO_Array_Delete
2462 : OO_Delete);
2463
Douglas Gregor6642ca22010-02-26 05:06:18 +00002464 // C++ [expr.new]p19:
2465 //
2466 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002467 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00002468 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002469 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00002470 // the scope of T. If this lookup fails to find the name, or if
2471 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00002472 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00002473 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Brian Gesiakcb024022018-04-01 22:59:22 +00002474 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002475 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00002476 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00002477 LookupQualifiedName(FoundDelete, RD);
2478 }
John McCallfb6f5262010-03-18 08:19:33 +00002479 if (FoundDelete.isAmbiguous())
2480 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00002481
Richard Smithb2f0f052016-10-10 18:54:32 +00002482 bool FoundGlobalDelete = FoundDelete.empty();
Douglas Gregor6642ca22010-02-26 05:06:18 +00002483 if (FoundDelete.empty()) {
Brian Gesiakcb024022018-04-01 22:59:22 +00002484 if (DeleteScope == AFS_Class)
2485 return true;
2486
Douglas Gregor6642ca22010-02-26 05:06:18 +00002487 DeclareGlobalNewDelete();
2488 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2489 }
2490
2491 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00002492
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002493 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00002494
John McCalld3be2c82010-09-14 21:34:24 +00002495 // Whether we're looking for a placement operator delete is dictated
2496 // by whether we selected a placement operator new, not by whether
2497 // we had explicit placement arguments. This matters for things like
2498 // struct A { void *operator new(size_t, int = 0); ... };
2499 // A *a = new A()
Richard Smithb2f0f052016-10-10 18:54:32 +00002500 //
2501 // We don't have any definition for what a "placement allocation function"
2502 // is, but we assume it's any allocation function whose
2503 // parameter-declaration-clause is anything other than (size_t).
2504 //
2505 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2506 // This affects whether an exception from the constructor of an overaligned
2507 // type uses the sized or non-sized form of aligned operator delete.
2508 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2509 OperatorNew->isVariadic();
John McCalld3be2c82010-09-14 21:34:24 +00002510
2511 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002512 // C++ [expr.new]p20:
2513 // A declaration of a placement deallocation function matches the
2514 // declaration of a placement allocation function if it has the
2515 // same number of parameters and, after parameter transformations
2516 // (8.3.5), all parameter types except the first are
2517 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002518 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00002519 // To perform this comparison, we compute the function type that
2520 // the deallocation function should have, and use that type both
2521 // for template argument deduction and for comparison purposes.
2522 QualType ExpectedFunctionType;
2523 {
2524 const FunctionProtoType *Proto
2525 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00002526
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002527 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002528 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00002529 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2530 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002531
John McCalldb40c7f2010-12-14 08:05:40 +00002532 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithb2f0f052016-10-10 18:54:32 +00002533 // FIXME: This is not part of the standard's rule.
John McCalldb40c7f2010-12-14 08:05:40 +00002534 EPI.Variadic = Proto->isVariadic();
2535
Douglas Gregor6642ca22010-02-26 05:06:18 +00002536 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00002537 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002538 }
2539
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002540 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00002541 DEnd = FoundDelete.end();
2542 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002543 FunctionDecl *Fn = nullptr;
Richard Smithbaa47832016-12-01 02:11:49 +00002544 if (FunctionTemplateDecl *FnTmpl =
2545 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002546 // Perform template argument deduction to try to match the
2547 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00002548 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00002549 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2550 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00002551 continue;
2552 } else
2553 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2554
Richard Smithbaa47832016-12-01 02:11:49 +00002555 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2556 ExpectedFunctionType,
2557 /*AdjustExcpetionSpec*/true),
2558 ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00002559 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00002560 }
Daniel Jaspere9abe642016-10-10 14:13:55 +00002561
Richard Smithb2f0f052016-10-10 18:54:32 +00002562 if (getLangOpts().CUDA)
2563 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2564 } else {
Richard Smith1cdec012013-09-29 04:40:38 +00002565 // C++1y [expr.new]p22:
2566 // For a non-placement allocation function, the normal deallocation
2567 // function lookup is used
Richard Smithb2f0f052016-10-10 18:54:32 +00002568 //
2569 // Per [expr.delete]p10, this lookup prefers a member operator delete
2570 // without a size_t argument, but prefers a non-member operator delete
2571 // with a size_t where possible (which it always is in this case).
2572 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2573 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2574 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2575 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2576 &BestDeallocFns);
2577 if (Selected)
2578 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2579 else {
2580 // If we failed to select an operator, all remaining functions are viable
2581 // but ambiguous.
2582 for (auto Fn : BestDeallocFns)
2583 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
Richard Smith1cdec012013-09-29 04:40:38 +00002584 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002585 }
2586
2587 // C++ [expr.new]p20:
2588 // [...] If the lookup finds a single matching deallocation
2589 // function, that function will be called; otherwise, no
2590 // deallocation function will be called.
2591 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002592 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002593
Richard Smithb2f0f052016-10-10 18:54:32 +00002594 // C++1z [expr.new]p23:
2595 // If the lookup finds a usual deallocation function (3.7.4.2)
2596 // with a parameter of type std::size_t and that function, considered
Douglas Gregor6642ca22010-02-26 05:06:18 +00002597 // as a placement deallocation function, would have been
2598 // selected as a match for the allocation function, the program
2599 // is ill-formed.
Richard Smithb2f0f052016-10-10 18:54:32 +00002600 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
Richard Smith1cdec012013-09-29 04:40:38 +00002601 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Richard Smithf75dcbe2016-10-11 00:21:10 +00002602 UsualDeallocFnInfo Info(*this,
2603 DeclAccessPair::make(OperatorDelete, AS_public));
Richard Smithb2f0f052016-10-10 18:54:32 +00002604 // Core issue, per mail to core reflector, 2016-10-09:
2605 // If this is a member operator delete, and there is a corresponding
2606 // non-sized member operator delete, this isn't /really/ a sized
2607 // deallocation function, it just happens to have a size_t parameter.
2608 bool IsSizedDelete = Info.HasSizeT;
2609 if (IsSizedDelete && !FoundGlobalDelete) {
2610 auto NonSizedDelete =
2611 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2612 /*WantAlign*/Info.HasAlignValT);
2613 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2614 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2615 IsSizedDelete = false;
2616 }
2617
2618 if (IsSizedDelete) {
2619 SourceRange R = PlaceArgs.empty()
2620 ? SourceRange()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002621 : SourceRange(PlaceArgs.front()->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002622 PlaceArgs.back()->getEndLoc());
Richard Smithb2f0f052016-10-10 18:54:32 +00002623 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2624 if (!OperatorDelete->isImplicit())
2625 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2626 << DeleteName;
2627 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002628 }
Richard Smithb2f0f052016-10-10 18:54:32 +00002629
2630 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2631 Matches[0].first);
2632 } else if (!Matches.empty()) {
2633 // We found multiple suitable operators. Per [expr.new]p20, that means we
2634 // call no 'operator delete' function, but we should at least warn the user.
2635 // FIXME: Suppress this warning if the construction cannot throw.
2636 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2637 << DeleteName << AllocElemType;
2638
2639 for (auto &Match : Matches)
2640 Diag(Match.second->getLocation(),
2641 diag::note_member_declared_here) << DeleteName;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002642 }
2643
Sebastian Redlfaf68082008-12-03 20:26:15 +00002644 return false;
2645}
2646
2647/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2648/// delete. These are:
2649/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002650/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002651/// void* operator new(std::size_t) throw(std::bad_alloc);
2652/// void* operator new[](std::size_t) throw(std::bad_alloc);
2653/// void operator delete(void *) throw();
2654/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002655/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002656/// void* operator new(std::size_t);
2657/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002658/// void operator delete(void *) noexcept;
2659/// void operator delete[](void *) noexcept;
2660/// // C++1y:
2661/// void* operator new(std::size_t);
2662/// void* operator new[](std::size_t);
2663/// void operator delete(void *) noexcept;
2664/// void operator delete[](void *) noexcept;
2665/// void operator delete(void *, std::size_t) noexcept;
2666/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002667/// @endcode
2668/// Note that the placement and nothrow forms of new are *not* implicitly
2669/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002670void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002671 if (GlobalNewDeleteDeclared)
2672 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002673
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00002674 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2675 // are not supported.
2676 if (getLangOpts().OpenCLCPlusPlus)
2677 return;
2678
Douglas Gregor87f54062009-09-15 22:30:29 +00002679 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002680 // [...] The following allocation and deallocation functions (18.4) are
2681 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002682 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002683 //
Sebastian Redl37588092011-03-14 18:08:30 +00002684 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002685 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002686 // void* operator new[](std::size_t) throw(std::bad_alloc);
2687 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002688 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002689 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002690 // void* operator new(std::size_t);
2691 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002692 // void operator delete(void*) noexcept;
2693 // void operator delete[](void*) noexcept;
2694 // C++1y:
2695 // void* operator new(std::size_t);
2696 // void* operator new[](std::size_t);
2697 // void operator delete(void*) noexcept;
2698 // void operator delete[](void*) noexcept;
2699 // void operator delete(void*, std::size_t) noexcept;
2700 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002701 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002702 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002703 // new, operator new[], operator delete, operator delete[].
2704 //
2705 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2706 // "std" or "bad_alloc" as necessary to form the exception specification.
2707 // However, we do not make these implicit declarations visible to name
2708 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002709 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002710 // The "std::bad_alloc" class has not yet been declared, so build it
2711 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002712 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2713 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002714 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002716 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002717 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002718 }
Richard Smith59139022016-09-30 22:41:36 +00002719 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
Richard Smith96269c52016-09-29 22:49:46 +00002720 // The "std::align_val_t" enum class has not yet been declared, so build it
2721 // implicitly.
2722 auto *AlignValT = EnumDecl::Create(
2723 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2724 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2725 AlignValT->setIntegerType(Context.getSizeType());
2726 AlignValT->setPromotionType(Context.getSizeType());
2727 AlignValT->setImplicit(true);
2728 StdAlignValT = AlignValT;
2729 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002730
Sebastian Redlfaf68082008-12-03 20:26:15 +00002731 GlobalNewDeleteDeclared = true;
2732
2733 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2734 QualType SizeT = Context.getSizeType();
2735
Richard Smith96269c52016-09-29 22:49:46 +00002736 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2737 QualType Return, QualType Param) {
2738 llvm::SmallVector<QualType, 3> Params;
2739 Params.push_back(Param);
2740
2741 // Create up to four variants of the function (sized/aligned).
2742 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2743 (Kind == OO_Delete || Kind == OO_Array_Delete);
Richard Smith59139022016-09-30 22:41:36 +00002744 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002745
2746 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2747 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2748 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
Richard Smith96269c52016-09-29 22:49:46 +00002749 if (Sized)
2750 Params.push_back(SizeT);
2751
Simon Pilgrimd69fc8e2016-09-30 14:18:06 +00002752 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
Richard Smith96269c52016-09-29 22:49:46 +00002753 if (Aligned)
2754 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2755
2756 DeclareGlobalAllocationFunction(
2757 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2758
2759 if (Aligned)
2760 Params.pop_back();
2761 }
2762 }
2763 };
2764
2765 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2766 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2767 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2768 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002769}
2770
2771/// DeclareGlobalAllocationFunction - Declares a single implicit global
2772/// allocation function if it doesn't already exist.
2773void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002774 QualType Return,
Richard Smith96269c52016-09-29 22:49:46 +00002775 ArrayRef<QualType> Params) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002776 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2777
2778 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002779 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2780 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2781 Alloc != AllocEnd; ++Alloc) {
2782 // Only look at non-template functions, as it is the predefined,
2783 // non-templated allocation function we are trying to declare here.
2784 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith96269c52016-09-29 22:49:46 +00002785 if (Func->getNumParams() == Params.size()) {
2786 llvm::SmallVector<QualType, 3> FuncParams;
2787 for (auto *P : Func->parameters())
2788 FuncParams.push_back(
2789 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2790 if (llvm::makeArrayRef(FuncParams) == Params) {
Serge Pavlovd5489072013-09-14 12:00:01 +00002791 // Make the function visible to name lookup, even if we found it in
2792 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002793 // allocation function, or is suppressing that function.
Richard Smith90dc5252017-06-23 01:04:34 +00002794 Func->setVisibleDespiteOwningModule();
Chandler Carruth93538422010-02-03 11:02:14 +00002795 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002796 }
Chandler Carruth93538422010-02-03 11:02:14 +00002797 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002798 }
2799 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002800
Richard Smithc015bc22014-02-07 22:39:53 +00002801 FunctionProtoType::ExtProtoInfo EPI;
2802
Richard Smithf8b417c2014-02-08 00:42:45 +00002803 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002804 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002805 = (Name.getCXXOverloadedOperator() == OO_New ||
2806 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002807 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002808 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002809 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002810 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002811 EPI.ExceptionSpec.Type = EST_Dynamic;
2812 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002813 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002814 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002815 EPI.ExceptionSpec =
2816 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002818
Artem Belevich07db5cf2016-10-21 20:34:05 +00002819 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2820 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2821 FunctionDecl *Alloc = FunctionDecl::Create(
2822 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2823 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2824 Alloc->setImplicit();
Vassil Vassilev41cafcd2017-06-09 21:36:28 +00002825 // Global allocation functions should always be visible.
Richard Smith90dc5252017-06-23 01:04:34 +00002826 Alloc->setVisibleDespiteOwningModule();
Simon Pilgrim75c26882016-09-30 14:25:09 +00002827
Petr Hosek821b38f2018-12-04 03:25:25 +00002828 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2829 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2830 ? VisibilityAttr::Hidden
2831 : VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002832
Artem Belevich07db5cf2016-10-21 20:34:05 +00002833 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2834 for (QualType T : Params) {
2835 ParamDecls.push_back(ParmVarDecl::Create(
2836 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2837 /*TInfo=*/nullptr, SC_None, nullptr));
2838 ParamDecls.back()->setImplicit();
2839 }
2840 Alloc->setParams(ParamDecls);
2841 if (ExtraAttr)
2842 Alloc->addAttr(ExtraAttr);
2843 Context.getTranslationUnitDecl()->addDecl(Alloc);
2844 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2845 };
2846
2847 if (!LangOpts.CUDA)
2848 CreateAllocationFunctionDecl(nullptr);
2849 else {
2850 // Host and device get their own declaration so each can be
2851 // defined or re-declared independently.
2852 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2853 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
Richard Smithbdd14642014-02-04 01:14:30 +00002854 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002855}
2856
Richard Smith1cdec012013-09-29 04:40:38 +00002857FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2858 bool CanProvideSize,
Richard Smithb2f0f052016-10-10 18:54:32 +00002859 bool Overaligned,
Richard Smith1cdec012013-09-29 04:40:38 +00002860 DeclarationName Name) {
2861 DeclareGlobalNewDelete();
2862
2863 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2864 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2865
Richard Smithb2f0f052016-10-10 18:54:32 +00002866 // FIXME: It's possible for this to result in ambiguity, through a
2867 // user-declared variadic operator delete or the enable_if attribute. We
2868 // should probably not consider those cases to be usual deallocation
2869 // functions. But for now we just make an arbitrary choice in that case.
2870 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2871 Overaligned);
2872 assert(Result.FD && "operator delete missing from global scope?");
2873 return Result.FD;
2874}
Richard Smith1cdec012013-09-29 04:40:38 +00002875
Richard Smithb2f0f052016-10-10 18:54:32 +00002876FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2877 CXXRecordDecl *RD) {
2878 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
Richard Smith1cdec012013-09-29 04:40:38 +00002879
Richard Smithb2f0f052016-10-10 18:54:32 +00002880 FunctionDecl *OperatorDelete = nullptr;
2881 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2882 return nullptr;
2883 if (OperatorDelete)
2884 return OperatorDelete;
Artem Belevich94a55e82015-09-22 17:22:59 +00002885
Richard Smithb2f0f052016-10-10 18:54:32 +00002886 // If there's no class-specific operator delete, look up the global
2887 // non-array delete.
2888 return FindUsualDeallocationFunction(
2889 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2890 Name);
Richard Smith1cdec012013-09-29 04:40:38 +00002891}
2892
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002893bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2894 DeclarationName Name,
Richard Smithb2f0f052016-10-10 18:54:32 +00002895 FunctionDecl *&Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002896 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002897 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002898 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002899
John McCall27b18f82009-11-17 02:14:36 +00002900 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002901 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002902
Chandler Carruthb6f99172010-06-28 00:30:51 +00002903 Found.suppressDiagnostics();
2904
Richard Smithb2f0f052016-10-10 18:54:32 +00002905 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
Chandler Carruth9b418232010-08-08 07:04:00 +00002906
Richard Smithb2f0f052016-10-10 18:54:32 +00002907 // C++17 [expr.delete]p10:
2908 // If the deallocation functions have class scope, the one without a
2909 // parameter of type std::size_t is selected.
2910 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2911 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2912 /*WantAlign*/ Overaligned, &Matches);
Chandler Carruth9b418232010-08-08 07:04:00 +00002913
Richard Smithb2f0f052016-10-10 18:54:32 +00002914 // If we could find an overload, use it.
John McCall66a87592010-08-04 00:31:26 +00002915 if (Matches.size() == 1) {
Richard Smithb2f0f052016-10-10 18:54:32 +00002916 Operator = cast<CXXMethodDecl>(Matches[0].FD);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002917
Richard Smithb2f0f052016-10-10 18:54:32 +00002918 // FIXME: DiagnoseUseOfDecl?
Alexis Hunt1f69a022011-05-12 22:46:29 +00002919 if (Operator->isDeleted()) {
2920 if (Diagnose) {
2921 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002922 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002923 }
2924 return true;
2925 }
2926
Richard Smith921bd202012-02-26 09:11:52 +00002927 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
Richard Smithb2f0f052016-10-10 18:54:32 +00002928 Matches[0].Found, Diagnose) == AR_inaccessible)
Richard Smith921bd202012-02-26 09:11:52 +00002929 return true;
2930
John McCall66a87592010-08-04 00:31:26 +00002931 return false;
Richard Smithb2f0f052016-10-10 18:54:32 +00002932 }
John McCall66a87592010-08-04 00:31:26 +00002933
Richard Smithb2f0f052016-10-10 18:54:32 +00002934 // We found multiple suitable operators; complain about the ambiguity.
2935 // FIXME: The standard doesn't say to do this; it appears that the intent
2936 // is that this should never happen.
2937 if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002938 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002939 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2940 << Name << RD;
Richard Smithb2f0f052016-10-10 18:54:32 +00002941 for (auto &Match : Matches)
2942 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
Alexis Huntf91729462011-05-12 22:46:25 +00002943 }
John McCall66a87592010-08-04 00:31:26 +00002944 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002945 }
2946
2947 // We did find operator delete/operator delete[] declarations, but
2948 // none of them were suitable.
2949 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002950 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002951 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2952 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002953
Richard Smithb2f0f052016-10-10 18:54:32 +00002954 for (NamedDecl *D : Found)
2955 Diag(D->getUnderlyingDecl()->getLocation(),
Alexis Huntf91729462011-05-12 22:46:25 +00002956 diag::note_member_declared_here) << Name;
2957 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002958 return true;
2959 }
2960
Craig Topperc3ec1492014-05-26 06:22:03 +00002961 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002962 return false;
2963}
2964
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002965namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002966/// Checks whether delete-expression, and new-expression used for
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002967/// initializing deletee have the same array form.
2968class MismatchingNewDeleteDetector {
2969public:
2970 enum MismatchResult {
2971 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2972 NoMismatch,
2973 /// Indicates that variable is initialized with mismatching form of \a new.
2974 VarInitMismatches,
2975 /// Indicates that member is initialized with mismatching form of \a new.
2976 MemberInitMismatches,
2977 /// Indicates that 1 or more constructors' definitions could not been
2978 /// analyzed, and they will be checked again at the end of translation unit.
2979 AnalyzeLater
2980 };
2981
2982 /// \param EndOfTU True, if this is the final analysis at the end of
2983 /// translation unit. False, if this is the initial analysis at the point
2984 /// delete-expression was encountered.
2985 explicit MismatchingNewDeleteDetector(bool EndOfTU)
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00002986 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002987 HasUndefinedConstructors(false) {}
2988
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002989 /// Checks whether pointee of a delete-expression is initialized with
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002990 /// matching form of new-expression.
2991 ///
2992 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2993 /// point where delete-expression is encountered, then a warning will be
2994 /// issued immediately. If return value is \c AnalyzeLater at the point where
2995 /// delete-expression is seen, then member will be analyzed at the end of
2996 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2997 /// couldn't be analyzed. If at least one constructor initializes the member
2998 /// with matching type of new, the return value is \c NoMismatch.
2999 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003000 /// Analyzes a class member.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003001 /// \param Field Class member to analyze.
3002 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3003 /// for deleting the \p Field.
3004 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
Alexander Shaposhnikov3087b2c2016-09-01 23:18:00 +00003005 FieldDecl *Field;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003006 /// List of mismatching new-expressions used for initialization of the pointee
3007 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3008 /// Indicates whether delete-expression was in array form.
3009 bool IsArrayForm;
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003010
3011private:
3012 const bool EndOfTU;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003013 /// Indicates that there is at least one constructor without body.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003014 bool HasUndefinedConstructors;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003015 /// Returns \c CXXNewExpr from given initialization expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003016 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00003017 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003018 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003019 /// Returns whether member is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003020 /// \c new either by the member initializer or in-class initialization.
3021 ///
3022 /// If bodies of all constructors are not visible at the end of translation
3023 /// unit or at least one constructor initializes member with the matching
3024 /// form of \c new, mismatch cannot be proven, and this function will return
3025 /// \c NoMismatch.
3026 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003027 /// Returns whether variable is initialized with mismatching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003028 /// \c new.
3029 ///
3030 /// If variable is initialized with matching form of \c new or variable is not
3031 /// initialized with a \c new expression, this function will return true.
3032 /// If variable is initialized with mismatching form of \c new, returns false.
3033 /// \param D Variable to analyze.
3034 bool hasMatchingVarInit(const DeclRefExpr *D);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003035 /// Checks whether the constructor initializes pointee with mismatching
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003036 /// form of \c new.
3037 ///
3038 /// Returns true, if member is initialized with matching form of \c new in
3039 /// member initializer list. Returns false, if member is initialized with the
3040 /// matching form of \c new in this constructor's initializer or given
3041 /// constructor isn't defined at the point where delete-expression is seen, or
3042 /// member isn't initialized by the constructor.
3043 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003044 /// Checks whether member is initialized with matching form of
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003045 /// \c new in member initializer list.
3046 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3047 /// Checks whether member is initialized with mismatching form of \c new by
3048 /// in-class initializer.
3049 MismatchResult analyzeInClassInitializer();
3050};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003051}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003052
3053MismatchingNewDeleteDetector::MismatchResult
3054MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3055 NewExprs.clear();
3056 assert(DE && "Expected delete-expression");
3057 IsArrayForm = DE->isArrayForm();
3058 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3059 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3060 return analyzeMemberExpr(ME);
3061 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3062 if (!hasMatchingVarInit(D))
3063 return VarInitMismatches;
3064 }
3065 return NoMismatch;
3066}
3067
3068const CXXNewExpr *
3069MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3070 assert(E != nullptr && "Expected a valid initializer expression");
3071 E = E->IgnoreParenImpCasts();
3072 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3073 if (ILE->getNumInits() == 1)
3074 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3075 }
3076
3077 return dyn_cast_or_null<const CXXNewExpr>(E);
3078}
3079
3080bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3081 const CXXCtorInitializer *CI) {
3082 const CXXNewExpr *NE = nullptr;
3083 if (Field == CI->getMember() &&
3084 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3085 if (NE->isArray() == IsArrayForm)
3086 return true;
3087 else
3088 NewExprs.push_back(NE);
3089 }
3090 return false;
3091}
3092
3093bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3094 const CXXConstructorDecl *CD) {
3095 if (CD->isImplicit())
3096 return false;
3097 const FunctionDecl *Definition = CD;
3098 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3099 HasUndefinedConstructors = true;
3100 return EndOfTU;
3101 }
3102 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3103 if (hasMatchingNewInCtorInit(CI))
3104 return true;
3105 }
3106 return false;
3107}
3108
3109MismatchingNewDeleteDetector::MismatchResult
3110MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3111 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00003112 const Expr *InitExpr = Field->getInClassInitializer();
3113 if (!InitExpr)
3114 return EndOfTU ? NoMismatch : AnalyzeLater;
3115 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003116 if (NE->isArray() != IsArrayForm) {
3117 NewExprs.push_back(NE);
3118 return MemberInitMismatches;
3119 }
3120 }
3121 return NoMismatch;
3122}
3123
3124MismatchingNewDeleteDetector::MismatchResult
3125MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3126 bool DeleteWasArrayForm) {
3127 assert(Field != nullptr && "Analysis requires a valid class member.");
3128 this->Field = Field;
3129 IsArrayForm = DeleteWasArrayForm;
3130 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3131 for (const auto *CD : RD->ctors()) {
3132 if (hasMatchingNewInCtor(CD))
3133 return NoMismatch;
3134 }
3135 if (HasUndefinedConstructors)
3136 return EndOfTU ? NoMismatch : AnalyzeLater;
3137 if (!NewExprs.empty())
3138 return MemberInitMismatches;
3139 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3140 : NoMismatch;
3141}
3142
3143MismatchingNewDeleteDetector::MismatchResult
3144MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3145 assert(ME != nullptr && "Expected a member expression");
3146 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3147 return analyzeField(F, IsArrayForm);
3148 return NoMismatch;
3149}
3150
3151bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3152 const CXXNewExpr *NE = nullptr;
3153 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3154 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3155 NE->isArray() != IsArrayForm) {
3156 NewExprs.push_back(NE);
3157 }
3158 }
3159 return NewExprs.empty();
3160}
3161
3162static void
3163DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3164 const MismatchingNewDeleteDetector &Detector) {
3165 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3166 FixItHint H;
3167 if (!Detector.IsArrayForm)
3168 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3169 else {
3170 SourceLocation RSquare = Lexer::findLocationAfterToken(
3171 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3172 SemaRef.getLangOpts(), true);
3173 if (RSquare.isValid())
3174 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3175 }
3176 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3177 << Detector.IsArrayForm << H;
3178
3179 for (const auto *NE : Detector.NewExprs)
3180 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3181 << Detector.IsArrayForm;
3182}
3183
3184void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3185 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3186 return;
3187 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3188 switch (Detector.analyzeDeleteExpr(DE)) {
3189 case MismatchingNewDeleteDetector::VarInitMismatches:
3190 case MismatchingNewDeleteDetector::MemberInitMismatches: {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003191 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003192 break;
3193 }
3194 case MismatchingNewDeleteDetector::AnalyzeLater: {
3195 DeleteExprs[Detector.Field].push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003196 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003197 break;
3198 }
3199 case MismatchingNewDeleteDetector::NoMismatch:
3200 break;
3201 }
3202}
3203
3204void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3205 bool DeleteWasArrayForm) {
3206 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3207 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3208 case MismatchingNewDeleteDetector::VarInitMismatches:
3209 llvm_unreachable("This analysis should have been done for class members.");
3210 case MismatchingNewDeleteDetector::AnalyzeLater:
3211 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3212 "translation unit.");
3213 case MismatchingNewDeleteDetector::MemberInitMismatches:
3214 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3215 break;
3216 case MismatchingNewDeleteDetector::NoMismatch:
3217 break;
3218 }
3219}
3220
Sebastian Redlbd150f42008-11-21 19:14:01 +00003221/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3222/// @code ::delete ptr; @endcode
3223/// or
3224/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00003225ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00003226Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00003227 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003228 // C++ [expr.delete]p1:
3229 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00003230 // non-explicit conversion function to a pointer type. The result has type
3231 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003232 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00003233 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3234
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003235 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00003236 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003237 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00003238 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00003239
John Wiegley01296292011-04-08 18:41:53 +00003240 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00003241 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003242 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00003243 if (Ex.isInvalid())
3244 return ExprError();
John McCallef429022012-03-09 04:08:29 +00003245
John Wiegley01296292011-04-08 18:41:53 +00003246 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00003247
Richard Smithccc11812013-05-21 19:05:48 +00003248 class DeleteConverter : public ContextualImplicitConverter {
3249 public:
3250 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251
Craig Toppere14c0f82014-03-12 04:55:44 +00003252 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00003253 // FIXME: If we have an operator T* and an operator void*, we must pick
3254 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003255 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00003256 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00003257 return true;
3258 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00003259 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003260
Richard Smithccc11812013-05-21 19:05:48 +00003261 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003262 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003263 return S.Diag(Loc, diag::err_delete_operand) << T;
3264 }
3265
3266 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003267 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003268 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3269 }
3270
3271 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003272 QualType T,
3273 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003274 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3275 }
3276
3277 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003278 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003279 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3280 << ConvTy;
3281 }
3282
3283 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003284 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00003285 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3286 }
3287
3288 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00003289 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003290 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3291 << ConvTy;
3292 }
3293
3294 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00003295 QualType T,
3296 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00003297 llvm_unreachable("conversion functions are permitted");
3298 }
3299 } Converter;
3300
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003301 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00003302 if (Ex.isInvalid())
3303 return ExprError();
3304 Type = Ex.get()->getType();
3305 if (!Converter.match(Type))
3306 // FIXME: PerformContextualImplicitConversion should return ExprError
3307 // itself in this case.
3308 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003309
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003310 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003311 QualType PointeeElem = Context.getBaseElementType(Pointee);
3312
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003313 if (Pointee.getAddressSpace() != LangAS::Default &&
3314 !getLangOpts().OpenCLCPlusPlus)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003315 return Diag(Ex.get()->getBeginLoc(),
Eli Friedmanae4280f2011-07-26 22:25:31 +00003316 diag::err_address_space_qualified_delete)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003317 << Pointee.getUnqualifiedType()
3318 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003319
Craig Topperc3ec1492014-05-26 06:22:03 +00003320 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003321 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003322 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00003323 // effectively bans deletion of "void*". However, most compilers support
3324 // this, so we treat it as a warning unless we're in a SFINAE context.
3325 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00003326 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00003327 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00003328 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00003329 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00003330 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003331 // FIXME: This can result in errors if the definition was imported from a
3332 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00003333 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003334 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00003335 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3336 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3337 }
3338 }
3339
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003340 if (Pointee->isArrayType() && !ArrayForm) {
3341 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00003342 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00003343 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00003344 ArrayForm = true;
3345 }
3346
Anders Carlssona471db02009-08-16 20:29:29 +00003347 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3348 ArrayForm ? OO_Array_Delete : OO_Delete);
3349
Eli Friedmanae4280f2011-07-26 22:25:31 +00003350 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003351 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00003352 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3353 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00003354 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355
John McCall284c48f2011-01-27 09:37:56 +00003356 // If we're allocating an array of records, check whether the
3357 // usual operator delete[] has a size_t parameter.
3358 if (ArrayForm) {
3359 // If the user specifically asked to use the global allocator,
3360 // we'll need to do the lookup into the class.
3361 if (UseGlobal)
3362 UsualArrayDeleteWantsSize =
3363 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3364
3365 // Otherwise, the usual operator delete[] should be the
3366 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00003367 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
Richard Smithb2f0f052016-10-10 18:54:32 +00003368 UsualArrayDeleteWantsSize =
Richard Smithf75dcbe2016-10-11 00:21:10 +00003369 UsualDeallocFnInfo(*this,
3370 DeclAccessPair::make(OperatorDelete, AS_public))
3371 .HasSizeT;
John McCall284c48f2011-01-27 09:37:56 +00003372 }
3373
Richard Smitheec915d62012-02-18 04:13:32 +00003374 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00003375 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00003376 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00003377 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00003378 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3379 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00003380 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00003381
Nico Weber5a9259c2016-01-15 21:45:31 +00003382 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3383 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3384 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3385 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00003386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387
Richard Smithb2f0f052016-10-10 18:54:32 +00003388 if (!OperatorDelete) {
Sven van Haastregte6e76fd2018-06-14 09:51:54 +00003389 if (getLangOpts().OpenCLCPlusPlus) {
3390 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3391 return ExprError();
3392 }
3393
Richard Smithb2f0f052016-10-10 18:54:32 +00003394 bool IsComplete = isCompleteType(StartLoc, Pointee);
3395 bool CanProvideSize =
3396 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3397 Pointee.isDestructedType());
3398 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3399
Anders Carlssone1d34ba02009-11-15 18:45:20 +00003400 // Look for a global declaration.
Richard Smithb2f0f052016-10-10 18:54:32 +00003401 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3402 Overaligned, DeleteName);
3403 }
Mike Stump11289f42009-09-09 15:08:12 +00003404
Eli Friedmanfa0df832012-02-02 03:46:19 +00003405 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003406
Richard Smith5b349582017-10-13 01:55:36 +00003407 // Check access and ambiguity of destructor if we're going to call it.
3408 // Note that this is required even for a virtual delete.
3409 bool IsVirtualDelete = false;
Eli Friedmanae4280f2011-07-26 22:25:31 +00003410 if (PointeeRD) {
3411 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Richard Smith5b349582017-10-13 01:55:36 +00003412 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3413 PDiag(diag::err_access_dtor) << PointeeElem);
3414 IsVirtualDelete = Dtor->isVirtual();
Douglas Gregorfa778132011-02-01 15:50:11 +00003415 }
3416 }
Akira Hatanakacae83f72017-06-29 18:48:40 +00003417
Akira Hatanaka71645c22018-12-21 07:05:36 +00003418 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
Richard Smith5b349582017-10-13 01:55:36 +00003419
3420 // Convert the operand to the type of the first parameter of operator
3421 // delete. This is only necessary if we selected a destroying operator
3422 // delete that we are going to call (non-virtually); converting to void*
3423 // is trivial and left to AST consumers to handle.
3424 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3425 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
Richard Smith25172012017-12-05 23:54:25 +00003426 Qualifiers Qs = Pointee.getQualifiers();
3427 if (Qs.hasCVRQualifiers()) {
3428 // Qualifiers are irrelevant to this conversion; we're only looking
3429 // for access and ambiguity.
3430 Qs.removeCVRQualifiers();
3431 QualType Unqual = Context.getPointerType(
3432 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3433 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3434 }
Richard Smith5b349582017-10-13 01:55:36 +00003435 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3436 if (Ex.isInvalid())
3437 return ExprError();
3438 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00003439 }
3440
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003441 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003442 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3443 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00003444 AnalyzeDeleteExprMismatch(Result);
3445 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00003446}
3447
Eric Fiselierfa752f22018-03-21 19:19:48 +00003448static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3449 bool IsDelete,
3450 FunctionDecl *&Operator) {
3451
3452 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3453 IsDelete ? OO_Delete : OO_New);
3454
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003455 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
Eric Fiselierfa752f22018-03-21 19:19:48 +00003456 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3457 assert(!R.empty() && "implicitly declared allocation functions not found");
3458 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3459
3460 // We do our own custom access checks below.
3461 R.suppressDiagnostics();
3462
3463 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3464 OverloadCandidateSet Candidates(R.getNameLoc(),
3465 OverloadCandidateSet::CSK_Normal);
3466 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3467 FnOvl != FnOvlEnd; ++FnOvl) {
3468 // Even member operator new/delete are implicitly treated as
3469 // static, so don't use AddMemberCandidate.
3470 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3471
3472 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3473 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3474 /*ExplicitTemplateArgs=*/nullptr, Args,
3475 Candidates,
3476 /*SuppressUserConversions=*/false);
3477 continue;
3478 }
3479
3480 FunctionDecl *Fn = cast<FunctionDecl>(D);
3481 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3482 /*SuppressUserConversions=*/false);
3483 }
3484
3485 SourceRange Range = TheCall->getSourceRange();
3486
3487 // Do the resolution.
3488 OverloadCandidateSet::iterator Best;
3489 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3490 case OR_Success: {
3491 // Got one!
3492 FunctionDecl *FnDecl = Best->Function;
3493 assert(R.getNamingClass() == nullptr &&
3494 "class members should not be considered");
3495
3496 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3497 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3498 << (IsDelete ? 1 : 0) << Range;
3499 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3500 << R.getLookupName() << FnDecl->getSourceRange();
3501 return true;
3502 }
3503
3504 Operator = FnDecl;
3505 return false;
3506 }
3507
3508 case OR_No_Viable_Function:
3509 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3510 << R.getLookupName() << Range;
3511 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3512 return true;
3513
3514 case OR_Ambiguous:
3515 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3516 << R.getLookupName() << Range;
3517 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3518 return true;
3519
3520 case OR_Deleted: {
3521 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3522 << Best->Function->isDeleted() << R.getLookupName()
3523 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3524 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3525 return true;
3526 }
3527 }
3528 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3529}
3530
3531ExprResult
3532Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3533 bool IsDelete) {
3534 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3535 if (!getLangOpts().CPlusPlus) {
3536 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3537 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3538 << "C++";
3539 return ExprError();
3540 }
3541 // CodeGen assumes it can find the global new and delete to call,
3542 // so ensure that they are declared.
3543 DeclareGlobalNewDelete();
3544
3545 FunctionDecl *OperatorNewOrDelete = nullptr;
3546 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3547 OperatorNewOrDelete))
3548 return ExprError();
3549 assert(OperatorNewOrDelete && "should be found");
3550
Akira Hatanaka71645c22018-12-21 07:05:36 +00003551 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3552 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3553
Eric Fiselierfa752f22018-03-21 19:19:48 +00003554 TheCall->setType(OperatorNewOrDelete->getReturnType());
3555 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3556 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3557 InitializedEntity Entity =
3558 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3559 ExprResult Arg = PerformCopyInitialization(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003560 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
Eric Fiselierfa752f22018-03-21 19:19:48 +00003561 if (Arg.isInvalid())
3562 return ExprError();
3563 TheCall->setArg(i, Arg.get());
3564 }
3565 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3566 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3567 "Callee expected to be implicit cast to a builtin function pointer");
3568 Callee->setType(OperatorNewOrDelete->getType());
3569
3570 return TheCallResult;
3571}
3572
Nico Weber5a9259c2016-01-15 21:45:31 +00003573void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3574 bool IsDelete, bool CallCanBeVirtual,
3575 bool WarnOnNonAbstractTypes,
3576 SourceLocation DtorLoc) {
Nico Weber955bb842017-08-30 20:25:22 +00003577 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
Nico Weber5a9259c2016-01-15 21:45:31 +00003578 return;
3579
3580 // C++ [expr.delete]p3:
3581 // In the first alternative (delete object), if the static type of the
3582 // object to be deleted is different from its dynamic type, the static
3583 // type shall be a base class of the dynamic type of the object to be
3584 // deleted and the static type shall have a virtual destructor or the
3585 // behavior is undefined.
3586 //
3587 const CXXRecordDecl *PointeeRD = dtor->getParent();
3588 // Note: a final class cannot be derived from, no issue there
3589 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3590 return;
3591
Nico Weberbf2260c2017-08-31 06:17:08 +00003592 // If the superclass is in a system header, there's nothing that can be done.
3593 // The `delete` (where we emit the warning) can be in a system header,
3594 // what matters for this warning is where the deleted type is defined.
3595 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3596 return;
3597
Brian Gesiak5488ab42019-01-11 01:54:53 +00003598 QualType ClassType = dtor->getThisType()->getPointeeType();
Nico Weber5a9259c2016-01-15 21:45:31 +00003599 if (PointeeRD->isAbstract()) {
3600 // If the class is abstract, we warn by default, because we're
3601 // sure the code has undefined behavior.
3602 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3603 << ClassType;
3604 } else if (WarnOnNonAbstractTypes) {
3605 // Otherwise, if this is not an array delete, it's a bit suspect,
3606 // but not necessarily wrong.
3607 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3608 << ClassType;
3609 }
3610 if (!IsDelete) {
3611 std::string TypeStr;
3612 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3613 Diag(DtorLoc, diag::note_delete_non_virtual)
3614 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3615 }
3616}
3617
Richard Smith03a4aa32016-06-23 19:02:52 +00003618Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3619 SourceLocation StmtLoc,
3620 ConditionKind CK) {
3621 ExprResult E =
3622 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3623 if (E.isInvalid())
3624 return ConditionError();
Richard Smithb130fe72016-06-23 19:16:49 +00003625 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3626 CK == ConditionKind::ConstexprIf);
Richard Smith03a4aa32016-06-23 19:02:52 +00003627}
3628
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003629/// Check the use of the given variable as a C++ condition in an if,
Douglas Gregor633caca2009-11-23 23:44:04 +00003630/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00003631ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00003632 SourceLocation StmtLoc,
Richard Smith03a4aa32016-06-23 19:02:52 +00003633 ConditionKind CK) {
Richard Smith27d807c2013-04-30 13:56:41 +00003634 if (ConditionVar->isInvalidDecl())
3635 return ExprError();
3636
Douglas Gregor633caca2009-11-23 23:44:04 +00003637 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638
Douglas Gregor633caca2009-11-23 23:44:04 +00003639 // C++ [stmt.select]p2:
3640 // The declarator shall not specify a function or an array.
3641 if (T->isFunctionType())
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_function_type)
3644 << ConditionVar->getSourceRange());
3645 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00003647 diag::err_invalid_use_of_array_type)
3648 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00003649
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003650 ExprResult Condition = DeclRefExpr::Create(
3651 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3652 /*enclosing*/ false, ConditionVar->getLocation(),
3653 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00003654
Eli Friedmanfa0df832012-02-02 03:46:19 +00003655 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00003656
Richard Smith03a4aa32016-06-23 19:02:52 +00003657 switch (CK) {
3658 case ConditionKind::Boolean:
3659 return CheckBooleanCondition(StmtLoc, Condition.get());
3660
Richard Smithb130fe72016-06-23 19:16:49 +00003661 case ConditionKind::ConstexprIf:
3662 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3663
Richard Smith03a4aa32016-06-23 19:02:52 +00003664 case ConditionKind::Switch:
3665 return CheckSwitchCondition(StmtLoc, Condition.get());
John Wiegley01296292011-04-08 18:41:53 +00003666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
Richard Smith03a4aa32016-06-23 19:02:52 +00003668 llvm_unreachable("unexpected condition kind");
Douglas Gregor633caca2009-11-23 23:44:04 +00003669}
3670
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003671/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
Richard Smithb130fe72016-06-23 19:16:49 +00003672ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003673 // C++ 6.4p4:
3674 // The value of a condition that is an initialized declaration in a statement
3675 // other than a switch statement is the value of the declared variable
3676 // implicitly converted to type bool. If that conversion is ill-formed, the
3677 // program is ill-formed.
3678 // The value of a condition that is an expression is the value of the
3679 // expression, implicitly converted to bool.
3680 //
Richard Smithb130fe72016-06-23 19:16:49 +00003681 // FIXME: Return this value to the caller so they don't need to recompute it.
3682 llvm::APSInt Value(/*BitWidth*/1);
3683 return (IsConstexpr && !CondExpr->isValueDependent())
3684 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3685 CCEK_ConstexprIf)
3686 : PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00003687}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003688
3689/// Helper function to determine whether this is the (deprecated) C++
3690/// conversion from a string literal to a pointer to non-const char or
3691/// non-const wchar_t (for narrow and wide string literals,
3692/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00003693bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003694Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3695 // Look inside the implicit cast, if it exists.
3696 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3697 From = Cast->getSubExpr();
3698
3699 // A string literal (2.13.4) that is not a wide string literal can
3700 // be converted to an rvalue of type "pointer to char"; a wide
3701 // string literal can be converted to an rvalue of type "pointer
3702 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00003703 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003704 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00003705 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00003706 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003707 // This conversion is considered only when there is an
3708 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003709 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3710 switch (StrLit->getKind()) {
3711 case StringLiteral::UTF8:
3712 case StringLiteral::UTF16:
3713 case StringLiteral::UTF32:
3714 // We don't allow UTF literals to be implicitly converted
3715 break;
3716 case StringLiteral::Ascii:
3717 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3718 ToPointeeType->getKind() == BuiltinType::Char_S);
3719 case StringLiteral::Wide:
Dmitry Polukhin9d64f722016-04-14 09:52:06 +00003720 return Context.typesAreCompatible(Context.getWideCharType(),
3721 QualType(ToPointeeType, 0));
Douglas Gregorfb65e592011-07-27 05:40:30 +00003722 }
3723 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003724 }
3725
3726 return false;
3727}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003728
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003730 SourceLocation CastLoc,
3731 QualType Ty,
3732 CastKind Kind,
3733 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003734 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003735 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003736 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003737 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003738 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003739 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003740 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003741 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Richard Smith72d74052013-07-20 19:41:36 +00003743 if (S.RequireNonAbstractType(CastLoc, Ty,
3744 diag::err_allocation_of_abstract_type))
3745 return ExprError();
3746
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003747 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003748 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
Richard Smith5179eb72016-06-28 19:03:57 +00003750 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3751 InitializedEntity::InitializeTemporary(Ty));
Richard Smith7c9442a2015-02-24 21:44:43 +00003752 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003753 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003754
Richard Smithf8adcdc2014-07-17 05:12:35 +00003755 ExprResult Result = S.BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003756 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003757 ConstructorArgs, HadMultipleCandidates,
3758 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3759 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003760 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003761 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003762
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003763 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003764 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003765
John McCalle3027922010-08-25 11:45:40 +00003766 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003767 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768
Richard Smithd3f2d322015-02-24 21:16:19 +00003769 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003770 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003771 return ExprError();
3772
Douglas Gregora4253922010-04-16 22:17:36 +00003773 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003774 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3775 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003776 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003777 if (Result.isInvalid())
3778 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003779 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003780 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3781 CK_UserDefinedConversion, Result.get(),
3782 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003783
Douglas Gregor668443e2011-01-20 00:18:04 +00003784 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003785 }
3786 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003787}
Douglas Gregora4253922010-04-16 22:17:36 +00003788
Douglas Gregor5fb53972009-01-14 15:45:31 +00003789/// PerformImplicitConversion - Perform an implicit conversion of the
3790/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003791/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003792/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003793/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003794ExprResult
3795Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003796 const ImplicitConversionSequence &ICS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003797 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003798 CheckedConversionKind CCK) {
Richard Smith1ef75542018-06-27 20:30:34 +00003799 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3800 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3801 return From;
3802
John McCall0d1da222010-01-12 00:44:57 +00003803 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003804 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003805 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3806 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003807 if (Res.isInvalid())
3808 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003809 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003810 break;
John Wiegley01296292011-04-08 18:41:53 +00003811 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003812
Anders Carlsson110b07b2009-09-15 06:28:28 +00003813 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003815 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003816 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003817 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003818 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003819 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003820 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003821
Anders Carlsson110b07b2009-09-15 06:28:28 +00003822 // If the user-defined conversion is specified by a conversion function,
3823 // the initial standard conversion sequence converts the source type to
3824 // the implicit object parameter of the conversion function.
3825 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003826 } else {
3827 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003828 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003829 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003830 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003831 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003832 // initial standard conversion sequence converts the source type to
3833 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003834 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836 }
Richard Smith72d74052013-07-20 19:41:36 +00003837 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003838 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003839 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003840 PerformImplicitConversion(From, BeforeToType,
3841 ICS.UserDefined.Before, AA_Converting,
3842 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003843 if (Res.isInvalid())
3844 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003845 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003847
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003848 ExprResult CastArg = BuildCXXCastArgument(
3849 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3850 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3851 ICS.UserDefined.HadMultipleCandidates, From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003852
3853 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003854 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003855
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003856 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003857
Richard Smith1ef75542018-06-27 20:30:34 +00003858 // C++ [over.match.oper]p7:
3859 // [...] the second standard conversion sequence of a user-defined
3860 // conversion sequence is not applied.
3861 if (CCK == CCK_ForBuiltinOverloadedOp)
3862 return From;
3863
Richard Smith507840d2011-11-29 22:48:16 +00003864 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3865 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003866 }
John McCall0d1da222010-01-12 00:44:57 +00003867
3868 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003869 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003870 PDiag(diag::err_typecheck_ambiguous_condition)
3871 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003872 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003873
Douglas Gregor39c16d42008-10-24 04:54:22 +00003874 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003875 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003876
3877 case ImplicitConversionSequence::BadConversion:
Richard Smithe15a3702016-10-06 23:12:58 +00003878 bool Diagnosed =
3879 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3880 From->getType(), From, Action);
3881 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
John Wiegley01296292011-04-08 18:41:53 +00003882 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003883 }
3884
3885 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003886 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003887}
3888
Richard Smith507840d2011-11-29 22:48:16 +00003889/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003890/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003891/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003892/// expression. Flavor is the context in which we're performing this
3893/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003894ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003895Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003896 const StandardConversionSequence& SCS,
Simon Pilgrim75c26882016-09-30 14:25:09 +00003897 AssignmentAction Action,
John McCall31168b02011-06-15 23:02:42 +00003898 CheckedConversionKind CCK) {
3899 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003900
Mike Stump87c57ac2009-05-16 07:39:55 +00003901 // Overall FIXME: we are recomputing too many types here and doing far too
3902 // much extra work. What this means is that we need to keep track of more
3903 // information that is computed when we try the implicit conversion initially,
3904 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003905 QualType FromType = From->getType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00003906
Douglas Gregor2fe98832008-11-03 19:09:14 +00003907 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003908 // FIXME: When can ToType be a reference type?
3909 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003910 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003911 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003912 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003913 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003914 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003915 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003916 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003917 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3918 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003919 ConstructorArgs, /*HadMultipleCandidates*/ false,
3920 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3921 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003922 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003923 return BuildCXXConstructExpr(
Richard Smithc2bebe92016-05-11 20:37:46 +00003924 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3925 SCS.FoundCopyConstructor, SCS.CopyConstructor,
Richard Smithf8adcdc2014-07-17 05:12:35 +00003926 From, /*HadMultipleCandidates*/ false,
3927 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3928 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003929 }
3930
Douglas Gregor980fb162010-04-29 18:24:40 +00003931 // Resolve overloaded function references.
3932 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3933 DeclAccessPair Found;
3934 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3935 true, Found);
3936 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003937 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003938
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003939 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
John Wiegley01296292011-04-08 18:41:53 +00003940 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003941
Douglas Gregor980fb162010-04-29 18:24:40 +00003942 From = FixOverloadedFunctionReference(From, Found, Fn);
3943 FromType = From->getType();
3944 }
3945
Richard Smitha23ab512013-05-23 00:30:41 +00003946 // If we're converting to an atomic type, first convert to the corresponding
3947 // non-atomic type.
3948 QualType ToAtomicType;
3949 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3950 ToAtomicType = ToType;
3951 ToType = ToAtomic->getValueType();
3952 }
3953
George Burgess IV8d141e02015-12-14 22:00:49 +00003954 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003955 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003956 switch (SCS.First) {
3957 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003958 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3959 FromType = FromAtomic->getValueType().getUnqualifiedType();
3960 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3961 From, /*BasePath=*/nullptr, VK_RValue);
3962 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003963 break;
3964
Eli Friedman946b7b52012-01-24 22:51:26 +00003965 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003966 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003967 ExprResult FromRes = DefaultLvalueConversion(From);
3968 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003969 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003970 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003971 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003972 }
John McCall34376a62010-12-04 03:47:34 +00003973
Douglas Gregor39c16d42008-10-24 04:54:22 +00003974 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003975 FromType = Context.getArrayDecayedType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003976 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003977 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003978 break;
3979
3980 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003981 FromType = Context.getPointerType(FromType);
Simon Pilgrim75c26882016-09-30 14:25:09 +00003982 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003983 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003984 break;
3985
3986 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003987 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003988 }
3989
Richard Smith507840d2011-11-29 22:48:16 +00003990 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003991 switch (SCS.Second) {
3992 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003993 // C++ [except.spec]p5:
3994 // [For] assignment to and initialization of pointers to functions,
3995 // pointers to member functions, and references to functions: the
3996 // target entity shall allow at least the exceptions allowed by the
3997 // source value in the assignment or initialization.
3998 switch (Action) {
3999 case AA_Assigning:
4000 case AA_Initializing:
4001 // Note, function argument passing and returning are initialization.
4002 case AA_Passing:
4003 case AA_Returning:
4004 case AA_Sending:
4005 case AA_Passing_CFAudited:
4006 if (CheckExceptionSpecCompatibility(From, ToType))
4007 return ExprError();
4008 break;
4009
4010 case AA_Casting:
4011 case AA_Converting:
4012 // Casts and implicit conversions are not initialization, so are not
4013 // checked for exception specification mismatches.
4014 break;
4015 }
Sebastian Redl5d431642009-10-10 12:04:10 +00004016 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00004017 break;
4018
4019 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004020 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00004021 if (ToType->isBooleanType()) {
4022 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4023 SCS.Second == ICK_Integral_Promotion &&
4024 "only enums with fixed underlying type can promote to bool");
4025 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004026 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004027 } else {
4028 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004029 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00004030 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004031 break;
4032
4033 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00004034 case ICK_Floating_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004035 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004036 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004037 break;
4038
4039 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00004040 case ICK_Complex_Conversion: {
4041 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4042 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4043 CastKind CK;
4044 if (FromEl->isRealFloatingType()) {
4045 if (ToEl->isRealFloatingType())
4046 CK = CK_FloatingComplexCast;
4047 else
4048 CK = CK_FloatingComplexToIntegralComplex;
4049 } else if (ToEl->isRealFloatingType()) {
4050 CK = CK_IntegralComplexToFloatingComplex;
4051 } else {
4052 CK = CK_IntegralComplexCast;
4053 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004054 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004055 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004056 break;
John McCall8cb679e2010-11-15 09:13:47 +00004057 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00004058
Douglas Gregor39c16d42008-10-24 04:54:22 +00004059 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00004060 if (ToType->isRealFloatingType())
Simon Pilgrim75c26882016-09-30 14:25:09 +00004061 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004062 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004063 else
Simon Pilgrim75c26882016-09-30 14:25:09 +00004064 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004065 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004066 break;
4067
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00004068 case ICK_Compatible_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004069 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004070 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004071 break;
4072
John McCall31168b02011-06-15 23:02:42 +00004073 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004074 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00004075 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00004076 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00004077 if (Action == AA_Initializing || Action == AA_Assigning)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004078 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004079 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004080 << ToType << From->getType() << Action << From->getSourceRange()
4081 << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004082 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004083 Diag(From->getBeginLoc(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00004084 diag::ext_typecheck_convert_incompatible_pointer)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004085 << From->getType() << ToType << Action << From->getSourceRange()
4086 << 0;
John McCall31168b02011-06-15 23:02:42 +00004087
Douglas Gregor33823722011-06-11 01:09:30 +00004088 if (From->getType()->isObjCObjectPointerType() &&
4089 ToType->isObjCObjectPointerType())
4090 EmitRelatedResultTypeNote(From);
Brian Kelley11352a82017-03-29 18:09:02 +00004091 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4092 !CheckObjCARCUnavailableWeakConversion(ToType,
4093 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00004094 if (Action == AA_Initializing)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004095 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
John McCall9c3467e2011-09-09 06:12:06 +00004096 else
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004097 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4098 << (Action == AA_Casting) << From->getType() << ToType
4099 << From->getSourceRange();
John McCall9c3467e2011-09-09 06:12:06 +00004100 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004101
Richard Smith354abec2017-12-08 23:29:59 +00004102 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004103 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004104 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004105 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00004106
4107 // Make sure we extend blocks if necessary.
4108 // FIXME: doing this here is really ugly.
4109 if (Kind == CK_BlockPointerToObjCPointerCast) {
4110 ExprResult E = From;
4111 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004112 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00004113 }
Brian Kelley11352a82017-03-29 18:09:02 +00004114 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4115 CheckObjCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00004116 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004117 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004118 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004120
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004121 case ICK_Pointer_Member: {
Richard Smith354abec2017-12-08 23:29:59 +00004122 CastKind Kind;
John McCallcf142162010-08-07 06:22:56 +00004123 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00004124 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004125 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00004126 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00004127 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00004128
4129 // We may not have been able to figure out what this member pointer resolved
4130 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00004131 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00004132 (void)isCompleteType(From->getExprLoc(), From->getType());
4133 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00004134 }
David Majnemerd96b9972014-08-08 00:10:39 +00004135
Richard Smith507840d2011-11-29 22:48:16 +00004136 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004137 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00004138 break;
4139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004140
Abramo Bagnara7ccce982011-04-07 09:26:19 +00004141 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004142 // Perform half-to-boolean conversion via float.
4143 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004144 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00004145 FromType = Context.FloatTy;
4146 }
4147
Richard Smith507840d2011-11-29 22:48:16 +00004148 From = ImpCastExprToType(From, Context.BoolTy,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004149 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004150 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00004151 break;
4152
Douglas Gregor88d292c2010-05-13 16:44:06 +00004153 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00004154 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004155 if (CheckDerivedToBaseConversion(
4156 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4157 From->getSourceRange(), &BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00004158 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00004159
Richard Smith507840d2011-11-29 22:48:16 +00004160 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4161 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004162 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00004163 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00004164 }
4165
Douglas Gregor46188682010-05-18 22:42:18 +00004166 case ICK_Vector_Conversion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00004167 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004168 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004169 break;
4170
George Burgess IVdf1ed002016-01-13 01:52:39 +00004171 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00004172 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00004173 Expr *Elem = prepareVectorSplat(ToType, From).get();
4174 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4175 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00004176 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00004177 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178
Douglas Gregor46188682010-05-18 22:42:18 +00004179 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00004180 // Case 1. x -> _Complex y
4181 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4182 QualType ElType = ToComplex->getElementType();
4183 bool isFloatingComplex = ElType->isRealFloatingType();
4184
4185 // x -> y
4186 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4187 // do nothing
4188 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004189 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004190 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00004191 } else {
4192 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004193 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004194 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00004195 }
4196 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00004197 From = ImpCastExprToType(From, ToType,
4198 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004199 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00004200
4201 // Case 2. _Complex x -> y
4202 } else {
4203 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4204 assert(FromComplex);
4205
4206 QualType ElType = FromComplex->getElementType();
4207 bool isFloatingComplex = ElType->isRealFloatingType();
4208
4209 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00004210 From = ImpCastExprToType(From, ElType,
4211 isFloatingComplex ? CK_FloatingComplexToReal
Simon Pilgrim75c26882016-09-30 14:25:09 +00004212 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004213 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004214
4215 // x -> y
4216 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4217 // do nothing
4218 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00004219 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004220 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004221 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004222 } else {
4223 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00004224 From = ImpCastExprToType(From, ToType,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004225 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004226 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00004227 }
4228 }
Douglas Gregor46188682010-05-18 22:42:18 +00004229 break;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004230
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00004231 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00004232 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004233 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00004234 break;
4235 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004236
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004237 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004238 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004239 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00004240 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4241 if (FromRes.isInvalid())
4242 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004243 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00004244 assert ((ConvTy == Sema::Compatible) &&
4245 "Improper transparent union conversion");
4246 (void)ConvTy;
4247 break;
4248 }
4249
Guy Benyei259f9f42013-02-07 16:05:33 +00004250 case ICK_Zero_Event_Conversion:
Egor Churaev89831422016-12-23 14:55:49 +00004251 case ICK_Zero_Queue_Conversion:
4252 From = ImpCastExprToType(From, ToType,
Andrew Savonichevb555b762018-10-23 15:19:20 +00004253 CK_ZeroToOCLOpaqueType,
Egor Churaev89831422016-12-23 14:55:49 +00004254 From->getValueKind()).get();
4255 break;
4256
Douglas Gregor46188682010-05-18 22:42:18 +00004257 case ICK_Lvalue_To_Rvalue:
4258 case ICK_Array_To_Pointer:
4259 case ICK_Function_To_Pointer:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004260 case ICK_Function_Conversion:
Douglas Gregor46188682010-05-18 22:42:18 +00004261 case ICK_Qualification:
4262 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00004263 case ICK_C_Only_Conversion:
George Burgess IV2099b542016-09-02 22:59:57 +00004264 case ICK_Incompatible_Pointer_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00004265 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004266 }
4267
4268 switch (SCS.Third) {
4269 case ICK_Identity:
4270 // Nothing to do.
4271 break;
4272
Richard Smitheb7ef2e2016-10-20 21:53:09 +00004273 case ICK_Function_Conversion:
4274 // If both sides are functions (or pointers/references to them), there could
4275 // be incompatible exception declarations.
4276 if (CheckExceptionSpecCompatibility(From, ToType))
4277 return ExprError();
4278
4279 From = ImpCastExprToType(From, ToType, CK_NoOp,
4280 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4281 break;
4282
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004283 case ICK_Qualification: {
4284 // The qualification keeps the category of the inner expression, unless the
4285 // target type isn't a reference.
Anastasia Stulova04307942018-11-16 16:22:56 +00004286 ExprValueKind VK =
4287 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4288
4289 CastKind CK = CK_NoOp;
4290
4291 if (ToType->isReferenceType() &&
4292 ToType->getPointeeType().getAddressSpace() !=
4293 From->getType().getAddressSpace())
4294 CK = CK_AddressSpaceConversion;
4295
4296 if (ToType->isPointerType() &&
4297 ToType->getPointeeType().getAddressSpace() !=
4298 From->getType()->getPointeeType().getAddressSpace())
4299 CK = CK_AddressSpaceConversion;
4300
4301 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4302 /*BasePath=*/nullptr, CCK)
4303 .get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00004304
Douglas Gregore981bb02011-03-14 16:13:32 +00004305 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004306 !getLangOpts().WritableStrings) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004307 Diag(From->getBeginLoc(),
4308 getLangOpts().CPlusPlus11
4309 ? diag::ext_deprecated_string_literal_conversion
4310 : diag::warn_deprecated_string_literal_conversion)
4311 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004312 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00004313
Douglas Gregor39c16d42008-10-24 04:54:22 +00004314 break;
Richard Smitha23ab512013-05-23 00:30:41 +00004315 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00004316
Douglas Gregor39c16d42008-10-24 04:54:22 +00004317 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004318 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00004319 }
4320
Douglas Gregor298f43d2012-04-12 20:42:30 +00004321 // If this conversion sequence involved a scalar -> atomic conversion, perform
4322 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00004323 if (!ToAtomicType.isNull()) {
4324 assert(Context.hasSameType(
4325 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4326 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004327 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00004328 }
4329
George Burgess IV8d141e02015-12-14 22:00:49 +00004330 // If this conversion sequence succeeded and involved implicitly converting a
4331 // _Nullable type to a _Nonnull one, complain.
Richard Smith1ef75542018-06-27 20:30:34 +00004332 if (!isCast(CCK))
George Burgess IV8d141e02015-12-14 22:00:49 +00004333 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004334 From->getBeginLoc());
George Burgess IV8d141e02015-12-14 22:00:49 +00004335
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004336 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00004337}
4338
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004339/// Check the completeness of a type in a unary type trait.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004340///
4341/// If the particular type trait requires a complete type, tries to complete
4342/// it. If completing the type fails, a diagnostic is emitted and false
4343/// returned. If completing the type succeeds or no completion was required,
4344/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00004345static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004346 SourceLocation Loc,
4347 QualType ArgTy) {
4348 // C++0x [meta.unary.prop]p3:
4349 // For all of the class templates X declared in this Clause, instantiating
4350 // that template with a template argument that is a class template
4351 // specialization may result in the implicit instantiation of the template
4352 // argument if and only if the semantics of X require that the argument
4353 // must be a complete type.
4354 // We apply this rule to all the type trait expressions used to implement
4355 // these class templates. We also try to follow any GCC documented behavior
4356 // in these expressions to ensure portability of standard libraries.
4357 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004358 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00004359 // is_complete_type somewhat obviously cannot require a complete type.
4360 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004361 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004362
4363 // These traits are modeled on the type predicates in C++0x
4364 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4365 // requiring a complete type, as whether or not they return true cannot be
4366 // impacted by the completeness of the type.
4367 case UTT_IsVoid:
4368 case UTT_IsIntegral:
4369 case UTT_IsFloatingPoint:
4370 case UTT_IsArray:
4371 case UTT_IsPointer:
4372 case UTT_IsLvalueReference:
4373 case UTT_IsRvalueReference:
4374 case UTT_IsMemberFunctionPointer:
4375 case UTT_IsMemberObjectPointer:
4376 case UTT_IsEnum:
4377 case UTT_IsUnion:
4378 case UTT_IsClass:
4379 case UTT_IsFunction:
4380 case UTT_IsReference:
4381 case UTT_IsArithmetic:
4382 case UTT_IsFundamental:
4383 case UTT_IsObject:
4384 case UTT_IsScalar:
4385 case UTT_IsCompound:
4386 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00004387 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00004388
4389 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4390 // which requires some of its traits to have the complete type. However,
4391 // the completeness of the type cannot impact these traits' semantics, and
4392 // so they don't require it. This matches the comments on these traits in
4393 // Table 49.
4394 case UTT_IsConst:
4395 case UTT_IsVolatile:
4396 case UTT_IsSigned:
4397 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00004398
4399 // This type trait always returns false, checking the type is moot.
4400 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004401 return true;
4402
David Majnemer213bea32015-11-16 06:58:51 +00004403 // C++14 [meta.unary.prop]:
4404 // If T is a non-union class type, T shall be a complete type.
4405 case UTT_IsEmpty:
4406 case UTT_IsPolymorphic:
4407 case UTT_IsAbstract:
4408 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4409 if (!RD->isUnion())
4410 return !S.RequireCompleteType(
4411 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4412 return true;
4413
4414 // C++14 [meta.unary.prop]:
4415 // If T is a class type, T shall be a complete type.
4416 case UTT_IsFinal:
4417 case UTT_IsSealed:
4418 if (ArgTy->getAsCXXRecordDecl())
4419 return !S.RequireCompleteType(
4420 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4421 return true;
4422
Richard Smithf03e9082017-06-01 00:28:16 +00004423 // C++1z [meta.unary.prop]:
4424 // remove_all_extents_t<T> shall be a complete type or cv void.
Eric Fiselier07360662017-04-12 22:12:15 +00004425 case UTT_IsAggregate:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004426 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004427 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004428 case UTT_IsStandardLayout:
4429 case UTT_IsPOD:
4430 case UTT_IsLiteral:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004431 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4432 // or an array of unknown bound. But GCC actually imposes the same constraints
4433 // as above.
Chandler Carruth8e172c62011-05-01 06:51:22 +00004434 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004435 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004436 case UTT_HasNothrowConstructor:
4437 case UTT_HasNothrowCopy:
4438 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004439 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00004440 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004441 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00004442 case UTT_HasTrivialCopy:
4443 case UTT_HasTrivialDestructor:
4444 case UTT_HasVirtualDestructor:
Karthik Bhate1ae1b22017-06-28 08:52:08 +00004445 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4446 LLVM_FALLTHROUGH;
4447
4448 // C++1z [meta.unary.prop]:
4449 // T shall be a complete type, cv void, or an array of unknown bound.
4450 case UTT_IsDestructible:
4451 case UTT_IsNothrowDestructible:
4452 case UTT_IsTriviallyDestructible:
Erich Keanee63e9d72017-10-24 21:31:50 +00004453 case UTT_HasUniqueObjectRepresentations:
Richard Smithf03e9082017-06-01 00:28:16 +00004454 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00004455 return true;
4456
4457 return !S.RequireCompleteType(
Richard Smithf03e9082017-06-01 00:28:16 +00004458 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00004459 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00004460}
4461
Joao Matosc9523d42013-03-27 01:34:16 +00004462static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4463 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
Simon Pilgrim75c26882016-09-30 14:25:09 +00004464 bool (CXXRecordDecl::*HasTrivial)() const,
4465 bool (CXXRecordDecl::*HasNonTrivial)() const,
Joao Matosc9523d42013-03-27 01:34:16 +00004466 bool (CXXMethodDecl::*IsDesiredOp)() const)
4467{
4468 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4469 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4470 return true;
4471
4472 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4473 DeclarationNameInfo NameInfo(Name, KeyLoc);
4474 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4475 if (Self.LookupQualifiedName(Res, RD)) {
4476 bool FoundOperator = false;
4477 Res.suppressDiagnostics();
4478 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4479 Op != OpEnd; ++Op) {
4480 if (isa<FunctionTemplateDecl>(*Op))
4481 continue;
4482
4483 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4484 if((Operator->*IsDesiredOp)()) {
4485 FoundOperator = true;
4486 const FunctionProtoType *CPT =
4487 Operator->getType()->getAs<FunctionProtoType>();
4488 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004489 if (!CPT || !CPT->isNothrow())
Joao Matosc9523d42013-03-27 01:34:16 +00004490 return false;
4491 }
4492 }
4493 return FoundOperator;
4494 }
4495 return false;
4496}
4497
Alp Toker95e7ff22014-01-01 05:57:51 +00004498static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00004499 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004500 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00004501
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004502 ASTContext &C = Self.Context;
4503 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004504 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004505 // Type trait expressions corresponding to the primary type category
4506 // predicates in C++0x [meta.unary.cat].
4507 case UTT_IsVoid:
4508 return T->isVoidType();
4509 case UTT_IsIntegral:
4510 return T->isIntegralType(C);
4511 case UTT_IsFloatingPoint:
4512 return T->isFloatingType();
4513 case UTT_IsArray:
4514 return T->isArrayType();
4515 case UTT_IsPointer:
4516 return T->isPointerType();
4517 case UTT_IsLvalueReference:
4518 return T->isLValueReferenceType();
4519 case UTT_IsRvalueReference:
4520 return T->isRValueReferenceType();
4521 case UTT_IsMemberFunctionPointer:
4522 return T->isMemberFunctionPointerType();
4523 case UTT_IsMemberObjectPointer:
4524 return T->isMemberDataPointerType();
4525 case UTT_IsEnum:
4526 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00004527 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00004528 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004529 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00004530 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004531 case UTT_IsFunction:
4532 return T->isFunctionType();
4533
4534 // Type trait expressions which correspond to the convenient composition
4535 // predicates in C++0x [meta.unary.comp].
4536 case UTT_IsReference:
4537 return T->isReferenceType();
4538 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00004539 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004540 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00004541 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004542 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00004543 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004544 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00004545 // Note: semantic analysis depends on Objective-C lifetime types to be
4546 // considered scalar types. However, such types do not actually behave
4547 // like scalar types at run time (since they may require retain/release
4548 // operations), so we report them as non-scalar.
4549 if (T->isObjCLifetimeType()) {
4550 switch (T.getObjCLifetime()) {
4551 case Qualifiers::OCL_None:
4552 case Qualifiers::OCL_ExplicitNone:
4553 return true;
4554
4555 case Qualifiers::OCL_Strong:
4556 case Qualifiers::OCL_Weak:
4557 case Qualifiers::OCL_Autoreleasing:
4558 return false;
4559 }
4560 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00004561
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00004562 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004563 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00004564 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004565 case UTT_IsMemberPointer:
4566 return T->isMemberPointerType();
4567
4568 // Type trait expressions which correspond to the type property predicates
4569 // in C++0x [meta.unary.prop].
4570 case UTT_IsConst:
4571 return T.isConstQualified();
4572 case UTT_IsVolatile:
4573 return T.isVolatileQualified();
4574 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004575 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00004576 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004577 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004578 case UTT_IsStandardLayout:
4579 return T->isStandardLayoutType();
4580 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004581 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004582 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004583 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004584 case UTT_IsEmpty:
4585 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4586 return !RD->isUnion() && RD->isEmpty();
4587 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004588 case UTT_IsPolymorphic:
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->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004591 return false;
4592 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00004593 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004594 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004595 return false;
Eric Fiselier07360662017-04-12 22:12:15 +00004596 case UTT_IsAggregate:
4597 // Report vector extensions and complex types as aggregates because they
4598 // support aggregate initialization. GCC mirrors this behavior for vectors
4599 // but not _Complex.
4600 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4601 T->isAnyComplexType();
David Majnemer213bea32015-11-16 06:58:51 +00004602 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4603 // even then only when it is used with the 'interface struct ...' syntax
4604 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00004605 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00004606 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00004607 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00004608 case UTT_IsSealed:
4609 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00004610 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00004611 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00004612 case UTT_IsSigned:
4613 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00004614 case UTT_IsUnsigned:
4615 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004616
4617 // Type trait expressions which query classes regarding their construction,
4618 // destruction, and copying. Rather than being based directly on the
4619 // related type predicates in the standard, they are specified by both
4620 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4621 // specifications.
4622 //
4623 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4624 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00004625 //
4626 // Note that these builtins do not behave as documented in g++: if a class
4627 // has both a trivial and a non-trivial special member of a particular kind,
4628 // they return false! For now, we emulate this behavior.
4629 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4630 // does not correctly compute triviality in the presence of multiple special
4631 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00004632 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004633 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4634 // If __is_pod (type) is true then the trait is true, else if type is
4635 // a cv class or union type (or array thereof) with a trivial default
4636 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004637 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004638 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004639 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4640 return RD->hasTrivialDefaultConstructor() &&
4641 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004642 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004643 case UTT_HasTrivialMoveConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00004644 // This trait is implemented by MSVC 2012 and needed to parse the
4645 // standard library headers. Specifically this is used as the logic
4646 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004647 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004648 return true;
4649 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4650 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4651 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004652 case UTT_HasTrivialCopy:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004653 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4654 // If __is_pod (type) is true or type is a reference type then
4655 // the trait is true, else if type is a cv class or union type
4656 // with a trivial copy constructor ([class.copy]) then the trait
4657 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004658 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004659 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004660 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4661 return RD->hasTrivialCopyConstructor() &&
4662 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004663 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004664 case UTT_HasTrivialMoveAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00004665 // This trait is implemented by MSVC 2012 and needed to parse the
4666 // standard library headers. Specifically it is used as the logic
4667 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004668 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004669 return true;
4670 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4671 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4672 return false;
Akira Hatanaka367b1a82018-04-09 19:39:27 +00004673 case UTT_HasTrivialAssign:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004674 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4675 // If type is const qualified or is a reference type then the
4676 // trait is false. Otherwise if __is_pod (type) is true then the
4677 // trait is true, else if type is a cv class or union type with
4678 // a trivial copy assignment ([class.copy]) then the trait is
4679 // true, else it is false.
4680 // Note: the const and reference restrictions are interesting,
4681 // given that const and reference members don't prevent a class
4682 // from having a trivial copy assignment operator (but do cause
4683 // errors if the copy assignment operator is actually used, q.v.
4684 // [class.copy]p12).
4685
Richard Smith92f241f2012-12-08 02:53:02 +00004686 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004687 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004688 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004689 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004690 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4691 return RD->hasTrivialCopyAssignment() &&
4692 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004693 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004694 case UTT_IsDestructible:
Richard Smithf03e9082017-06-01 00:28:16 +00004695 case UTT_IsTriviallyDestructible:
Alp Toker73287bf2014-01-20 00:24:09 +00004696 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00004697 // C++14 [meta.unary.prop]:
4698 // For reference types, is_destructible<T>::value is true.
4699 if (T->isReferenceType())
4700 return true;
4701
4702 // Objective-C++ ARC: autorelease types don't require destruction.
4703 if (T->isObjCLifetimeType() &&
4704 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4705 return true;
4706
4707 // C++14 [meta.unary.prop]:
4708 // For incomplete types and function types, is_destructible<T>::value is
4709 // false.
4710 if (T->isIncompleteType() || T->isFunctionType())
4711 return false;
4712
Richard Smithf03e9082017-06-01 00:28:16 +00004713 // A type that requires destruction (via a non-trivial destructor or ARC
4714 // lifetime semantics) is not trivially-destructible.
4715 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4716 return false;
4717
David Majnemerac73de92015-08-11 03:03:28 +00004718 // C++14 [meta.unary.prop]:
4719 // For object types and given U equal to remove_all_extents_t<T>, if the
4720 // expression std::declval<U&>().~U() is well-formed when treated as an
4721 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4722 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4723 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4724 if (!Destructor)
4725 return false;
4726 // C++14 [dcl.fct.def.delete]p2:
4727 // A program that refers to a deleted function implicitly or
4728 // explicitly, other than to declare it, is ill-formed.
4729 if (Destructor->isDeleted())
4730 return false;
4731 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4732 return false;
4733 if (UTT == UTT_IsNothrowDestructible) {
4734 const FunctionProtoType *CPT =
4735 Destructor->getType()->getAs<FunctionProtoType>();
4736 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Richard Smitheaf11ad2018-05-03 03:58:32 +00004737 if (!CPT || !CPT->isNothrow())
David Majnemerac73de92015-08-11 03:03:28 +00004738 return false;
4739 }
4740 }
4741 return true;
4742
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004743 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004744 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004745 // If __is_pod (type) is true or type is a reference type
4746 // then the trait is true, else if type is a cv class or union
4747 // type (or array thereof) with a trivial destructor
4748 // ([class.dtor]) then the trait is true, else it is
4749 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004750 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004751 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004752
John McCall31168b02011-06-15 23:02:42 +00004753 // Objective-C++ ARC: autorelease types don't require destruction.
Simon Pilgrim75c26882016-09-30 14:25:09 +00004754 if (T->isObjCLifetimeType() &&
John McCall31168b02011-06-15 23:02:42 +00004755 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4756 return true;
Simon Pilgrim75c26882016-09-30 14:25:09 +00004757
Richard Smith92f241f2012-12-08 02:53:02 +00004758 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4759 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004760 return false;
4761 // TODO: Propagate nothrowness for implicitly declared special members.
4762 case UTT_HasNothrowAssign:
4763 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4764 // If type is const qualified or is a reference type then the
4765 // trait is false. Otherwise if __has_trivial_assign (type)
4766 // is true then the trait is true, else if type is a cv class
4767 // or union type with copy assignment operators that are known
4768 // not to throw an exception then the trait is true, else it is
4769 // false.
4770 if (C.getBaseElementType(T).isConstQualified())
4771 return false;
4772 if (T->isReferenceType())
4773 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004774 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004775 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004776
Joao Matosc9523d42013-03-27 01:34:16 +00004777 if (const RecordType *RT = T->getAs<RecordType>())
4778 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4779 &CXXRecordDecl::hasTrivialCopyAssignment,
4780 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4781 &CXXMethodDecl::isCopyAssignmentOperator);
4782 return false;
4783 case UTT_HasNothrowMoveAssign:
4784 // This trait is implemented by MSVC 2012 and needed to parse the
4785 // standard library headers. Specifically this is used as the logic
4786 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004787 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004788 return true;
4789
4790 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4791 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4792 &CXXRecordDecl::hasTrivialMoveAssignment,
4793 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4794 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004795 return false;
4796 case UTT_HasNothrowCopy:
4797 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4798 // If __has_trivial_copy (type) is true then the trait is true, else
4799 // if type is a cv class or union type with copy constructors that are
4800 // known not to throw an exception then the trait is true, else it is
4801 // false.
John McCall31168b02011-06-15 23:02:42 +00004802 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004803 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004804 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4805 if (RD->hasTrivialCopyConstructor() &&
4806 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004807 return true;
4808
4809 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004810 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004811 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004812 // A template constructor is never a copy constructor.
4813 // FIXME: However, it may actually be selected at the actual overload
4814 // resolution point.
Hal Finkelfec83452016-11-27 16:26:14 +00004815 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004816 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004817 // UsingDecl itself is not a constructor
4818 if (isa<UsingDecl>(ND))
4819 continue;
4820 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004821 if (Constructor->isCopyConstructor(FoundTQs)) {
4822 FoundConstructor = true;
4823 const FunctionProtoType *CPT
4824 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004825 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4826 if (!CPT)
4827 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004828 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004829 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004830 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004831 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004832 }
4833 }
4834
Richard Smith938f40b2011-06-11 17:19:42 +00004835 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004836 }
4837 return false;
4838 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004839 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004840 // If __has_trivial_constructor (type) is true then the trait is
4841 // true, else if type is a cv class or union type (or array
4842 // thereof) with a default constructor that is known not to
4843 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004844 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004845 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004846 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4847 if (RD->hasTrivialDefaultConstructor() &&
4848 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004849 return true;
4850
Alp Tokerb4bca412014-01-20 00:23:47 +00004851 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004852 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004853 // FIXME: In C++0x, a constructor template can be a default constructor.
Hal Finkelfec83452016-11-27 16:26:14 +00004854 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004855 continue;
Hal Finkelfec83452016-11-27 16:26:14 +00004856 // UsingDecl itself is not a constructor
4857 if (isa<UsingDecl>(ND))
4858 continue;
4859 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
Sebastian Redlc15c3262010-09-13 22:02:47 +00004860 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004861 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004862 const FunctionProtoType *CPT
4863 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004864 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4865 if (!CPT)
4866 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004867 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004868 // For now, we'll be conservative and assume that they can throw.
Richard Smitheaf11ad2018-05-03 03:58:32 +00004869 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004870 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004871 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004872 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004873 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004874 }
4875 return false;
4876 case UTT_HasVirtualDestructor:
4877 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4878 // If type is a class type with a virtual destructor ([class.dtor])
4879 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004880 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004881 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004882 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004883 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004884
4885 // These type trait expressions are modeled on the specifications for the
4886 // Embarcadero C++0x type trait functions:
4887 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4888 case UTT_IsCompleteType:
4889 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4890 // Returns True if and only if T is a complete type at the point of the
4891 // function call.
4892 return !T->isIncompleteType();
Erich Keanee63e9d72017-10-24 21:31:50 +00004893 case UTT_HasUniqueObjectRepresentations:
Erich Keane8a6b7402017-11-30 16:37:02 +00004894 return C.hasUniqueObjectRepresentations(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004895 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004896}
Sebastian Redl5822f082009-02-07 20:10:22 +00004897
Alp Tokercbb90342013-12-13 20:49:58 +00004898static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4899 QualType RhsT, SourceLocation KeyLoc);
4900
Douglas Gregor29c42f22012-02-24 07:38:34 +00004901static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4902 ArrayRef<TypeSourceInfo *> Args,
4903 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004904 if (Kind <= UTT_Last)
4905 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4906
Eric Fiselier1af6c112018-01-12 00:09:37 +00004907 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4908 // traits to avoid duplication.
4909 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
Alp Tokercbb90342013-12-13 20:49:58 +00004910 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4911 Args[1]->getType(), RParenLoc);
4912
Douglas Gregor29c42f22012-02-24 07:38:34 +00004913 switch (Kind) {
Eric Fiselier1af6c112018-01-12 00:09:37 +00004914 case clang::BTT_ReferenceBindsToTemporary:
Alp Toker73287bf2014-01-20 00:24:09 +00004915 case clang::TT_IsConstructible:
4916 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004917 case clang::TT_IsTriviallyConstructible: {
4918 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004919 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004920 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004921 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004922 // definition for is_constructible, as defined below, is known to call
4923 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004924 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00004925 // The predicate condition for a template specialization
4926 // is_constructible<T, Args...> shall be satisfied if and only if the
4927 // following variable definition would be well-formed for some invented
Douglas Gregor29c42f22012-02-24 07:38:34 +00004928 // variable t:
4929 //
4930 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004931 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004932
4933 // Precondition: T and all types in the parameter pack Args shall be
4934 // complete types, (possibly cv-qualified) void, or arrays of
4935 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004936 for (const auto *TSI : Args) {
4937 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004938 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004939 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004940
Simon Pilgrim75c26882016-09-30 14:25:09 +00004941 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004942 diag::err_incomplete_type_used_in_type_trait_expr))
4943 return false;
4944 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004945
David Majnemer9658ecc2015-11-13 05:32:43 +00004946 // Make sure the first argument is not incomplete nor a function type.
4947 QualType T = Args[0]->getType();
4948 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004949 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004950
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004951 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004952 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004953 if (RD && RD->isAbstract())
4954 return false;
4955
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004956 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4957 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004958 ArgExprs.reserve(Args.size() - 1);
4959 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004960 QualType ArgTy = Args[I]->getType();
4961 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4962 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004963 OpaqueArgExprs.push_back(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004964 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
David Majnemer9658ecc2015-11-13 05:32:43 +00004965 ArgTy.getNonLValueExprType(S.Context),
4966 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004967 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004968 for (Expr &E : OpaqueArgExprs)
4969 ArgExprs.push_back(&E);
4970
Simon Pilgrim75c26882016-09-30 14:25:09 +00004971 // Perform the initialization in an unevaluated context within a SFINAE
Douglas Gregor29c42f22012-02-24 07:38:34 +00004972 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00004973 EnterExpressionEvaluationContext Unevaluated(
4974 S, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004975 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4976 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4977 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4978 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4979 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004980 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004981 if (Init.Failed())
4982 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004983
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004984 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004985 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4986 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004987
Alp Toker73287bf2014-01-20 00:24:09 +00004988 if (Kind == clang::TT_IsConstructible)
4989 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004990
Eric Fiselier1af6c112018-01-12 00:09:37 +00004991 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4992 if (!T->isReferenceType())
4993 return false;
4994
4995 return !Init.isDirectReferenceBinding();
4996 }
4997
Alp Toker73287bf2014-01-20 00:24:09 +00004998 if (Kind == clang::TT_IsNothrowConstructible)
4999 return S.canThrow(Result.get()) == CT_Cannot;
5000
5001 if (Kind == clang::TT_IsTriviallyConstructible) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005002 // Under Objective-C ARC and Weak, if the destination has non-trivial
5003 // Objective-C lifetime, this is a non-trivial construction.
5004 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005005 return false;
5006
5007 // The initialization succeeded; now make sure there are no non-trivial
5008 // calls.
5009 return !Result.get()->hasNonTrivialCall(S.Context);
5010 }
5011
5012 llvm_unreachable("unhandled type trait");
5013 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005014 }
Alp Tokercbb90342013-12-13 20:49:58 +00005015 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00005016 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005017
Douglas Gregor29c42f22012-02-24 07:38:34 +00005018 return false;
5019}
5020
Simon Pilgrim75c26882016-09-30 14:25:09 +00005021ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5022 ArrayRef<TypeSourceInfo *> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005023 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00005024 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00005025
Alp Toker95e7ff22014-01-01 05:57:51 +00005026 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5027 *this, Kind, KWLoc, Args[0]->getType()))
5028 return ExprError();
5029
Douglas Gregor29c42f22012-02-24 07:38:34 +00005030 bool Dependent = false;
5031 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5032 if (Args[I]->getType()->isDependentType()) {
5033 Dependent = true;
5034 break;
5035 }
5036 }
Alp Tokercbb90342013-12-13 20:49:58 +00005037
5038 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005039 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00005040 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5041
5042 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5043 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005044}
5045
Alp Toker88f64e62013-12-13 21:19:30 +00005046ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5047 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00005048 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005049 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00005050 ConvertedArgs.reserve(Args.size());
Simon Pilgrim75c26882016-09-30 14:25:09 +00005051
Douglas Gregor29c42f22012-02-24 07:38:34 +00005052 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5053 TypeSourceInfo *TInfo;
5054 QualType T = GetTypeFromParser(Args[I], &TInfo);
5055 if (!TInfo)
5056 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
Simon Pilgrim75c26882016-09-30 14:25:09 +00005057
5058 ConvertedArgs.push_back(TInfo);
Douglas Gregor29c42f22012-02-24 07:38:34 +00005059 }
Alp Tokercbb90342013-12-13 20:49:58 +00005060
Douglas Gregor29c42f22012-02-24 07:38:34 +00005061 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5062}
5063
Alp Tokercbb90342013-12-13 20:49:58 +00005064static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5065 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005066 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5067 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005068
5069 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00005070 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005071 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00005072 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005073 // Base and Derived are not unions and name the same class type without
5074 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005075
John McCall388ef532011-01-28 22:02:36 +00005076 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
John McCall388ef532011-01-28 22:02:36 +00005077 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
Erik Pilkington07f8c432017-05-10 17:18:56 +00005078 if (!rhsRecord || !lhsRecord) {
5079 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5080 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5081 if (!LHSObjTy || !RHSObjTy)
5082 return false;
5083
5084 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5085 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5086 if (!BaseInterface || !DerivedInterface)
5087 return false;
5088
5089 if (Self.RequireCompleteType(
5090 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5091 return false;
5092
5093 return BaseInterface->isSuperClassOf(DerivedInterface);
5094 }
John McCall388ef532011-01-28 22:02:36 +00005095
5096 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5097 == (lhsRecord == rhsRecord));
5098
5099 if (lhsRecord == rhsRecord)
5100 return !lhsRecord->getDecl()->isUnion();
5101
5102 // C++0x [meta.rel]p2:
5103 // If Base and Derived are class types and are different types
5104 // (ignoring possible cv-qualifiers) then Derived shall be a
5105 // complete type.
Simon Pilgrim75c26882016-09-30 14:25:09 +00005106 if (Self.RequireCompleteType(KeyLoc, RhsT,
John McCall388ef532011-01-28 22:02:36 +00005107 diag::err_incomplete_type_used_in_type_trait_expr))
5108 return false;
5109
5110 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5111 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5112 }
John Wiegley65497cc2011-04-27 23:09:49 +00005113 case BTT_IsSame:
5114 return Self.Context.hasSameType(LhsT, RhsT);
George Burgess IV31ac1fa2017-10-16 22:58:37 +00005115 case BTT_TypeCompatible: {
5116 // GCC ignores cv-qualifiers on arrays for this builtin.
5117 Qualifiers LhsQuals, RhsQuals;
5118 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5119 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5120 return Self.Context.typesAreCompatible(Lhs, Rhs);
5121 }
John Wiegley65497cc2011-04-27 23:09:49 +00005122 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00005123 case BTT_IsConvertibleTo: {
5124 // C++0x [meta.rel]p4:
5125 // Given the following function prototype:
5126 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005127 // template <class T>
Douglas Gregor8006e762011-01-27 20:28:01 +00005128 // typename add_rvalue_reference<T>::type create();
5129 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005130 // the predicate condition for a template specialization
5131 // is_convertible<From, To> shall be satisfied if and only if
5132 // the return expression in the following code would be
Douglas Gregor8006e762011-01-27 20:28:01 +00005133 // well-formed, including any implicit conversions to the return
5134 // type of the function:
5135 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005136 // To test() {
Douglas Gregor8006e762011-01-27 20:28:01 +00005137 // return create<From>();
5138 // }
5139 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005140 // Access checking is performed as if in a context unrelated to To and
5141 // From. Only the validity of the immediate context of the expression
Douglas Gregor8006e762011-01-27 20:28:01 +00005142 // of the return-statement (including conversions to the return type)
5143 // is considered.
5144 //
5145 // We model the initialization as a copy-initialization of a temporary
5146 // of the appropriate type, which for this expression is identical to the
5147 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005148
5149 // Functions aren't allowed to return function or array types.
5150 if (RhsT->isFunctionType() || RhsT->isArrayType())
5151 return false;
5152
5153 // A return statement in a void function must have void type.
5154 if (RhsT->isVoidType())
5155 return LhsT->isVoidType();
5156
5157 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00005158 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005159 return false;
5160
5161 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00005162 if (LhsT->isObjectType() || LhsT->isFunctionType())
5163 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00005164
5165 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00005166 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00005167 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00005168 Expr::getValueKindForType(LhsT));
5169 Expr *FromPtr = &From;
Simon Pilgrim75c26882016-09-30 14:25:09 +00005170 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
Douglas Gregor8006e762011-01-27 20:28:01 +00005171 SourceLocation()));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005172
5173 // Perform the initialization in an unevaluated context within a SFINAE
Eli Friedmana59b1902012-01-25 01:05:57 +00005174 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005175 EnterExpressionEvaluationContext Unevaluated(
5176 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00005177 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5178 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005179 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005180 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00005181 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00005182
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005183 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00005184 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5185 }
Alp Toker73287bf2014-01-20 00:24:09 +00005186
David Majnemerb3d96882016-05-23 17:21:55 +00005187 case BTT_IsAssignable:
Alp Toker73287bf2014-01-20 00:24:09 +00005188 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00005189 case BTT_IsTriviallyAssignable: {
5190 // C++11 [meta.unary.prop]p3:
5191 // is_trivially_assignable is defined as:
5192 // is_assignable<T, U>::value is true and the assignment, as defined by
5193 // is_assignable, is known to call no operation that is not trivial
5194 //
5195 // is_assignable is defined as:
Simon Pilgrim75c26882016-09-30 14:25:09 +00005196 // The expression declval<T>() = declval<U>() is well-formed when
Douglas Gregor1be329d2012-02-23 07:33:15 +00005197 // treated as an unevaluated operand (Clause 5).
5198 //
Simon Pilgrim75c26882016-09-30 14:25:09 +00005199 // For both, T and U shall be complete types, (possibly cv-qualified)
Douglas Gregor1be329d2012-02-23 07:33:15 +00005200 // void, or arrays of unknown bound.
5201 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005202 Self.RequireCompleteType(KeyLoc, LhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005203 diag::err_incomplete_type_used_in_type_trait_expr))
5204 return false;
5205 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
Simon Pilgrim75c26882016-09-30 14:25:09 +00005206 Self.RequireCompleteType(KeyLoc, RhsT,
Douglas Gregor1be329d2012-02-23 07:33:15 +00005207 diag::err_incomplete_type_used_in_type_trait_expr))
5208 return false;
5209
5210 // cv void is never assignable.
5211 if (LhsT->isVoidType() || RhsT->isVoidType())
5212 return false;
5213
Simon Pilgrim75c26882016-09-30 14:25:09 +00005214 // Build expressions that emulate the effect of declval<T>() and
Douglas Gregor1be329d2012-02-23 07:33:15 +00005215 // declval<U>().
5216 if (LhsT->isObjectType() || LhsT->isFunctionType())
5217 LhsT = Self.Context.getRValueReferenceType(LhsT);
5218 if (RhsT->isObjectType() || RhsT->isFunctionType())
5219 RhsT = Self.Context.getRValueReferenceType(RhsT);
5220 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5221 Expr::getValueKindForType(LhsT));
5222 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5223 Expr::getValueKindForType(RhsT));
Simon Pilgrim75c26882016-09-30 14:25:09 +00005224
5225 // Attempt the assignment in an unevaluated context within a SFINAE
Douglas Gregor1be329d2012-02-23 07:33:15 +00005226 // trap at translation unit scope.
Faisal Valid143a0c2017-04-01 21:30:49 +00005227 EnterExpressionEvaluationContext Unevaluated(
5228 Self, Sema::ExpressionEvaluationContext::Unevaluated);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005229 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
Erich Keane1a3b8fd2017-12-12 16:22:31 +00005230 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00005231 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5232 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00005233 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5234 return false;
5235
David Majnemerb3d96882016-05-23 17:21:55 +00005236 if (BTT == BTT_IsAssignable)
5237 return true;
5238
Alp Toker73287bf2014-01-20 00:24:09 +00005239 if (BTT == BTT_IsNothrowAssignable)
5240 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00005241
Alp Toker73287bf2014-01-20 00:24:09 +00005242 if (BTT == BTT_IsTriviallyAssignable) {
Brian Kelley93c640b2017-03-29 17:40:35 +00005243 // Under Objective-C ARC and Weak, if the destination has non-trivial
5244 // Objective-C lifetime, this is a non-trivial assignment.
5245 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
Alp Toker73287bf2014-01-20 00:24:09 +00005246 return false;
5247
5248 return !Result.get()->hasNonTrivialCall(Self.Context);
5249 }
5250
5251 llvm_unreachable("unhandled type trait");
5252 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00005253 }
Alp Tokercbb90342013-12-13 20:49:58 +00005254 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00005255 }
5256 llvm_unreachable("Unknown type trait or not implemented");
5257}
5258
John Wiegley6242b6a2011-04-28 00:16:57 +00005259ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5260 SourceLocation KWLoc,
5261 ParsedType Ty,
5262 Expr* DimExpr,
5263 SourceLocation RParen) {
5264 TypeSourceInfo *TSInfo;
5265 QualType T = GetTypeFromParser(Ty, &TSInfo);
5266 if (!TSInfo)
5267 TSInfo = Context.getTrivialTypeSourceInfo(T);
5268
5269 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5270}
5271
5272static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5273 QualType T, Expr *DimExpr,
5274 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005275 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00005276
5277 switch(ATT) {
5278 case ATT_ArrayRank:
5279 if (T->isArrayType()) {
5280 unsigned Dim = 0;
5281 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5282 ++Dim;
5283 T = AT->getElementType();
5284 }
5285 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00005286 }
John Wiegleyd3522222011-04-28 02:06:46 +00005287 return 0;
5288
John Wiegley6242b6a2011-04-28 00:16:57 +00005289 case ATT_ArrayExtent: {
5290 llvm::APSInt Value;
5291 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00005292 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00005293 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00005294 false).isInvalid())
5295 return 0;
5296 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00005297 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5298 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00005299 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00005300 }
Richard Smithf4c51d92012-02-04 09:53:13 +00005301 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00005302
5303 if (T->isArrayType()) {
5304 unsigned D = 0;
5305 bool Matched = false;
5306 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5307 if (Dim == D) {
5308 Matched = true;
5309 break;
5310 }
5311 ++D;
5312 T = AT->getElementType();
5313 }
5314
John Wiegleyd3522222011-04-28 02:06:46 +00005315 if (Matched && T->isArrayType()) {
5316 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5317 return CAT->getSize().getLimitedValue();
5318 }
John Wiegley6242b6a2011-04-28 00:16:57 +00005319 }
John Wiegleyd3522222011-04-28 02:06:46 +00005320 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00005321 }
5322 }
5323 llvm_unreachable("Unknown type trait or not implemented");
5324}
5325
5326ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5327 SourceLocation KWLoc,
5328 TypeSourceInfo *TSInfo,
5329 Expr* DimExpr,
5330 SourceLocation RParen) {
5331 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00005332
Chandler Carruthc5276e52011-05-01 08:48:21 +00005333 // FIXME: This should likely be tracked as an APInt to remove any host
5334 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00005335 uint64_t Value = 0;
5336 if (!T->isDependentType())
5337 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5338
Chandler Carruthc5276e52011-05-01 08:48:21 +00005339 // While the specification for these traits from the Embarcadero C++
5340 // compiler's documentation says the return type is 'unsigned int', Clang
5341 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5342 // compiler, there is no difference. On several other platforms this is an
5343 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005344 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5345 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00005346}
5347
John Wiegleyf9f65842011-04-25 06:54:41 +00005348ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005349 SourceLocation KWLoc,
5350 Expr *Queried,
5351 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005352 // If error parsing the expression, ignore.
5353 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005354 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00005355
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005356 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005357
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005358 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00005359}
5360
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005361static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5362 switch (ET) {
5363 case ET_IsLValueExpr: return E->isLValue();
5364 case ET_IsRValueExpr: return E->isRValue();
5365 }
5366 llvm_unreachable("Expression trait not covered by switch");
5367}
5368
John Wiegleyf9f65842011-04-25 06:54:41 +00005369ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005370 SourceLocation KWLoc,
5371 Expr *Queried,
5372 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00005373 if (Queried->isTypeDependent()) {
5374 // Delay type-checking for type-dependent expressions.
5375 } else if (Queried->getType()->isPlaceholderType()) {
5376 ExprResult PE = CheckPlaceholderExpr(Queried);
5377 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005378 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00005379 }
5380
Chandler Carruth20b9bc82011-05-01 07:44:20 +00005381 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00005382
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005383 return new (Context)
5384 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00005385}
5386
Richard Trieu82402a02011-09-15 21:56:47 +00005387QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00005388 ExprValueKind &VK,
5389 SourceLocation Loc,
5390 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005391 assert(!LHS.get()->getType()->isPlaceholderType() &&
5392 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00005393 "placeholders should have been weeded out by now");
5394
Richard Smith4baaa5a2016-12-03 01:14:32 +00005395 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5396 // temporary materialization conversion otherwise.
5397 if (isIndirect)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005398 LHS = DefaultLvalueConversion(LHS.get());
Richard Smith4baaa5a2016-12-03 01:14:32 +00005399 else if (LHS.get()->isRValue())
5400 LHS = TemporaryMaterializationConversion(LHS.get());
5401 if (LHS.isInvalid())
5402 return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005403
5404 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005405 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00005406 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00005407
Sebastian Redl5822f082009-02-07 20:10:22 +00005408 const char *OpSpelling = isIndirect ? "->*" : ".*";
5409 // C++ 5.5p2
5410 // The binary operator .* [p3: ->*] binds its second operand, which shall
5411 // be of type "pointer to member of T" (where T is a completely-defined
5412 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00005413 QualType RHSType = RHS.get()->getType();
5414 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00005415 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005416 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005417 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00005418 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00005419 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00005420
Sebastian Redl5822f082009-02-07 20:10:22 +00005421 QualType Class(MemPtr->getClass(), 0);
5422
Douglas Gregord07ba342010-10-13 20:41:14 +00005423 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5424 // member pointer points must be completely-defined. However, there is no
5425 // reason for this semantic distinction, and the rule is not enforced by
5426 // other compilers. Therefore, we do not check this property, as it is
5427 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00005428
Sebastian Redl5822f082009-02-07 20:10:22 +00005429 // C++ 5.5p2
5430 // [...] to its first operand, which shall be of class T or of a class of
5431 // which T is an unambiguous and accessible base class. [p3: a pointer to
5432 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00005433 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005434 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00005435 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5436 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005437 else {
5438 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00005439 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00005440 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00005441 return QualType();
5442 }
5443 }
5444
Richard Trieu82402a02011-09-15 21:56:47 +00005445 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005446 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005447 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5448 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00005449 return QualType();
5450 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005451
Richard Smith0f59cb32015-12-18 21:45:41 +00005452 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00005453 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00005454 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00005455 return QualType();
5456 }
Richard Smithdb05cd32013-12-12 03:40:18 +00005457
5458 CXXCastPath BasePath;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005459 if (CheckDerivedToBaseConversion(
5460 LHSType, Class, Loc,
Stephen Kelly1c301dc2018-08-09 21:09:38 +00005461 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005462 &BasePath))
Richard Smithdb05cd32013-12-12 03:40:18 +00005463 return QualType();
5464
Eli Friedman1fcf66b2010-01-16 00:00:48 +00005465 // Cast LHS to type of use.
Richard Smith01e4a7f22017-06-09 22:25:28 +00005466 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5467 if (isIndirect)
5468 UseType = Context.getPointerType(UseType);
Eli Friedmanbe4b3632011-09-27 21:58:52 +00005469 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005470 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00005471 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00005472 }
5473
Richard Trieu82402a02011-09-15 21:56:47 +00005474 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00005475 // Diagnose use of pointer-to-member type which when used as
5476 // the functional cast in a pointer-to-member expression.
5477 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5478 return QualType();
5479 }
John McCall7decc9e2010-11-18 06:31:45 +00005480
Sebastian Redl5822f082009-02-07 20:10:22 +00005481 // C++ 5.5p2
5482 // The result is an object or a function of the type specified by the
5483 // second operand.
5484 // The cv qualifiers are the union of those in the pointer and the left side,
5485 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00005486 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00005487 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00005488
Douglas Gregor1d042092011-01-26 16:40:18 +00005489 // C++0x [expr.mptr.oper]p6:
5490 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005491 // ill-formed if the second operand is a pointer to member function with
5492 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5493 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00005494 // is a pointer to member function with ref-qualifier &&.
5495 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5496 switch (Proto->getRefQualifier()) {
5497 case RQ_None:
5498 // Do nothing
5499 break;
5500
5501 case RQ_LValue:
Richard Smith25923272017-08-25 01:47:55 +00005502 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
Nicolas Lesser1ad0e9f2018-07-13 16:27:45 +00005503 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5504 // is (exactly) 'const'.
5505 if (Proto->isConst() && !Proto->isVolatile())
Richard Smith25923272017-08-25 01:47:55 +00005506 Diag(Loc, getLangOpts().CPlusPlus2a
5507 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5508 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5509 else
5510 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5511 << RHSType << 1 << LHS.get()->getSourceRange();
5512 }
Douglas Gregor1d042092011-01-26 16:40:18 +00005513 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005514
Douglas Gregor1d042092011-01-26 16:40:18 +00005515 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00005516 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00005517 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00005518 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00005519 break;
5520 }
5521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522
John McCall7decc9e2010-11-18 06:31:45 +00005523 // C++ [expr.mptr.oper]p6:
5524 // The result of a .* expression whose second operand is a pointer
5525 // to a data member is of the same value category as its
5526 // first operand. The result of a .* expression whose second
5527 // operand is a pointer to a member function is a prvalue. The
5528 // result of an ->* expression is an lvalue if its second operand
5529 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00005530 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00005531 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00005532 return Context.BoundMemberTy;
5533 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00005534 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00005535 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00005536 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00005537 }
John McCall7decc9e2010-11-18 06:31:45 +00005538
Sebastian Redl5822f082009-02-07 20:10:22 +00005539 return Result;
5540}
Sebastian Redl1a99f442009-04-16 17:51:27 +00005541
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005542/// Try to convert a type to another according to C++11 5.16p3.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005543///
5544/// This is part of the parameter validation for the ? operator. If either
5545/// value operand is a class type, the two operands are attempted to be
5546/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005547/// It returns true if the program is ill-formed and has already been diagnosed
5548/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005549static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5550 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00005551 bool &HaveConversion,
5552 QualType &ToType) {
5553 HaveConversion = false;
5554 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005556 InitializationKind Kind =
5557 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
Richard Smith2414bca2016-04-25 19:30:37 +00005558 // C++11 5.16p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005559 // The process for determining whether an operand expression E1 of type T1
5560 // can be converted to match an operand expression E2 of type T2 is defined
5561 // as follows:
Richard Smith2414bca2016-04-25 19:30:37 +00005562 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5563 // implicitly converted to type "lvalue reference to T2", subject to the
5564 // constraint that in the conversion the reference must bind directly to
5565 // an lvalue.
5566 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00005567 // implicitly converted to the type "rvalue reference to R2", subject to
Richard Smith2414bca2016-04-25 19:30:37 +00005568 // the constraint that the reference must bind directly.
5569 if (To->isLValue() || To->isXValue()) {
5570 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5571 : Self.Context.getRValueReferenceType(ToType);
5572
Douglas Gregor838fcc32010-03-26 20:14:36 +00005573 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005574
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005575 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005576 if (InitSeq.isDirectReferenceBinding()) {
5577 ToType = T;
5578 HaveConversion = true;
5579 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005580 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581
Douglas Gregor838fcc32010-03-26 20:14:36 +00005582 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005583 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005584 }
John McCall65eb8792010-02-25 01:37:24 +00005585
Sebastian Redl1a99f442009-04-16 17:51:27 +00005586 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5587 // -- if E1 and E2 have class type, and the underlying class types are
5588 // the same or one is a base class of the other:
5589 QualType FTy = From->getType();
5590 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005591 const RecordType *FRec = FTy->getAs<RecordType>();
5592 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005593 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00005594 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5595 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5596 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005597 // E1 can be converted to match E2 if the class of T2 is the
5598 // same type as, or a base class of, the class of T1, and
5599 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00005600 if (FRec == TRec || FDerivedFromT) {
5601 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005602 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005603 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005604 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005605 HaveConversion = true;
5606 return false;
5607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608
Douglas Gregor838fcc32010-03-26 20:14:36 +00005609 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005610 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005611 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005612 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005613
Douglas Gregor838fcc32010-03-26 20:14:36 +00005614 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005615 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005616
Douglas Gregor838fcc32010-03-26 20:14:36 +00005617 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5618 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005619 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00005620 // an rvalue).
5621 //
5622 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5623 // to the array-to-pointer or function-to-pointer conversions.
Richard Smith16d31502016-12-21 01:31:56 +00005624 TTy = TTy.getNonLValueExprType(Self.Context);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005625
Douglas Gregor838fcc32010-03-26 20:14:36 +00005626 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005627 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00005628 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00005629 ToType = TTy;
5630 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005631 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005632
Sebastian Redl1a99f442009-04-16 17:51:27 +00005633 return false;
5634}
5635
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005636/// Try to find a common type for two according to C++0x 5.16p5.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005637///
5638/// This is part of the parameter validation for the ? operator. If either
5639/// value operand is a class type, overload resolution is used to find a
5640/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00005641static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005642 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00005643 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00005644 OverloadCandidateSet CandidateSet(QuestionLoc,
5645 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00005646 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005647 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005648
5649 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005650 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00005651 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005652 // We found a match. Perform the conversions on the arguments and move on.
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005653 ExprResult LHSRes = Self.PerformImplicitConversion(
5654 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5655 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005656 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005657 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005658 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00005659
George Burgess IV5f6ab9a2017-06-08 20:55:21 +00005660 ExprResult RHSRes = Self.PerformImplicitConversion(
5661 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5662 Sema::AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005663 if (RHSRes.isInvalid())
5664 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005665 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00005666 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00005667 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005668 return false;
John Wiegley01296292011-04-08 18:41:53 +00005669 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00005670
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005671 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005672
5673 // Emit a better diagnostic if one of the expressions is a null pointer
5674 // constant and the other is a pointer type. In this case, the user most
5675 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00005676 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005677 return true;
5678
5679 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005680 << LHS.get()->getType() << RHS.get()->getType()
5681 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005682 return true;
5683
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005684 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00005685 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00005686 << LHS.get()->getType() << RHS.get()->getType()
5687 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00005688 // FIXME: Print the possible common types by printing the return types of
5689 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005690 break;
5691
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005692 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00005693 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005694 }
5695 return true;
5696}
5697
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005698/// Perform an "extended" implicit conversion as returned by
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005699/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00005700static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00005701 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005702 InitializationKind Kind =
5703 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005704 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005705 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005706 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00005707 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005708 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005709
John Wiegley01296292011-04-08 18:41:53 +00005710 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00005711 return false;
5712}
5713
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005714/// Check the operands of ?: under C++ semantics.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005715///
5716/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5717/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00005718QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5719 ExprResult &RHS, ExprValueKind &VK,
5720 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00005721 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00005722 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5723 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005724
Richard Smith45edb702012-08-07 22:06:48 +00005725 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00005726 // The first expression is contextually converted to bool.
Simon Dardis7cd58762017-05-12 19:11:06 +00005727 //
5728 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5729 // a is that of a integer vector with the same number of elements and
5730 // size as the vectors of b and c. If one of either b or c is a scalar
5731 // it is implicitly converted to match the type of the vector.
5732 // Otherwise the expression is ill-formed. If both b and c are scalars,
5733 // then b and c are checked and converted to the type of a if possible.
5734 // Unlike the OpenCL ?: operator, the expression is evaluated as
5735 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
John Wiegley01296292011-04-08 18:41:53 +00005736 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005737 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00005738 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005739 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005740 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005741 }
5742
John McCall7decc9e2010-11-18 06:31:45 +00005743 // Assume r-value.
5744 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005745 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00005746
Sebastian Redl1a99f442009-04-16 17:51:27 +00005747 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00005748 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005749 return Context.DependentTy;
5750
Richard Smith45edb702012-08-07 22:06:48 +00005751 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00005752 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00005753 QualType LTy = LHS.get()->getType();
5754 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005755 bool LVoid = LTy->isVoidType();
5756 bool RVoid = RTy->isVoidType();
5757 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005758 // ... one of the following shall hold:
5759 // -- The second or the third operand (but not both) is a (possibly
5760 // parenthesized) throw-expression; the result is of the type
5761 // and value category of the other.
5762 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5763 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5764 if (LThrow != RThrow) {
5765 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5766 VK = NonThrow->getValueKind();
5767 // DR (no number yet): the result is a bit-field if the
5768 // non-throw-expression operand is a bit-field.
5769 OK = NonThrow->getObjectKind();
5770 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00005771 }
5772
Sebastian Redl1a99f442009-04-16 17:51:27 +00005773 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00005774 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00005775 if (LVoid && RVoid)
5776 return Context.VoidTy;
5777
5778 // Neither holds, error.
5779 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5780 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00005781 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005782 return QualType();
5783 }
5784
5785 // Neither is void.
5786
Richard Smithf2b084f2012-08-08 06:13:49 +00005787 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00005788 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005789 // either has (cv) class type [...] an attempt is made to convert each of
5790 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005791 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005792 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005793 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005794 QualType L2RType, R2LType;
5795 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005796 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005797 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005798 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005799 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005800
Sebastian Redl1a99f442009-04-16 17:51:27 +00005801 // If both can be converted, [...] the program is ill-formed.
5802 if (HaveL2R && HaveR2L) {
5803 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005804 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005805 return QualType();
5806 }
5807
5808 // If exactly one conversion is possible, that conversion is applied to
5809 // the chosen operand and the converted operands are used in place of the
5810 // original operands for the remainder of this section.
5811 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005812 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005813 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005814 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005815 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005816 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005817 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005818 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005819 }
5820 }
5821
Richard Smithf2b084f2012-08-08 06:13:49 +00005822 // C++11 [expr.cond]p3
5823 // if both are glvalues of the same value category and the same type except
5824 // for cv-qualification, an attempt is made to convert each of those
5825 // operands to the type of the other.
Richard Smith1be59c52016-10-22 01:32:19 +00005826 // FIXME:
5827 // Resolving a defect in P0012R1: we extend this to cover all cases where
5828 // one of the operands is reference-compatible with the other, in order
5829 // to support conditionals between functions differing in noexcept.
Richard Smithf2b084f2012-08-08 06:13:49 +00005830 ExprValueKind LVK = LHS.get()->getValueKind();
5831 ExprValueKind RVK = RHS.get()->getValueKind();
5832 if (!Context.hasSameType(LTy, RTy) &&
Richard Smithf2b084f2012-08-08 06:13:49 +00005833 LVK == RVK && LVK != VK_RValue) {
Richard Smith1be59c52016-10-22 01:32:19 +00005834 // DerivedToBase was already handled by the class-specific case above.
5835 // FIXME: Should we allow ObjC conversions here?
5836 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5837 if (CompareReferenceRelationship(
5838 QuestionLoc, LTy, RTy, DerivedToBase,
5839 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005840 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5841 // [...] subject to the constraint that the reference must bind
5842 // directly [...]
5843 !RHS.get()->refersToBitField() &&
5844 !RHS.get()->refersToVectorElement()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005845 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005846 RTy = RHS.get()->getType();
Richard Smith1be59c52016-10-22 01:32:19 +00005847 } else if (CompareReferenceRelationship(
5848 QuestionLoc, RTy, LTy, DerivedToBase,
5849 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
Richard Smithb8c0f552016-12-09 18:49:13 +00005850 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5851 !LHS.get()->refersToBitField() &&
5852 !LHS.get()->refersToVectorElement()) {
Richard Smith1be59c52016-10-22 01:32:19 +00005853 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5854 LTy = LHS.get()->getType();
Richard Smithf2b084f2012-08-08 06:13:49 +00005855 }
5856 }
5857
5858 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005859 // If the second and third operands are glvalues of the same value
5860 // category and have the same type, the result is of that type and
5861 // value category and it is a bit-field if the second or the third
5862 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005863 // We only extend this to bitfields, not to the crazy other kinds of
5864 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005865 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005866 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005867 LHS.get()->isOrdinaryOrBitFieldObject() &&
5868 RHS.get()->isOrdinaryOrBitFieldObject()) {
5869 VK = LHS.get()->getValueKind();
5870 if (LHS.get()->getObjectKind() == OK_BitField ||
5871 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005872 OK = OK_BitField;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005873
5874 // If we have function pointer types, unify them anyway to unify their
5875 // exception specifications, if any.
5876 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5877 Qualifiers Qs = LTy.getQualifiers();
Richard Smith5e9746f2016-10-21 22:00:42 +00005878 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005879 /*ConvertArgs*/false);
5880 LTy = Context.getQualifiedType(LTy, Qs);
5881
5882 assert(!LTy.isNull() && "failed to find composite pointer type for "
5883 "canonically equivalent function ptr types");
5884 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5885 }
5886
John McCall7decc9e2010-11-18 06:31:45 +00005887 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005888 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005889
Richard Smithf2b084f2012-08-08 06:13:49 +00005890 // C++11 [expr.cond]p5
5891 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005892 // do not have the same type, and either has (cv) class type, ...
5893 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5894 // ... overload resolution is used to determine the conversions (if any)
5895 // to be applied to the operands. If the overload resolution fails, the
5896 // program is ill-formed.
5897 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5898 return QualType();
5899 }
5900
Richard Smithf2b084f2012-08-08 06:13:49 +00005901 // C++11 [expr.cond]p6
5902 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005903 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005904 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5905 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005906 if (LHS.isInvalid() || RHS.isInvalid())
5907 return QualType();
5908 LTy = LHS.get()->getType();
5909 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005910
5911 // After those conversions, one of the following shall hold:
5912 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005913 // is of that type. If the operands have class type, the result
5914 // is a prvalue temporary of the result type, which is
5915 // copy-initialized from either the second operand or the third
5916 // operand depending on the value of the first operand.
5917 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5918 if (LTy->isRecordType()) {
5919 // The operands have class type. Make a temporary copy.
5920 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005921
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005922 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5923 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005924 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005925 if (LHSCopy.isInvalid())
5926 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005927
5928 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5929 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005930 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005931 if (RHSCopy.isInvalid())
5932 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005933
John Wiegley01296292011-04-08 18:41:53 +00005934 LHS = LHSCopy;
5935 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005936 }
5937
Richard Smitheb7ef2e2016-10-20 21:53:09 +00005938 // If we have function pointer types, unify them anyway to unify their
5939 // exception specifications, if any.
5940 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5941 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5942 assert(!LTy.isNull() && "failed to find composite pointer type for "
5943 "canonically equivalent function ptr types");
5944 }
5945
Sebastian Redl1a99f442009-04-16 17:51:27 +00005946 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005947 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005948
Douglas Gregor46188682010-05-18 22:42:18 +00005949 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005950 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005951 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5952 /*AllowBothBool*/true,
5953 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005954
Sebastian Redl1a99f442009-04-16 17:51:27 +00005955 // -- The second and third operands have arithmetic or enumeration type;
5956 // the usual arithmetic conversions are performed to bring them to a
5957 // common type, and the result is of that type.
5958 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005959 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005960 if (LHS.isInvalid() || RHS.isInvalid())
5961 return QualType();
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00005962 if (ResTy.isNull()) {
5963 Diag(QuestionLoc,
5964 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5965 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5966 return QualType();
5967 }
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005968
5969 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5970 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5971
5972 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005973 }
5974
5975 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005976 // type and the other is a null pointer constant, or both are null
5977 // pointer constants, at least one of which is non-integral; pointer
5978 // conversions and qualification conversions are performed to bring them
5979 // to their composite pointer type. The result is of the composite
5980 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005981 // -- The second and third operands have pointer to member type, or one has
5982 // pointer to member type and the other is a null pointer constant;
5983 // pointer to member conversions and qualification conversions are
5984 // performed to bring them to a common type, whose cv-qualification
5985 // shall match the cv-qualification of either the second or the third
5986 // operand. The result is of the common type.
Richard Smith5e9746f2016-10-21 22:00:42 +00005987 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5988 if (!Composite.isNull())
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005989 return Composite;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005990
Douglas Gregor697a3912010-04-01 22:47:07 +00005991 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005992 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5993 if (!Composite.isNull())
5994 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005995
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005996 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005997 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005998 return QualType();
5999
Sebastian Redl1a99f442009-04-16 17:51:27 +00006000 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00006001 << LHS.get()->getType() << RHS.get()->getType()
6002 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00006003 return QualType();
6004}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006005
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006006static FunctionProtoType::ExceptionSpecInfo
6007mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6008 FunctionProtoType::ExceptionSpecInfo ESI2,
6009 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6010 ExceptionSpecificationType EST1 = ESI1.Type;
6011 ExceptionSpecificationType EST2 = ESI2.Type;
6012
6013 // If either of them can throw anything, that is the result.
6014 if (EST1 == EST_None) return ESI1;
6015 if (EST2 == EST_None) return ESI2;
6016 if (EST1 == EST_MSAny) return ESI1;
6017 if (EST2 == EST_MSAny) return ESI2;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006018 if (EST1 == EST_NoexceptFalse) return ESI1;
6019 if (EST2 == EST_NoexceptFalse) return ESI2;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006020
6021 // If either of them is non-throwing, the result is the other.
6022 if (EST1 == EST_DynamicNone) return ESI2;
6023 if (EST2 == EST_DynamicNone) return ESI1;
6024 if (EST1 == EST_BasicNoexcept) return ESI2;
6025 if (EST2 == EST_BasicNoexcept) return ESI1;
Richard Smitheaf11ad2018-05-03 03:58:32 +00006026 if (EST1 == EST_NoexceptTrue) return ESI2;
6027 if (EST2 == EST_NoexceptTrue) return ESI1;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006028
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006029 // If we're left with value-dependent computed noexcept expressions, we're
6030 // stuck. Before C++17, we can just drop the exception specification entirely,
6031 // since it's not actually part of the canonical type. And this should never
6032 // happen in C++17, because it would mean we were computing the composite
6033 // pointer type of dependent types, which should never happen.
Richard Smitheaf11ad2018-05-03 03:58:32 +00006034 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
Aaron Ballmanc351fba2017-12-04 20:27:34 +00006035 assert(!S.getLangOpts().CPlusPlus17 &&
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006036 "computing composite pointer type of dependent types");
6037 return FunctionProtoType::ExceptionSpecInfo();
6038 }
6039
6040 // Switch over the possibilities so that people adding new values know to
6041 // update this function.
6042 switch (EST1) {
6043 case EST_None:
6044 case EST_DynamicNone:
6045 case EST_MSAny:
6046 case EST_BasicNoexcept:
Richard Smitheaf11ad2018-05-03 03:58:32 +00006047 case EST_DependentNoexcept:
6048 case EST_NoexceptFalse:
6049 case EST_NoexceptTrue:
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006050 llvm_unreachable("handled above");
6051
6052 case EST_Dynamic: {
6053 // This is the fun case: both exception specifications are dynamic. Form
6054 // the union of the two lists.
6055 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6056 llvm::SmallPtrSet<QualType, 8> Found;
6057 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6058 for (QualType E : Exceptions)
6059 if (Found.insert(S.Context.getCanonicalType(E)).second)
6060 ExceptionTypeStorage.push_back(E);
6061
6062 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6063 Result.Exceptions = ExceptionTypeStorage;
6064 return Result;
6065 }
6066
6067 case EST_Unevaluated:
6068 case EST_Uninstantiated:
6069 case EST_Unparsed:
6070 llvm_unreachable("shouldn't see unresolved exception specifications here");
6071 }
6072
6073 llvm_unreachable("invalid ExceptionSpecificationType");
6074}
6075
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006076/// Find a merged pointer type and convert the two expressions to it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006077///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006078/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006079/// and @p E2 according to C++1z 5p14. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006080/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006081/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006082///
Douglas Gregor19175ff2010-04-16 23:20:25 +00006083/// \param Loc The location of the operator requiring these two expressions to
6084/// be converted to the composite pointer type.
6085///
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006086/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006087QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00006088 Expr *&E1, Expr *&E2,
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006089 bool ConvertArgs) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006090 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006091
6092 // C++1z [expr]p14:
6093 // The composite pointer type of two operands p1 and p2 having types T1
6094 // and T2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006095 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00006096
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006097 // where at least one is a pointer or pointer to member type or
6098 // std::nullptr_t is:
6099 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6100 T1->isNullPtrType();
6101 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6102 T2->isNullPtrType();
6103 if (!T1IsPointerLike && !T2IsPointerLike)
Richard Smithf2b084f2012-08-08 06:13:49 +00006104 return QualType();
Richard Smithf2b084f2012-08-08 06:13:49 +00006105
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006106 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6107 // This can't actually happen, following the standard, but we also use this
6108 // to implement the end of [expr.conv], which hits this case.
6109 //
6110 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6111 if (T1IsPointerLike &&
6112 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006113 if (ConvertArgs)
6114 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6115 ? CK_NullToMemberPointer
6116 : CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006117 return T1;
6118 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006119 if (T2IsPointerLike &&
6120 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006121 if (ConvertArgs)
6122 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6123 ? CK_NullToMemberPointer
6124 : CK_NullToPointer).get();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006125 return T2;
6126 }
Mike Stump11289f42009-09-09 15:08:12 +00006127
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006128 // Now both have to be pointers or member pointers.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006129 if (!T1IsPointerLike || !T2IsPointerLike)
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006130 return QualType();
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006131 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6132 "nullptr_t should be a null pointer constant");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006133
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006134 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6135 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6136 // the union of cv1 and cv2;
6137 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6138 // "pointer to function", where the function types are otherwise the same,
6139 // "pointer to function";
6140 // FIXME: This rule is defective: it should also permit removing noexcept
6141 // from a pointer to member function. As a Clang extension, we also
6142 // permit removing 'noreturn', so we generalize this rule to;
6143 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6144 // "pointer to member function" and the pointee types can be unified
6145 // by a function pointer conversion, that conversion is applied
6146 // before checking the following rules.
6147 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6148 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6149 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6150 // respectively;
6151 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6152 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6153 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6154 // T1 or the cv-combined type of T1 and T2, respectively;
6155 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6156 // T2;
6157 //
6158 // If looked at in the right way, these bullets all do the same thing.
6159 // What we do here is, we build the two possible cv-combined types, and try
6160 // the conversions in both directions. If only one works, or if the two
6161 // composite types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00006162 // FIXME: extended qualifiers?
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006163 //
6164 // Note that this will fail to find a composite pointer type for "pointer
6165 // to void" and "pointer to function". We can't actually perform the final
6166 // conversion in this case, even though a composite pointer type formally
6167 // exists.
6168 SmallVector<unsigned, 4> QualifierUnion;
6169 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006170 QualType Composite1 = T1;
6171 QualType Composite2 = T2;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006172 unsigned NeedConstBefore = 0;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006173 while (true) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006174 const PointerType *Ptr1, *Ptr2;
6175 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6176 (Ptr2 = Composite2->getAs<PointerType>())) {
6177 Composite1 = Ptr1->getPointeeType();
6178 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006179
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006180 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006181 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006182 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006183 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006184
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006185 QualifierUnion.push_back(
6186 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00006187 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006188 continue;
6189 }
Mike Stump11289f42009-09-09 15:08:12 +00006190
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006191 const MemberPointerType *MemPtr1, *MemPtr2;
6192 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6193 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6194 Composite1 = MemPtr1->getPointeeType();
6195 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006196
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006197 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006198 // of where we need to fill in additional 'const' qualifiers.
Richard Smith5e9746f2016-10-21 22:00:42 +00006199 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006200 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006201
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006202 QualifierUnion.push_back(
6203 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6204 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6205 MemPtr2->getClass()));
6206 continue;
6207 }
Mike Stump11289f42009-09-09 15:08:12 +00006208
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006209 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00006210
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006211 // Cannot unwrap any more types.
6212 break;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006213 }
Mike Stump11289f42009-09-09 15:08:12 +00006214
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006215 // Apply the function pointer conversion to unify the types. We've already
6216 // unwrapped down to the function types, and we want to merge rather than
6217 // just convert, so do this ourselves rather than calling
6218 // IsFunctionConversion.
6219 //
6220 // FIXME: In order to match the standard wording as closely as possible, we
6221 // currently only do this under a single level of pointers. Ideally, we would
6222 // allow this in general, and set NeedConstBefore to the relevant depth on
6223 // the side(s) where we changed anything.
6224 if (QualifierUnion.size() == 1) {
6225 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6226 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6227 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6228 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6229
6230 // The result is noreturn if both operands are.
6231 bool Noreturn =
6232 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6233 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6234 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6235
6236 // The result is nothrow if both operands are.
6237 SmallVector<QualType, 8> ExceptionTypeStorage;
6238 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6239 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6240 ExceptionTypeStorage);
6241
6242 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6243 FPT1->getParamTypes(), EPI1);
6244 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6245 FPT2->getParamTypes(), EPI2);
6246 }
6247 }
6248 }
6249
Richard Smith5e9746f2016-10-21 22:00:42 +00006250 if (NeedConstBefore) {
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006251 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006252 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006253 // requirements of C++ [conv.qual]p4 bullet 3.
Richard Smith5e9746f2016-10-21 22:00:42 +00006254 for (unsigned I = 0; I != NeedConstBefore; ++I)
6255 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006256 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00006257 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006258
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006259 // Rewrap the composites as pointers or member pointers with the union CVRs.
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006260 auto MOC = MemberOfClass.rbegin();
6261 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6262 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6263 auto Classes = *MOC++;
6264 if (Classes.first && Classes.second) {
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006265 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00006266 Composite1 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006267 Context.getQualifiedType(Composite1, Quals), Classes.first);
John McCall8ccfcb52009-09-24 19:53:00 +00006268 Composite2 = Context.getMemberPointerType(
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006269 Context.getQualifiedType(Composite2, Quals), Classes.second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006270 } else {
6271 // Rebuild pointer type
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006272 Composite1 =
6273 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6274 Composite2 =
6275 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006276 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006277 }
6278
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006279 struct Conversion {
6280 Sema &S;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006281 Expr *&E1, *&E2;
6282 QualType Composite;
Richard Smithe38da032016-10-20 07:53:17 +00006283 InitializedEntity Entity;
6284 InitializationKind Kind;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006285 InitializationSequence E1ToC, E2ToC;
Richard Smithe38da032016-10-20 07:53:17 +00006286 bool Viable;
Mike Stump11289f42009-09-09 15:08:12 +00006287
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006288 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6289 QualType Composite)
Richard Smithe38da032016-10-20 07:53:17 +00006290 : S(S), E1(E1), E2(E2), Composite(Composite),
6291 Entity(InitializedEntity::InitializeTemporary(Composite)),
6292 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6293 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6294 Viable(E1ToC && E2ToC) {}
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006295
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006296 bool perform() {
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006297 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6298 if (E1Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006299 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006300 E1 = E1Result.getAs<Expr>();
6301
6302 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6303 if (E2Result.isInvalid())
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006304 return true;
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006305 E2 = E2Result.getAs<Expr>();
6306
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006307 return false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00006308 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006309 };
Douglas Gregor19175ff2010-04-16 23:20:25 +00006310
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006311 // Try to convert to each composite pointer type.
6312 Conversion C1(*this, Loc, E1, E2, Composite1);
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006313 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6314 if (ConvertArgs && C1.perform())
6315 return QualType();
6316 return C1.Composite;
6317 }
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006318 Conversion C2(*this, Loc, E1, E2, Composite2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00006319
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006320 if (C1.Viable == C2.Viable) {
6321 // Either Composite1 and Composite2 are viable and are different, or
6322 // neither is viable.
6323 // FIXME: How both be viable and different?
6324 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006325 }
6326
Richard Smith6ffdb1f2016-10-20 01:20:00 +00006327 // Convert to the chosen type.
Richard Smitheb7ef2e2016-10-20 21:53:09 +00006328 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6329 return QualType();
6330
6331 return C1.Viable ? C1.Composite : C2.Composite;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00006332}
Anders Carlsson85a307d2009-05-17 18:41:29 +00006333
John McCalldadc5752010-08-24 06:29:42 +00006334ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00006335 if (!E)
6336 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006337
John McCall31168b02011-06-15 23:02:42 +00006338 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6339
6340 // If the result is a glvalue, we shouldn't bind it.
6341 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006342 return E;
Mike Stump11289f42009-09-09 15:08:12 +00006343
John McCall31168b02011-06-15 23:02:42 +00006344 // In ARC, calls that return a retainable type can return retained,
6345 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006346 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00006347 E->getType()->isObjCRetainableType()) {
6348
6349 bool ReturnsRetained;
6350
6351 // For actual calls, we compute this by examining the type of the
6352 // called value.
6353 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6354 Expr *Callee = Call->getCallee()->IgnoreParens();
6355 QualType T = Callee->getType();
6356
6357 if (T == Context.BoundMemberTy) {
6358 // Handle pointer-to-members.
6359 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6360 T = BinOp->getRHS()->getType();
6361 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6362 T = Mem->getMemberDecl()->getType();
6363 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006364
John McCall31168b02011-06-15 23:02:42 +00006365 if (const PointerType *Ptr = T->getAs<PointerType>())
6366 T = Ptr->getPointeeType();
6367 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6368 T = Ptr->getPointeeType();
6369 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6370 T = MemPtr->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006371
John McCall31168b02011-06-15 23:02:42 +00006372 const FunctionType *FTy = T->getAs<FunctionType>();
6373 assert(FTy && "call to value not of function type?");
6374 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6375
6376 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6377 // type always produce a +1 object.
6378 } else if (isa<StmtExpr>(E)) {
6379 ReturnsRetained = true;
6380
Ted Kremeneke65b0862012-03-06 20:05:56 +00006381 // We hit this case with the lambda conversion-to-block optimization;
6382 // we don't want any extra casts here.
6383 } else if (isa<CastExpr>(E) &&
6384 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006385 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006386
John McCall31168b02011-06-15 23:02:42 +00006387 // For message sends and property references, we try to find an
6388 // actual method. FIXME: we should infer retention by selector in
6389 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00006390 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00006391 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00006392 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6393 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00006394 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6395 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00006396 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006397 // Don't do reclaims if we're using the zero-element array
6398 // constant.
6399 if (ArrayLit->getNumElements() == 0 &&
6400 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6401 return E;
6402
Ted Kremeneke65b0862012-03-06 20:05:56 +00006403 D = ArrayLit->getArrayWithObjectsMethod();
6404 } else if (ObjCDictionaryLiteral *DictLit
6405 = dyn_cast<ObjCDictionaryLiteral>(E)) {
Akira Hatanaka4d53a1c2017-04-15 06:42:00 +00006406 // Don't do reclaims if we're using the zero-element dictionary
6407 // constant.
6408 if (DictLit->getNumElements() == 0 &&
6409 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6410 return E;
6411
Ted Kremeneke65b0862012-03-06 20:05:56 +00006412 D = DictLit->getDictWithObjectsMethod();
6413 }
John McCall31168b02011-06-15 23:02:42 +00006414
6415 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00006416
6417 // Don't do reclaims on performSelector calls; despite their
6418 // return type, the invoked method doesn't necessarily actually
6419 // return an object.
6420 if (!ReturnsRetained &&
6421 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006422 return E;
John McCall31168b02011-06-15 23:02:42 +00006423 }
6424
John McCall16de4d22011-11-14 19:53:16 +00006425 // Don't reclaim an object of Class type.
6426 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006427 return E;
John McCall16de4d22011-11-14 19:53:16 +00006428
Tim Shen4a05bb82016-06-21 20:29:17 +00006429 Cleanup.setExprNeedsCleanups(true);
John McCall4db5c3c2011-07-07 06:58:02 +00006430
John McCall2d637d22011-09-10 06:18:15 +00006431 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6432 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006433 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6434 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00006435 }
6436
David Blaikiebbafb8a2012-03-11 07:00:24 +00006437 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006438 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00006439
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006440 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6441 // a fast path for the common case that the type is directly a RecordType.
6442 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00006443 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006444 while (!RT) {
6445 switch (T->getTypeClass()) {
6446 case Type::Record:
6447 RT = cast<RecordType>(T);
6448 break;
6449 case Type::ConstantArray:
6450 case Type::IncompleteArray:
6451 case Type::VariableArray:
6452 case Type::DependentSizedArray:
6453 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6454 break;
6455 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006456 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00006457 }
6458 }
Mike Stump11289f42009-09-09 15:08:12 +00006459
Richard Smithfd555f62012-02-22 02:04:18 +00006460 // That should be enough to guarantee that this type is complete, if we're
6461 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00006462 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00006463 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006464 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006465
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006466 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6467 ExpressionEvaluationContextRecord::EK_Decltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00006468 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00006469
John McCall31168b02011-06-15 23:02:42 +00006470 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00006471 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00006472 CheckDestructorAccess(E->getExprLoc(), Destructor,
6473 PDiag(diag::err_access_dtor_temp)
6474 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006475 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6476 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00006477
Richard Smithfd555f62012-02-22 02:04:18 +00006478 // If destructor is trivial, we can avoid the extra copy.
6479 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006480 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00006481
John McCall28fc7092011-11-10 05:35:25 +00006482 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006483 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006484 }
Richard Smitheec915d62012-02-18 04:13:32 +00006485
6486 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00006487 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6488
6489 if (IsDecltype)
6490 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6491
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006492 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00006493}
6494
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006495ExprResult
John McCall5d413782010-12-06 08:20:24 +00006496Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006497 if (SubExpr.isInvalid())
6498 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006499
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006500 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00006501}
6502
John McCall28fc7092011-11-10 05:35:25 +00006503Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00006504 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00006505
Eli Friedman3bda6b12012-02-02 23:15:15 +00006506 CleanupVarDeclMarking();
6507
John McCall28fc7092011-11-10 05:35:25 +00006508 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6509 assert(ExprCleanupObjects.size() >= FirstCleanup);
Tim Shen4a05bb82016-06-21 20:29:17 +00006510 assert(Cleanup.exprNeedsCleanups() ||
6511 ExprCleanupObjects.size() == FirstCleanup);
6512 if (!Cleanup.exprNeedsCleanups())
John McCall28fc7092011-11-10 05:35:25 +00006513 return SubExpr;
6514
Craig Topper5fc8fc22014-08-27 06:28:36 +00006515 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6516 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00006517
Tim Shen4a05bb82016-06-21 20:29:17 +00006518 auto *E = ExprWithCleanups::Create(
6519 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
John McCall28fc7092011-11-10 05:35:25 +00006520 DiscardCleanupsInEvaluationContext();
6521
6522 return E;
6523}
6524
John McCall5d413782010-12-06 08:20:24 +00006525Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00006526 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006527
Eli Friedman3bda6b12012-02-02 23:15:15 +00006528 CleanupVarDeclMarking();
6529
Tim Shen4a05bb82016-06-21 20:29:17 +00006530 if (!Cleanup.exprNeedsCleanups())
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006531 return SubStmt;
6532
6533 // FIXME: In order to attach the temporaries, wrap the statement into
6534 // a StmtExpr; currently this is only used for asm statements.
6535 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6536 // a new AsmStmtWithTemporaries.
Benjamin Kramer07420902017-12-24 16:24:20 +00006537 CompoundStmt *CompStmt = CompoundStmt::Create(
6538 Context, SubStmt, SourceLocation(), SourceLocation());
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006539 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6540 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00006541 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006542}
6543
Richard Smithfd555f62012-02-22 02:04:18 +00006544/// Process the expression contained within a decltype. For such expressions,
6545/// certain semantic checks on temporaries are delayed until this point, and
6546/// are omitted for the 'topmost' call in the decltype expression. If the
6547/// topmost call bound a temporary, strip that temporary off the expression.
6548ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006549 assert(ExprEvalContexts.back().ExprContext ==
6550 ExpressionEvaluationContextRecord::EK_Decltype &&
6551 "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00006552
Akira Hatanaka0a848562019-01-10 20:12:16 +00006553 ExprResult Result = CheckPlaceholderExpr(E);
6554 if (Result.isInvalid())
6555 return ExprError();
6556 E = Result.get();
6557
Richard Smithfd555f62012-02-22 02:04:18 +00006558 // C++11 [expr.call]p11:
6559 // If a function call is a prvalue of object type,
6560 // -- if the function call is either
6561 // -- the operand of a decltype-specifier, or
6562 // -- the right operand of a comma operator that is the operand of a
6563 // decltype-specifier,
6564 // a temporary object is not introduced for the prvalue.
6565
6566 // Recursively rebuild ParenExprs and comma expressions to strip out the
6567 // outermost CXXBindTemporaryExpr, if any.
6568 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6569 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6570 if (SubExpr.isInvalid())
6571 return ExprError();
6572 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006573 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006574 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00006575 }
6576 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6577 if (BO->getOpcode() == BO_Comma) {
6578 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6579 if (RHS.isInvalid())
6580 return ExprError();
6581 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006582 return E;
6583 return new (Context) BinaryOperator(
6584 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
Adam Nemet484aa452017-03-27 19:17:25 +00006585 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
Richard Smithfd555f62012-02-22 02:04:18 +00006586 }
6587 }
6588
6589 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00006590 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6591 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00006592 if (TopCall)
6593 E = TopCall;
6594 else
Craig Topperc3ec1492014-05-26 06:22:03 +00006595 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00006596
6597 // Disable the special decltype handling now.
Nicolas Lesserb6d5c582018-07-12 18:45:41 +00006598 ExprEvalContexts.back().ExprContext =
6599 ExpressionEvaluationContextRecord::EK_Other;
Richard Smithfd555f62012-02-22 02:04:18 +00006600
Richard Smithf86b0ae2012-07-28 19:54:11 +00006601 // In MS mode, don't perform any extra checking of call return types within a
6602 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00006603 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006604 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00006605
Richard Smithfd555f62012-02-22 02:04:18 +00006606 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006607 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6608 I != N; ++I) {
6609 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006610 if (Call == TopCall)
6611 continue;
6612
David Majnemerced8bdf2015-02-25 17:36:15 +00006613 if (CheckCallReturnType(Call->getCallReturnType(Context),
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006614 Call->getBeginLoc(), Call, Call->getDirectCallee()))
Richard Smithfd555f62012-02-22 02:04:18 +00006615 return ExprError();
6616 }
6617
6618 // Now all relevant types are complete, check the destructors are accessible
6619 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00006620 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6621 I != N; ++I) {
6622 CXXBindTemporaryExpr *Bind =
6623 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00006624 if (Bind == TopBind)
6625 continue;
6626
6627 CXXTemporary *Temp = Bind->getTemporary();
6628
6629 CXXRecordDecl *RD =
6630 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6631 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6632 Temp->setDestructor(Destructor);
6633
Richard Smith7d847b12012-05-11 22:20:10 +00006634 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6635 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00006636 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00006637 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00006638 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6639 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00006640
6641 // We need a cleanup, but we don't need to remember the temporary.
Tim Shen4a05bb82016-06-21 20:29:17 +00006642 Cleanup.setExprNeedsCleanups(true);
Richard Smithfd555f62012-02-22 02:04:18 +00006643 }
6644
6645 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006646 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00006647}
6648
Richard Smith79c927b2013-11-06 19:31:51 +00006649/// Note a set of 'operator->' functions that were used for a member access.
6650static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00006651 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00006652 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6653 // FIXME: Make this configurable?
6654 unsigned Limit = 9;
6655 if (OperatorArrows.size() > Limit) {
6656 // Produce Limit-1 normal notes and one 'skipping' note.
6657 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6658 SkipCount = OperatorArrows.size() - (Limit - 1);
6659 }
6660
6661 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6662 if (I == SkipStart) {
6663 S.Diag(OperatorArrows[I]->getLocation(),
6664 diag::note_operator_arrows_suppressed)
6665 << SkipCount;
6666 I += SkipCount;
6667 } else {
6668 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6669 << OperatorArrows[I]->getCallResultType();
6670 ++I;
6671 }
6672 }
6673}
6674
Nico Weber964d3322015-02-16 22:35:45 +00006675ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6676 SourceLocation OpLoc,
6677 tok::TokenKind OpKind,
6678 ParsedType &ObjectType,
6679 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006680 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00006681 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00006682 if (Result.isInvalid()) return ExprError();
6683 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00006684
John McCall526ab472011-10-25 17:37:35 +00006685 Result = CheckPlaceholderExpr(Base);
6686 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006687 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00006688
John McCallb268a282010-08-23 23:25:46 +00006689 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00006690 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006691 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00006692 // If we have a pointer to a dependent type and are using the -> operator,
6693 // the object type is the type that the pointer points to. We might still
6694 // have enough information about that type to do something useful.
6695 if (OpKind == tok::arrow)
6696 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6697 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006698
John McCallba7bf592010-08-24 05:47:05 +00006699 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00006700 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006701 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006702 }
Mike Stump11289f42009-09-09 15:08:12 +00006703
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006704 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00006705 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006706 // returned, with the original second operand.
6707 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00006708 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006709 bool NoArrowOperatorFound = false;
6710 bool FirstIteration = true;
6711 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00006712 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00006713 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00006714 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00006715 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006716
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006717 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00006718 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6719 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00006720 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00006721 noteOperatorArrows(*this, OperatorArrows);
6722 Diag(OpLoc, diag::note_operator_arrow_depth)
6723 << getLangOpts().ArrowDepth;
6724 return ExprError();
6725 }
6726
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006727 Result = BuildOverloadedArrowExpr(
6728 S, Base, OpLoc,
6729 // When in a template specialization and on the first loop iteration,
6730 // potentially give the default diagnostic (with the fixit in a
6731 // separate note) instead of having the error reported back to here
6732 // and giving a diagnostic with a fixit attached to the error itself.
6733 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00006734 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006735 : &NoArrowOperatorFound);
6736 if (Result.isInvalid()) {
6737 if (NoArrowOperatorFound) {
6738 if (FirstIteration) {
6739 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00006740 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006741 << FixItHint::CreateReplacement(OpLoc, ".");
6742 OpKind = tok::period;
6743 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006744 }
6745 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6746 << BaseType << Base->getSourceRange();
6747 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00006748 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006749 Diag(CD->getBeginLoc(),
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00006750 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006751 }
6752 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006753 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006754 }
John McCallb268a282010-08-23 23:25:46 +00006755 Base = Result.get();
6756 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00006757 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00006758 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00006759 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00006760 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00006761 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6762 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00006763 return ExprError();
6764 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006765 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006766 }
Mike Stump11289f42009-09-09 15:08:12 +00006767
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00006768 if (OpKind == tok::arrow &&
6769 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00006770 BaseType = BaseType->getPointeeType();
6771 }
Mike Stump11289f42009-09-09 15:08:12 +00006772
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006773 // Objective-C properties allow "." access on Objective-C pointer types,
6774 // so adjust the base type to the object type itself.
6775 if (BaseType->isObjCObjectPointerType())
6776 BaseType = BaseType->getPointeeType();
Simon Pilgrim75c26882016-09-30 14:25:09 +00006777
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006778 // C++ [basic.lookup.classref]p2:
6779 // [...] If the type of the object expression is of pointer to scalar
6780 // type, the unqualified-id is looked up in the context of the complete
6781 // postfix-expression.
6782 //
6783 // This also indicates that we could be parsing a pseudo-destructor-name.
6784 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00006785 // expressions or normal member (ivar or property) access expressions, and
6786 // it's legal for the type to be incomplete if this is a pseudo-destructor
6787 // call. We'll do more incomplete-type checks later in the lookup process,
6788 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006789 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00006790 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006791 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00006792 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00006793 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00006794 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00006795 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006796 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006797 }
Mike Stump11289f42009-09-09 15:08:12 +00006798
Douglas Gregor3024f072012-04-16 07:05:22 +00006799 // The object type must be complete (or dependent), or
6800 // C++11 [expr.prim.general]p3:
6801 // Unlike the object expression in other contexts, *this is not required to
Simon Pilgrim75c26882016-09-30 14:25:09 +00006802 // be of complete type for purposes of class member access (5.2.5) outside
Douglas Gregor3024f072012-04-16 07:05:22 +00006803 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00006804 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00006805 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006806 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00006807 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006808
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006809 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006810 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00006811 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00006812 // type C (or of pointer to a class type C), the unqualified-id is looked
6813 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00006814 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00006815 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00006816}
6817
Simon Pilgrim75c26882016-09-30 14:25:09 +00006818static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00006819 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00006820 if (Base->hasPlaceholderType()) {
6821 ExprResult result = S.CheckPlaceholderExpr(Base);
6822 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006823 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00006824 }
6825 ObjectType = Base->getType();
6826
David Blaikie1d578782011-12-16 16:03:09 +00006827 // C++ [expr.pseudo]p2:
6828 // The left-hand side of the dot operator shall be of scalar type. The
6829 // left-hand side of the arrow operator shall be of pointer to scalar type.
6830 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00006831 // Note that this is rather different from the normal handling for the
6832 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00006833 if (OpKind == tok::arrow) {
6834 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6835 ObjectType = Ptr->getPointeeType();
6836 } else if (!Base->isTypeDependent()) {
Nico Webera6916892016-06-10 18:53:04 +00006837 // The user wrote "p->" when they probably meant "p."; fix it.
David Blaikie1d578782011-12-16 16:03:09 +00006838 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6839 << ObjectType << true
6840 << FixItHint::CreateReplacement(OpLoc, ".");
6841 if (S.isSFINAEContext())
6842 return true;
6843
6844 OpKind = tok::period;
6845 }
6846 }
6847
6848 return false;
6849}
6850
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006851/// Check if it's ok to try and recover dot pseudo destructor calls on
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006852/// pointer objects.
6853static bool
6854canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6855 QualType DestructedType) {
6856 // If this is a record type, check if its destructor is callable.
6857 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
Bruno Ricci4eb701c2019-01-24 13:52:47 +00006858 if (RD->hasDefinition())
6859 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6860 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006861 return false;
6862 }
6863
6864 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6865 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6866 DestructedType->isVectorType();
6867}
6868
John McCalldadc5752010-08-24 06:29:42 +00006869ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006870 SourceLocation OpLoc,
6871 tok::TokenKind OpKind,
6872 const CXXScopeSpec &SS,
6873 TypeSourceInfo *ScopeTypeInfo,
6874 SourceLocation CCLoc,
6875 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006876 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00006877 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006878
Eli Friedman0ce4de42012-01-25 04:35:06 +00006879 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006880 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6881 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006882
Douglas Gregorc5c57342012-09-10 14:57:06 +00006883 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6884 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00006885 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00006886 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006887 else {
Nico Weber58829272012-01-23 05:50:57 +00006888 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6889 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00006890 return ExprError();
6891 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006892 }
6893
6894 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006895 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006896 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006897 if (DestructedTypeInfo) {
6898 QualType DestructedType = DestructedTypeInfo->getType();
6899 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006900 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00006901 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6902 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006903 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6904 // Foo *foo;
6905 // foo.~Foo();
6906 if (OpKind == tok::period && ObjectType->isPointerType() &&
6907 Context.hasSameUnqualifiedType(DestructedType,
6908 ObjectType->getPointeeType())) {
6909 auto Diagnostic =
6910 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6911 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006912
Alex Lorenz56fb6fe2017-01-20 15:38:58 +00006913 // Issue a fixit only when the destructor is valid.
6914 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6915 *this, DestructedType))
6916 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6917
6918 // Recover by setting the object type to the destructed type and the
6919 // operator to '->'.
6920 ObjectType = DestructedType;
6921 OpKind = tok::arrow;
6922 } else {
6923 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6924 << ObjectType << DestructedType << Base->getSourceRange()
6925 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6926
6927 // Recover by setting the destructed type to the object type.
6928 DestructedType = ObjectType;
6929 DestructedTypeInfo =
6930 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6931 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6932 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006933 } else if (DestructedType.getObjCLifetime() !=
John McCall31168b02011-06-15 23:02:42 +00006934 ObjectType.getObjCLifetime()) {
Simon Pilgrim75c26882016-09-30 14:25:09 +00006935
John McCall31168b02011-06-15 23:02:42 +00006936 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6937 // Okay: just pretend that the user provided the correctly-qualified
6938 // type.
6939 } else {
6940 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6941 << ObjectType << DestructedType << Base->getSourceRange()
6942 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6943 }
Simon Pilgrim75c26882016-09-30 14:25:09 +00006944
John McCall31168b02011-06-15 23:02:42 +00006945 // Recover by setting the destructed type to the object type.
6946 DestructedType = ObjectType;
6947 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6948 DestructedTypeStart);
6949 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6950 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00006951 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006953
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006954 // C++ [expr.pseudo]p2:
6955 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6956 // form
6957 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006958 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006959 //
6960 // shall designate the same scalar type.
6961 if (ScopeTypeInfo) {
6962 QualType ScopeType = ScopeTypeInfo->getType();
6963 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00006964 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006965
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006966 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006967 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00006968 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00006969 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006970
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006971 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00006972 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006973 }
6974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975
John McCallb268a282010-08-23 23:25:46 +00006976 Expr *Result
6977 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6978 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006979 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006980 ScopeTypeInfo,
6981 CCLoc,
6982 TildeLoc,
6983 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006984
David Majnemerced8bdf2015-02-25 17:36:15 +00006985 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006986}
6987
John McCalldadc5752010-08-24 06:29:42 +00006988ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006989 SourceLocation OpLoc,
6990 tok::TokenKind OpKind,
6991 CXXScopeSpec &SS,
6992 UnqualifiedId &FirstTypeName,
6993 SourceLocation CCLoc,
6994 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006995 UnqualifiedId &SecondTypeName) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00006996 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
6997 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006998 "Invalid first type name in pseudo-destructor");
Faisal Vali2ab8c152017-12-30 04:15:27 +00006999 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7000 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007001 "Invalid second type name in pseudo-destructor");
7002
Eli Friedman0ce4de42012-01-25 04:35:06 +00007003 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007004 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7005 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00007006
7007 // Compute the object type that we should use for name lookup purposes. Only
7008 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00007009 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007010 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00007011 if (ObjectType->isRecordType())
7012 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00007013 else if (ObjectType->isDependentType())
7014 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007015 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007016
7017 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007018 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007019 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00007020 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00007021 PseudoDestructorTypeStorage Destructed;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007022 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007023 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007024 SecondTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007025 S, &SS, true, false, ObjectTypePtrForLookup,
7026 /*IsCtorOrDtorName*/true);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007027 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00007028 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7029 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007030 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00007031 // couldn't find anything useful in scope. Just store the identifier and
7032 // it's location, and we'll perform (qualified) name lookup again at
7033 // template instantiation time.
7034 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7035 SecondTypeName.StartLocation);
7036 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007037 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007038 diag::err_pseudo_dtor_destructor_non_type)
7039 << SecondTypeName.Identifier << ObjectType;
7040 if (isSFINAEContext())
7041 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007042
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007043 // Recover by assuming we had the right type all along.
7044 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007045 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007046 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007047 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007048 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007049 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007050 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007051 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007052 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007053 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007054 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007055 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007056 TemplateId->TemplateNameLoc,
7057 TemplateId->LAngleLoc,
7058 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007059 TemplateId->RAngleLoc,
7060 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007061 if (T.isInvalid() || !T.get()) {
7062 // Recover by assuming we had the right type all along.
7063 DestructedType = ObjectType;
7064 } else
7065 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007067
7068 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007069 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00007070 if (!DestructedType.isNull()) {
7071 if (!DestructedTypeInfo)
7072 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007073 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00007074 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7075 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007076
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007077 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00007078 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007079 QualType ScopeType;
Faisal Vali2ab8c152017-12-30 04:15:27 +00007080 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007081 FirstTypeName.Identifier) {
Faisal Vali2ab8c152017-12-30 04:15:27 +00007082 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007083 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00007084 FirstTypeName.StartLocation,
Richard Smith74f02342017-01-19 21:00:13 +00007085 S, &SS, true, false, ObjectTypePtrForLookup,
7086 /*IsCtorOrDtorName*/true);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007087 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007088 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007089 diag::err_pseudo_dtor_destructor_non_type)
7090 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007091
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007092 if (isSFINAEContext())
7093 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007094
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007095 // Just drop this type. It's unnecessary anyway.
7096 ScopeType = QualType();
7097 } else
7098 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007099 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007100 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007101 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00007102 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007103 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00007104 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00007105 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00007106 TemplateId->Template,
Richard Smith74f02342017-01-19 21:00:13 +00007107 TemplateId->Name,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007108 TemplateId->TemplateNameLoc,
7109 TemplateId->LAngleLoc,
7110 TemplateArgsPtr,
Richard Smith74f02342017-01-19 21:00:13 +00007111 TemplateId->RAngleLoc,
7112 /*IsCtorOrDtorName*/true);
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00007113 if (T.isInvalid() || !T.get()) {
7114 // Recover by dropping this type.
7115 ScopeType = QualType();
7116 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007117 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00007118 }
7119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007120
Douglas Gregor90ad9222010-02-24 23:02:30 +00007121 if (!ScopeType.isNull() && !ScopeTypeInfo)
7122 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7123 FirstTypeName.StartLocation);
7124
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007125
John McCallb268a282010-08-23 23:25:46 +00007126 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00007127 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007128 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00007129}
7130
David Blaikie1d578782011-12-16 16:03:09 +00007131ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7132 SourceLocation OpLoc,
7133 tok::TokenKind OpKind,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007134 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007135 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00007136 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00007137 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7138 return ExprError();
7139
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007140 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7141 false);
David Blaikie1d578782011-12-16 16:03:09 +00007142
7143 TypeLocBuilder TLB;
7144 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7145 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7146 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7147 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7148
7149 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00007150 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00007151 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00007152}
7153
John Wiegley01296292011-04-08 18:41:53 +00007154ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00007155 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007156 bool HadMultipleCandidates) {
Richard Smith7ed5fb22018-07-27 17:13:18 +00007157 // Convert the expression to match the conversion function's implicit object
7158 // parameter.
7159 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7160 FoundDecl, Method);
7161 if (Exp.isInvalid())
7162 return true;
7163
Eli Friedman98b01ed2012-03-01 04:01:32 +00007164 if (Method->getParent()->isLambda() &&
7165 Method->getConversionType()->isBlockPointerType()) {
7166 // This is a lambda coversion to block pointer; check if the argument
Richard Smith7ed5fb22018-07-27 17:13:18 +00007167 // was a LambdaExpr.
Eli Friedman98b01ed2012-03-01 04:01:32 +00007168 Expr *SubE = E;
7169 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7170 if (CE && CE->getCastKind() == CK_NoOp)
7171 SubE = CE->getSubExpr();
7172 SubE = SubE->IgnoreParens();
7173 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7174 SubE = BE->getSubExpr();
7175 if (isa<LambdaExpr>(SubE)) {
7176 // For the conversion to block pointer on a lambda expression, we
7177 // construct a special BlockLiteral instead; this doesn't really make
7178 // a difference in ARC, but outside of ARC the resulting block literal
7179 // follows the normal lifetime rules for block literals instead of being
7180 // autoreleased.
7181 DiagnosticErrorTrap Trap(Diags);
Faisal Valid143a0c2017-04-01 21:30:49 +00007182 PushExpressionEvaluationContext(
7183 ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith7ed5fb22018-07-27 17:13:18 +00007184 ExprResult BlockExp = BuildBlockForLambdaConversion(
7185 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
Akira Hatanakac482acd2016-05-04 18:07:20 +00007186 PopExpressionEvaluationContext();
7187
Richard Smith7ed5fb22018-07-27 17:13:18 +00007188 if (BlockExp.isInvalid())
7189 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7190 return BlockExp;
Eli Friedman98b01ed2012-03-01 04:01:32 +00007191 }
7192 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00007193
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00007194 MemberExpr *ME = new (Context) MemberExpr(
7195 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
7196 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007197 if (HadMultipleCandidates)
7198 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00007199 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00007200
Alp Toker314cc812014-01-25 16:55:45 +00007201 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00007202 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7203 ResultType = ResultType.getNonLValueExprType(Context);
7204
Bruno Riccic5885cf2018-12-21 15:20:32 +00007205 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7206 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
George Burgess IVce6284b2017-01-28 02:19:40 +00007207
7208 if (CheckFunctionCall(Method, CE,
7209 Method->getType()->castAs<FunctionProtoType>()))
7210 return ExprError();
7211
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007212 return CE;
7213}
7214
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007215ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7216 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00007217 // If the operand is an unresolved lookup expression, the expression is ill-
7218 // formed per [over.over]p1, because overloaded function names cannot be used
7219 // without arguments except in explicit contexts.
7220 ExprResult R = CheckPlaceholderExpr(Operand);
7221 if (R.isInvalid())
7222 return R;
7223
7224 // The operand may have been modified when checking the placeholder type.
7225 Operand = R.get();
7226
Richard Smith51ec0cf2017-02-21 01:17:38 +00007227 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00007228 // The expression operand for noexcept is in an unevaluated expression
7229 // context, so side effects could result in unintended consequences.
7230 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7231 }
7232
Richard Smithf623c962012-04-17 00:58:00 +00007233 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007234 return new (Context)
7235 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00007236}
7237
7238ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7239 Expr *Operand, SourceLocation RParen) {
7240 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00007241}
7242
Eli Friedmanf798f652012-05-24 22:04:19 +00007243static bool IsSpecialDiscardedValue(Expr *E) {
7244 // In C++11, discarded-value expressions of a certain form are special,
7245 // according to [expr]p10:
7246 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7247 // expression is an lvalue of volatile-qualified type and it has
7248 // one of the following forms:
7249 E = E->IgnoreParens();
7250
Eli Friedmanc49c2262012-05-24 22:36:31 +00007251 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007252 if (isa<DeclRefExpr>(E))
7253 return true;
7254
Eli Friedmanc49c2262012-05-24 22:36:31 +00007255 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007256 if (isa<ArraySubscriptExpr>(E))
7257 return true;
7258
Eli Friedmanc49c2262012-05-24 22:36:31 +00007259 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007260 if (isa<MemberExpr>(E))
7261 return true;
7262
Eli Friedmanc49c2262012-05-24 22:36:31 +00007263 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00007264 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7265 if (UO->getOpcode() == UO_Deref)
7266 return true;
7267
7268 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00007269 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00007270 if (BO->isPtrMemOp())
7271 return true;
7272
Eli Friedmanc49c2262012-05-24 22:36:31 +00007273 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00007274 if (BO->getOpcode() == BO_Comma)
7275 return IsSpecialDiscardedValue(BO->getRHS());
7276 }
7277
Eli Friedmanc49c2262012-05-24 22:36:31 +00007278 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00007279 // operands are one of the above, or
7280 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7281 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7282 IsSpecialDiscardedValue(CO->getFalseExpr());
7283 // The related edge case of "*x ?: *x".
7284 if (BinaryConditionalOperator *BCO =
7285 dyn_cast<BinaryConditionalOperator>(E)) {
7286 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7287 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7288 IsSpecialDiscardedValue(BCO->getFalseExpr());
7289 }
7290
7291 // Objective-C++ extensions to the rule.
7292 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7293 return true;
7294
7295 return false;
7296}
7297
John McCall34376a62010-12-04 03:47:34 +00007298/// Perform the conversions required for an expression used in a
7299/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00007300ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00007301 if (E->hasPlaceholderType()) {
7302 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007303 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007304 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00007305 }
7306
John McCallfee942d2010-12-02 02:07:15 +00007307 // C99 6.3.2.1:
7308 // [Except in specific positions,] an lvalue that does not have
7309 // array type is converted to the value stored in the
7310 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00007311 if (E->isRValue()) {
7312 // In C, function designators (i.e. expressions of function type)
7313 // are r-values, but we still want to do function-to-pointer decay
7314 // on them. This is both technically correct and convenient for
7315 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007316 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00007317 return DefaultFunctionArrayConversion(E);
7318
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007319 return E;
John McCalld68b2d02011-06-27 21:24:11 +00007320 }
John McCallfee942d2010-12-02 02:07:15 +00007321
Eli Friedmanf798f652012-05-24 22:04:19 +00007322 if (getLangOpts().CPlusPlus) {
7323 // The C++11 standard defines the notion of a discarded-value expression;
7324 // normally, we don't need to do anything to handle it, but if it is a
7325 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7326 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007327 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00007328 E->getType().isVolatileQualified() &&
7329 IsSpecialDiscardedValue(E)) {
7330 ExprResult Res = DefaultLvalueConversion(E);
7331 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007332 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007333 E = Res.get();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007334 }
Richard Smith122f88d2016-12-06 23:52:28 +00007335
7336 // C++1z:
7337 // If the expression is a prvalue after this optional conversion, the
7338 // temporary materialization conversion is applied.
7339 //
7340 // We skip this step: IR generation is able to synthesize the storage for
7341 // itself in the aggregate case, and adding the extra node to the AST is
7342 // just clutter.
7343 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7344 // FIXME: Do any other AST consumers care about this?
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007345 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00007346 }
John McCall34376a62010-12-04 03:47:34 +00007347
7348 // GCC seems to also exclude expressions of incomplete enum type.
7349 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7350 if (!T->getDecl()->isComplete()) {
7351 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007352 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007353 return E;
John McCall34376a62010-12-04 03:47:34 +00007354 }
7355 }
7356
John Wiegley01296292011-04-08 18:41:53 +00007357 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7358 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007359 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007360 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00007361
John McCallca61b652010-12-04 12:29:11 +00007362 if (!E->getType()->isVoidType())
7363 RequireCompleteType(E->getExprLoc(), E->getType(),
7364 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007365 return E;
John McCall34376a62010-12-04 03:47:34 +00007366}
7367
Faisal Valia17d19f2013-11-07 05:17:06 +00007368// If we can unambiguously determine whether Var can never be used
7369// in a constant expression, return true.
7370// - if the variable and its initializer are non-dependent, then
7371// we can unambiguously check if the variable is a constant expression.
7372// - if the initializer is not value dependent - we can determine whether
7373// it can be used to initialize a constant expression. If Init can not
Simon Pilgrim75c26882016-09-30 14:25:09 +00007374// be used to initialize a constant expression we conclude that Var can
Faisal Valia17d19f2013-11-07 05:17:06 +00007375// never be a constant expression.
7376// - FXIME: if the initializer is dependent, we can still do some analysis and
7377// identify certain cases unambiguously as non-const by using a Visitor:
7378// - such as those that involve odr-use of a ParmVarDecl, involve a new
7379// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
Simon Pilgrim75c26882016-09-30 14:25:09 +00007380static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
Faisal Valia17d19f2013-11-07 05:17:06 +00007381 ASTContext &Context) {
7382 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00007383 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007384
7385 // If there is no initializer - this can not be a constant expression.
7386 if (!Var->getAnyInitializer(DefVD)) return true;
7387 assert(DefVD);
7388 if (DefVD->isWeak()) return false;
7389 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00007390
Faisal Valia17d19f2013-11-07 05:17:06 +00007391 Expr *Init = cast<Expr>(Eval->Value);
7392
7393 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00007394 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7395 // of value-dependent expressions, and use it here to determine whether the
7396 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007397 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00007398 }
7399
Simon Pilgrim75c26882016-09-30 14:25:09 +00007400 return !IsVariableAConstantExpression(Var, Context);
Faisal Valia17d19f2013-11-07 05:17:06 +00007401}
7402
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007403/// Check if the current lambda has any potential captures
Simon Pilgrim75c26882016-09-30 14:25:09 +00007404/// that must be captured by any of its enclosing lambdas that are ready to
7405/// capture. If there is a lambda that can capture a nested
7406/// potential-capture, go ahead and do so. Also, check to see if any
7407/// variables are uncaptureable or do not involve an odr-use so do not
Faisal Valiab3d6462013-12-07 20:22:44 +00007408/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007409
Faisal Valiab3d6462013-12-07 20:22:44 +00007410static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7411 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7412
Simon Pilgrim75c26882016-09-30 14:25:09 +00007413 assert(!S.isUnevaluatedContext());
7414 assert(S.CurContext->isDependentContext());
Alexey Bataev31939e32016-11-11 12:36:20 +00007415#ifndef NDEBUG
7416 DeclContext *DC = S.CurContext;
7417 while (DC && isa<CapturedDecl>(DC))
7418 DC = DC->getParent();
7419 assert(
7420 CurrentLSI->CallOperator == DC &&
Faisal Valiab3d6462013-12-07 20:22:44 +00007421 "The current call operator must be synchronized with Sema's CurContext");
Alexey Bataev31939e32016-11-11 12:36:20 +00007422#endif // NDEBUG
Faisal Valiab3d6462013-12-07 20:22:44 +00007423
7424 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7425
Faisal Valiab3d6462013-12-07 20:22:44 +00007426 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00007427 // lambda (within a generic outer lambda), must be captured by an
7428 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00007429 const unsigned NumPotentialCaptures =
7430 CurrentLSI->getNumPotentialVariableCaptures();
7431 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00007432 Expr *VarExpr = nullptr;
7433 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00007434 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00007435 // If the variable is clearly identified as non-odr-used and the full
Simon Pilgrim75c26882016-09-30 14:25:09 +00007436 // expression is not instantiation dependent, only then do we not
Faisal Valiab3d6462013-12-07 20:22:44 +00007437 // need to check enclosing lambda's for speculative captures.
7438 // For e.g.:
7439 // Even though 'x' is not odr-used, it should be captured.
7440 // int test() {
7441 // const int x = 10;
7442 // auto L = [=](auto a) {
7443 // (void) +x + a;
7444 // };
7445 // }
7446 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00007447 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00007448 continue;
7449
7450 // If we have a capture-capable lambda for the variable, go ahead and
7451 // capture the variable in that lambda (and all its enclosing lambdas).
7452 if (const Optional<unsigned> Index =
7453 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007454 S.FunctionScopes, Var, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007455 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7456 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7457 &FunctionScopeIndexOfCapturableLambda);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007458 }
7459 const bool IsVarNeverAConstantExpression =
Faisal Valia17d19f2013-11-07 05:17:06 +00007460 VariableCanNeverBeAConstantExpression(Var, S.Context);
7461 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7462 // This full expression is not instantiation dependent or the variable
Simon Pilgrim75c26882016-09-30 14:25:09 +00007463 // can not be used in a constant expression - which means
7464 // this variable must be odr-used here, so diagnose a
Faisal Valia17d19f2013-11-07 05:17:06 +00007465 // capture violation early, if the variable is un-captureable.
7466 // This is purely for diagnosing errors early. Otherwise, this
7467 // error would get diagnosed when the lambda becomes capture ready.
7468 QualType CaptureType, DeclRefType;
7469 SourceLocation ExprLoc = VarExpr->getExprLoc();
7470 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007471 /*EllipsisLoc*/ SourceLocation(),
7472 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007473 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00007474 // We will never be able to capture this variable, and we need
7475 // to be able to in any and all instantiations, so diagnose it.
7476 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
Simon Pilgrim75c26882016-09-30 14:25:09 +00007477 /*EllipsisLoc*/ SourceLocation(),
7478 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00007479 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007480 }
7481 }
7482 }
7483
Faisal Valiab3d6462013-12-07 20:22:44 +00007484 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00007485 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007486 // If we have a capture-capable lambda for 'this', go ahead and capture
7487 // 'this' in that lambda (and all its enclosing lambdas).
7488 if (const Optional<unsigned> Index =
7489 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Reid Kleckner87a31802018-03-12 21:43:02 +00007490 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00007491 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7492 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7493 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7494 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00007495 }
7496 }
Faisal Valiab3d6462013-12-07 20:22:44 +00007497
7498 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00007499 CurrentLSI->clearPotentialCaptures();
7500}
7501
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007502static ExprResult attemptRecovery(Sema &SemaRef,
7503 const TypoCorrectionConsumer &Consumer,
Benjamin Kramer7320b992016-06-15 14:20:56 +00007504 const TypoCorrection &TC) {
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007505 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7506 Consumer.getLookupResult().getLookupKind());
7507 const CXXScopeSpec *SS = Consumer.getSS();
7508 CXXScopeSpec NewSS;
7509
7510 // Use an approprate CXXScopeSpec for building the expr.
7511 if (auto *NNS = TC.getCorrectionSpecifier())
7512 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7513 else if (SS && !TC.WillReplaceSpecifier())
7514 NewSS = *SS;
7515
Richard Smithde6d6c42015-12-29 19:43:10 +00007516 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007517 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007518 R.addDecl(ND);
7519 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00007520 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007521 CXXRecordDecl *Record = nullptr;
7522 if (auto *NNS = TC.getCorrectionSpecifier())
7523 Record = NNS->getAsType()->getAsCXXRecordDecl();
7524 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00007525 Record =
7526 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7527 if (Record)
7528 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007529
7530 // Detect and handle the case where the decl might be an implicit
7531 // member.
7532 bool MightBeImplicitMember;
7533 if (!Consumer.isAddressOfOperand())
7534 MightBeImplicitMember = true;
7535 else if (!NewSS.isEmpty())
7536 MightBeImplicitMember = false;
7537 else if (R.isOverloadedResult())
7538 MightBeImplicitMember = false;
7539 else if (R.isUnresolvableResult())
7540 MightBeImplicitMember = true;
7541 else
7542 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7543 isa<IndirectFieldDecl>(ND) ||
7544 isa<MSPropertyDecl>(ND);
7545
7546 if (MightBeImplicitMember)
7547 return SemaRef.BuildPossibleImplicitMemberExpr(
7548 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00007549 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007550 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7551 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7552 Ivar->getIdentifier());
7553 }
7554 }
7555
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00007556 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7557 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007558}
7559
Kaelyn Takata6c759512014-10-27 18:07:37 +00007560namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007561class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7562 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7563
7564public:
7565 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7566 : TypoExprs(TypoExprs) {}
7567 bool VisitTypoExpr(TypoExpr *TE) {
7568 TypoExprs.insert(TE);
7569 return true;
7570 }
7571};
7572
Kaelyn Takata6c759512014-10-27 18:07:37 +00007573class TransformTypos : public TreeTransform<TransformTypos> {
7574 typedef TreeTransform<TransformTypos> BaseTransform;
7575
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007576 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7577 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00007578 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007579 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007580 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007581 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007582
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007583 /// Emit diagnostics for all of the TypoExprs encountered.
Kaelyn Takata6c759512014-10-27 18:07:37 +00007584 /// If the TypoExprs were successfully corrected, then the diagnostics should
7585 /// suggest the corrections. Otherwise the diagnostics will not suggest
7586 /// anything (having been passed an empty TypoCorrection).
7587 void EmitAllDiagnostics() {
George Burgess IV00f70bd2018-03-01 05:43:23 +00007588 for (TypoExpr *TE : TypoExprs) {
Kaelyn Takata6c759512014-10-27 18:07:37 +00007589 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007590 if (State.DiagHandler) {
7591 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7592 ExprResult Replacement = TransformCache[TE];
7593
7594 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7595 // TypoCorrection, replacing the existing decls. This ensures the right
7596 // NamedDecl is used in diagnostics e.g. in the case where overload
7597 // resolution was used to select one from several possible decls that
7598 // had been stored in the TypoCorrection.
7599 if (auto *ND = getDeclFromExpr(
7600 Replacement.isInvalid() ? nullptr : Replacement.get()))
7601 TC.setCorrectionDecl(ND);
7602
7603 State.DiagHandler(TC);
7604 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007605 SemaRef.clearDelayedTypo(TE);
7606 }
7607 }
7608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007609 /// If corrections for the first TypoExpr have been exhausted for a
Kaelyn Takata6c759512014-10-27 18:07:37 +00007610 /// given combination of the other TypoExprs, retry those corrections against
7611 /// the next combination of substitutions for the other TypoExprs by advancing
7612 /// to the next potential correction of the second TypoExpr. For the second
7613 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7614 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7615 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7616 /// TransformCache). Returns true if there is still any untried combinations
7617 /// of corrections.
7618 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7619 for (auto TE : TypoExprs) {
7620 auto &State = SemaRef.getTypoExprState(TE);
7621 TransformCache.erase(TE);
7622 if (!State.Consumer->finished())
7623 return true;
7624 State.Consumer->resetCorrectionStream();
7625 }
7626 return false;
7627 }
7628
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007629 NamedDecl *getDeclFromExpr(Expr *E) {
7630 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7631 E = OverloadResolution[OE];
7632
7633 if (!E)
7634 return nullptr;
7635 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007636 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007637 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00007638 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007639 // FIXME: Add any other expr types that could be be seen by the delayed typo
7640 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00007641 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007642 return nullptr;
7643 }
7644
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007645 ExprResult TryTransform(Expr *E) {
7646 Sema::SFINAETrap Trap(SemaRef);
7647 ExprResult Res = TransformExpr(E);
7648 if (Trap.hasErrorOccurred() || Res.isInvalid())
7649 return ExprError();
7650
7651 return ExprFilter(Res.get());
7652 }
7653
Kaelyn Takata6c759512014-10-27 18:07:37 +00007654public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007655 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7656 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00007657
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007658 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7659 MultiExprArg Args,
7660 SourceLocation RParenLoc,
7661 Expr *ExecConfig = nullptr) {
7662 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7663 RParenLoc, ExecConfig);
7664 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00007665 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00007666 Expr *ResultCall = Result.get();
7667 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7668 ResultCall = BE->getSubExpr();
7669 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7670 OverloadResolution[OE] = CE->getCallee();
7671 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00007672 }
7673 return Result;
7674 }
7675
Kaelyn Takata6c759512014-10-27 18:07:37 +00007676 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7677
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00007678 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7679
Kaelyn Takata6c759512014-10-27 18:07:37 +00007680 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007681 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007682 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007683 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007684
Kaelyn Takata6c759512014-10-27 18:07:37 +00007685 // Exit if either the transform was valid or if there were no TypoExprs
7686 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007687 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00007688 !CheckAndAdvanceTypoExprCorrectionStreams())
7689 break;
7690 }
7691
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007692 // Ensure none of the TypoExprs have multiple typo correction candidates
7693 // with the same edit length that pass all the checks and filters.
7694 // TODO: Properly handle various permutations of possible corrections when
7695 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007696 // Also, disable typo correction while attempting the transform when
7697 // handling potentially ambiguous typo corrections as any new TypoExprs will
7698 // have been introduced by the application of one of the correction
7699 // candidates and add little to no value if corrected.
7700 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007701 while (!AmbiguousTypoExprs.empty()) {
7702 auto TE = AmbiguousTypoExprs.back();
7703 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00007704 auto &State = SemaRef.getTypoExprState(TE);
7705 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007706 TransformCache.erase(TE);
7707 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00007708 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007709 TransformCache.erase(TE);
7710 Res = ExprError();
7711 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00007712 }
7713 AmbiguousTypoExprs.remove(TE);
7714 State.Consumer->restoreSavedPosition();
7715 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007716 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00007717 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007718
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007719 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007720 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00007721 FindTypoExprs(TypoExprs).TraverseStmt(E);
7722
Kaelyn Takata6c759512014-10-27 18:07:37 +00007723 EmitAllDiagnostics();
7724
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007725 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00007726 }
7727
7728 ExprResult TransformTypoExpr(TypoExpr *E) {
7729 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7730 // cached transformation result if there is one and the TypoExpr isn't the
7731 // first one that was encountered.
7732 auto &CacheEntry = TransformCache[E];
7733 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7734 return CacheEntry;
7735 }
7736
7737 auto &State = SemaRef.getTypoExprState(E);
7738 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7739
7740 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7741 // typo correction and return it.
7742 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00007743 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007744 continue;
Richard Smith1cf45412017-01-04 23:14:16 +00007745 // FIXME: If we would typo-correct to an invalid declaration, it's
7746 // probably best to just suppress all errors from this typo correction.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007747 ExprResult NE = State.RecoveryHandler ?
7748 State.RecoveryHandler(SemaRef, E, TC) :
7749 attemptRecovery(SemaRef, *State.Consumer, TC);
7750 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007751 // Check whether there may be a second viable correction with the same
7752 // edit distance; if so, remember this TypoExpr may have an ambiguous
7753 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007754 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00007755 if ((Next = State.Consumer->peekNextCorrection()) &&
7756 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7757 AmbiguousTypoExprs.insert(E);
7758 } else {
7759 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007760 }
7761 assert(!NE.isUnset() &&
7762 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00007763 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00007764 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00007765 }
7766 return CacheEntry = ExprError();
7767 }
7768};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007769}
Faisal Valia17d19f2013-11-07 05:17:06 +00007770
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007771ExprResult
7772Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7773 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007774 // If the current evaluation context indicates there are uncorrected typos
7775 // and the current expression isn't guaranteed to not have typos, try to
7776 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00007777 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00007778 (E->isTypeDependent() || E->isValueDependent() ||
7779 E->isInstantiationDependent())) {
7780 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00007781 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00007782 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00007783 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00007784 ExprEvalContexts.back().NumTypos -= TyposResolved;
7785 return Result;
7786 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00007787 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00007788 }
7789 return E;
7790}
7791
Richard Smith945f8d32013-01-14 22:39:08 +00007792ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007793 bool DiscardedValue,
Richard Smithb3d203f2018-10-19 19:01:34 +00007794 bool IsConstexpr) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00007795 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00007796
7797 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00007798 return ExprError();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007799
Richard Smithb3d203f2018-10-19 19:01:34 +00007800 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00007801 return ExprError();
7802
Richard Smith945f8d32013-01-14 22:39:08 +00007803 if (DiscardedValue) {
Richard Smithb3d203f2018-10-19 19:01:34 +00007804 // Top-level expressions default to 'id' when we're in a debugger.
7805 if (getLangOpts().DebuggerCastResultToId &&
7806 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7807 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7808 if (FullExpr.isInvalid())
7809 return ExprError();
7810 }
7811
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007812 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007813 if (FullExpr.isInvalid())
7814 return ExprError();
7815
Nikola Smiljanic01a75982014-05-29 10:55:11 +00007816 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007817 if (FullExpr.isInvalid())
7818 return ExprError();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007819
7820 DiagnoseUnusedExprResult(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00007821 }
John Wiegley01296292011-04-08 18:41:53 +00007822
Kaelyn Takata49d84322014-11-11 23:26:56 +00007823 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7824 if (FullExpr.isInvalid())
7825 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00007826
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007827 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00007828
Simon Pilgrim75c26882016-09-30 14:25:09 +00007829 // At the end of this full expression (which could be a deeply nested
7830 // lambda), if there is a potential capture within the nested lambda,
Faisal Vali218e94b2013-11-12 03:56:08 +00007831 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00007832 // Consider the following code:
7833 // void f(int, int);
7834 // void f(const int&, double);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007835 // void foo() {
Faisal Valia17d19f2013-11-07 05:17:06 +00007836 // const int x = 10, y = 20;
7837 // auto L = [=](auto a) {
7838 // auto M = [=](auto b) {
7839 // f(x, b); <-- requires x to be captured by L and M
7840 // f(y, a); <-- requires y to be captured by L, but not all Ms
7841 // };
7842 // };
7843 // }
7844
Simon Pilgrim75c26882016-09-30 14:25:09 +00007845 // FIXME: Also consider what happens for something like this that involves
7846 // the gnu-extension statement-expressions or even lambda-init-captures:
Faisal Valia17d19f2013-11-07 05:17:06 +00007847 // void f() {
7848 // const int n = 0;
7849 // auto L = [&](auto a) {
7850 // +n + ({ 0; a; });
7851 // };
7852 // }
Simon Pilgrim75c26882016-09-30 14:25:09 +00007853 //
7854 // Here, we see +n, and then the full-expression 0; ends, so we don't
7855 // capture n (and instead remove it from our list of potential captures),
7856 // and then the full-expression +n + ({ 0; }); ends, but it's too late
Faisal Vali218e94b2013-11-12 03:56:08 +00007857 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00007858
Alexey Bataev31939e32016-11-11 12:36:20 +00007859 LambdaScopeInfo *const CurrentLSI =
7860 getCurLambda(/*IgnoreCapturedRegions=*/true);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007861 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007862 // even if CurContext is not a lambda call operator. Refer to that Bug Report
Simon Pilgrim75c26882016-09-30 14:25:09 +00007863 // for an example of the code that might cause this asynchrony.
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007864 // By ensuring we are in the context of a lambda's call operator
7865 // we can fix the bug (we only need to check whether we need to capture
Simon Pilgrim75c26882016-09-30 14:25:09 +00007866 // if we are within a lambda's body); but per the comments in that
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007867 // PR, a proper fix would entail :
7868 // "Alternative suggestion:
Simon Pilgrim75c26882016-09-30 14:25:09 +00007869 // - Add to Sema an integer holding the smallest (outermost) scope
7870 // index that we are *lexically* within, and save/restore/set to
7871 // FunctionScopes.size() in InstantiatingTemplate's
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007872 // constructor/destructor.
Simon Pilgrim75c26882016-09-30 14:25:09 +00007873 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00007874 // stop at the outermost enclosing lexical scope."
Alexey Bataev31939e32016-11-11 12:36:20 +00007875 DeclContext *DC = CurContext;
7876 while (DC && isa<CapturedDecl>(DC))
7877 DC = DC->getParent();
7878 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
Faisal Valiab3d6462013-12-07 20:22:44 +00007879 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00007880 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00007881 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7882 *this);
John McCall5d413782010-12-06 08:20:24 +00007883 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00007884}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007885
7886StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7887 if (!FullStmt) return StmtError();
7888
John McCall5d413782010-12-06 08:20:24 +00007889 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00007890}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007891
Simon Pilgrim75c26882016-09-30 14:25:09 +00007892Sema::IfExistsResult
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007893Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7894 CXXScopeSpec &SS,
7895 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007896 DeclarationName TargetName = TargetNameInfo.getName();
7897 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00007898 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007899
Douglas Gregor43edb322011-10-24 22:31:10 +00007900 // If the name itself is dependent, then the result is dependent.
7901 if (TargetName.isDependentName())
7902 return IER_Dependent;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007903
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007904 // Do the redeclaration lookup in the current scope.
7905 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7906 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00007907 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007908 R.suppressDiagnostics();
Simon Pilgrim75c26882016-09-30 14:25:09 +00007909
Douglas Gregor43edb322011-10-24 22:31:10 +00007910 switch (R.getResultKind()) {
7911 case LookupResult::Found:
7912 case LookupResult::FoundOverloaded:
7913 case LookupResult::FoundUnresolvedValue:
7914 case LookupResult::Ambiguous:
7915 return IER_Exists;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007916
Douglas Gregor43edb322011-10-24 22:31:10 +00007917 case LookupResult::NotFound:
7918 return IER_DoesNotExist;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007919
Douglas Gregor43edb322011-10-24 22:31:10 +00007920 case LookupResult::NotFoundInCurrentInstantiation:
7921 return IER_Dependent;
7922 }
David Blaikie8a40f702012-01-17 06:56:22 +00007923
7924 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00007925}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007926
Simon Pilgrim75c26882016-09-30 14:25:09 +00007927Sema::IfExistsResult
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007928Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7929 bool IsIfExists, CXXScopeSpec &SS,
7930 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007931 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Simon Pilgrim75c26882016-09-30 14:25:09 +00007932
Richard Smith151c4562016-12-20 21:35:28 +00007933 // Check for an unexpanded parameter pack.
7934 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7935 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7936 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00007937 return IER_Error;
Simon Pilgrim75c26882016-09-30 14:25:09 +00007938
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00007939 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7940}