1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Implements semantic analysis for C++ expressions.
11///
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DynamicRecursiveASTVisitor.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprConcepts.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/Type.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/AlignedAllocation.h"
29#include "clang/Basic/DiagnosticSema.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Basic/TokenKinds.h"
33#include "clang/Lex/Preprocessor.h"
34#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/EnterExpressionEvaluationContext.h"
36#include "clang/Sema/Initialization.h"
37#include "clang/Sema/Lookup.h"
38#include "clang/Sema/ParsedTemplate.h"
39#include "clang/Sema/Scope.h"
40#include "clang/Sema/ScopeInfo.h"
41#include "clang/Sema/SemaCUDA.h"
42#include "clang/Sema/SemaHLSL.h"
43#include "clang/Sema/SemaLambda.h"
44#include "clang/Sema/SemaObjC.h"
45#include "clang/Sema/SemaPPC.h"
46#include "clang/Sema/Template.h"
47#include "clang/Sema/TemplateDeduction.h"
48#include "llvm/ADT/APInt.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/ADT/StringExtras.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/TypeSize.h"
53#include <optional>
54using namespace clang;
55using namespace sema;
56
57ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
58 SourceLocation NameLoc,
59 const IdentifierInfo &Name) {
60 NestedNameSpecifier NNS = SS.getScopeRep();
61 QualType Type(NNS.getAsType(), 0);
62 if ([[maybe_unused]] const auto *DNT = dyn_cast<DependentNameType>(Val&: Type))
63 assert(DNT->getIdentifier() == &Name && "not a constructor name");
64
65 // This reference to the type is located entirely at the location of the
66 // final identifier in the qualified-id.
67 return CreateParsedType(T: Type,
68 TInfo: Context.getTrivialTypeSourceInfo(T: Type, Loc: NameLoc));
69}
70
71ParsedType Sema::getConstructorName(const IdentifierInfo &II,
72 SourceLocation NameLoc, Scope *S,
73 CXXScopeSpec &SS, bool EnteringContext) {
74 CXXRecordDecl *CurClass = getCurrentClass(S, SS: &SS);
75 assert(CurClass && &II == CurClass->getIdentifier() &&
76 "not a constructor name");
77
78 // When naming a constructor as a member of a dependent context (eg, in a
79 // friend declaration or an inherited constructor declaration), form an
80 // unresolved "typename" type.
81 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
82 QualType T = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
83 NNS: SS.getScopeRep(), Name: &II);
84 return ParsedType::make(P: T);
85 }
86
87 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, DC: CurClass))
88 return ParsedType();
89
90 // Find the injected-class-name declaration. Note that we make no attempt to
91 // diagnose cases where the injected-class-name is shadowed: the only
92 // declaration that can validly shadow the injected-class-name is a
93 // non-static data member, and if the class contains both a non-static data
94 // member and a constructor then it is ill-formed (we check that in
95 // CheckCompletedCXXClass).
96 CXXRecordDecl *InjectedClassName = nullptr;
97 for (NamedDecl *ND : CurClass->lookup(Name: &II)) {
98 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
99 if (RD && RD->isInjectedClassName()) {
100 InjectedClassName = RD;
101 break;
102 }
103 }
104 if (!InjectedClassName) {
105 if (!CurClass->isInvalidDecl()) {
106 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
107 // properly. Work around it here for now.
108 Diag(Loc: SS.getLastQualifierNameLoc(),
109 DiagID: diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
110 }
111 return ParsedType();
112 }
113
114 QualType T = Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier: SS.getScopeRep(),
115 TD: InjectedClassName, /*OwnsTag=*/false);
116 return ParsedType::make(P: T);
117}
118
119ParsedType Sema::getDestructorName(const IdentifierInfo &II,
120 SourceLocation NameLoc, Scope *S,
121 CXXScopeSpec &SS, ParsedType ObjectTypePtr,
122 bool EnteringContext) {
123 // Determine where to perform name lookup.
124
125 // FIXME: This area of the standard is very messy, and the current
126 // wording is rather unclear about which scopes we search for the
127 // destructor name; see core issues 399 and 555. Issue 399 in
128 // particular shows where the current description of destructor name
129 // lookup is completely out of line with existing practice, e.g.,
130 // this appears to be ill-formed:
131 //
132 // namespace N {
133 // template <typename T> struct S {
134 // ~S();
135 // };
136 // }
137 //
138 // void f(N::S<int>* s) {
139 // s->N::S<int>::~S();
140 // }
141 //
142 // See also PR6358 and PR6359.
143 //
144 // For now, we accept all the cases in which the name given could plausibly
145 // be interpreted as a correct destructor name, issuing off-by-default
146 // extension diagnostics on the cases that don't strictly conform to the
147 // C++20 rules. This basically means we always consider looking in the
148 // nested-name-specifier prefix, the complete nested-name-specifier, and
149 // the scope, and accept if we find the expected type in any of the three
150 // places.
151
152 if (SS.isInvalid())
153 return nullptr;
154
155 // Whether we've failed with a diagnostic already.
156 bool Failed = false;
157
158 llvm::SmallVector<NamedDecl*, 8> FoundDecls;
159 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
160
161 // If we have an object type, it's because we are in a
162 // pseudo-destructor-expression or a member access expression, and
163 // we know what type we're looking for.
164 QualType SearchType =
165 ObjectTypePtr ? GetTypeFromParser(Ty: ObjectTypePtr) : QualType();
166
167 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
168 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
169 auto *Type = dyn_cast<TypeDecl>(Val: D->getUnderlyingDecl());
170 if (!Type)
171 return false;
172
173 if (SearchType.isNull() || SearchType->isDependentType())
174 return true;
175
176 CanQualType T = Context.getCanonicalTypeDeclType(TD: Type);
177 return Context.hasSameUnqualifiedType(T1: T, T2: SearchType);
178 };
179
180 unsigned NumAcceptableResults = 0;
181 for (NamedDecl *D : Found) {
182 if (IsAcceptableResult(D))
183 ++NumAcceptableResults;
184
185 // Don't list a class twice in the lookup failure diagnostic if it's
186 // found by both its injected-class-name and by the name in the enclosing
187 // scope.
188 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
189 if (RD->isInjectedClassName())
190 D = cast<NamedDecl>(Val: RD->getParent());
191
192 if (FoundDeclSet.insert(Ptr: D).second)
193 FoundDecls.push_back(Elt: D);
194 }
195
196 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
197 // results, and all non-matching results if we have a search type. It's not
198 // clear what the right behavior is if destructor lookup hits an ambiguity,
199 // but other compilers do generally accept at least some kinds of
200 // ambiguity.
201 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
202 Diag(Loc: NameLoc, DiagID: diag::ext_dtor_name_ambiguous);
203 LookupResult::Filter F = Found.makeFilter();
204 while (F.hasNext()) {
205 NamedDecl *D = F.next();
206 if (auto *TD = dyn_cast<TypeDecl>(Val: D->getUnderlyingDecl()))
207 Diag(Loc: D->getLocation(), DiagID: diag::note_destructor_type_here)
208 << Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None,
209 /*Qualifier=*/std::nullopt, Decl: TD);
210 else
211 Diag(Loc: D->getLocation(), DiagID: diag::note_destructor_nontype_here);
212
213 if (!IsAcceptableResult(D))
214 F.erase();
215 }
216 F.done();
217 }
218
219 if (Found.isAmbiguous())
220 Failed = true;
221
222 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
223 if (IsAcceptableResult(Type)) {
224 QualType T = Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None,
225 /*Qualifier=*/std::nullopt, Decl: Type);
226 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
227 return CreateParsedType(T,
228 TInfo: Context.getTrivialTypeSourceInfo(T, Loc: NameLoc));
229 }
230 }
231
232 return nullptr;
233 };
234
235 bool IsDependent = false;
236
237 auto LookupInObjectType = [&]() -> ParsedType {
238 if (Failed || SearchType.isNull())
239 return nullptr;
240
241 IsDependent |= SearchType->isDependentType();
242
243 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
244 DeclContext *LookupCtx = computeDeclContext(T: SearchType);
245 if (!LookupCtx)
246 return nullptr;
247 LookupQualifiedName(R&: Found, LookupCtx);
248 return CheckLookupResult(Found);
249 };
250
251 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
252 if (Failed)
253 return nullptr;
254
255 IsDependent |= isDependentScopeSpecifier(SS: LookupSS);
256 DeclContext *LookupCtx = computeDeclContext(SS: LookupSS, EnteringContext);
257 if (!LookupCtx)
258 return nullptr;
259
260 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
261 if (RequireCompleteDeclContext(SS&: LookupSS, DC: LookupCtx)) {
262 Failed = true;
263 return nullptr;
264 }
265 LookupQualifiedName(R&: Found, LookupCtx);
266 return CheckLookupResult(Found);
267 };
268
269 auto LookupInScope = [&]() -> ParsedType {
270 if (Failed || !S)
271 return nullptr;
272
273 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
274 LookupName(R&: Found, S);
275 return CheckLookupResult(Found);
276 };
277
278 // C++2a [basic.lookup.qual]p6:
279 // In a qualified-id of the form
280 //
281 // nested-name-specifier[opt] type-name :: ~ type-name
282 //
283 // the second type-name is looked up in the same scope as the first.
284 //
285 // We interpret this as meaning that if you do a dual-scope lookup for the
286 // first name, you also do a dual-scope lookup for the second name, per
287 // C++ [basic.lookup.classref]p4:
288 //
289 // If the id-expression in a class member access is a qualified-id of the
290 // form
291 //
292 // class-name-or-namespace-name :: ...
293 //
294 // the class-name-or-namespace-name following the . or -> is first looked
295 // up in the class of the object expression and the name, if found, is used.
296 // Otherwise, it is looked up in the context of the entire
297 // postfix-expression.
298 //
299 // This looks in the same scopes as for an unqualified destructor name:
300 //
301 // C++ [basic.lookup.classref]p3:
302 // If the unqualified-id is ~ type-name, the type-name is looked up
303 // in the context of the entire postfix-expression. If the type T
304 // of the object expression is of a class type C, the type-name is
305 // also looked up in the scope of class C. At least one of the
306 // lookups shall find a name that refers to cv T.
307 //
308 // FIXME: The intent is unclear here. Should type-name::~type-name look in
309 // the scope anyway if it finds a non-matching name declared in the class?
310 // If both lookups succeed and find a dependent result, which result should
311 // we retain? (Same question for p->~type-name().)
312
313 auto Prefix = [&]() -> NestedNameSpecifierLoc {
314 NestedNameSpecifierLoc NNS = SS.getWithLocInContext(Context);
315 if (!NNS)
316 return NestedNameSpecifierLoc();
317 if (auto TL = NNS.getAsTypeLoc())
318 return TL.getPrefix();
319 return NNS.getAsNamespaceAndPrefix().Prefix;
320 }();
321
322 if (Prefix) {
323 // This is
324 //
325 // nested-name-specifier type-name :: ~ type-name
326 //
327 // Look for the second type-name in the nested-name-specifier.
328 CXXScopeSpec PrefixSS;
329 PrefixSS.Adopt(Other: Prefix);
330 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
331 return T;
332 } else {
333 // This is one of
334 //
335 // type-name :: ~ type-name
336 // ~ type-name
337 //
338 // Look in the scope and (if any) the object type.
339 if (ParsedType T = LookupInScope())
340 return T;
341 if (ParsedType T = LookupInObjectType())
342 return T;
343 }
344
345 if (Failed)
346 return nullptr;
347
348 if (IsDependent) {
349 // We didn't find our type, but that's OK: it's dependent anyway.
350
351 // FIXME: What if we have no nested-name-specifier?
352 TypeSourceInfo *TSI = nullptr;
353 QualType T =
354 CheckTypenameType(Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
355 QualifierLoc: SS.getWithLocInContext(Context), II, IILoc: NameLoc, TSI: &TSI,
356 /*DeducedTSTContext=*/true);
357 if (T.isNull())
358 return ParsedType();
359 return CreateParsedType(T, TInfo: TSI);
360 }
361
362 // The remaining cases are all non-standard extensions imitating the behavior
363 // of various other compilers.
364 unsigned NumNonExtensionDecls = FoundDecls.size();
365
366 if (SS.isSet()) {
367 // For compatibility with older broken C++ rules and existing code,
368 //
369 // nested-name-specifier :: ~ type-name
370 //
371 // also looks for type-name within the nested-name-specifier.
372 if (ParsedType T = LookupInNestedNameSpec(SS)) {
373 Diag(Loc: SS.getEndLoc(), DiagID: diag::ext_dtor_named_in_wrong_scope)
374 << SS.getRange()
375 << FixItHint::CreateInsertion(InsertionLoc: SS.getEndLoc(),
376 Code: ("::" + II.getName()).str());
377 return T;
378 }
379
380 // For compatibility with other compilers and older versions of Clang,
381 //
382 // nested-name-specifier type-name :: ~ type-name
383 //
384 // also looks for type-name in the scope. Unfortunately, we can't
385 // reasonably apply this fallback for dependent nested-name-specifiers.
386 if (Prefix) {
387 if (ParsedType T = LookupInScope()) {
388 Diag(Loc: SS.getEndLoc(), DiagID: diag::ext_qualified_dtor_named_in_lexical_scope)
389 << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
390 Diag(Loc: FoundDecls.back()->getLocation(), DiagID: diag::note_destructor_type_here)
391 << GetTypeFromParser(Ty: T);
392 return T;
393 }
394 }
395 }
396
397 // We didn't find anything matching; tell the user what we did find (if
398 // anything).
399
400 // Don't tell the user about declarations we shouldn't have found.
401 FoundDecls.resize(N: NumNonExtensionDecls);
402
403 // List types before non-types.
404 llvm::stable_sort(Range&: FoundDecls, C: [](NamedDecl *A, NamedDecl *B) {
405 return isa<TypeDecl>(Val: A->getUnderlyingDecl()) >
406 isa<TypeDecl>(Val: B->getUnderlyingDecl());
407 });
408
409 // Suggest a fixit to properly name the destroyed type.
410 auto MakeFixItHint = [&]{
411 const CXXRecordDecl *Destroyed = nullptr;
412 // FIXME: If we have a scope specifier, suggest its last component?
413 if (!SearchType.isNull())
414 Destroyed = SearchType->getAsCXXRecordDecl();
415 else if (S)
416 Destroyed = dyn_cast_or_null<CXXRecordDecl>(Val: S->getEntity());
417 if (Destroyed)
418 return FixItHint::CreateReplacement(RemoveRange: SourceRange(NameLoc),
419 Code: Destroyed->getNameAsString());
420 return FixItHint();
421 };
422
423 if (FoundDecls.empty()) {
424 // FIXME: Attempt typo-correction?
425 Diag(Loc: NameLoc, DiagID: diag::err_undeclared_destructor_name)
426 << &II << MakeFixItHint();
427 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
428 if (auto *TD = dyn_cast<TypeDecl>(Val: FoundDecls[0]->getUnderlyingDecl())) {
429 assert(!SearchType.isNull() &&
430 "should only reject a type result if we have a search type");
431 Diag(Loc: NameLoc, DiagID: diag::err_destructor_expr_type_mismatch)
432 << Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None,
433 /*Qualifier=*/std::nullopt, Decl: TD)
434 << SearchType << MakeFixItHint();
435 } else {
436 Diag(Loc: NameLoc, DiagID: diag::err_destructor_expr_nontype)
437 << &II << MakeFixItHint();
438 }
439 } else {
440 Diag(Loc: NameLoc, DiagID: SearchType.isNull() ? diag::err_destructor_name_nontype
441 : diag::err_destructor_expr_mismatch)
442 << &II << SearchType << MakeFixItHint();
443 }
444
445 for (NamedDecl *FoundD : FoundDecls) {
446 if (auto *TD = dyn_cast<TypeDecl>(Val: FoundD->getUnderlyingDecl()))
447 Diag(Loc: FoundD->getLocation(), DiagID: diag::note_destructor_type_here)
448 << Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None,
449 /*Qualifier=*/std::nullopt, Decl: TD);
450 else
451 Diag(Loc: FoundD->getLocation(), DiagID: diag::note_destructor_nontype_here)
452 << FoundD;
453 }
454
455 return nullptr;
456}
457
458ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
459 ParsedType ObjectType) {
460 if (DS.getTypeSpecType() == DeclSpec::TST_error)
461 return nullptr;
462
463 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
464 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
465 return nullptr;
466 }
467
468 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
469 "unexpected type in getDestructorType");
470 QualType T = BuildDecltypeType(E: DS.getRepAsExpr());
471
472 // If we know the type of the object, check that the correct destructor
473 // type was named now; we can give better diagnostics this way.
474 QualType SearchType = GetTypeFromParser(Ty: ObjectType);
475 if (!SearchType.isNull() && !SearchType->isDependentType() &&
476 !Context.hasSameUnqualifiedType(T1: T, T2: SearchType)) {
477 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_destructor_expr_type_mismatch)
478 << T << SearchType;
479 return nullptr;
480 }
481
482 return ParsedType::make(P: T);
483}
484
485bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
486 const UnqualifiedId &Name, bool IsUDSuffix) {
487 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
488 if (!IsUDSuffix) {
489 // [over.literal] p8
490 //
491 // double operator""_Bq(long double); // OK: not a reserved identifier
492 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
493 const IdentifierInfo *II = Name.Identifier;
494 ReservedIdentifierStatus Status = II->isReserved(LangOpts: PP.getLangOpts());
495 SourceLocation Loc = Name.getEndLoc();
496
497 auto Hint = FixItHint::CreateReplacement(
498 RemoveRange: Name.getSourceRange(),
499 Code: (StringRef("operator\"\"") + II->getName()).str());
500
501 // Only emit this diagnostic if we start with an underscore, else the
502 // diagnostic for C++11 requiring a space between the quotes and the
503 // identifier conflicts with this and gets confusing. The diagnostic stating
504 // this is a reserved name should force the underscore, which gets this
505 // back.
506 if (II->isReservedLiteralSuffixId() !=
507 ReservedLiteralSuffixIdStatus::NotStartsWithUnderscore)
508 Diag(Loc, DiagID: diag::warn_deprecated_literal_operator_id) << II << Hint;
509
510 if (isReservedInAllContexts(Status))
511 Diag(Loc, DiagID: diag::warn_reserved_extern_symbol)
512 << II << static_cast<int>(Status) << Hint;
513 }
514
515 switch (SS.getScopeRep().getKind()) {
516 case NestedNameSpecifier::Kind::Type:
517 // Per C++11 [over.literal]p2, literal operators can only be declared at
518 // namespace scope. Therefore, this unqualified-id cannot name anything.
519 // Reject it early, because we have no AST representation for this in the
520 // case where the scope is dependent.
521 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_literal_operator_id_outside_namespace)
522 << SS.getScopeRep();
523 return true;
524
525 case NestedNameSpecifier::Kind::Null:
526 case NestedNameSpecifier::Kind::Global:
527 case NestedNameSpecifier::Kind::MicrosoftSuper:
528 case NestedNameSpecifier::Kind::Namespace:
529 return false;
530 }
531
532 llvm_unreachable("unknown nested name specifier kind");
533}
534
535ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
536 SourceLocation TypeidLoc,
537 TypeSourceInfo *Operand,
538 SourceLocation RParenLoc) {
539 // C++ [expr.typeid]p4:
540 // The top-level cv-qualifiers of the lvalue expression or the type-id
541 // that is the operand of typeid are always ignored.
542 // If the type of the type-id is a class type or a reference to a class
543 // type, the class shall be completely-defined.
544 Qualifiers Quals;
545 QualType T
546 = Context.getUnqualifiedArrayType(T: Operand->getType().getNonReferenceType(),
547 Quals);
548 if (T->isRecordType() &&
549 RequireCompleteType(Loc: TypeidLoc, T, DiagID: diag::err_incomplete_typeid))
550 return ExprError();
551
552 if (T->isVariablyModifiedType())
553 return ExprError(Diag(Loc: TypeidLoc, DiagID: diag::err_variably_modified_typeid) << T);
554
555 if (CheckQualifiedFunctionForTypeId(T, Loc: TypeidLoc))
556 return ExprError();
557
558 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
559 SourceRange(TypeidLoc, RParenLoc));
560}
561
562ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
563 SourceLocation TypeidLoc,
564 Expr *E,
565 SourceLocation RParenLoc) {
566 bool WasEvaluated = false;
567 if (E && !E->isTypeDependent()) {
568 if (E->hasPlaceholderType()) {
569 ExprResult result = CheckPlaceholderExpr(E);
570 if (result.isInvalid()) return ExprError();
571 E = result.get();
572 }
573
574 QualType T = E->getType();
575 if (auto *RecordD = T->getAsCXXRecordDecl()) {
576 // C++ [expr.typeid]p3:
577 // [...] If the type of the expression is a class type, the class
578 // shall be completely-defined.
579 if (RequireCompleteType(Loc: TypeidLoc, T, DiagID: diag::err_incomplete_typeid))
580 return ExprError();
581
582 // C++ [expr.typeid]p3:
583 // When typeid is applied to an expression other than an glvalue of a
584 // polymorphic class type [...] [the] expression is an unevaluated
585 // operand. [...]
586 if (RecordD->isPolymorphic() && E->isGLValue()) {
587 if (isUnevaluatedContext()) {
588 // The operand was processed in unevaluated context, switch the
589 // context and recheck the subexpression.
590 ExprResult Result = TransformToPotentiallyEvaluated(E);
591 if (Result.isInvalid())
592 return ExprError();
593 E = Result.get();
594 }
595
596 // We require a vtable to query the type at run time.
597 MarkVTableUsed(Loc: TypeidLoc, Class: RecordD);
598 WasEvaluated = true;
599 }
600 }
601
602 ExprResult Result = CheckUnevaluatedOperand(E);
603 if (Result.isInvalid())
604 return ExprError();
605 E = Result.get();
606
607 // C++ [expr.typeid]p4:
608 // [...] If the type of the type-id is a reference to a possibly
609 // cv-qualified type, the result of the typeid expression refers to a
610 // std::type_info object representing the cv-unqualified referenced
611 // type.
612 Qualifiers Quals;
613 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
614 if (!Context.hasSameType(T1: T, T2: UnqualT)) {
615 T = UnqualT;
616 E = ImpCastExprToType(E, Type: UnqualT, CK: CK_NoOp, VK: E->getValueKind()).get();
617 }
618 }
619
620 if (E->getType()->isVariablyModifiedType())
621 return ExprError(Diag(Loc: TypeidLoc, DiagID: diag::err_variably_modified_typeid)
622 << E->getType());
623 else if (!inTemplateInstantiation() &&
624 E->HasSideEffects(Ctx: Context, IncludePossibleEffects: WasEvaluated)) {
625 // The expression operand for typeid is in an unevaluated expression
626 // context, so side effects could result in unintended consequences.
627 Diag(Loc: E->getExprLoc(), DiagID: WasEvaluated
628 ? diag::warn_side_effects_typeid
629 : diag::warn_side_effects_unevaluated_context);
630 }
631
632 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
633 SourceRange(TypeidLoc, RParenLoc));
634}
635
636/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
637ExprResult
638Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
639 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
640 // typeid is not supported in OpenCL.
641 if (getLangOpts().OpenCLCPlusPlus) {
642 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_openclcxx_not_supported)
643 << "typeid");
644 }
645
646 // Find the std::type_info type.
647 if (!getStdNamespace()) {
648 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_need_header_before_typeid)
649 << (getLangOpts().CPlusPlus20 ? 1 : 0));
650 }
651
652 if (!CXXTypeInfoDecl) {
653 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get(Name: "type_info");
654 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
655 LookupQualifiedName(R, LookupCtx: getStdNamespace());
656 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
657 // Microsoft's typeinfo doesn't have type_info in std but in the global
658 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
659 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
660 LookupQualifiedName(R, LookupCtx: Context.getTranslationUnitDecl());
661 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
662 }
663 if (!CXXTypeInfoDecl)
664 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_need_header_before_typeid)
665 << (getLangOpts().CPlusPlus20 ? 1 : 0));
666 }
667
668 if (!getLangOpts().RTTI) {
669 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_no_typeid_with_fno_rtti));
670 }
671
672 CanQualType TypeInfoType = Context.getCanonicalTagType(TD: CXXTypeInfoDecl);
673
674 if (isType) {
675 // The operand is a type; handle it as such.
676 TypeSourceInfo *TInfo = nullptr;
677 QualType T = GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrExpr),
678 TInfo: &TInfo);
679 if (T.isNull())
680 return ExprError();
681
682 if (!TInfo)
683 TInfo = Context.getTrivialTypeSourceInfo(T, Loc: OpLoc);
684
685 return BuildCXXTypeId(TypeInfoType, TypeidLoc: OpLoc, Operand: TInfo, RParenLoc);
686 }
687
688 // The operand is an expression.
689 ExprResult Result =
690 BuildCXXTypeId(TypeInfoType, TypeidLoc: OpLoc, E: (Expr *)TyOrExpr, RParenLoc);
691
692 if (!getLangOpts().RTTIData && !Result.isInvalid())
693 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Val: Result.get()))
694 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
695 Diag(Loc: OpLoc, DiagID: diag::warn_no_typeid_with_rtti_disabled)
696 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
697 DiagnosticOptions::MSVC);
698 return Result;
699}
700
701/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
702/// a single GUID.
703static void
704getUuidAttrOfType(Sema &SemaRef, QualType QT,
705 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
706 // Optionally remove one level of pointer, reference or array indirection.
707 const Type *Ty = QT.getTypePtr();
708 if (QT->isPointerOrReferenceType())
709 Ty = QT->getPointeeType().getTypePtr();
710 else if (QT->isArrayType())
711 Ty = Ty->getBaseElementTypeUnsafe();
712
713 const auto *TD = Ty->getAsTagDecl();
714 if (!TD)
715 return;
716
717 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
718 UuidAttrs.insert(X: Uuid);
719 return;
720 }
721
722 // __uuidof can grab UUIDs from template arguments.
723 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: TD)) {
724 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
725 for (const TemplateArgument &TA : TAL.asArray()) {
726 const UuidAttr *UuidForTA = nullptr;
727 if (TA.getKind() == TemplateArgument::Type)
728 getUuidAttrOfType(SemaRef, QT: TA.getAsType(), UuidAttrs);
729 else if (TA.getKind() == TemplateArgument::Declaration)
730 getUuidAttrOfType(SemaRef, QT: TA.getAsDecl()->getType(), UuidAttrs);
731
732 if (UuidForTA)
733 UuidAttrs.insert(X: UuidForTA);
734 }
735 }
736}
737
738ExprResult Sema::BuildCXXUuidof(QualType Type,
739 SourceLocation TypeidLoc,
740 TypeSourceInfo *Operand,
741 SourceLocation RParenLoc) {
742 MSGuidDecl *Guid = nullptr;
743 if (!Operand->getType()->isDependentType()) {
744 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
745 getUuidAttrOfType(SemaRef&: *this, QT: Operand->getType(), UuidAttrs);
746 if (UuidAttrs.empty())
747 return ExprError(Diag(Loc: TypeidLoc, DiagID: diag::err_uuidof_without_guid));
748 if (UuidAttrs.size() > 1)
749 return ExprError(Diag(Loc: TypeidLoc, DiagID: diag::err_uuidof_with_multiple_guids));
750 Guid = UuidAttrs.back()->getGuidDecl();
751 }
752
753 return new (Context)
754 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
755}
756
757ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
758 Expr *E, SourceLocation RParenLoc) {
759 MSGuidDecl *Guid = nullptr;
760 if (!E->getType()->isDependentType()) {
761 if (E->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
762 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
763 Guid = Context.getMSGuidDecl(Parts: MSGuidDecl::Parts{});
764 } else {
765 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
766 getUuidAttrOfType(SemaRef&: *this, QT: E->getType(), UuidAttrs);
767 if (UuidAttrs.empty())
768 return ExprError(Diag(Loc: TypeidLoc, DiagID: diag::err_uuidof_without_guid));
769 if (UuidAttrs.size() > 1)
770 return ExprError(Diag(Loc: TypeidLoc, DiagID: diag::err_uuidof_with_multiple_guids));
771 Guid = UuidAttrs.back()->getGuidDecl();
772 }
773 }
774
775 return new (Context)
776 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
777}
778
779/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
780ExprResult
781Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
782 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
783 QualType GuidType = Context.getMSGuidType();
784 GuidType.addConst();
785
786 if (isType) {
787 // The operand is a type; handle it as such.
788 TypeSourceInfo *TInfo = nullptr;
789 QualType T = GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: TyOrExpr),
790 TInfo: &TInfo);
791 if (T.isNull())
792 return ExprError();
793
794 if (!TInfo)
795 TInfo = Context.getTrivialTypeSourceInfo(T, Loc: OpLoc);
796
797 return BuildCXXUuidof(Type: GuidType, TypeidLoc: OpLoc, Operand: TInfo, RParenLoc);
798 }
799
800 // The operand is an expression.
801 return BuildCXXUuidof(Type: GuidType, TypeidLoc: OpLoc, E: (Expr*)TyOrExpr, RParenLoc);
802}
803
804ExprResult
805Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
806 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
807 "Unknown C++ Boolean value!");
808 return new (Context)
809 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
810}
811
812ExprResult
813Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
814 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
815}
816
817ExprResult
818Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
819 bool IsThrownVarInScope = false;
820 if (Ex) {
821 // C++0x [class.copymove]p31:
822 // When certain criteria are met, an implementation is allowed to omit the
823 // copy/move construction of a class object [...]
824 //
825 // - in a throw-expression, when the operand is the name of a
826 // non-volatile automatic object (other than a function or catch-
827 // clause parameter) whose scope does not extend beyond the end of the
828 // innermost enclosing try-block (if there is one), the copy/move
829 // operation from the operand to the exception object (15.1) can be
830 // omitted by constructing the automatic object directly into the
831 // exception object
832 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: Ex->IgnoreParens()))
833 if (const auto *Var = dyn_cast<VarDecl>(Val: DRE->getDecl());
834 Var && Var->hasLocalStorage() &&
835 !Var->getType().isVolatileQualified()) {
836 for (; S; S = S->getParent()) {
837 if (S->isDeclScope(D: Var)) {
838 IsThrownVarInScope = true;
839 break;
840 }
841
842 // FIXME: Many of the scope checks here seem incorrect.
843 if (S->getFlags() &
844 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
845 Scope::ObjCMethodScope | Scope::TryScope))
846 break;
847 }
848 }
849 }
850
851 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
852}
853
854ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
855 bool IsThrownVarInScope) {
856 const llvm::Triple &T = Context.getTargetInfo().getTriple();
857 const bool IsOpenMPGPUTarget =
858 getLangOpts().OpenMPIsTargetDevice && T.isGPU();
859
860 DiagnoseExceptionUse(Loc: OpLoc, /* IsTry= */ false);
861
862 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
863 if (IsOpenMPGPUTarget)
864 targetDiag(Loc: OpLoc, DiagID: diag::warn_throw_not_valid_on_target) << T.str();
865
866 // Exceptions aren't allowed in CUDA device code.
867 if (getLangOpts().CUDA)
868 CUDA().DiagIfDeviceCode(Loc: OpLoc, DiagID: diag::err_cuda_device_exceptions)
869 << "throw" << CUDA().CurrentTarget();
870
871 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
872 Diag(Loc: OpLoc, DiagID: diag::err_omp_simd_region_cannot_use_stmt) << "throw";
873
874 // Exceptions that escape a compute construct are ill-formed.
875 if (getLangOpts().OpenACC && getCurScope() &&
876 getCurScope()->isInOpenACCComputeConstructScope(Flags: Scope::TryScope))
877 Diag(Loc: OpLoc, DiagID: diag::err_acc_branch_in_out_compute_construct)
878 << /*throw*/ 2 << /*out of*/ 0;
879
880 if (Ex && !Ex->isTypeDependent()) {
881 // Initialize the exception result. This implicitly weeds out
882 // abstract types or types with inaccessible copy constructors.
883
884 // C++0x [class.copymove]p31:
885 // When certain criteria are met, an implementation is allowed to omit the
886 // copy/move construction of a class object [...]
887 //
888 // - in a throw-expression, when the operand is the name of a
889 // non-volatile automatic object (other than a function or
890 // catch-clause
891 // parameter) whose scope does not extend beyond the end of the
892 // innermost enclosing try-block (if there is one), the copy/move
893 // operation from the operand to the exception object (15.1) can be
894 // omitted by constructing the automatic object directly into the
895 // exception object
896 NamedReturnInfo NRInfo =
897 IsThrownVarInScope ? getNamedReturnInfo(E&: Ex) : NamedReturnInfo();
898
899 QualType ExceptionObjectTy = Context.getExceptionObjectType(T: Ex->getType());
900 if (CheckCXXThrowOperand(ThrowLoc: OpLoc, ThrowTy: ExceptionObjectTy, E: Ex))
901 return ExprError();
902
903 InitializedEntity Entity =
904 InitializedEntity::InitializeException(ThrowLoc: OpLoc, Type: ExceptionObjectTy);
905 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Value: Ex);
906 if (Res.isInvalid())
907 return ExprError();
908 Ex = Res.get();
909 }
910
911 // PPC MMA non-pointer types are not allowed as throw expr types.
912 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
913 PPC().CheckPPCMMAType(Type: Ex->getType(), TypeLoc: Ex->getBeginLoc());
914
915 return new (Context)
916 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
917}
918
919static void
920collectPublicBases(CXXRecordDecl *RD,
921 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
922 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
923 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
924 bool ParentIsPublic) {
925 for (const CXXBaseSpecifier &BS : RD->bases()) {
926 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
927 bool NewSubobject;
928 // Virtual bases constitute the same subobject. Non-virtual bases are
929 // always distinct subobjects.
930 if (BS.isVirtual())
931 NewSubobject = VBases.insert(Ptr: BaseDecl).second;
932 else
933 NewSubobject = true;
934
935 if (NewSubobject)
936 ++SubobjectsSeen[BaseDecl];
937
938 // Only add subobjects which have public access throughout the entire chain.
939 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
940 if (PublicPath)
941 PublicSubobjectsSeen.insert(X: BaseDecl);
942
943 // Recurse on to each base subobject.
944 collectPublicBases(RD: BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
945 ParentIsPublic: PublicPath);
946 }
947}
948
949static void getUnambiguousPublicSubobjects(
950 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
951 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
952 llvm::SmallPtrSet<CXXRecordDecl *, 2> VBases;
953 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
954 SubobjectsSeen[RD] = 1;
955 PublicSubobjectsSeen.insert(X: RD);
956 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
957 /*ParentIsPublic=*/true);
958
959 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
960 // Skip ambiguous objects.
961 if (SubobjectsSeen[PublicSubobject] > 1)
962 continue;
963
964 Objects.push_back(Elt: PublicSubobject);
965 }
966}
967
968bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
969 QualType ExceptionObjectTy, Expr *E) {
970 // If the type of the exception would be an incomplete type or a pointer
971 // to an incomplete type other than (cv) void the program is ill-formed.
972 QualType Ty = ExceptionObjectTy;
973 bool isPointer = false;
974 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
975 Ty = Ptr->getPointeeType();
976 isPointer = true;
977 }
978
979 // Cannot throw WebAssembly reference type.
980 if (Ty.isWebAssemblyReferenceType()) {
981 Diag(Loc: ThrowLoc, DiagID: diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
982 return true;
983 }
984
985 // Cannot throw WebAssembly table.
986 if (isPointer && Ty.isWebAssemblyReferenceType()) {
987 Diag(Loc: ThrowLoc, DiagID: diag::err_wasm_table_art) << 2 << E->getSourceRange();
988 return true;
989 }
990
991 if (!isPointer || !Ty->isVoidType()) {
992 if (RequireCompleteType(Loc: ThrowLoc, T: Ty,
993 DiagID: isPointer ? diag::err_throw_incomplete_ptr
994 : diag::err_throw_incomplete,
995 Args: E->getSourceRange()))
996 return true;
997
998 if (!isPointer && Ty->isSizelessType()) {
999 Diag(Loc: ThrowLoc, DiagID: diag::err_throw_sizeless) << Ty << E->getSourceRange();
1000 return true;
1001 }
1002
1003 if (RequireNonAbstractType(Loc: ThrowLoc, T: ExceptionObjectTy,
1004 DiagID: diag::err_throw_abstract_type, Args: E))
1005 return true;
1006 }
1007
1008 // If the exception has class type, we need additional handling.
1009 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
1010 if (!RD)
1011 return false;
1012
1013 // If we are throwing a polymorphic class type or pointer thereof,
1014 // exception handling will make use of the vtable.
1015 MarkVTableUsed(Loc: ThrowLoc, Class: RD);
1016
1017 // If a pointer is thrown, the referenced object will not be destroyed.
1018 if (isPointer)
1019 return false;
1020
1021 // If the class has a destructor, we must be able to call it.
1022 if (!RD->hasIrrelevantDestructor()) {
1023 if (CXXDestructorDecl *Destructor = LookupDestructor(Class: RD)) {
1024 MarkFunctionReferenced(Loc: E->getExprLoc(), Func: Destructor);
1025 CheckDestructorAccess(Loc: E->getExprLoc(), Dtor: Destructor,
1026 PDiag: PDiag(DiagID: diag::err_access_dtor_exception) << Ty);
1027 if (DiagnoseUseOfDecl(D: Destructor, Locs: E->getExprLoc()))
1028 return true;
1029 }
1030 }
1031
1032 // The MSVC ABI creates a list of all types which can catch the exception
1033 // object. This list also references the appropriate copy constructor to call
1034 // if the object is caught by value and has a non-trivial copy constructor.
1035 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1036 // We are only interested in the public, unambiguous bases contained within
1037 // the exception object. Bases which are ambiguous or otherwise
1038 // inaccessible are not catchable types.
1039 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1040 getUnambiguousPublicSubobjects(RD, Objects&: UnambiguousPublicSubobjects);
1041
1042 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1043 // Attempt to lookup the copy constructor. Various pieces of machinery
1044 // will spring into action, like template instantiation, which means this
1045 // cannot be a simple walk of the class's decls. Instead, we must perform
1046 // lookup and overload resolution.
1047 CXXConstructorDecl *CD = LookupCopyingConstructor(Class: Subobject, Quals: 0);
1048 if (!CD || CD->isDeleted())
1049 continue;
1050
1051 // Mark the constructor referenced as it is used by this throw expression.
1052 MarkFunctionReferenced(Loc: E->getExprLoc(), Func: CD);
1053
1054 // Skip this copy constructor if it is trivial, we don't need to record it
1055 // in the catchable type data.
1056 if (CD->isTrivial())
1057 continue;
1058
1059 // The copy constructor is non-trivial, create a mapping from this class
1060 // type to this constructor.
1061 // N.B. The selection of copy constructor is not sensitive to this
1062 // particular throw-site. Lookup will be performed at the catch-site to
1063 // ensure that the copy constructor is, in fact, accessible (via
1064 // friendship or any other means).
1065 Context.addCopyConstructorForExceptionObject(RD: Subobject, CD);
1066
1067 // We don't keep the instantiated default argument expressions around so
1068 // we must rebuild them here.
1069 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1070 if (CheckCXXDefaultArgExpr(CallLoc: ThrowLoc, FD: CD, Param: CD->getParamDecl(i: I)))
1071 return true;
1072 }
1073 }
1074 }
1075
1076 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1077 // the runtime with no ability for the compiler to request additional
1078 // alignment. Warn if the exception type requires alignment beyond the minimum
1079 // guaranteed by the target C++ runtime.
1080 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1081 CharUnits TypeAlign = Context.getTypeAlignInChars(T: Ty);
1082 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1083 if (ExnObjAlign < TypeAlign) {
1084 Diag(Loc: ThrowLoc, DiagID: diag::warn_throw_underaligned_obj);
1085 Diag(Loc: ThrowLoc, DiagID: diag::note_throw_underaligned_obj)
1086 << Ty << (unsigned)TypeAlign.getQuantity()
1087 << (unsigned)ExnObjAlign.getQuantity();
1088 }
1089 }
1090 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1091 if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1092 auto Ty = Dtor->getType();
1093 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1094 if (!isUnresolvedExceptionSpec(ESpecType: FT->getExceptionSpecType()) &&
1095 !FT->isNothrow())
1096 Diag(Loc: ThrowLoc, DiagID: diag::err_throw_object_throwing_dtor) << RD;
1097 }
1098 }
1099 }
1100
1101 return false;
1102}
1103
1104static QualType adjustCVQualifiersForCXXThisWithinLambda(
1105 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1106 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1107
1108 QualType ClassType = ThisTy->getPointeeType();
1109 LambdaScopeInfo *CurLSI = nullptr;
1110 DeclContext *CurDC = CurSemaContext;
1111
1112 // Iterate through the stack of lambdas starting from the innermost lambda to
1113 // the outermost lambda, checking if '*this' is ever captured by copy - since
1114 // that could change the cv-qualifiers of the '*this' object.
1115 // The object referred to by '*this' starts out with the cv-qualifiers of its
1116 // member function. We then start with the innermost lambda and iterate
1117 // outward checking to see if any lambda performs a by-copy capture of '*this'
1118 // - and if so, any nested lambda must respect the 'constness' of that
1119 // capturing lamdbda's call operator.
1120 //
1121
1122 // Since the FunctionScopeInfo stack is representative of the lexical
1123 // nesting of the lambda expressions during initial parsing (and is the best
1124 // place for querying information about captures about lambdas that are
1125 // partially processed) and perhaps during instantiation of function templates
1126 // that contain lambda expressions that need to be transformed BUT not
1127 // necessarily during instantiation of a nested generic lambda's function call
1128 // operator (which might even be instantiated at the end of the TU) - at which
1129 // time the DeclContext tree is mature enough to query capture information
1130 // reliably - we use a two pronged approach to walk through all the lexically
1131 // enclosing lambda expressions:
1132 //
1133 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1134 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1135 // enclosed by the call-operator of the LSI below it on the stack (while
1136 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1137 // the stack represents the innermost lambda.
1138 //
1139 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1140 // represents a lambda's call operator. If it does, we must be instantiating
1141 // a generic lambda's call operator (represented by the Current LSI, and
1142 // should be the only scenario where an inconsistency between the LSI and the
1143 // DeclContext should occur), so climb out the DeclContexts if they
1144 // represent lambdas, while querying the corresponding closure types
1145 // regarding capture information.
1146
1147 // 1) Climb down the function scope info stack.
1148 for (int I = FunctionScopes.size();
1149 I-- && isa<LambdaScopeInfo>(Val: FunctionScopes[I]) &&
1150 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1151 cast<LambdaScopeInfo>(Val: FunctionScopes[I])->CallOperator);
1152 CurDC = getLambdaAwareParentOfDeclContext(DC: CurDC)) {
1153 CurLSI = cast<LambdaScopeInfo>(Val: FunctionScopes[I]);
1154
1155 if (!CurLSI->isCXXThisCaptured())
1156 continue;
1157
1158 auto C = CurLSI->getCXXThisCapture();
1159
1160 if (C.isCopyCapture()) {
1161 if (CurLSI->lambdaCaptureShouldBeConst())
1162 ClassType.addConst();
1163 return ASTCtx.getPointerType(T: ClassType);
1164 }
1165 }
1166
1167 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1168 // can happen during instantiation of its nested generic lambda call
1169 // operator); 2. if we're in a lambda scope (lambda body).
1170 if (CurLSI && isLambdaCallOperator(DC: CurDC)) {
1171 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1172 "While computing 'this' capture-type for a generic lambda, when we "
1173 "run out of enclosing LSI's, yet the enclosing DC is a "
1174 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1175 "lambda call oeprator");
1176 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1177
1178 auto IsThisCaptured =
1179 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1180 IsConst = false;
1181 IsByCopy = false;
1182 for (auto &&C : Closure->captures()) {
1183 if (C.capturesThis()) {
1184 if (C.getCaptureKind() == LCK_StarThis)
1185 IsByCopy = true;
1186 if (Closure->getLambdaCallOperator()->isConst())
1187 IsConst = true;
1188 return true;
1189 }
1190 }
1191 return false;
1192 };
1193
1194 bool IsByCopyCapture = false;
1195 bool IsConstCapture = false;
1196 CXXRecordDecl *Closure = cast<CXXRecordDecl>(Val: CurDC->getParent());
1197 while (Closure &&
1198 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1199 if (IsByCopyCapture) {
1200 if (IsConstCapture)
1201 ClassType.addConst();
1202 return ASTCtx.getPointerType(T: ClassType);
1203 }
1204 Closure = isLambdaCallOperator(DC: Closure->getParent())
1205 ? cast<CXXRecordDecl>(Val: Closure->getParent()->getParent())
1206 : nullptr;
1207 }
1208 }
1209 return ThisTy;
1210}
1211
1212QualType Sema::getCurrentThisType() {
1213 DeclContext *DC = getFunctionLevelDeclContext();
1214 QualType ThisTy = CXXThisTypeOverride;
1215
1216 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(Val: DC)) {
1217 if (method && method->isImplicitObjectMemberFunction())
1218 ThisTy = method->getThisType().getNonReferenceType();
1219 }
1220
1221 if (ThisTy.isNull() && isLambdaCallWithImplicitObjectParameter(DC: CurContext) &&
1222 inTemplateInstantiation() && isa<CXXRecordDecl>(Val: DC)) {
1223
1224 // This is a lambda call operator that is being instantiated as a default
1225 // initializer. DC must point to the enclosing class type, so we can recover
1226 // the 'this' type from it.
1227 CanQualType ClassTy = Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: DC));
1228 // There are no cv-qualifiers for 'this' within default initializers,
1229 // per [expr.prim.general]p4.
1230 ThisTy = Context.getPointerType(T: ClassTy);
1231 }
1232
1233 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1234 // might need to be adjusted if the lambda or any of its enclosing lambda's
1235 // captures '*this' by copy.
1236 if (!ThisTy.isNull() && isLambdaCallOperator(DC: CurContext))
1237 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1238 CurSemaContext: CurContext, ASTCtx&: Context);
1239 return ThisTy;
1240}
1241
1242Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1243 Decl *ContextDecl,
1244 Qualifiers CXXThisTypeQuals,
1245 bool Enabled)
1246 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1247{
1248 if (!Enabled || !ContextDecl)
1249 return;
1250
1251 CXXRecordDecl *Record = nullptr;
1252 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(Val: ContextDecl))
1253 Record = Template->getTemplatedDecl();
1254 else
1255 Record = cast<CXXRecordDecl>(Val: ContextDecl);
1256
1257 // 'this' never refers to the lambda class itself.
1258 if (Record->isLambda())
1259 return;
1260
1261 QualType T = S.Context.getCanonicalTagType(TD: Record);
1262 T = S.getASTContext().getQualifiedType(T, Qs: CXXThisTypeQuals);
1263
1264 S.CXXThisTypeOverride =
1265 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1266
1267 this->Enabled = true;
1268}
1269
1270
1271Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1272 if (Enabled) {
1273 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1274 }
1275}
1276
1277static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
1278 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1279 assert(!LSI->isCXXThisCaptured());
1280 // [=, this] {}; // until C++20: Error: this when = is the default
1281 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
1282 !Sema.getLangOpts().CPlusPlus20)
1283 return;
1284 Sema.Diag(Loc: DiagLoc, DiagID: diag::note_lambda_this_capture_fixit)
1285 << FixItHint::CreateInsertion(
1286 InsertionLoc: DiagLoc, Code: LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1287}
1288
1289bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1290 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1291 const bool ByCopy) {
1292 // We don't need to capture this in an unevaluated context.
1293 if (isUnevaluatedContext() && !Explicit)
1294 return true;
1295
1296 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1297
1298 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1299 ? *FunctionScopeIndexToStopAt
1300 : FunctionScopes.size() - 1;
1301
1302 // Check that we can capture the *enclosing object* (referred to by '*this')
1303 // by the capturing-entity/closure (lambda/block/etc) at
1304 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1305
1306 // Note: The *enclosing object* can only be captured by-value by a
1307 // closure that is a lambda, using the explicit notation:
1308 // [*this] { ... }.
1309 // Every other capture of the *enclosing object* results in its by-reference
1310 // capture.
1311
1312 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1313 // stack), we can capture the *enclosing object* only if:
1314 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1315 // - or, 'L' has an implicit capture.
1316 // AND
1317 // -- there is no enclosing closure
1318 // -- or, there is some enclosing closure 'E' that has already captured the
1319 // *enclosing object*, and every intervening closure (if any) between 'E'
1320 // and 'L' can implicitly capture the *enclosing object*.
1321 // -- or, every enclosing closure can implicitly capture the
1322 // *enclosing object*
1323
1324
1325 unsigned NumCapturingClosures = 0;
1326 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1327 if (CapturingScopeInfo *CSI =
1328 dyn_cast<CapturingScopeInfo>(Val: FunctionScopes[idx])) {
1329 if (CSI->CXXThisCaptureIndex != 0) {
1330 // 'this' is already being captured; there isn't anything more to do.
1331 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(IsODRUse: BuildAndDiagnose);
1332 break;
1333 }
1334 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI);
1335 if (LSI && isGenericLambdaCallOperatorSpecialization(MD: LSI->CallOperator)) {
1336 // This context can't implicitly capture 'this'; fail out.
1337 if (BuildAndDiagnose) {
1338 LSI->CallOperator->setInvalidDecl();
1339 Diag(Loc, DiagID: diag::err_this_capture)
1340 << (Explicit && idx == MaxFunctionScopesIndex);
1341 if (!Explicit)
1342 buildLambdaThisCaptureFixit(Sema&: *this, LSI);
1343 }
1344 return true;
1345 }
1346 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1347 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1348 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1349 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1350 (Explicit && idx == MaxFunctionScopesIndex)) {
1351 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1352 // iteration through can be an explicit capture, all enclosing closures,
1353 // if any, must perform implicit captures.
1354
1355 // This closure can capture 'this'; continue looking upwards.
1356 NumCapturingClosures++;
1357 continue;
1358 }
1359 // This context can't implicitly capture 'this'; fail out.
1360 if (BuildAndDiagnose) {
1361 LSI->CallOperator->setInvalidDecl();
1362 Diag(Loc, DiagID: diag::err_this_capture)
1363 << (Explicit && idx == MaxFunctionScopesIndex);
1364 }
1365 if (!Explicit)
1366 buildLambdaThisCaptureFixit(Sema&: *this, LSI);
1367 return true;
1368 }
1369 break;
1370 }
1371 if (!BuildAndDiagnose) return false;
1372
1373 // If we got here, then the closure at MaxFunctionScopesIndex on the
1374 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1375 // (including implicit by-reference captures in any enclosing closures).
1376
1377 // In the loop below, respect the ByCopy flag only for the closure requesting
1378 // the capture (i.e. first iteration through the loop below). Ignore it for
1379 // all enclosing closure's up to NumCapturingClosures (since they must be
1380 // implicitly capturing the *enclosing object* by reference (see loop
1381 // above)).
1382 assert((!ByCopy ||
1383 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1384 "Only a lambda can capture the enclosing object (referred to by "
1385 "*this) by copy");
1386 QualType ThisTy = getCurrentThisType();
1387 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1388 --idx, --NumCapturingClosures) {
1389 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(Val: FunctionScopes[idx]);
1390
1391 // The type of the corresponding data member (not a 'this' pointer if 'by
1392 // copy').
1393 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1394
1395 bool isNested = NumCapturingClosures > 1;
1396 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1397 }
1398 return false;
1399}
1400
1401ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1402 // C++20 [expr.prim.this]p1:
1403 // The keyword this names a pointer to the object for which an
1404 // implicit object member function is invoked or a non-static
1405 // data member's initializer is evaluated.
1406 QualType ThisTy = getCurrentThisType();
1407
1408 if (CheckCXXThisType(Loc, Type: ThisTy))
1409 return ExprError();
1410
1411 return BuildCXXThisExpr(Loc, Type: ThisTy, /*IsImplicit=*/false);
1412}
1413
1414bool Sema::CheckCXXThisType(SourceLocation Loc, QualType Type) {
1415 if (!Type.isNull())
1416 return false;
1417
1418 // C++20 [expr.prim.this]p3:
1419 // If a declaration declares a member function or member function template
1420 // of a class X, the expression this is a prvalue of type
1421 // "pointer to cv-qualifier-seq X" wherever X is the current class between
1422 // the optional cv-qualifier-seq and the end of the function-definition,
1423 // member-declarator, or declarator. It shall not appear within the
1424 // declaration of either a static member function or an explicit object
1425 // member function of the current class (although its type and value
1426 // category are defined within such member functions as they are within
1427 // an implicit object member function).
1428 DeclContext *DC = getFunctionLevelDeclContext();
1429 const auto *Method = dyn_cast<CXXMethodDecl>(Val: DC);
1430 if (Method && Method->isExplicitObjectMemberFunction()) {
1431 Diag(Loc, DiagID: diag::err_invalid_this_use) << 1;
1432 } else if (Method && isLambdaCallWithExplicitObjectParameter(DC: CurContext)) {
1433 Diag(Loc, DiagID: diag::err_invalid_this_use) << 1;
1434 } else {
1435 Diag(Loc, DiagID: diag::err_invalid_this_use) << 0;
1436 }
1437 return true;
1438}
1439
1440Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1441 bool IsImplicit) {
1442 auto *This = CXXThisExpr::Create(Ctx: Context, L: Loc, Ty: Type, IsImplicit);
1443 MarkThisReferenced(This);
1444 return This;
1445}
1446
1447void Sema::MarkThisReferenced(CXXThisExpr *This) {
1448 CheckCXXThisCapture(Loc: This->getExprLoc());
1449 if (This->isTypeDependent())
1450 return;
1451
1452 // Check if 'this' is captured by value in a lambda with a dependent explicit
1453 // object parameter, and mark it as type-dependent as well if so.
1454 auto IsDependent = [&]() {
1455 for (auto *Scope : llvm::reverse(C&: FunctionScopes)) {
1456 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: Scope);
1457 if (!LSI)
1458 continue;
1459
1460 if (LSI->Lambda && !LSI->Lambda->Encloses(DC: CurContext) &&
1461 LSI->AfterParameterList)
1462 return false;
1463
1464 // If this lambda captures 'this' by value, then 'this' is dependent iff
1465 // this lambda has a dependent explicit object parameter. If we can't
1466 // determine whether it does (e.g. because the CXXMethodDecl's type is
1467 // null), assume it doesn't.
1468 if (LSI->isCXXThisCaptured()) {
1469 if (!LSI->getCXXThisCapture().isCopyCapture())
1470 continue;
1471
1472 const auto *MD = LSI->CallOperator;
1473 if (MD->getType().isNull())
1474 return false;
1475
1476 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
1477 return Ty && MD->isExplicitObjectMemberFunction() &&
1478 Ty->getParamType(i: 0)->isDependentType();
1479 }
1480 }
1481 return false;
1482 }();
1483
1484 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);
1485}
1486
1487bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1488 // If we're outside the body of a member function, then we'll have a specified
1489 // type for 'this'.
1490 if (CXXThisTypeOverride.isNull())
1491 return false;
1492
1493 // Determine whether we're looking into a class that's currently being
1494 // defined.
1495 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1496 return Class && Class->isBeingDefined();
1497}
1498
1499ExprResult
1500Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1501 SourceLocation LParenOrBraceLoc,
1502 MultiExprArg exprs,
1503 SourceLocation RParenOrBraceLoc,
1504 bool ListInitialization) {
1505 if (!TypeRep)
1506 return ExprError();
1507
1508 TypeSourceInfo *TInfo;
1509 QualType Ty = GetTypeFromParser(Ty: TypeRep, TInfo: &TInfo);
1510 if (!TInfo)
1511 TInfo = Context.getTrivialTypeSourceInfo(T: Ty, Loc: SourceLocation());
1512
1513 auto Result = BuildCXXTypeConstructExpr(Type: TInfo, LParenLoc: LParenOrBraceLoc, Exprs: exprs,
1514 RParenLoc: RParenOrBraceLoc, ListInitialization);
1515 if (Result.isInvalid())
1516 Result = CreateRecoveryExpr(Begin: TInfo->getTypeLoc().getBeginLoc(),
1517 End: RParenOrBraceLoc, SubExprs: exprs, T: Ty);
1518 return Result;
1519}
1520
1521ExprResult
1522Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1523 SourceLocation LParenOrBraceLoc,
1524 MultiExprArg Exprs,
1525 SourceLocation RParenOrBraceLoc,
1526 bool ListInitialization) {
1527 QualType Ty = TInfo->getType();
1528 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1529 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1530
1531 InitializedEntity Entity =
1532 InitializedEntity::InitializeTemporary(Context, TypeInfo: TInfo);
1533 InitializationKind Kind =
1534 Exprs.size()
1535 ? ListInitialization
1536 ? InitializationKind::CreateDirectList(
1537 InitLoc: TyBeginLoc, LBraceLoc: LParenOrBraceLoc, RBraceLoc: RParenOrBraceLoc)
1538 : InitializationKind::CreateDirect(InitLoc: TyBeginLoc, LParenLoc: LParenOrBraceLoc,
1539 RParenLoc: RParenOrBraceLoc)
1540 : InitializationKind::CreateValue(InitLoc: TyBeginLoc, LParenLoc: LParenOrBraceLoc,
1541 RParenLoc: RParenOrBraceLoc);
1542
1543 // C++17 [expr.type.conv]p1:
1544 // If the type is a placeholder for a deduced class type, [...perform class
1545 // template argument deduction...]
1546 // C++23:
1547 // Otherwise, if the type contains a placeholder type, it is replaced by the
1548 // type determined by placeholder type deduction.
1549 DeducedType *Deduced = Ty->getContainedDeducedType();
1550 if (Deduced && !Deduced->isDeduced() &&
1551 isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
1552 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1553 Kind, Init: Exprs);
1554 if (Ty.isNull())
1555 return ExprError();
1556 Entity = InitializedEntity::InitializeTemporary(TypeInfo: TInfo, Type: Ty);
1557 } else if (Deduced && !Deduced->isDeduced()) {
1558 MultiExprArg Inits = Exprs;
1559 if (ListInitialization) {
1560 auto *ILE = cast<InitListExpr>(Val: Exprs[0]);
1561 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1562 }
1563
1564 if (Inits.empty())
1565 return ExprError(Diag(Loc: TyBeginLoc, DiagID: diag::err_auto_expr_init_no_expression)
1566 << Ty << FullRange);
1567 if (Inits.size() > 1) {
1568 Expr *FirstBad = Inits[1];
1569 return ExprError(Diag(Loc: FirstBad->getBeginLoc(),
1570 DiagID: diag::err_auto_expr_init_multiple_expressions)
1571 << Ty << FullRange);
1572 }
1573 if (getLangOpts().CPlusPlus23) {
1574 if (Ty->getAs<AutoType>())
1575 Diag(Loc: TyBeginLoc, DiagID: diag::warn_cxx20_compat_auto_expr) << FullRange;
1576 }
1577 Expr *Deduce = Inits[0];
1578 if (isa<InitListExpr>(Val: Deduce))
1579 return ExprError(
1580 Diag(Loc: Deduce->getBeginLoc(), DiagID: diag::err_auto_expr_init_paren_braces)
1581 << ListInitialization << Ty << FullRange);
1582 QualType DeducedType;
1583 TemplateDeductionInfo Info(Deduce->getExprLoc());
1584 TemplateDeductionResult Result =
1585 DeduceAutoType(AutoTypeLoc: TInfo->getTypeLoc(), Initializer: Deduce, Result&: DeducedType, Info);
1586 if (Result != TemplateDeductionResult::Success &&
1587 Result != TemplateDeductionResult::AlreadyDiagnosed)
1588 return ExprError(Diag(Loc: TyBeginLoc, DiagID: diag::err_auto_expr_deduction_failure)
1589 << Ty << Deduce->getType() << FullRange
1590 << Deduce->getSourceRange());
1591 if (DeducedType.isNull()) {
1592 assert(Result == TemplateDeductionResult::AlreadyDiagnosed);
1593 return ExprError();
1594 }
1595
1596 Ty = DeducedType;
1597 Entity = InitializedEntity::InitializeTemporary(TypeInfo: TInfo, Type: Ty);
1598 }
1599
1600 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs))
1601 return CXXUnresolvedConstructExpr::Create(
1602 Context, T: Ty.getNonReferenceType(), TSI: TInfo, LParenLoc: LParenOrBraceLoc, Args: Exprs,
1603 RParenLoc: RParenOrBraceLoc, IsListInit: ListInitialization);
1604
1605 // C++ [expr.type.conv]p1:
1606 // If the expression list is a parenthesized single expression, the type
1607 // conversion expression is equivalent (in definedness, and if defined in
1608 // meaning) to the corresponding cast expression.
1609 if (Exprs.size() == 1 && !ListInitialization &&
1610 !isa<InitListExpr>(Val: Exprs[0])) {
1611 Expr *Arg = Exprs[0];
1612 return BuildCXXFunctionalCastExpr(TInfo, Type: Ty, LParenLoc: LParenOrBraceLoc, CastExpr: Arg,
1613 RParenLoc: RParenOrBraceLoc);
1614 }
1615
1616 // For an expression of the form T(), T shall not be an array type.
1617 QualType ElemTy = Ty;
1618 if (Ty->isArrayType()) {
1619 if (!ListInitialization)
1620 return ExprError(Diag(Loc: TyBeginLoc, DiagID: diag::err_value_init_for_array_type)
1621 << FullRange);
1622 ElemTy = Context.getBaseElementType(QT: Ty);
1623 }
1624
1625 // Only construct objects with object types.
1626 // The standard doesn't explicitly forbid function types here, but that's an
1627 // obvious oversight, as there's no way to dynamically construct a function
1628 // in general.
1629 if (Ty->isFunctionType())
1630 return ExprError(Diag(Loc: TyBeginLoc, DiagID: diag::err_init_for_function_type)
1631 << Ty << FullRange);
1632
1633 // C++17 [expr.type.conv]p2, per DR2351:
1634 // If the type is cv void and the initializer is () or {}, the expression is
1635 // a prvalue of the specified type that performs no initialization.
1636 if (Ty->isVoidType()) {
1637 if (Exprs.empty())
1638 return new (Context) CXXScalarValueInitExpr(
1639 Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd());
1640 if (ListInitialization &&
1641 cast<InitListExpr>(Val: Exprs[0])->getNumInits() == 0) {
1642 return CXXFunctionalCastExpr::Create(
1643 Context, T: Ty.getUnqualifiedType(), VK: VK_PRValue, Written: TInfo, Kind: CK_ToVoid,
1644 Op: Exprs[0], /*Path=*/nullptr, FPO: CurFPFeatureOverrides(),
1645 LPLoc: Exprs[0]->getBeginLoc(), RPLoc: Exprs[0]->getEndLoc());
1646 }
1647 } else if (RequireCompleteType(Loc: TyBeginLoc, T: ElemTy,
1648 DiagID: diag::err_invalid_incomplete_type_use,
1649 Args: FullRange))
1650 return ExprError();
1651
1652 // Otherwise, the expression is a prvalue of the specified type whose
1653 // result object is direct-initialized (11.6) with the initializer.
1654 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1655 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Exprs);
1656
1657 if (Result.isInvalid())
1658 return Result;
1659
1660 Expr *Inner = Result.get();
1661 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Val: Inner))
1662 Inner = BTE->getSubExpr();
1663 if (auto *CE = dyn_cast<ConstantExpr>(Val: Inner);
1664 CE && CE->isImmediateInvocation())
1665 Inner = CE->getSubExpr();
1666 if (!isa<CXXTemporaryObjectExpr>(Val: Inner) &&
1667 !isa<CXXScalarValueInitExpr>(Val: Inner)) {
1668 // If we created a CXXTemporaryObjectExpr, that node also represents the
1669 // functional cast. Otherwise, create an explicit cast to represent
1670 // the syntactic form of a functional-style cast that was used here.
1671 //
1672 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1673 // would give a more consistent AST representation than using a
1674 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1675 // is sometimes handled by initialization and sometimes not.
1676 QualType ResultType = Result.get()->getType();
1677 SourceRange Locs = ListInitialization
1678 ? SourceRange()
1679 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1680 Result = CXXFunctionalCastExpr::Create(
1681 Context, T: ResultType, VK: Expr::getValueKindForType(T: Ty), Written: TInfo, Kind: CK_NoOp,
1682 Op: Result.get(), /*Path=*/nullptr, FPO: CurFPFeatureOverrides(),
1683 LPLoc: Locs.getBegin(), RPLoc: Locs.getEnd());
1684 }
1685
1686 return Result;
1687}
1688
1689bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1690 // [CUDA] Ignore this function, if we can't call it.
1691 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1692 if (getLangOpts().CUDA) {
1693 auto CallPreference = CUDA().IdentifyPreference(Caller, Callee: Method);
1694 // If it's not callable at all, it's not the right function.
1695 if (CallPreference < SemaCUDA::CFP_WrongSide)
1696 return false;
1697 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1698 // Maybe. We have to check if there are better alternatives.
1699 DeclContext::lookup_result R =
1700 Method->getDeclContext()->lookup(Name: Method->getDeclName());
1701 for (const auto *D : R) {
1702 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
1703 if (CUDA().IdentifyPreference(Caller, Callee: FD) > SemaCUDA::CFP_WrongSide)
1704 return false;
1705 }
1706 }
1707 // We've found no better variants.
1708 }
1709 }
1710
1711 SmallVector<const FunctionDecl*, 4> PreventedBy;
1712 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1713
1714 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1715 return Result;
1716
1717 // In case of CUDA, return true if none of the 1-argument deallocator
1718 // functions are actually callable.
1719 return llvm::none_of(Range&: PreventedBy, P: [&](const FunctionDecl *FD) {
1720 assert(FD->getNumParams() == 1 &&
1721 "Only single-operand functions should be in PreventedBy");
1722 return CUDA().IdentifyPreference(Caller, Callee: FD) >= SemaCUDA::CFP_HostDevice;
1723 });
1724}
1725
1726/// Determine whether the given function is a non-placement
1727/// deallocation function.
1728static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1729 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FD))
1730 return S.isUsualDeallocationFunction(Method);
1731
1732 if (!FD->getDeclName().isAnyOperatorDelete())
1733 return false;
1734
1735 if (FD->isTypeAwareOperatorNewOrDelete())
1736 return FunctionDecl::RequiredTypeAwareDeleteParameterCount ==
1737 FD->getNumParams();
1738
1739 unsigned UsualParams = 1;
1740 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1741 S.Context.hasSameUnqualifiedType(
1742 T1: FD->getParamDecl(i: UsualParams)->getType(),
1743 T2: S.Context.getSizeType()))
1744 ++UsualParams;
1745
1746 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1747 S.Context.hasSameUnqualifiedType(
1748 T1: FD->getParamDecl(i: UsualParams)->getType(),
1749 T2: S.Context.getCanonicalTagType(TD: S.getStdAlignValT())))
1750 ++UsualParams;
1751
1752 return UsualParams == FD->getNumParams();
1753}
1754
1755namespace {
1756 struct UsualDeallocFnInfo {
1757 UsualDeallocFnInfo()
1758 : Found(), FD(nullptr),
1759 IDP(AlignedAllocationMode::No, SizedDeallocationMode::No) {}
1760 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found, QualType AllocType,
1761 SourceLocation Loc)
1762 : Found(Found), FD(dyn_cast<FunctionDecl>(Val: Found->getUnderlyingDecl())),
1763 Destroying(false),
1764 IDP({AllocType, TypeAwareAllocationMode::No,
1765 AlignedAllocationMode::No, SizedDeallocationMode::No}),
1766 CUDAPref(SemaCUDA::CFP_Native) {
1767 // A function template declaration is only a usual deallocation function
1768 // if it is a typed delete.
1769 if (!FD) {
1770 if (AllocType.isNull())
1771 return;
1772 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Found->getUnderlyingDecl());
1773 if (!FTD)
1774 return;
1775 FunctionDecl *InstantiatedDecl =
1776 S.BuildTypeAwareUsualDelete(FnDecl: FTD, AllocType, Loc);
1777 if (!InstantiatedDecl)
1778 return;
1779 FD = InstantiatedDecl;
1780 }
1781 unsigned NumBaseParams = 1;
1782 if (FD->isTypeAwareOperatorNewOrDelete()) {
1783 // If this is a type aware operator delete we instantiate an appropriate
1784 // specialization of std::type_identity<>. If we do not know the
1785 // type being deallocated, or if the type-identity parameter of the
1786 // deallocation function does not match the constructed type_identity
1787 // specialization we reject the declaration.
1788 if (AllocType.isNull()) {
1789 FD = nullptr;
1790 return;
1791 }
1792 QualType TypeIdentityTag = FD->getParamDecl(i: 0)->getType();
1793 QualType ExpectedTypeIdentityTag =
1794 S.tryBuildStdTypeIdentity(Type: AllocType, Loc);
1795 if (ExpectedTypeIdentityTag.isNull()) {
1796 FD = nullptr;
1797 return;
1798 }
1799 if (!S.Context.hasSameType(T1: TypeIdentityTag, T2: ExpectedTypeIdentityTag)) {
1800 FD = nullptr;
1801 return;
1802 }
1803 IDP.PassTypeIdentity = TypeAwareAllocationMode::Yes;
1804 ++NumBaseParams;
1805 }
1806
1807 if (FD->isDestroyingOperatorDelete()) {
1808 Destroying = true;
1809 ++NumBaseParams;
1810 }
1811
1812 if (NumBaseParams < FD->getNumParams() &&
1813 S.Context.hasSameUnqualifiedType(
1814 T1: FD->getParamDecl(i: NumBaseParams)->getType(),
1815 T2: S.Context.getSizeType())) {
1816 ++NumBaseParams;
1817 IDP.PassSize = SizedDeallocationMode::Yes;
1818 }
1819
1820 if (NumBaseParams < FD->getNumParams() &&
1821 FD->getParamDecl(i: NumBaseParams)->getType()->isAlignValT()) {
1822 ++NumBaseParams;
1823 IDP.PassAlignment = AlignedAllocationMode::Yes;
1824 }
1825
1826 // In CUDA, determine how much we'd like / dislike to call this.
1827 if (S.getLangOpts().CUDA)
1828 CUDAPref = S.CUDA().IdentifyPreference(
1829 Caller: S.getCurFunctionDecl(/*AllowLambda=*/true), Callee: FD);
1830 }
1831
1832 explicit operator bool() const { return FD; }
1833
1834 int Compare(Sema &S, const UsualDeallocFnInfo &Other,
1835 ImplicitDeallocationParameters TargetIDP) const {
1836 assert(!TargetIDP.Type.isNull() ||
1837 !isTypeAwareAllocation(Other.IDP.PassTypeIdentity));
1838
1839 // C++ P0722:
1840 // A destroying operator delete is preferred over a non-destroying
1841 // operator delete.
1842 if (Destroying != Other.Destroying)
1843 return Destroying ? 1 : -1;
1844
1845 const ImplicitDeallocationParameters &OtherIDP = Other.IDP;
1846 // Selection for type awareness has priority over alignment and size
1847 if (IDP.PassTypeIdentity != OtherIDP.PassTypeIdentity)
1848 return IDP.PassTypeIdentity == TargetIDP.PassTypeIdentity ? 1 : -1;
1849
1850 // C++17 [expr.delete]p10:
1851 // If the type has new-extended alignment, a function with a parameter
1852 // of type std::align_val_t is preferred; otherwise a function without
1853 // such a parameter is preferred
1854 if (IDP.PassAlignment != OtherIDP.PassAlignment)
1855 return IDP.PassAlignment == TargetIDP.PassAlignment ? 1 : -1;
1856
1857 if (IDP.PassSize != OtherIDP.PassSize)
1858 return IDP.PassSize == TargetIDP.PassSize ? 1 : -1;
1859
1860 if (isTypeAwareAllocation(Mode: IDP.PassTypeIdentity)) {
1861 // Type aware allocation involves templates so we need to choose
1862 // the best type
1863 FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
1864 FunctionTemplateDecl *OtherPrimaryTemplate =
1865 Other.FD->getPrimaryTemplate();
1866 if ((!PrimaryTemplate) != (!OtherPrimaryTemplate))
1867 return OtherPrimaryTemplate ? 1 : -1;
1868
1869 if (PrimaryTemplate && OtherPrimaryTemplate) {
1870 const auto *DC = dyn_cast<CXXRecordDecl>(Val: Found->getDeclContext());
1871 const auto *OtherDC =
1872 dyn_cast<CXXRecordDecl>(Val: Other.Found->getDeclContext());
1873 unsigned ImplicitArgCount = Destroying + IDP.getNumImplicitArgs();
1874 if (FunctionTemplateDecl *Best = S.getMoreSpecializedTemplate(
1875 FT1: PrimaryTemplate, FT2: OtherPrimaryTemplate, Loc: SourceLocation(),
1876 TPOC: TPOC_Call, NumCallArguments1: ImplicitArgCount,
1877 RawObj1Ty: DC ? S.Context.getCanonicalTagType(TD: DC) : QualType{},
1878 RawObj2Ty: OtherDC ? S.Context.getCanonicalTagType(TD: OtherDC) : QualType{},
1879 Reversed: false)) {
1880 return Best == PrimaryTemplate ? 1 : -1;
1881 }
1882 }
1883 }
1884
1885 // Use CUDA call preference as a tiebreaker.
1886 if (CUDAPref > Other.CUDAPref)
1887 return 1;
1888 if (CUDAPref == Other.CUDAPref)
1889 return 0;
1890 return -1;
1891 }
1892
1893 DeclAccessPair Found;
1894 FunctionDecl *FD;
1895 bool Destroying;
1896 ImplicitDeallocationParameters IDP;
1897 SemaCUDA::CUDAFunctionPreference CUDAPref;
1898 };
1899}
1900
1901/// Determine whether a type has new-extended alignment. This may be called when
1902/// the type is incomplete (for a delete-expression with an incomplete pointee
1903/// type), in which case it will conservatively return false if the alignment is
1904/// not known.
1905static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1906 return S.getLangOpts().AlignedAllocation &&
1907 S.getASTContext().getTypeAlignIfKnown(T: AllocType) >
1908 S.getASTContext().getTargetInfo().getNewAlign();
1909}
1910
1911static bool CheckDeleteOperator(Sema &S, SourceLocation StartLoc,
1912 SourceRange Range, bool Diagnose,
1913 CXXRecordDecl *NamingClass, DeclAccessPair Decl,
1914 FunctionDecl *Operator) {
1915 if (Operator->isTypeAwareOperatorNewOrDelete()) {
1916 QualType SelectedTypeIdentityParameter =
1917 Operator->getParamDecl(i: 0)->getType();
1918 if (S.RequireCompleteType(Loc: StartLoc, T: SelectedTypeIdentityParameter,
1919 DiagID: diag::err_incomplete_type))
1920 return true;
1921 }
1922
1923 // FIXME: DiagnoseUseOfDecl?
1924 if (Operator->isDeleted()) {
1925 if (Diagnose) {
1926 StringLiteral *Msg = Operator->getDeletedMessage();
1927 S.Diag(Loc: StartLoc, DiagID: diag::err_deleted_function_use)
1928 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
1929 S.NoteDeletedFunction(FD: Operator);
1930 }
1931 return true;
1932 }
1933 Sema::AccessResult Accessible =
1934 S.CheckAllocationAccess(OperatorLoc: StartLoc, PlacementRange: Range, NamingClass, FoundDecl: Decl, Diagnose);
1935 return Accessible == Sema::AR_inaccessible;
1936}
1937
1938/// Select the correct "usual" deallocation function to use from a selection of
1939/// deallocation functions (either global or class-scope).
1940static UsualDeallocFnInfo resolveDeallocationOverload(
1941 Sema &S, LookupResult &R, const ImplicitDeallocationParameters &IDP,
1942 SourceLocation Loc,
1943 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1944
1945 UsualDeallocFnInfo Best;
1946 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1947 UsualDeallocFnInfo Info(S, I.getPair(), IDP.Type, Loc);
1948 if (!Info || !isNonPlacementDeallocationFunction(S, FD: Info.FD) ||
1949 Info.CUDAPref == SemaCUDA::CFP_Never)
1950 continue;
1951
1952 if (!isTypeAwareAllocation(Mode: IDP.PassTypeIdentity) &&
1953 isTypeAwareAllocation(Mode: Info.IDP.PassTypeIdentity))
1954 continue;
1955 if (!Best) {
1956 Best = Info;
1957 if (BestFns)
1958 BestFns->push_back(Elt: Info);
1959 continue;
1960 }
1961 int ComparisonResult = Best.Compare(S, Other: Info, TargetIDP: IDP);
1962 if (ComparisonResult > 0)
1963 continue;
1964
1965 // If more than one preferred function is found, all non-preferred
1966 // functions are eliminated from further consideration.
1967 if (BestFns && ComparisonResult < 0)
1968 BestFns->clear();
1969
1970 Best = Info;
1971 if (BestFns)
1972 BestFns->push_back(Elt: Info);
1973 }
1974
1975 return Best;
1976}
1977
1978/// Determine whether a given type is a class for which 'delete[]' would call
1979/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1980/// we need to store the array size (even if the type is
1981/// trivially-destructible).
1982static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1983 TypeAwareAllocationMode PassType,
1984 QualType allocType) {
1985 const auto *record =
1986 allocType->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>();
1987 if (!record) return false;
1988
1989 // Try to find an operator delete[] in class scope.
1990
1991 DeclarationName deleteName =
1992 S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete);
1993 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1994 S.LookupQualifiedName(R&: ops, LookupCtx: record->getDecl()->getDefinitionOrSelf());
1995
1996 // We're just doing this for information.
1997 ops.suppressDiagnostics();
1998
1999 // Very likely: there's no operator delete[].
2000 if (ops.empty()) return false;
2001
2002 // If it's ambiguous, it should be illegal to call operator delete[]
2003 // on this thing, so it doesn't matter if we allocate extra space or not.
2004 if (ops.isAmbiguous()) return false;
2005
2006 // C++17 [expr.delete]p10:
2007 // If the deallocation functions have class scope, the one without a
2008 // parameter of type std::size_t is selected.
2009 ImplicitDeallocationParameters IDP = {
2010 allocType, PassType,
2011 alignedAllocationModeFromBool(IsAligned: hasNewExtendedAlignment(S, AllocType: allocType)),
2012 SizedDeallocationMode::No};
2013 auto Best = resolveDeallocationOverload(S, R&: ops, IDP, Loc: loc);
2014 return Best && isSizedDeallocation(Mode: Best.IDP.PassSize);
2015}
2016
2017ExprResult
2018Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
2019 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
2020 SourceLocation PlacementRParen, SourceRange TypeIdParens,
2021 Declarator &D, Expr *Initializer) {
2022 std::optional<Expr *> ArraySize;
2023 // If the specified type is an array, unwrap it and save the expression.
2024 if (D.getNumTypeObjects() > 0 &&
2025 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Array) {
2026 DeclaratorChunk &Chunk = D.getTypeObject(i: 0);
2027 if (D.getDeclSpec().hasAutoTypeSpec())
2028 return ExprError(Diag(Loc: Chunk.Loc, DiagID: diag::err_new_array_of_auto)
2029 << D.getSourceRange());
2030 if (Chunk.Arr.hasStatic)
2031 return ExprError(Diag(Loc: Chunk.Loc, DiagID: diag::err_static_illegal_in_new)
2032 << D.getSourceRange());
2033 if (!Chunk.Arr.NumElts && !Initializer)
2034 return ExprError(Diag(Loc: Chunk.Loc, DiagID: diag::err_array_new_needs_size)
2035 << D.getSourceRange());
2036
2037 ArraySize = Chunk.Arr.NumElts;
2038 D.DropFirstTypeObject();
2039 }
2040
2041 // Every dimension shall be of constant size.
2042 if (ArraySize) {
2043 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
2044 if (D.getTypeObject(i: I).Kind != DeclaratorChunk::Array)
2045 break;
2046
2047 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(i: I).Arr;
2048 if (Expr *NumElts = Array.NumElts) {
2049 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
2050 // FIXME: GCC permits constant folding here. We should either do so consistently
2051 // or not do so at all, rather than changing behavior in C++14 onwards.
2052 if (getLangOpts().CPlusPlus14) {
2053 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
2054 // shall be a converted constant expression (5.19) of type std::size_t
2055 // and shall evaluate to a strictly positive value.
2056 llvm::APSInt Value(Context.getIntWidth(T: Context.getSizeType()));
2057 Array.NumElts =
2058 CheckConvertedConstantExpression(From: NumElts, T: Context.getSizeType(),
2059 Value, CCE: CCEKind::ArrayBound)
2060 .get();
2061 } else {
2062 Array.NumElts = VerifyIntegerConstantExpression(
2063 E: NumElts, Result: nullptr, DiagID: diag::err_new_array_nonconst,
2064 CanFold: AllowFoldKind::Allow)
2065 .get();
2066 }
2067 if (!Array.NumElts)
2068 return ExprError();
2069 }
2070 }
2071 }
2072 }
2073
2074 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
2075 QualType AllocType = TInfo->getType();
2076 if (D.isInvalidType())
2077 return ExprError();
2078
2079 SourceRange DirectInitRange;
2080 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Val: Initializer))
2081 DirectInitRange = List->getSourceRange();
2082
2083 return BuildCXXNew(Range: SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
2084 PlacementLParen, PlacementArgs, PlacementRParen,
2085 TypeIdParens, AllocType, AllocTypeInfo: TInfo, ArraySize, DirectInitRange,
2086 Initializer);
2087}
2088
2089static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style,
2090 Expr *Init, bool IsCPlusPlus20) {
2091 if (!Init)
2092 return true;
2093 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: Init))
2094 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
2095 if (isa<ImplicitValueInitExpr>(Val: Init))
2096 return true;
2097 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Val: Init))
2098 return !CCE->isListInitialization() &&
2099 CCE->getConstructor()->isDefaultConstructor();
2100 else if (Style == CXXNewInitializationStyle::Braces) {
2101 assert(isa<InitListExpr>(Init) &&
2102 "Shouldn't create list CXXConstructExprs for arrays.");
2103 return true;
2104 }
2105 return false;
2106}
2107
2108bool
2109Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
2110 if (!getLangOpts().AlignedAllocationUnavailable)
2111 return false;
2112 if (FD.isDefined())
2113 return false;
2114 UnsignedOrNone AlignmentParam = std::nullopt;
2115 if (FD.isReplaceableGlobalAllocationFunction(AlignmentParam: &AlignmentParam) &&
2116 AlignmentParam)
2117 return true;
2118 return false;
2119}
2120
2121// Emit a diagnostic if an aligned allocation/deallocation function that is not
2122// implemented in the standard library is selected.
2123void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
2124 SourceLocation Loc) {
2125 if (isUnavailableAlignedAllocationFunction(FD)) {
2126 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2127 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2128 Platform: getASTContext().getTargetInfo().getPlatformName());
2129 VersionTuple OSVersion = alignedAllocMinVersion(OS: T.getOS());
2130
2131 bool IsDelete = FD.getDeclName().isAnyOperatorDelete();
2132 Diag(Loc, DiagID: diag::err_aligned_allocation_unavailable)
2133 << IsDelete << FD.getType().getAsString() << OSName
2134 << OSVersion.getAsString() << OSVersion.empty();
2135 Diag(Loc, DiagID: diag::note_silence_aligned_allocation_unavailable);
2136 }
2137}
2138
2139ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
2140 SourceLocation PlacementLParen,
2141 MultiExprArg PlacementArgs,
2142 SourceLocation PlacementRParen,
2143 SourceRange TypeIdParens, QualType AllocType,
2144 TypeSourceInfo *AllocTypeInfo,
2145 std::optional<Expr *> ArraySize,
2146 SourceRange DirectInitRange, Expr *Initializer) {
2147 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2148 SourceLocation StartLoc = Range.getBegin();
2149
2150 CXXNewInitializationStyle InitStyle;
2151 if (DirectInitRange.isValid()) {
2152 assert(Initializer && "Have parens but no initializer.");
2153 InitStyle = CXXNewInitializationStyle::Parens;
2154 } else if (isa_and_nonnull<InitListExpr>(Val: Initializer))
2155 InitStyle = CXXNewInitializationStyle::Braces;
2156 else {
2157 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2158 isa<CXXConstructExpr>(Initializer)) &&
2159 "Initializer expression that cannot have been implicitly created.");
2160 InitStyle = CXXNewInitializationStyle::None;
2161 }
2162
2163 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2164 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Val: Initializer)) {
2165 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2166 "paren init for non-call init");
2167 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2168 } else if (auto *List = dyn_cast_or_null<CXXParenListInitExpr>(Val: Initializer)) {
2169 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2170 "paren init for non-call init");
2171 Exprs = List->getInitExprs();
2172 }
2173
2174 // C++11 [expr.new]p15:
2175 // A new-expression that creates an object of type T initializes that
2176 // object as follows:
2177 InitializationKind Kind = [&] {
2178 switch (InitStyle) {
2179 // - If the new-initializer is omitted, the object is default-
2180 // initialized (8.5); if no initialization is performed,
2181 // the object has indeterminate value
2182 case CXXNewInitializationStyle::None:
2183 return InitializationKind::CreateDefault(InitLoc: TypeRange.getBegin());
2184 // - Otherwise, the new-initializer is interpreted according to the
2185 // initialization rules of 8.5 for direct-initialization.
2186 case CXXNewInitializationStyle::Parens:
2187 return InitializationKind::CreateDirect(InitLoc: TypeRange.getBegin(),
2188 LParenLoc: DirectInitRange.getBegin(),
2189 RParenLoc: DirectInitRange.getEnd());
2190 case CXXNewInitializationStyle::Braces:
2191 return InitializationKind::CreateDirectList(InitLoc: TypeRange.getBegin(),
2192 LBraceLoc: Initializer->getBeginLoc(),
2193 RBraceLoc: Initializer->getEndLoc());
2194 }
2195 llvm_unreachable("Unknown initialization kind");
2196 }();
2197
2198 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2199 auto *Deduced = AllocType->getContainedDeducedType();
2200 if (Deduced && !Deduced->isDeduced() &&
2201 isa<DeducedTemplateSpecializationType>(Val: Deduced)) {
2202 if (ArraySize)
2203 return ExprError(
2204 Diag(Loc: *ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2205 DiagID: diag::err_deduced_class_template_compound_type)
2206 << /*array*/ 2
2207 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2208
2209 InitializedEntity Entity = InitializedEntity::InitializeNew(
2210 NewLoc: StartLoc, Type: AllocType, IsVariableLengthArrayNew: InitializedEntity::NewArrayKind::KnownLength);
2211 AllocType = DeduceTemplateSpecializationFromInitializer(
2212 TInfo: AllocTypeInfo, Entity, Kind, Init: Exprs);
2213 if (AllocType.isNull())
2214 return ExprError();
2215 } else if (Deduced && !Deduced->isDeduced()) {
2216 MultiExprArg Inits = Exprs;
2217 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2218 if (Braced) {
2219 auto *ILE = cast<InitListExpr>(Val: Exprs[0]);
2220 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2221 }
2222
2223 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2224 return ExprError(Diag(Loc: StartLoc, DiagID: diag::err_auto_new_requires_ctor_arg)
2225 << AllocType << TypeRange);
2226 if (Inits.size() > 1) {
2227 Expr *FirstBad = Inits[1];
2228 return ExprError(Diag(Loc: FirstBad->getBeginLoc(),
2229 DiagID: diag::err_auto_new_ctor_multiple_expressions)
2230 << AllocType << TypeRange);
2231 }
2232 if (Braced && !getLangOpts().CPlusPlus17)
2233 Diag(Loc: Initializer->getBeginLoc(), DiagID: diag::ext_auto_new_list_init)
2234 << AllocType << TypeRange;
2235 Expr *Deduce = Inits[0];
2236 if (isa<InitListExpr>(Val: Deduce))
2237 return ExprError(
2238 Diag(Loc: Deduce->getBeginLoc(), DiagID: diag::err_auto_expr_init_paren_braces)
2239 << Braced << AllocType << TypeRange);
2240 QualType DeducedType;
2241 TemplateDeductionInfo Info(Deduce->getExprLoc());
2242 TemplateDeductionResult Result =
2243 DeduceAutoType(AutoTypeLoc: AllocTypeInfo->getTypeLoc(), Initializer: Deduce, Result&: DeducedType, Info);
2244 if (Result != TemplateDeductionResult::Success &&
2245 Result != TemplateDeductionResult::AlreadyDiagnosed)
2246 return ExprError(Diag(Loc: StartLoc, DiagID: diag::err_auto_new_deduction_failure)
2247 << AllocType << Deduce->getType() << TypeRange
2248 << Deduce->getSourceRange());
2249 if (DeducedType.isNull()) {
2250 assert(Result == TemplateDeductionResult::AlreadyDiagnosed);
2251 return ExprError();
2252 }
2253 AllocType = DeducedType;
2254 }
2255
2256 // Per C++0x [expr.new]p5, the type being constructed may be a
2257 // typedef of an array type.
2258 // Dependent case will be handled separately.
2259 if (!ArraySize && !AllocType->isDependentType()) {
2260 if (const ConstantArrayType *Array
2261 = Context.getAsConstantArrayType(T: AllocType)) {
2262 ArraySize = IntegerLiteral::Create(C: Context, V: Array->getSize(),
2263 type: Context.getSizeType(),
2264 l: TypeRange.getEnd());
2265 AllocType = Array->getElementType();
2266 }
2267 }
2268
2269 if (CheckAllocatedType(AllocType, Loc: TypeRange.getBegin(), R: TypeRange))
2270 return ExprError();
2271
2272 if (ArraySize && !checkArrayElementAlignment(EltTy: AllocType, Loc: TypeRange.getBegin()))
2273 return ExprError();
2274
2275 // In ARC, infer 'retaining' for the allocated
2276 if (getLangOpts().ObjCAutoRefCount &&
2277 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2278 AllocType->isObjCLifetimeType()) {
2279 AllocType = Context.getLifetimeQualifiedType(type: AllocType,
2280 lifetime: AllocType->getObjCARCImplicitLifetime());
2281 }
2282
2283 QualType ResultType = Context.getPointerType(T: AllocType);
2284
2285 if (ArraySize && *ArraySize &&
2286 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2287 ExprResult result = CheckPlaceholderExpr(E: *ArraySize);
2288 if (result.isInvalid()) return ExprError();
2289 ArraySize = result.get();
2290 }
2291 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2292 // integral or enumeration type with a non-negative value."
2293 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2294 // enumeration type, or a class type for which a single non-explicit
2295 // conversion function to integral or unscoped enumeration type exists.
2296 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2297 // std::size_t.
2298 std::optional<uint64_t> KnownArraySize;
2299 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2300 ExprResult ConvertedSize;
2301 if (getLangOpts().CPlusPlus14) {
2302 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2303
2304 ConvertedSize = PerformImplicitConversion(
2305 From: *ArraySize, ToType: Context.getSizeType(), Action: AssignmentAction::Converting);
2306
2307 if (!ConvertedSize.isInvalid() && (*ArraySize)->getType()->isRecordType())
2308 // Diagnose the compatibility of this conversion.
2309 Diag(Loc: StartLoc, DiagID: diag::warn_cxx98_compat_array_size_conversion)
2310 << (*ArraySize)->getType() << 0 << "'size_t'";
2311 } else {
2312 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2313 protected:
2314 Expr *ArraySize;
2315
2316 public:
2317 SizeConvertDiagnoser(Expr *ArraySize)
2318 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2319 ArraySize(ArraySize) {}
2320
2321 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2322 QualType T) override {
2323 return S.Diag(Loc, DiagID: diag::err_array_size_not_integral)
2324 << S.getLangOpts().CPlusPlus11 << T;
2325 }
2326
2327 SemaDiagnosticBuilder diagnoseIncomplete(
2328 Sema &S, SourceLocation Loc, QualType T) override {
2329 return S.Diag(Loc, DiagID: diag::err_array_size_incomplete_type)
2330 << T << ArraySize->getSourceRange();
2331 }
2332
2333 SemaDiagnosticBuilder diagnoseExplicitConv(
2334 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2335 return S.Diag(Loc, DiagID: diag::err_array_size_explicit_conversion) << T << ConvTy;
2336 }
2337
2338 SemaDiagnosticBuilder noteExplicitConv(
2339 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2340 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_array_size_conversion)
2341 << ConvTy->isEnumeralType() << ConvTy;
2342 }
2343
2344 SemaDiagnosticBuilder diagnoseAmbiguous(
2345 Sema &S, SourceLocation Loc, QualType T) override {
2346 return S.Diag(Loc, DiagID: diag::err_array_size_ambiguous_conversion) << T;
2347 }
2348
2349 SemaDiagnosticBuilder noteAmbiguous(
2350 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2351 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_array_size_conversion)
2352 << ConvTy->isEnumeralType() << ConvTy;
2353 }
2354
2355 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2356 QualType T,
2357 QualType ConvTy) override {
2358 return S.Diag(Loc,
2359 DiagID: S.getLangOpts().CPlusPlus11
2360 ? diag::warn_cxx98_compat_array_size_conversion
2361 : diag::ext_array_size_conversion)
2362 << T << ConvTy->isEnumeralType() << ConvTy;
2363 }
2364 } SizeDiagnoser(*ArraySize);
2365
2366 ConvertedSize = PerformContextualImplicitConversion(Loc: StartLoc, FromE: *ArraySize,
2367 Converter&: SizeDiagnoser);
2368 }
2369 if (ConvertedSize.isInvalid())
2370 return ExprError();
2371
2372 ArraySize = ConvertedSize.get();
2373 QualType SizeType = (*ArraySize)->getType();
2374
2375 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2376 return ExprError();
2377
2378 // C++98 [expr.new]p7:
2379 // The expression in a direct-new-declarator shall have integral type
2380 // with a non-negative value.
2381 //
2382 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2383 // per CWG1464. Otherwise, if it's not a constant, we must have an
2384 // unparenthesized array type.
2385
2386 // We've already performed any required implicit conversion to integer or
2387 // unscoped enumeration type.
2388 // FIXME: Per CWG1464, we are required to check the value prior to
2389 // converting to size_t. This will never find a negative array size in
2390 // C++14 onwards, because Value is always unsigned here!
2391 if (std::optional<llvm::APSInt> Value =
2392 (*ArraySize)->getIntegerConstantExpr(Ctx: Context)) {
2393 if (Value->isSigned() && Value->isNegative()) {
2394 return ExprError(Diag(Loc: (*ArraySize)->getBeginLoc(),
2395 DiagID: diag::err_typecheck_negative_array_size)
2396 << (*ArraySize)->getSourceRange());
2397 }
2398
2399 if (!AllocType->isDependentType()) {
2400 unsigned ActiveSizeBits =
2401 ConstantArrayType::getNumAddressingBits(Context, ElementType: AllocType, NumElements: *Value);
2402 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2403 return ExprError(
2404 Diag(Loc: (*ArraySize)->getBeginLoc(), DiagID: diag::err_array_too_large)
2405 << toString(I: *Value, Radix: 10, Signed: Value->isSigned(),
2406 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2407 /*InsertSeparators=*/true)
2408 << (*ArraySize)->getSourceRange());
2409 }
2410
2411 KnownArraySize = Value->getZExtValue();
2412 } else if (TypeIdParens.isValid()) {
2413 // Can't have dynamic array size when the type-id is in parentheses.
2414 Diag(Loc: (*ArraySize)->getBeginLoc(), DiagID: diag::ext_new_paren_array_nonconst)
2415 << (*ArraySize)->getSourceRange()
2416 << FixItHint::CreateRemoval(RemoveRange: TypeIdParens.getBegin())
2417 << FixItHint::CreateRemoval(RemoveRange: TypeIdParens.getEnd());
2418
2419 TypeIdParens = SourceRange();
2420 }
2421
2422 // Note that we do *not* convert the argument in any way. It can
2423 // be signed, larger than size_t, whatever.
2424 }
2425
2426 FunctionDecl *OperatorNew = nullptr;
2427 FunctionDecl *OperatorDelete = nullptr;
2428 unsigned Alignment =
2429 AllocType->isDependentType() ? 0 : Context.getTypeAlign(T: AllocType);
2430 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2431 ImplicitAllocationParameters IAP = {
2432 AllocType, ShouldUseTypeAwareOperatorNewOrDelete(),
2433 alignedAllocationModeFromBool(IsAligned: getLangOpts().AlignedAllocation &&
2434 Alignment > NewAlignment)};
2435
2436 if (CheckArgsForPlaceholders(args: PlacementArgs))
2437 return ExprError();
2438
2439 AllocationFunctionScope Scope = UseGlobal ? AllocationFunctionScope::Global
2440 : AllocationFunctionScope::Both;
2441 SourceRange AllocationParameterRange = Range;
2442 if (PlacementLParen.isValid() && PlacementRParen.isValid())
2443 AllocationParameterRange = SourceRange(PlacementLParen, PlacementRParen);
2444 if (!AllocType->isDependentType() &&
2445 !Expr::hasAnyTypeDependentArguments(Exprs: PlacementArgs) &&
2446 FindAllocationFunctions(StartLoc, Range: AllocationParameterRange, NewScope: Scope, DeleteScope: Scope,
2447 AllocType, IsArray: ArraySize.has_value(), IAP,
2448 PlaceArgs: PlacementArgs, OperatorNew, OperatorDelete))
2449 return ExprError();
2450
2451 // If this is an array allocation, compute whether the usual array
2452 // deallocation function for the type has a size_t parameter.
2453 bool UsualArrayDeleteWantsSize = false;
2454 if (ArraySize && !AllocType->isDependentType())
2455 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(
2456 S&: *this, loc: StartLoc, PassType: IAP.PassTypeIdentity, allocType: AllocType);
2457
2458 SmallVector<Expr *, 8> AllPlaceArgs;
2459 if (OperatorNew) {
2460 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2461 VariadicCallType CallType = Proto->isVariadic()
2462 ? VariadicCallType::Function
2463 : VariadicCallType::DoesNotApply;
2464
2465 // We've already converted the placement args, just fill in any default
2466 // arguments. Skip the first parameter because we don't have a corresponding
2467 // argument. Skip the second parameter too if we're passing in the
2468 // alignment; we've already filled it in.
2469 unsigned NumImplicitArgs = 1;
2470 if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) {
2471 assert(OperatorNew->isTypeAwareOperatorNewOrDelete());
2472 NumImplicitArgs++;
2473 }
2474 if (isAlignedAllocation(Mode: IAP.PassAlignment))
2475 NumImplicitArgs++;
2476 if (GatherArgumentsForCall(CallLoc: AllocationParameterRange.getBegin(), FDecl: OperatorNew,
2477 Proto, FirstParam: NumImplicitArgs, Args: PlacementArgs,
2478 AllArgs&: AllPlaceArgs, CallType))
2479 return ExprError();
2480
2481 if (!AllPlaceArgs.empty())
2482 PlacementArgs = AllPlaceArgs;
2483
2484 // We would like to perform some checking on the given `operator new` call,
2485 // but the PlacementArgs does not contain the implicit arguments,
2486 // namely allocation size and maybe allocation alignment,
2487 // so we need to conjure them.
2488
2489 QualType SizeTy = Context.getSizeType();
2490 unsigned SizeTyWidth = Context.getTypeSize(T: SizeTy);
2491
2492 llvm::APInt SingleEltSize(
2493 SizeTyWidth, Context.getTypeSizeInChars(T: AllocType).getQuantity());
2494
2495 // How many bytes do we want to allocate here?
2496 std::optional<llvm::APInt> AllocationSize;
2497 if (!ArraySize && !AllocType->isDependentType()) {
2498 // For non-array operator new, we only want to allocate one element.
2499 AllocationSize = SingleEltSize;
2500 } else if (KnownArraySize && !AllocType->isDependentType()) {
2501 // For array operator new, only deal with static array size case.
2502 bool Overflow;
2503 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2504 .umul_ov(RHS: SingleEltSize, Overflow);
2505 (void)Overflow;
2506 assert(
2507 !Overflow &&
2508 "Expected that all the overflows would have been handled already.");
2509 }
2510
2511 IntegerLiteral AllocationSizeLiteral(
2512 Context, AllocationSize.value_or(u: llvm::APInt::getZero(numBits: SizeTyWidth)),
2513 SizeTy, StartLoc);
2514 // Otherwise, if we failed to constant-fold the allocation size, we'll
2515 // just give up and pass-in something opaque, that isn't a null pointer.
2516 OpaqueValueExpr OpaqueAllocationSize(StartLoc, SizeTy, VK_PRValue,
2517 OK_Ordinary, /*SourceExpr=*/nullptr);
2518
2519 // Let's synthesize the alignment argument in case we will need it.
2520 // Since we *really* want to allocate these on stack, this is slightly ugly
2521 // because there might not be a `std::align_val_t` type.
2522 EnumDecl *StdAlignValT = getStdAlignValT();
2523 QualType AlignValT =
2524 StdAlignValT ? Context.getCanonicalTagType(TD: StdAlignValT) : SizeTy;
2525 IntegerLiteral AlignmentLiteral(
2526 Context,
2527 llvm::APInt(Context.getTypeSize(T: SizeTy),
2528 Alignment / Context.getCharWidth()),
2529 SizeTy, StartLoc);
2530 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2531 CK_IntegralCast, &AlignmentLiteral,
2532 VK_PRValue, FPOptionsOverride());
2533
2534 // Adjust placement args by prepending conjured size and alignment exprs.
2535 llvm::SmallVector<Expr *, 8> CallArgs;
2536 CallArgs.reserve(N: NumImplicitArgs + PlacementArgs.size());
2537 CallArgs.emplace_back(Args: AllocationSize
2538 ? static_cast<Expr *>(&AllocationSizeLiteral)
2539 : &OpaqueAllocationSize);
2540 if (isAlignedAllocation(Mode: IAP.PassAlignment))
2541 CallArgs.emplace_back(Args: &DesiredAlignment);
2542 llvm::append_range(C&: CallArgs, R&: PlacementArgs);
2543
2544 DiagnoseSentinelCalls(D: OperatorNew, Loc: PlacementLParen, Args: CallArgs);
2545
2546 checkCall(FDecl: OperatorNew, Proto, /*ThisArg=*/nullptr, Args: CallArgs,
2547 /*IsMemberFunction=*/false, Loc: StartLoc, Range, CallType);
2548
2549 // Warn if the type is over-aligned and is being allocated by (unaligned)
2550 // global operator new.
2551 if (PlacementArgs.empty() && !isAlignedAllocation(Mode: IAP.PassAlignment) &&
2552 (OperatorNew->isImplicit() ||
2553 (OperatorNew->getBeginLoc().isValid() &&
2554 getSourceManager().isInSystemHeader(Loc: OperatorNew->getBeginLoc())))) {
2555 if (Alignment > NewAlignment)
2556 Diag(Loc: StartLoc, DiagID: diag::warn_overaligned_type)
2557 << AllocType
2558 << unsigned(Alignment / Context.getCharWidth())
2559 << unsigned(NewAlignment / Context.getCharWidth());
2560 }
2561 }
2562
2563 // Array 'new' can't have any initializers except empty parentheses.
2564 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2565 // dialect distinction.
2566 if (ArraySize && !isLegalArrayNewInitializer(Style: InitStyle, Init: Initializer,
2567 IsCPlusPlus20: getLangOpts().CPlusPlus20)) {
2568 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2569 Exprs.back()->getEndLoc());
2570 Diag(Loc: StartLoc, DiagID: diag::err_new_array_init_args) << InitRange;
2571 return ExprError();
2572 }
2573
2574 // If we can perform the initialization, and we've not already done so,
2575 // do it now.
2576 if (!AllocType->isDependentType() &&
2577 !Expr::hasAnyTypeDependentArguments(Exprs)) {
2578 // The type we initialize is the complete type, including the array bound.
2579 QualType InitType;
2580 if (KnownArraySize)
2581 InitType = Context.getConstantArrayType(
2582 EltTy: AllocType,
2583 ArySize: llvm::APInt(Context.getTypeSize(T: Context.getSizeType()),
2584 *KnownArraySize),
2585 SizeExpr: *ArraySize, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
2586 else if (ArraySize)
2587 InitType = Context.getIncompleteArrayType(EltTy: AllocType,
2588 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
2589 else
2590 InitType = AllocType;
2591
2592 bool VariableLengthArrayNew = ArraySize && *ArraySize && !KnownArraySize;
2593 InitializedEntity Entity = InitializedEntity::InitializeNew(
2594 NewLoc: StartLoc, Type: InitType,
2595 IsVariableLengthArrayNew: VariableLengthArrayNew ? InitializedEntity::NewArrayKind::UnknownLength
2596 : InitializedEntity::NewArrayKind::KnownLength);
2597 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2598 ExprResult FullInit = InitSeq.Perform(S&: *this, Entity, Kind, Args: Exprs);
2599 if (FullInit.isInvalid())
2600 return ExprError();
2601
2602 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2603 // we don't want the initialized object to be destructed.
2604 // FIXME: We should not create these in the first place.
2605 if (CXXBindTemporaryExpr *Binder =
2606 dyn_cast_or_null<CXXBindTemporaryExpr>(Val: FullInit.get()))
2607 FullInit = Binder->getSubExpr();
2608
2609 Initializer = FullInit.get();
2610
2611 // FIXME: If we have a KnownArraySize, check that the array bound of the
2612 // initializer is no greater than that constant value.
2613
2614 if (ArraySize && !*ArraySize) {
2615 auto *CAT = Context.getAsConstantArrayType(T: Initializer->getType());
2616 if (CAT) {
2617 // FIXME: Track that the array size was inferred rather than explicitly
2618 // specified.
2619 ArraySize = IntegerLiteral::Create(
2620 C: Context, V: CAT->getSize(), type: Context.getSizeType(), l: TypeRange.getEnd());
2621 } else {
2622 Diag(Loc: TypeRange.getEnd(), DiagID: diag::err_new_array_size_unknown_from_init)
2623 << Initializer->getSourceRange();
2624 }
2625 }
2626 }
2627
2628 // Mark the new and delete operators as referenced.
2629 if (OperatorNew) {
2630 if (DiagnoseUseOfDecl(D: OperatorNew, Locs: StartLoc))
2631 return ExprError();
2632 MarkFunctionReferenced(Loc: StartLoc, Func: OperatorNew);
2633 }
2634 if (OperatorDelete) {
2635 if (DiagnoseUseOfDecl(D: OperatorDelete, Locs: StartLoc))
2636 return ExprError();
2637 MarkFunctionReferenced(Loc: StartLoc, Func: OperatorDelete);
2638 }
2639
2640 // new[] will trigger vector deleting destructor emission if the class has
2641 // virtual destructor for MSVC compatibility. Perform necessary checks.
2642 if (Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts())) {
2643 if (const CXXConstructExpr *CCE =
2644 dyn_cast_or_null<CXXConstructExpr>(Val: Initializer);
2645 CCE && ArraySize) {
2646 CXXRecordDecl *ClassDecl = CCE->getConstructor()->getParent();
2647 // We probably already did this for another new[] with this class so don't
2648 // do it twice.
2649 if (!Context.classMaybeNeedsVectorDeletingDestructor(RD: ClassDecl)) {
2650 auto *Dtor = ClassDecl->getDestructor();
2651 if (Dtor && Dtor->isVirtual() && !Dtor->isDeleted()) {
2652 Context.setClassMaybeNeedsVectorDeletingDestructor(ClassDecl);
2653 if (!Dtor->isDefined() && !Dtor->isInvalidDecl()) {
2654 // Call CheckDestructor if destructor is not defined. This is
2655 // needed to find operators delete and delete[] for vector deleting
2656 // destructor body because new[] will trigger emission of vector
2657 // deleting destructor body even if destructor is defined in another
2658 // translation unit.
2659 ContextRAII SavedContext(*this, Dtor);
2660 CheckDestructor(Destructor: Dtor);
2661 }
2662 }
2663 }
2664 }
2665 }
2666
2667 return CXXNewExpr::Create(Ctx: Context, IsGlobalNew: UseGlobal, OperatorNew, OperatorDelete,
2668 IAP, UsualArrayDeleteWantsSize, PlacementArgs,
2669 TypeIdParens, ArraySize, InitializationStyle: InitStyle, Initializer,
2670 Ty: ResultType, AllocatedTypeInfo: AllocTypeInfo, Range, DirectInitRange);
2671}
2672
2673bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2674 SourceRange R) {
2675 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2676 // abstract class type or array thereof.
2677 if (AllocType->isFunctionType())
2678 return Diag(Loc, DiagID: diag::err_bad_new_type)
2679 << AllocType << 0 << R;
2680 else if (AllocType->isReferenceType())
2681 return Diag(Loc, DiagID: diag::err_bad_new_type)
2682 << AllocType << 1 << R;
2683 else if (!AllocType->isDependentType() &&
2684 RequireCompleteSizedType(
2685 Loc, T: AllocType, DiagID: diag::err_new_incomplete_or_sizeless_type, Args: R))
2686 return true;
2687 else if (RequireNonAbstractType(Loc, T: AllocType,
2688 DiagID: diag::err_allocation_of_abstract_type))
2689 return true;
2690 else if (AllocType->isVariablyModifiedType())
2691 return Diag(Loc, DiagID: diag::err_variably_modified_new_type)
2692 << AllocType;
2693 else if (AllocType.getAddressSpace() != LangAS::Default &&
2694 !getLangOpts().OpenCLCPlusPlus)
2695 return Diag(Loc, DiagID: diag::err_address_space_qualified_new)
2696 << AllocType.getUnqualifiedType()
2697 << Qualifiers::getAddrSpaceAsString(AS: AllocType.getAddressSpace());
2698
2699 else if (getLangOpts().ObjCAutoRefCount) {
2700 if (const ArrayType *AT = Context.getAsArrayType(T: AllocType)) {
2701 QualType BaseAllocType = Context.getBaseElementType(VAT: AT);
2702 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2703 BaseAllocType->isObjCLifetimeType())
2704 return Diag(Loc, DiagID: diag::err_arc_new_array_without_ownership)
2705 << BaseAllocType;
2706 }
2707 }
2708
2709 return false;
2710}
2711
2712enum class ResolveMode { Typed, Untyped };
2713static bool resolveAllocationOverloadInterior(
2714 Sema &S, LookupResult &R, SourceRange Range, ResolveMode Mode,
2715 SmallVectorImpl<Expr *> &Args, AlignedAllocationMode &PassAlignment,
2716 FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates,
2717 Expr *AlignArg, bool Diagnose) {
2718 unsigned NonTypeArgumentOffset = 0;
2719 if (Mode == ResolveMode::Typed) {
2720 ++NonTypeArgumentOffset;
2721 }
2722
2723 OverloadCandidateSet Candidates(R.getNameLoc(),
2724 OverloadCandidateSet::CSK_Normal);
2725 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2726 Alloc != AllocEnd; ++Alloc) {
2727 // Even member operator new/delete are implicitly treated as
2728 // static, so don't use AddMemberCandidate.
2729 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2730 bool IsTypeAware = D->getAsFunction()->isTypeAwareOperatorNewOrDelete();
2731 if (IsTypeAware == (Mode != ResolveMode::Typed))
2732 continue;
2733
2734 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
2735 S.AddTemplateOverloadCandidate(FunctionTemplate: FnTemplate, FoundDecl: Alloc.getPair(),
2736 /*ExplicitTemplateArgs=*/nullptr, Args,
2737 CandidateSet&: Candidates,
2738 /*SuppressUserConversions=*/false);
2739 continue;
2740 }
2741
2742 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
2743 S.AddOverloadCandidate(Function: Fn, FoundDecl: Alloc.getPair(), Args, CandidateSet&: Candidates,
2744 /*SuppressUserConversions=*/false);
2745 }
2746
2747 // Do the resolution.
2748 OverloadCandidateSet::iterator Best;
2749 switch (Candidates.BestViableFunction(S, Loc: R.getNameLoc(), Best)) {
2750 case OR_Success: {
2751 // Got one!
2752 FunctionDecl *FnDecl = Best->Function;
2753 if (S.CheckAllocationAccess(OperatorLoc: R.getNameLoc(), PlacementRange: Range, NamingClass: R.getNamingClass(),
2754 FoundDecl: Best->FoundDecl) == Sema::AR_inaccessible)
2755 return true;
2756
2757 Operator = FnDecl;
2758 return false;
2759 }
2760
2761 case OR_No_Viable_Function:
2762 // C++17 [expr.new]p13:
2763 // If no matching function is found and the allocated object type has
2764 // new-extended alignment, the alignment argument is removed from the
2765 // argument list, and overload resolution is performed again.
2766 if (isAlignedAllocation(Mode: PassAlignment)) {
2767 PassAlignment = AlignedAllocationMode::No;
2768 AlignArg = Args[NonTypeArgumentOffset + 1];
2769 Args.erase(CI: Args.begin() + NonTypeArgumentOffset + 1);
2770 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,
2771 PassAlignment, Operator,
2772 AlignedCandidates: &Candidates, AlignArg, Diagnose);
2773 }
2774
2775 // MSVC will fall back on trying to find a matching global operator new
2776 // if operator new[] cannot be found. Also, MSVC will leak by not
2777 // generating a call to operator delete or operator delete[], but we
2778 // will not replicate that bug.
2779 // FIXME: Find out how this interacts with the std::align_val_t fallback
2780 // once MSVC implements it.
2781 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2782 S.Context.getLangOpts().MSVCCompat && Mode != ResolveMode::Typed) {
2783 R.clear();
2784 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(Op: OO_New));
2785 S.LookupQualifiedName(R, LookupCtx: S.Context.getTranslationUnitDecl());
2786 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2787 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,
2788 PassAlignment, Operator,
2789 /*Candidates=*/AlignedCandidates: nullptr,
2790 /*AlignArg=*/nullptr, Diagnose);
2791 }
2792 if (Mode == ResolveMode::Typed) {
2793 // If we can't find a matching type aware operator we don't consider this
2794 // a failure.
2795 Operator = nullptr;
2796 return false;
2797 }
2798 if (Diagnose) {
2799 // If this is an allocation of the form 'new (p) X' for some object
2800 // pointer p (or an expression that will decay to such a pointer),
2801 // diagnose the reason for the error.
2802 if (!R.isClassLookup() && Args.size() == 2 &&
2803 (Args[1]->getType()->isObjectPointerType() ||
2804 Args[1]->getType()->isArrayType())) {
2805 const QualType Arg1Type = Args[1]->getType();
2806 QualType UnderlyingType = S.Context.getBaseElementType(QT: Arg1Type);
2807 if (UnderlyingType->isPointerType())
2808 UnderlyingType = UnderlyingType->getPointeeType();
2809 if (UnderlyingType.isConstQualified()) {
2810 S.Diag(Loc: Args[1]->getExprLoc(),
2811 DiagID: diag::err_placement_new_into_const_qualified_storage)
2812 << Arg1Type << Args[1]->getSourceRange();
2813 return true;
2814 }
2815 S.Diag(Loc: R.getNameLoc(), DiagID: diag::err_need_header_before_placement_new)
2816 << R.getLookupName() << Range;
2817 // Listing the candidates is unlikely to be useful; skip it.
2818 return true;
2819 }
2820
2821 // Finish checking all candidates before we note any. This checking can
2822 // produce additional diagnostics so can't be interleaved with our
2823 // emission of notes.
2824 //
2825 // For an aligned allocation, separately check the aligned and unaligned
2826 // candidates with their respective argument lists.
2827 SmallVector<OverloadCandidate*, 32> Cands;
2828 SmallVector<OverloadCandidate*, 32> AlignedCands;
2829 llvm::SmallVector<Expr*, 4> AlignedArgs;
2830 if (AlignedCandidates) {
2831 auto IsAligned = [NonTypeArgumentOffset](OverloadCandidate &C) {
2832 auto AlignArgOffset = NonTypeArgumentOffset + 1;
2833 return C.Function->getNumParams() > AlignArgOffset &&
2834 C.Function->getParamDecl(i: AlignArgOffset)
2835 ->getType()
2836 ->isAlignValT();
2837 };
2838 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2839
2840 AlignedArgs.reserve(N: Args.size() + NonTypeArgumentOffset + 1);
2841 for (unsigned Idx = 0; Idx < NonTypeArgumentOffset + 1; ++Idx)
2842 AlignedArgs.push_back(Elt: Args[Idx]);
2843 AlignedArgs.push_back(Elt: AlignArg);
2844 AlignedArgs.append(in_start: Args.begin() + NonTypeArgumentOffset + 1,
2845 in_end: Args.end());
2846 AlignedCands = AlignedCandidates->CompleteCandidates(
2847 S, OCD: OCD_AllCandidates, Args: AlignedArgs, OpLoc: R.getNameLoc(), Filter: IsAligned);
2848
2849 Cands = Candidates.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
2850 OpLoc: R.getNameLoc(), Filter: IsUnaligned);
2851 } else {
2852 Cands = Candidates.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
2853 OpLoc: R.getNameLoc());
2854 }
2855
2856 S.Diag(Loc: R.getNameLoc(), DiagID: diag::err_ovl_no_viable_function_in_call)
2857 << R.getLookupName() << Range;
2858 if (AlignedCandidates)
2859 AlignedCandidates->NoteCandidates(S, Args: AlignedArgs, Cands: AlignedCands, Opc: "",
2860 OpLoc: R.getNameLoc());
2861 Candidates.NoteCandidates(S, Args, Cands, Opc: "", OpLoc: R.getNameLoc());
2862 }
2863 return true;
2864
2865 case OR_Ambiguous:
2866 if (Diagnose) {
2867 Candidates.NoteCandidates(
2868 PA: PartialDiagnosticAt(R.getNameLoc(),
2869 S.PDiag(DiagID: diag::err_ovl_ambiguous_call)
2870 << R.getLookupName() << Range),
2871 S, OCD: OCD_AmbiguousCandidates, Args);
2872 }
2873 return true;
2874
2875 case OR_Deleted: {
2876 if (Diagnose)
2877 S.DiagnoseUseOfDeletedFunction(Loc: R.getNameLoc(), Range, Name: R.getLookupName(),
2878 CandidateSet&: Candidates, Fn: Best->Function, Args);
2879 return true;
2880 }
2881 }
2882 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2883}
2884
2885enum class DeallocLookupMode { Untyped, OptionallyTyped };
2886
2887static void LookupGlobalDeallocationFunctions(Sema &S, SourceLocation Loc,
2888 LookupResult &FoundDelete,
2889 DeallocLookupMode Mode,
2890 DeclarationName Name) {
2891 S.LookupQualifiedName(R&: FoundDelete, LookupCtx: S.Context.getTranslationUnitDecl());
2892 if (Mode != DeallocLookupMode::OptionallyTyped) {
2893 // We're going to remove either the typed or the non-typed
2894 bool RemoveTypedDecl = Mode == DeallocLookupMode::Untyped;
2895 LookupResult::Filter Filter = FoundDelete.makeFilter();
2896 while (Filter.hasNext()) {
2897 FunctionDecl *FD = Filter.next()->getUnderlyingDecl()->getAsFunction();
2898 if (FD->isTypeAwareOperatorNewOrDelete() == RemoveTypedDecl)
2899 Filter.erase();
2900 }
2901 Filter.done();
2902 }
2903}
2904
2905static bool resolveAllocationOverload(
2906 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2907 ImplicitAllocationParameters &IAP, FunctionDecl *&Operator,
2908 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2909 Operator = nullptr;
2910 if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) {
2911 assert(S.isStdTypeIdentity(Args[0]->getType(), nullptr));
2912 // The internal overload resolution work mutates the argument list
2913 // in accordance with the spec. We may want to change that in future,
2914 // but for now we deal with this by making a copy of the non-type-identity
2915 // arguments.
2916 SmallVector<Expr *> UntypedParameters;
2917 UntypedParameters.reserve(N: Args.size() - 1);
2918 UntypedParameters.push_back(Elt: Args[1]);
2919 // Type aware allocation implicitly includes the alignment parameter so
2920 // only include it in the untyped parameter list if alignment was explicitly
2921 // requested
2922 if (isAlignedAllocation(Mode: IAP.PassAlignment))
2923 UntypedParameters.push_back(Elt: Args[2]);
2924 UntypedParameters.append(in_start: Args.begin() + 3, in_end: Args.end());
2925
2926 AlignedAllocationMode InitialAlignmentMode = IAP.PassAlignment;
2927 IAP.PassAlignment = AlignedAllocationMode::Yes;
2928 if (resolveAllocationOverloadInterior(
2929 S, R, Range, Mode: ResolveMode::Typed, Args, PassAlignment&: IAP.PassAlignment, Operator,
2930 AlignedCandidates, AlignArg, Diagnose))
2931 return true;
2932 if (Operator)
2933 return false;
2934
2935 // If we got to this point we could not find a matching typed operator
2936 // so we update the IAP flags, and revert to our stored copy of the
2937 // type-identity-less argument list.
2938 IAP.PassTypeIdentity = TypeAwareAllocationMode::No;
2939 IAP.PassAlignment = InitialAlignmentMode;
2940 Args = std::move(UntypedParameters);
2941 }
2942 assert(!S.isStdTypeIdentity(Args[0]->getType(), nullptr));
2943 return resolveAllocationOverloadInterior(
2944 S, R, Range, Mode: ResolveMode::Untyped, Args, PassAlignment&: IAP.PassAlignment, Operator,
2945 AlignedCandidates, AlignArg, Diagnose);
2946}
2947
2948bool Sema::FindAllocationFunctions(
2949 SourceLocation StartLoc, SourceRange Range,
2950 AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope,
2951 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
2952 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
2953 FunctionDecl *&OperatorDelete, bool Diagnose) {
2954 // --- Choosing an allocation function ---
2955 // C++ 5.3.4p8 - 14 & 18
2956 // 1) If looking in AllocationFunctionScope::Global scope for allocation
2957 // functions, only look in
2958 // the global scope. Else, if AllocationFunctionScope::Class, only look in
2959 // the scope of the allocated class. If AllocationFunctionScope::Both, look
2960 // in both.
2961 // 2) If an array size is given, look for operator new[], else look for
2962 // operator new.
2963 // 3) The first argument is always size_t. Append the arguments from the
2964 // placement form.
2965
2966 SmallVector<Expr*, 8> AllocArgs;
2967 AllocArgs.reserve(N: IAP.getNumImplicitArgs() + PlaceArgs.size());
2968
2969 // C++ [expr.new]p8:
2970 // If the allocated type is a non-array type, the allocation
2971 // function's name is operator new and the deallocation function's
2972 // name is operator delete. If the allocated type is an array
2973 // type, the allocation function's name is operator new[] and the
2974 // deallocation function's name is operator delete[].
2975 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2976 Op: IsArray ? OO_Array_New : OO_New);
2977
2978 QualType AllocElemType = Context.getBaseElementType(QT: AllocType);
2979
2980 // We don't care about the actual value of these arguments.
2981 // FIXME: Should the Sema create the expression and embed it in the syntax
2982 // tree? Or should the consumer just recalculate the value?
2983 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2984
2985 // We use size_t as a stand in so that we can construct the init
2986 // expr on the stack
2987 QualType TypeIdentity = Context.getSizeType();
2988 if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) {
2989 QualType SpecializedTypeIdentity =
2990 tryBuildStdTypeIdentity(Type: IAP.Type, Loc: StartLoc);
2991 if (!SpecializedTypeIdentity.isNull()) {
2992 TypeIdentity = SpecializedTypeIdentity;
2993 if (RequireCompleteType(Loc: StartLoc, T: TypeIdentity,
2994 DiagID: diag::err_incomplete_type))
2995 return true;
2996 } else
2997 IAP.PassTypeIdentity = TypeAwareAllocationMode::No;
2998 }
2999 TypeAwareAllocationMode OriginalTypeAwareState = IAP.PassTypeIdentity;
3000
3001 CXXScalarValueInitExpr TypeIdentityParam(TypeIdentity, nullptr, StartLoc);
3002 if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity))
3003 AllocArgs.push_back(Elt: &TypeIdentityParam);
3004
3005 QualType SizeTy = Context.getSizeType();
3006 unsigned SizeTyWidth = Context.getTypeSize(T: SizeTy);
3007 IntegerLiteral Size(Context, llvm::APInt::getZero(numBits: SizeTyWidth), SizeTy,
3008 SourceLocation());
3009 AllocArgs.push_back(Elt: &Size);
3010
3011 QualType AlignValT = Context.VoidTy;
3012 bool IncludeAlignParam = isAlignedAllocation(Mode: IAP.PassAlignment) ||
3013 isTypeAwareAllocation(Mode: IAP.PassTypeIdentity);
3014 if (IncludeAlignParam) {
3015 DeclareGlobalNewDelete();
3016 AlignValT = Context.getCanonicalTagType(TD: getStdAlignValT());
3017 }
3018 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
3019 if (IncludeAlignParam)
3020 AllocArgs.push_back(Elt: &Align);
3021
3022 llvm::append_range(C&: AllocArgs, R&: PlaceArgs);
3023
3024 // Find the allocation function.
3025 {
3026 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
3027
3028 // C++1z [expr.new]p9:
3029 // If the new-expression begins with a unary :: operator, the allocation
3030 // function's name is looked up in the global scope. Otherwise, if the
3031 // allocated type is a class type T or array thereof, the allocation
3032 // function's name is looked up in the scope of T.
3033 if (AllocElemType->isRecordType() &&
3034 NewScope != AllocationFunctionScope::Global)
3035 LookupQualifiedName(R, LookupCtx: AllocElemType->getAsCXXRecordDecl());
3036
3037 // We can see ambiguity here if the allocation function is found in
3038 // multiple base classes.
3039 if (R.isAmbiguous())
3040 return true;
3041
3042 // If this lookup fails to find the name, or if the allocated type is not
3043 // a class type, the allocation function's name is looked up in the
3044 // global scope.
3045 if (R.empty()) {
3046 if (NewScope == AllocationFunctionScope::Class)
3047 return true;
3048
3049 LookupQualifiedName(R, LookupCtx: Context.getTranslationUnitDecl());
3050 }
3051
3052 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
3053 if (PlaceArgs.empty()) {
3054 Diag(Loc: StartLoc, DiagID: diag::err_openclcxx_not_supported) << "default new";
3055 } else {
3056 Diag(Loc: StartLoc, DiagID: diag::err_openclcxx_placement_new);
3057 }
3058 return true;
3059 }
3060
3061 assert(!R.empty() && "implicitly declared allocation functions not found");
3062 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3063
3064 // We do our own custom access checks below.
3065 R.suppressDiagnostics();
3066
3067 if (resolveAllocationOverload(S&: *this, R, Range, Args&: AllocArgs, IAP, Operator&: OperatorNew,
3068 /*Candidates=*/AlignedCandidates: nullptr,
3069 /*AlignArg=*/nullptr, Diagnose))
3070 return true;
3071 }
3072
3073 // We don't need an operator delete if we're running under -fno-exceptions.
3074 if (!getLangOpts().Exceptions) {
3075 OperatorDelete = nullptr;
3076 return false;
3077 }
3078
3079 // Note, the name of OperatorNew might have been changed from array to
3080 // non-array by resolveAllocationOverload.
3081 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3082 Op: OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
3083 ? OO_Array_Delete
3084 : OO_Delete);
3085
3086 // C++ [expr.new]p19:
3087 //
3088 // If the new-expression begins with a unary :: operator, the
3089 // deallocation function's name is looked up in the global
3090 // scope. Otherwise, if the allocated type is a class type T or an
3091 // array thereof, the deallocation function's name is looked up in
3092 // the scope of T. If this lookup fails to find the name, or if
3093 // the allocated type is not a class type or array thereof, the
3094 // deallocation function's name is looked up in the global scope.
3095 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
3096 if (AllocElemType->isRecordType() &&
3097 DeleteScope != AllocationFunctionScope::Global) {
3098 auto *RD = AllocElemType->castAsCXXRecordDecl();
3099 LookupQualifiedName(R&: FoundDelete, LookupCtx: RD);
3100 }
3101 if (FoundDelete.isAmbiguous())
3102 return true; // FIXME: clean up expressions?
3103
3104 // Filter out any destroying operator deletes. We can't possibly call such a
3105 // function in this context, because we're handling the case where the object
3106 // was not successfully constructed.
3107 // FIXME: This is not covered by the language rules yet.
3108 {
3109 LookupResult::Filter Filter = FoundDelete.makeFilter();
3110 while (Filter.hasNext()) {
3111 auto *FD = dyn_cast<FunctionDecl>(Val: Filter.next()->getUnderlyingDecl());
3112 if (FD && FD->isDestroyingOperatorDelete())
3113 Filter.erase();
3114 }
3115 Filter.done();
3116 }
3117
3118 auto GetRedeclContext = [](Decl *D) {
3119 return D->getDeclContext()->getRedeclContext();
3120 };
3121
3122 DeclContext *OperatorNewContext = GetRedeclContext(OperatorNew);
3123
3124 bool FoundGlobalDelete = FoundDelete.empty();
3125 bool IsClassScopedTypeAwareNew =
3126 isTypeAwareAllocation(Mode: IAP.PassTypeIdentity) &&
3127 OperatorNewContext->isRecord();
3128 auto DiagnoseMissingTypeAwareCleanupOperator = [&](bool IsPlacementOperator) {
3129 assert(isTypeAwareAllocation(IAP.PassTypeIdentity));
3130 if (Diagnose) {
3131 Diag(Loc: StartLoc, DiagID: diag::err_mismatching_type_aware_cleanup_deallocator)
3132 << OperatorNew->getDeclName() << IsPlacementOperator << DeleteName;
3133 Diag(Loc: OperatorNew->getLocation(), DiagID: diag::note_type_aware_operator_declared)
3134 << OperatorNew->isTypeAwareOperatorNewOrDelete()
3135 << OperatorNew->getDeclName() << OperatorNewContext;
3136 }
3137 };
3138 if (IsClassScopedTypeAwareNew && FoundDelete.empty()) {
3139 DiagnoseMissingTypeAwareCleanupOperator(/*isPlacementNew=*/false);
3140 return true;
3141 }
3142 if (FoundDelete.empty()) {
3143 FoundDelete.clear(Kind: LookupOrdinaryName);
3144
3145 if (DeleteScope == AllocationFunctionScope::Class)
3146 return true;
3147
3148 DeclareGlobalNewDelete();
3149 DeallocLookupMode LookupMode = isTypeAwareAllocation(Mode: OriginalTypeAwareState)
3150 ? DeallocLookupMode::OptionallyTyped
3151 : DeallocLookupMode::Untyped;
3152 LookupGlobalDeallocationFunctions(S&: *this, Loc: StartLoc, FoundDelete, Mode: LookupMode,
3153 Name: DeleteName);
3154 }
3155
3156 FoundDelete.suppressDiagnostics();
3157
3158 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
3159
3160 // Whether we're looking for a placement operator delete is dictated
3161 // by whether we selected a placement operator new, not by whether
3162 // we had explicit placement arguments. This matters for things like
3163 // struct A { void *operator new(size_t, int = 0); ... };
3164 // A *a = new A()
3165 //
3166 // We don't have any definition for what a "placement allocation function"
3167 // is, but we assume it's any allocation function whose
3168 // parameter-declaration-clause is anything other than (size_t).
3169 //
3170 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
3171 // This affects whether an exception from the constructor of an overaligned
3172 // type uses the sized or non-sized form of aligned operator delete.
3173
3174 unsigned NonPlacementNewArgCount = 1; // size parameter
3175 if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity))
3176 NonPlacementNewArgCount =
3177 /* type-identity */ 1 + /* size */ 1 + /* alignment */ 1;
3178 bool isPlacementNew = !PlaceArgs.empty() ||
3179 OperatorNew->param_size() != NonPlacementNewArgCount ||
3180 OperatorNew->isVariadic();
3181
3182 if (isPlacementNew) {
3183 // C++ [expr.new]p20:
3184 // A declaration of a placement deallocation function matches the
3185 // declaration of a placement allocation function if it has the
3186 // same number of parameters and, after parameter transformations
3187 // (8.3.5), all parameter types except the first are
3188 // identical. [...]
3189 //
3190 // To perform this comparison, we compute the function type that
3191 // the deallocation function should have, and use that type both
3192 // for template argument deduction and for comparison purposes.
3193 QualType ExpectedFunctionType;
3194 {
3195 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
3196
3197 SmallVector<QualType, 6> ArgTypes;
3198 int InitialParamOffset = 0;
3199 if (isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) {
3200 ArgTypes.push_back(Elt: TypeIdentity);
3201 InitialParamOffset = 1;
3202 }
3203 ArgTypes.push_back(Elt: Context.VoidPtrTy);
3204 for (unsigned I = ArgTypes.size() - InitialParamOffset,
3205 N = Proto->getNumParams();
3206 I < N; ++I)
3207 ArgTypes.push_back(Elt: Proto->getParamType(i: I));
3208
3209 FunctionProtoType::ExtProtoInfo EPI;
3210 // FIXME: This is not part of the standard's rule.
3211 EPI.Variadic = Proto->isVariadic();
3212
3213 ExpectedFunctionType
3214 = Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
3215 }
3216
3217 for (LookupResult::iterator D = FoundDelete.begin(),
3218 DEnd = FoundDelete.end();
3219 D != DEnd; ++D) {
3220 FunctionDecl *Fn = nullptr;
3221 if (FunctionTemplateDecl *FnTmpl =
3222 dyn_cast<FunctionTemplateDecl>(Val: (*D)->getUnderlyingDecl())) {
3223 // Perform template argument deduction to try to match the
3224 // expected function type.
3225 TemplateDeductionInfo Info(StartLoc);
3226 if (DeduceTemplateArguments(FunctionTemplate: FnTmpl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType, Specialization&: Fn,
3227 Info) != TemplateDeductionResult::Success)
3228 continue;
3229 } else
3230 Fn = cast<FunctionDecl>(Val: (*D)->getUnderlyingDecl());
3231
3232 if (Context.hasSameType(T1: adjustCCAndNoReturn(ArgFunctionType: Fn->getType(),
3233 FunctionType: ExpectedFunctionType,
3234 /*AdjustExcpetionSpec*/AdjustExceptionSpec: true),
3235 T2: ExpectedFunctionType))
3236 Matches.push_back(Elt: std::make_pair(x: D.getPair(), y&: Fn));
3237 }
3238
3239 if (getLangOpts().CUDA)
3240 CUDA().EraseUnwantedMatches(Caller: getCurFunctionDecl(/*AllowLambda=*/true),
3241 Matches);
3242 if (Matches.empty() && isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) {
3243 DiagnoseMissingTypeAwareCleanupOperator(isPlacementNew);
3244 return true;
3245 }
3246 } else {
3247 // C++1y [expr.new]p22:
3248 // For a non-placement allocation function, the normal deallocation
3249 // function lookup is used
3250 //
3251 // Per [expr.delete]p10, this lookup prefers a member operator delete
3252 // without a size_t argument, but prefers a non-member operator delete
3253 // with a size_t where possible (which it always is in this case).
3254 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
3255 ImplicitDeallocationParameters IDP = {
3256 AllocElemType, OriginalTypeAwareState,
3257 alignedAllocationModeFromBool(
3258 IsAligned: hasNewExtendedAlignment(S&: *this, AllocType: AllocElemType)),
3259 sizedDeallocationModeFromBool(IsSized: FoundGlobalDelete)};
3260 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
3261 S&: *this, R&: FoundDelete, IDP, Loc: StartLoc, BestFns: &BestDeallocFns);
3262 if (Selected && BestDeallocFns.empty())
3263 Matches.push_back(Elt: std::make_pair(x&: Selected.Found, y&: Selected.FD));
3264 else {
3265 // If we failed to select an operator, all remaining functions are viable
3266 // but ambiguous.
3267 for (auto Fn : BestDeallocFns)
3268 Matches.push_back(Elt: std::make_pair(x&: Fn.Found, y&: Fn.FD));
3269 }
3270 }
3271
3272 // C++ [expr.new]p20:
3273 // [...] If the lookup finds a single matching deallocation
3274 // function, that function will be called; otherwise, no
3275 // deallocation function will be called.
3276 if (Matches.size() == 1) {
3277 OperatorDelete = Matches[0].second;
3278 DeclContext *OperatorDeleteContext = GetRedeclContext(OperatorDelete);
3279 bool FoundTypeAwareOperator =
3280 OperatorDelete->isTypeAwareOperatorNewOrDelete() ||
3281 OperatorNew->isTypeAwareOperatorNewOrDelete();
3282 if (Diagnose && FoundTypeAwareOperator) {
3283 bool MismatchedTypeAwareness =
3284 OperatorDelete->isTypeAwareOperatorNewOrDelete() !=
3285 OperatorNew->isTypeAwareOperatorNewOrDelete();
3286 bool MismatchedContext = OperatorDeleteContext != OperatorNewContext;
3287 if (MismatchedTypeAwareness || MismatchedContext) {
3288 FunctionDecl *Operators[] = {OperatorDelete, OperatorNew};
3289 bool TypeAwareOperatorIndex =
3290 OperatorNew->isTypeAwareOperatorNewOrDelete();
3291 Diag(Loc: StartLoc, DiagID: diag::err_mismatching_type_aware_cleanup_deallocator)
3292 << Operators[TypeAwareOperatorIndex]->getDeclName()
3293 << isPlacementNew
3294 << Operators[!TypeAwareOperatorIndex]->getDeclName()
3295 << GetRedeclContext(Operators[TypeAwareOperatorIndex]);
3296 Diag(Loc: OperatorNew->getLocation(),
3297 DiagID: diag::note_type_aware_operator_declared)
3298 << OperatorNew->isTypeAwareOperatorNewOrDelete()
3299 << OperatorNew->getDeclName() << OperatorNewContext;
3300 Diag(Loc: OperatorDelete->getLocation(),
3301 DiagID: diag::note_type_aware_operator_declared)
3302 << OperatorDelete->isTypeAwareOperatorNewOrDelete()
3303 << OperatorDelete->getDeclName() << OperatorDeleteContext;
3304 }
3305 }
3306
3307 // C++1z [expr.new]p23:
3308 // If the lookup finds a usual deallocation function (3.7.4.2)
3309 // with a parameter of type std::size_t and that function, considered
3310 // as a placement deallocation function, would have been
3311 // selected as a match for the allocation function, the program
3312 // is ill-formed.
3313 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
3314 isNonPlacementDeallocationFunction(S&: *this, FD: OperatorDelete)) {
3315 UsualDeallocFnInfo Info(*this,
3316 DeclAccessPair::make(D: OperatorDelete, AS: AS_public),
3317 AllocElemType, StartLoc);
3318 // Core issue, per mail to core reflector, 2016-10-09:
3319 // If this is a member operator delete, and there is a corresponding
3320 // non-sized member operator delete, this isn't /really/ a sized
3321 // deallocation function, it just happens to have a size_t parameter.
3322 bool IsSizedDelete = isSizedDeallocation(Mode: Info.IDP.PassSize);
3323 if (IsSizedDelete && !FoundGlobalDelete) {
3324 ImplicitDeallocationParameters SizeTestingIDP = {
3325 AllocElemType, Info.IDP.PassTypeIdentity, Info.IDP.PassAlignment,
3326 SizedDeallocationMode::No};
3327 auto NonSizedDelete = resolveDeallocationOverload(
3328 S&: *this, R&: FoundDelete, IDP: SizeTestingIDP, Loc: StartLoc);
3329 if (NonSizedDelete &&
3330 !isSizedDeallocation(Mode: NonSizedDelete.IDP.PassSize) &&
3331 NonSizedDelete.IDP.PassAlignment == Info.IDP.PassAlignment)
3332 IsSizedDelete = false;
3333 }
3334
3335 if (IsSizedDelete && !isTypeAwareAllocation(Mode: IAP.PassTypeIdentity)) {
3336 SourceRange R = PlaceArgs.empty()
3337 ? SourceRange()
3338 : SourceRange(PlaceArgs.front()->getBeginLoc(),
3339 PlaceArgs.back()->getEndLoc());
3340 Diag(Loc: StartLoc, DiagID: diag::err_placement_new_non_placement_delete) << R;
3341 if (!OperatorDelete->isImplicit())
3342 Diag(Loc: OperatorDelete->getLocation(), DiagID: diag::note_previous_decl)
3343 << DeleteName;
3344 }
3345 }
3346 if (CheckDeleteOperator(S&: *this, StartLoc, Range, Diagnose,
3347 NamingClass: FoundDelete.getNamingClass(), Decl: Matches[0].first,
3348 Operator: Matches[0].second))
3349 return true;
3350
3351 } else if (!Matches.empty()) {
3352 // We found multiple suitable operators. Per [expr.new]p20, that means we
3353 // call no 'operator delete' function, but we should at least warn the user.
3354 // FIXME: Suppress this warning if the construction cannot throw.
3355 Diag(Loc: StartLoc, DiagID: diag::warn_ambiguous_suitable_delete_function_found)
3356 << DeleteName << AllocElemType;
3357
3358 for (auto &Match : Matches)
3359 Diag(Loc: Match.second->getLocation(),
3360 DiagID: diag::note_member_declared_here) << DeleteName;
3361 }
3362
3363 return false;
3364}
3365
3366void Sema::DeclareGlobalNewDelete() {
3367 if (GlobalNewDeleteDeclared)
3368 return;
3369
3370 // The implicitly declared new and delete operators
3371 // are not supported in OpenCL.
3372 if (getLangOpts().OpenCLCPlusPlus)
3373 return;
3374
3375 // C++ [basic.stc.dynamic.general]p2:
3376 // The library provides default definitions for the global allocation
3377 // and deallocation functions. Some global allocation and deallocation
3378 // functions are replaceable ([new.delete]); these are attached to the
3379 // global module ([module.unit]).
3380 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3381 PushGlobalModuleFragment(BeginLoc: SourceLocation());
3382
3383 // C++ [basic.std.dynamic]p2:
3384 // [...] The following allocation and deallocation functions (18.4) are
3385 // implicitly declared in global scope in each translation unit of a
3386 // program
3387 //
3388 // C++03:
3389 // void* operator new(std::size_t) throw(std::bad_alloc);
3390 // void* operator new[](std::size_t) throw(std::bad_alloc);
3391 // void operator delete(void*) throw();
3392 // void operator delete[](void*) throw();
3393 // C++11:
3394 // void* operator new(std::size_t);
3395 // void* operator new[](std::size_t);
3396 // void operator delete(void*) noexcept;
3397 // void operator delete[](void*) noexcept;
3398 // C++1y:
3399 // void* operator new(std::size_t);
3400 // void* operator new[](std::size_t);
3401 // void operator delete(void*) noexcept;
3402 // void operator delete[](void*) noexcept;
3403 // void operator delete(void*, std::size_t) noexcept;
3404 // void operator delete[](void*, std::size_t) noexcept;
3405 //
3406 // These implicit declarations introduce only the function names operator
3407 // new, operator new[], operator delete, operator delete[].
3408 //
3409 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3410 // "std" or "bad_alloc" as necessary to form the exception specification.
3411 // However, we do not make these implicit declarations visible to name
3412 // lookup.
3413 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3414 // The "std::bad_alloc" class has not yet been declared, so build it
3415 // implicitly.
3416 StdBadAlloc = CXXRecordDecl::Create(
3417 C: Context, TK: TagTypeKind::Class, DC: getOrCreateStdNamespace(),
3418 StartLoc: SourceLocation(), IdLoc: SourceLocation(),
3419 Id: &PP.getIdentifierTable().get(Name: "bad_alloc"), PrevDecl: nullptr);
3420 getStdBadAlloc()->setImplicit(true);
3421
3422 // The implicitly declared "std::bad_alloc" should live in global module
3423 // fragment.
3424 if (TheGlobalModuleFragment) {
3425 getStdBadAlloc()->setModuleOwnershipKind(
3426 Decl::ModuleOwnershipKind::ReachableWhenImported);
3427 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3428 }
3429 }
3430 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3431 // The "std::align_val_t" enum class has not yet been declared, so build it
3432 // implicitly.
3433 auto *AlignValT = EnumDecl::Create(
3434 C&: Context, DC: getOrCreateStdNamespace(), StartLoc: SourceLocation(), IdLoc: SourceLocation(),
3435 Id: &PP.getIdentifierTable().get(Name: "align_val_t"), PrevDecl: nullptr, IsScoped: true, IsScopedUsingClassTag: true, IsFixed: true);
3436
3437 // The implicitly declared "std::align_val_t" should live in global module
3438 // fragment.
3439 if (TheGlobalModuleFragment) {
3440 AlignValT->setModuleOwnershipKind(
3441 Decl::ModuleOwnershipKind::ReachableWhenImported);
3442 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3443 }
3444
3445 AlignValT->setIntegerType(Context.getSizeType());
3446 AlignValT->setPromotionType(Context.getSizeType());
3447 AlignValT->setImplicit(true);
3448
3449 // Add to the std namespace so that the module merger can find it via
3450 // noload_lookup and merge it with the module's explicit definition.
3451 // We want the created EnumDecl to be available for redeclaration lookups,
3452 // but not for regular name lookups (same pattern as
3453 // getOrCreateStdNamespace).
3454 getOrCreateStdNamespace()->addDecl(D: AlignValT);
3455
3456 StdAlignValT = AlignValT;
3457 }
3458
3459 GlobalNewDeleteDeclared = true;
3460
3461 QualType VoidPtr = Context.getPointerType(T: Context.VoidTy);
3462 QualType SizeT = Context.getSizeType();
3463
3464 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3465 QualType Return, QualType Param) {
3466 llvm::SmallVector<QualType, 3> Params;
3467 Params.push_back(Elt: Param);
3468
3469 // Create up to four variants of the function (sized/aligned).
3470 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3471 (Kind == OO_Delete || Kind == OO_Array_Delete);
3472 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3473
3474 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3475 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3476 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3477 if (Sized)
3478 Params.push_back(Elt: SizeT);
3479
3480 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3481 if (Aligned)
3482 Params.push_back(Elt: Context.getCanonicalTagType(TD: getStdAlignValT()));
3483
3484 DeclareGlobalAllocationFunction(
3485 Name: Context.DeclarationNames.getCXXOperatorName(Op: Kind), Return, Params);
3486
3487 if (Aligned)
3488 Params.pop_back();
3489 }
3490 }
3491 };
3492
3493 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3494 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3495 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3496 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3497
3498 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3499 PopGlobalModuleFragment();
3500}
3501
3502/// DeclareGlobalAllocationFunction - Declares a single implicit global
3503/// allocation function if it doesn't already exist.
3504void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
3505 QualType Return,
3506 ArrayRef<QualType> Params) {
3507 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3508
3509 // Check if this function is already declared.
3510 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3511 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3512 Alloc != AllocEnd; ++Alloc) {
3513 // Only look at non-template functions, as it is the predefined,
3514 // non-templated allocation function we are trying to declare here.
3515 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: *Alloc)) {
3516 if (Func->getNumParams() == Params.size()) {
3517 if (std::equal(first1: Func->param_begin(), last1: Func->param_end(), first2: Params.begin(),
3518 last2: Params.end(), binary_pred: [&](ParmVarDecl *D, QualType RT) {
3519 return Context.hasSameUnqualifiedType(T1: D->getType(),
3520 T2: RT);
3521 })) {
3522 // Make the function visible to name lookup, even if we found it in
3523 // an unimported module. It either is an implicitly-declared global
3524 // allocation function, or is suppressing that function.
3525 Func->setVisibleDespiteOwningModule();
3526 return;
3527 }
3528 }
3529 }
3530 }
3531
3532 FunctionProtoType::ExtProtoInfo EPI(
3533 Context.getTargetInfo().getDefaultCallingConv());
3534
3535 QualType BadAllocType;
3536 bool HasBadAllocExceptionSpec = Name.isAnyOperatorNew();
3537 if (HasBadAllocExceptionSpec) {
3538 if (!getLangOpts().CPlusPlus11) {
3539 BadAllocType = Context.getCanonicalTagType(TD: getStdBadAlloc());
3540 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3541 EPI.ExceptionSpec.Type = EST_Dynamic;
3542 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3543 }
3544 if (getLangOpts().NewInfallible) {
3545 EPI.ExceptionSpec.Type = EST_DynamicNone;
3546 }
3547 } else {
3548 EPI.ExceptionSpec =
3549 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
3550 }
3551
3552 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3553 // The MSVC STL has explicit cdecl on its (host-side) allocation function
3554 // specializations for the allocation, so in order to prevent a CC clash
3555 // we use the host's CC, if available, or CC_C as a fallback, for the
3556 // host-side implicit decls, knowing these do not get emitted when compiling
3557 // for device.
3558 if (getLangOpts().CUDAIsDevice && ExtraAttr &&
3559 isa<CUDAHostAttr>(Val: ExtraAttr) &&
3560 Context.getTargetInfo().getTriple().isSPIRV()) {
3561 if (auto *ATI = Context.getAuxTargetInfo())
3562 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(cc: ATI->getDefaultCallingConv());
3563 else
3564 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(cc: CallingConv::CC_C);
3565 }
3566 QualType FnType = Context.getFunctionType(ResultTy: Return, Args: Params, EPI);
3567 FunctionDecl *Alloc = FunctionDecl::Create(
3568 C&: Context, DC: GlobalCtx, StartLoc: SourceLocation(), NLoc: SourceLocation(), N: Name, T: FnType,
3569 /*TInfo=*/nullptr, SC: SC_None, UsesFPIntrin: getCurFPFeatures().isFPConstrained(), isInlineSpecified: false,
3570 hasWrittenPrototype: true);
3571 Alloc->setImplicit();
3572 // Global allocation functions should always be visible.
3573 Alloc->setVisibleDespiteOwningModule();
3574
3575 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3576 !getLangOpts().CheckNew)
3577 Alloc->addAttr(
3578 A: ReturnsNonNullAttr::CreateImplicit(Ctx&: Context, Range: Alloc->getLocation()));
3579
3580 // C++ [basic.stc.dynamic.general]p2:
3581 // The library provides default definitions for the global allocation
3582 // and deallocation functions. Some global allocation and deallocation
3583 // functions are replaceable ([new.delete]); these are attached to the
3584 // global module ([module.unit]).
3585 //
3586 // In the language wording, these functions are attched to the global
3587 // module all the time. But in the implementation, the global module
3588 // is only meaningful when we're in a module unit. So here we attach
3589 // these allocation functions to global module conditionally.
3590 if (TheGlobalModuleFragment) {
3591 Alloc->setModuleOwnershipKind(
3592 Decl::ModuleOwnershipKind::ReachableWhenImported);
3593 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3594 }
3595
3596 if (LangOpts.hasGlobalAllocationFunctionVisibility())
3597 Alloc->addAttr(A: VisibilityAttr::CreateImplicit(
3598 Ctx&: Context, Visibility: LangOpts.hasHiddenGlobalAllocationFunctionVisibility()
3599 ? VisibilityAttr::Hidden
3600 : LangOpts.hasProtectedGlobalAllocationFunctionVisibility()
3601 ? VisibilityAttr::Protected
3602 : VisibilityAttr::Default));
3603
3604 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
3605 for (QualType T : Params) {
3606 ParamDecls.push_back(Elt: ParmVarDecl::Create(
3607 C&: Context, DC: Alloc, StartLoc: SourceLocation(), IdLoc: SourceLocation(), Id: nullptr, T,
3608 /*TInfo=*/nullptr, S: SC_None, DefArg: nullptr));
3609 ParamDecls.back()->setImplicit();
3610 }
3611 Alloc->setParams(ParamDecls);
3612 if (ExtraAttr)
3613 Alloc->addAttr(A: ExtraAttr);
3614 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD: Alloc);
3615 Context.getTranslationUnitDecl()->addDecl(D: Alloc);
3616 IdResolver.tryAddTopLevelDecl(D: Alloc, Name);
3617 };
3618
3619 if (!LangOpts.CUDA)
3620 CreateAllocationFunctionDecl(nullptr);
3621 else {
3622 // Host and device get their own declaration so each can be
3623 // defined or re-declared independently.
3624 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Ctx&: Context));
3625 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Ctx&: Context));
3626 }
3627}
3628
3629FunctionDecl *
3630Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3631 ImplicitDeallocationParameters IDP,
3632 DeclarationName Name, bool Diagnose) {
3633 DeclareGlobalNewDelete();
3634
3635 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3636 LookupGlobalDeallocationFunctions(S&: *this, Loc: StartLoc, FoundDelete,
3637 Mode: DeallocLookupMode::OptionallyTyped, Name);
3638
3639 // FIXME: It's possible for this to result in ambiguity, through a
3640 // user-declared variadic operator delete or the enable_if attribute. We
3641 // should probably not consider those cases to be usual deallocation
3642 // functions. But for now we just make an arbitrary choice in that case.
3643 auto Result = resolveDeallocationOverload(S&: *this, R&: FoundDelete, IDP, Loc: StartLoc);
3644 if (!Result)
3645 return nullptr;
3646
3647 if (CheckDeleteOperator(S&: *this, StartLoc, Range: StartLoc, Diagnose,
3648 NamingClass: FoundDelete.getNamingClass(), Decl: Result.Found,
3649 Operator: Result.FD))
3650 return nullptr;
3651
3652 assert(Result.FD && "operator delete missing from global scope?");
3653 return Result.FD;
3654}
3655
3656FunctionDecl *Sema::FindDeallocationFunctionForDestructor(
3657 SourceLocation Loc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal,
3658 DeclarationName Name) {
3659
3660 FunctionDecl *OperatorDelete = nullptr;
3661 CanQualType DeallocType = Context.getCanonicalTagType(TD: RD);
3662 ImplicitDeallocationParameters IDP = {
3663 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
3664 AlignedAllocationMode::No, SizedDeallocationMode::No};
3665
3666 if (!LookForGlobal) {
3667 if (FindDeallocationFunction(StartLoc: Loc, RD, Name, Operator&: OperatorDelete, IDP, Diagnose))
3668 return nullptr;
3669
3670 if (OperatorDelete)
3671 return OperatorDelete;
3672 }
3673
3674 // If there's no class-specific operator delete, look up the global
3675 // non-array delete.
3676 IDP.PassAlignment = alignedAllocationModeFromBool(
3677 IsAligned: hasNewExtendedAlignment(S&: *this, AllocType: DeallocType));
3678 IDP.PassSize = SizedDeallocationMode::Yes;
3679 return FindUsualDeallocationFunction(StartLoc: Loc, IDP, Name, Diagnose);
3680}
3681
3682bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3683 DeclarationName Name,
3684 FunctionDecl *&Operator,
3685 ImplicitDeallocationParameters IDP,
3686 bool Diagnose) {
3687 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3688 // Try to find operator delete/operator delete[] in class scope.
3689 LookupQualifiedName(R&: Found, LookupCtx: RD);
3690
3691 if (Found.isAmbiguous()) {
3692 if (!Diagnose)
3693 Found.suppressDiagnostics();
3694 return true;
3695 }
3696
3697 Found.suppressDiagnostics();
3698
3699 if (!isAlignedAllocation(Mode: IDP.PassAlignment) &&
3700 hasNewExtendedAlignment(S&: *this, AllocType: Context.getCanonicalTagType(TD: RD)))
3701 IDP.PassAlignment = AlignedAllocationMode::Yes;
3702
3703 // C++17 [expr.delete]p10:
3704 // If the deallocation functions have class scope, the one without a
3705 // parameter of type std::size_t is selected.
3706 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3707 resolveDeallocationOverload(S&: *this, R&: Found, IDP, Loc: StartLoc, BestFns: &Matches);
3708
3709 // If we could find an overload, use it.
3710 if (Matches.size() == 1) {
3711 Operator = cast<CXXMethodDecl>(Val: Matches[0].FD);
3712 return CheckDeleteOperator(S&: *this, StartLoc, Range: StartLoc, Diagnose,
3713 NamingClass: Found.getNamingClass(), Decl: Matches[0].Found,
3714 Operator);
3715 }
3716
3717 // We found multiple suitable operators; complain about the ambiguity.
3718 // FIXME: The standard doesn't say to do this; it appears that the intent
3719 // is that this should never happen.
3720 if (!Matches.empty()) {
3721 if (Diagnose) {
3722 Diag(Loc: StartLoc, DiagID: diag::err_ambiguous_suitable_delete_member_function_found)
3723 << Name << RD;
3724 for (auto &Match : Matches)
3725 Diag(Loc: Match.FD->getLocation(), DiagID: diag::note_member_declared_here) << Name;
3726 }
3727 return true;
3728 }
3729
3730 // We did find operator delete/operator delete[] declarations, but
3731 // none of them were suitable.
3732 if (!Found.empty()) {
3733 if (Diagnose) {
3734 Diag(Loc: StartLoc, DiagID: diag::err_no_suitable_delete_member_function_found)
3735 << Name << RD;
3736
3737 for (NamedDecl *D : Found)
3738 Diag(Loc: D->getUnderlyingDecl()->getLocation(),
3739 DiagID: diag::note_member_declared_here) << Name;
3740 }
3741 return true;
3742 }
3743
3744 Operator = nullptr;
3745 return false;
3746}
3747
3748namespace {
3749/// Checks whether delete-expression, and new-expression used for
3750/// initializing deletee have the same array form.
3751class MismatchingNewDeleteDetector {
3752public:
3753 enum MismatchResult {
3754 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3755 NoMismatch,
3756 /// Indicates that variable is initialized with mismatching form of \a new.
3757 VarInitMismatches,
3758 /// Indicates that member is initialized with mismatching form of \a new.
3759 MemberInitMismatches,
3760 /// Indicates that 1 or more constructors' definitions could not been
3761 /// analyzed, and they will be checked again at the end of translation unit.
3762 AnalyzeLater
3763 };
3764
3765 /// \param EndOfTU True, if this is the final analysis at the end of
3766 /// translation unit. False, if this is the initial analysis at the point
3767 /// delete-expression was encountered.
3768 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3769 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3770 HasUndefinedConstructors(false) {}
3771
3772 /// Checks whether pointee of a delete-expression is initialized with
3773 /// matching form of new-expression.
3774 ///
3775 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3776 /// point where delete-expression is encountered, then a warning will be
3777 /// issued immediately. If return value is \c AnalyzeLater at the point where
3778 /// delete-expression is seen, then member will be analyzed at the end of
3779 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3780 /// couldn't be analyzed. If at least one constructor initializes the member
3781 /// with matching type of new, the return value is \c NoMismatch.
3782 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3783 /// Analyzes a class member.
3784 /// \param Field Class member to analyze.
3785 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3786 /// for deleting the \p Field.
3787 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3788 FieldDecl *Field;
3789 /// List of mismatching new-expressions used for initialization of the pointee
3790 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3791 /// Indicates whether delete-expression was in array form.
3792 bool IsArrayForm;
3793
3794private:
3795 const bool EndOfTU;
3796 /// Indicates that there is at least one constructor without body.
3797 bool HasUndefinedConstructors;
3798 /// Returns \c CXXNewExpr from given initialization expression.
3799 /// \param E Expression used for initializing pointee in delete-expression.
3800 /// E can be a single-element \c InitListExpr consisting of new-expression.
3801 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3802 /// Returns whether member is initialized with mismatching form of
3803 /// \c new either by the member initializer or in-class initialization.
3804 ///
3805 /// If bodies of all constructors are not visible at the end of translation
3806 /// unit or at least one constructor initializes member with the matching
3807 /// form of \c new, mismatch cannot be proven, and this function will return
3808 /// \c NoMismatch.
3809 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3810 /// Returns whether variable is initialized with mismatching form of
3811 /// \c new.
3812 ///
3813 /// If variable is initialized with matching form of \c new or variable is not
3814 /// initialized with a \c new expression, this function will return true.
3815 /// If variable is initialized with mismatching form of \c new, returns false.
3816 /// \param D Variable to analyze.
3817 bool hasMatchingVarInit(const DeclRefExpr *D);
3818 /// Checks whether the constructor initializes pointee with mismatching
3819 /// form of \c new.
3820 ///
3821 /// Returns true, if member is initialized with matching form of \c new in
3822 /// member initializer list. Returns false, if member is initialized with the
3823 /// matching form of \c new in this constructor's initializer or given
3824 /// constructor isn't defined at the point where delete-expression is seen, or
3825 /// member isn't initialized by the constructor.
3826 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3827 /// Checks whether member is initialized with matching form of
3828 /// \c new in member initializer list.
3829 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3830 /// Checks whether member is initialized with mismatching form of \c new by
3831 /// in-class initializer.
3832 MismatchResult analyzeInClassInitializer();
3833};
3834}
3835
3836MismatchingNewDeleteDetector::MismatchResult
3837MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3838 NewExprs.clear();
3839 assert(DE && "Expected delete-expression");
3840 IsArrayForm = DE->isArrayForm();
3841 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3842 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(Val: E)) {
3843 return analyzeMemberExpr(ME);
3844 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(Val: E)) {
3845 if (!hasMatchingVarInit(D))
3846 return VarInitMismatches;
3847 }
3848 return NoMismatch;
3849}
3850
3851const CXXNewExpr *
3852MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3853 assert(E != nullptr && "Expected a valid initializer expression");
3854 E = E->IgnoreParenImpCasts();
3855 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(Val: E)) {
3856 if (ILE->getNumInits() == 1)
3857 E = dyn_cast<const CXXNewExpr>(Val: ILE->getInit(Init: 0)->IgnoreParenImpCasts());
3858 }
3859
3860 return dyn_cast_or_null<const CXXNewExpr>(Val: E);
3861}
3862
3863bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3864 const CXXCtorInitializer *CI) {
3865 const CXXNewExpr *NE = nullptr;
3866 if (Field == CI->getMember() &&
3867 (NE = getNewExprFromInitListOrExpr(E: CI->getInit()))) {
3868 if (NE->isArray() == IsArrayForm)
3869 return true;
3870 else
3871 NewExprs.push_back(Elt: NE);
3872 }
3873 return false;
3874}
3875
3876bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3877 const CXXConstructorDecl *CD) {
3878 if (CD->isImplicit())
3879 return false;
3880 const FunctionDecl *Definition = CD;
3881 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3882 HasUndefinedConstructors = true;
3883 return EndOfTU;
3884 }
3885 for (const auto *CI : cast<const CXXConstructorDecl>(Val: Definition)->inits()) {
3886 if (hasMatchingNewInCtorInit(CI))
3887 return true;
3888 }
3889 return false;
3890}
3891
3892MismatchingNewDeleteDetector::MismatchResult
3893MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3894 assert(Field != nullptr && "This should be called only for members");
3895 const Expr *InitExpr = Field->getInClassInitializer();
3896 if (!InitExpr)
3897 return EndOfTU ? NoMismatch : AnalyzeLater;
3898 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(E: InitExpr)) {
3899 if (NE->isArray() != IsArrayForm) {
3900 NewExprs.push_back(Elt: NE);
3901 return MemberInitMismatches;
3902 }
3903 }
3904 return NoMismatch;
3905}
3906
3907MismatchingNewDeleteDetector::MismatchResult
3908MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3909 bool DeleteWasArrayForm) {
3910 assert(Field != nullptr && "Analysis requires a valid class member.");
3911 this->Field = Field;
3912 IsArrayForm = DeleteWasArrayForm;
3913 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Val: Field->getParent());
3914 for (const auto *CD : RD->ctors()) {
3915 if (hasMatchingNewInCtor(CD))
3916 return NoMismatch;
3917 }
3918 if (HasUndefinedConstructors)
3919 return EndOfTU ? NoMismatch : AnalyzeLater;
3920 if (!NewExprs.empty())
3921 return MemberInitMismatches;
3922 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3923 : NoMismatch;
3924}
3925
3926MismatchingNewDeleteDetector::MismatchResult
3927MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3928 assert(ME != nullptr && "Expected a member expression");
3929 if (FieldDecl *F = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
3930 return analyzeField(Field: F, DeleteWasArrayForm: IsArrayForm);
3931 return NoMismatch;
3932}
3933
3934bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3935 const CXXNewExpr *NE = nullptr;
3936 if (const VarDecl *VD = dyn_cast<const VarDecl>(Val: D->getDecl())) {
3937 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(E: VD->getInit())) &&
3938 NE->isArray() != IsArrayForm) {
3939 NewExprs.push_back(Elt: NE);
3940 }
3941 }
3942 return NewExprs.empty();
3943}
3944
3945static void
3946DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3947 const MismatchingNewDeleteDetector &Detector) {
3948 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(Loc: DeleteLoc);
3949 FixItHint H;
3950 if (!Detector.IsArrayForm)
3951 H = FixItHint::CreateInsertion(InsertionLoc: EndOfDelete, Code: "[]");
3952 else {
3953 SourceLocation RSquare = Lexer::findLocationAfterToken(
3954 loc: DeleteLoc, TKind: tok::l_square, SM: SemaRef.getSourceManager(),
3955 LangOpts: SemaRef.getLangOpts(), SkipTrailingWhitespaceAndNewLine: true);
3956 if (RSquare.isValid())
3957 H = FixItHint::CreateRemoval(RemoveRange: SourceRange(EndOfDelete, RSquare));
3958 }
3959 SemaRef.Diag(Loc: DeleteLoc, DiagID: diag::warn_mismatched_delete_new)
3960 << Detector.IsArrayForm << H;
3961
3962 for (const auto *NE : Detector.NewExprs)
3963 SemaRef.Diag(Loc: NE->getExprLoc(), DiagID: diag::note_allocated_here)
3964 << Detector.IsArrayForm;
3965}
3966
3967void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3968 if (Diags.isIgnored(DiagID: diag::warn_mismatched_delete_new, Loc: SourceLocation()))
3969 return;
3970 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3971 switch (Detector.analyzeDeleteExpr(DE)) {
3972 case MismatchingNewDeleteDetector::VarInitMismatches:
3973 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3974 DiagnoseMismatchedNewDelete(SemaRef&: *this, DeleteLoc: DE->getBeginLoc(), Detector);
3975 break;
3976 }
3977 case MismatchingNewDeleteDetector::AnalyzeLater: {
3978 DeleteExprs[Detector.Field].push_back(
3979 Elt: std::make_pair(x: DE->getBeginLoc(), y: DE->isArrayForm()));
3980 break;
3981 }
3982 case MismatchingNewDeleteDetector::NoMismatch:
3983 break;
3984 }
3985}
3986
3987void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3988 bool DeleteWasArrayForm) {
3989 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3990 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3991 case MismatchingNewDeleteDetector::VarInitMismatches:
3992 llvm_unreachable("This analysis should have been done for class members.");
3993 case MismatchingNewDeleteDetector::AnalyzeLater:
3994 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3995 "translation unit.");
3996 case MismatchingNewDeleteDetector::MemberInitMismatches:
3997 DiagnoseMismatchedNewDelete(SemaRef&: *this, DeleteLoc, Detector);
3998 break;
3999 case MismatchingNewDeleteDetector::NoMismatch:
4000 break;
4001 }
4002}
4003
4004ExprResult
4005Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
4006 bool ArrayForm, Expr *ExE) {
4007 // C++ [expr.delete]p1:
4008 // The operand shall have a pointer type, or a class type having a single
4009 // non-explicit conversion function to a pointer type. The result has type
4010 // void.
4011 //
4012 // DR599 amends "pointer type" to "pointer to object type" in both cases.
4013
4014 ExprResult Ex = ExE;
4015 FunctionDecl *OperatorDelete = nullptr;
4016 bool ArrayFormAsWritten = ArrayForm;
4017 bool UsualArrayDeleteWantsSize = false;
4018
4019 if (!Ex.get()->isTypeDependent()) {
4020 // Perform lvalue-to-rvalue cast, if needed.
4021 Ex = DefaultLvalueConversion(E: Ex.get());
4022 if (Ex.isInvalid())
4023 return ExprError();
4024
4025 QualType Type = Ex.get()->getType();
4026
4027 class DeleteConverter : public ContextualImplicitConverter {
4028 public:
4029 DeleteConverter() : ContextualImplicitConverter(false, true) {}
4030
4031 bool match(QualType ConvType) override {
4032 // FIXME: If we have an operator T* and an operator void*, we must pick
4033 // the operator T*.
4034 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4035 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
4036 return true;
4037 return false;
4038 }
4039
4040 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
4041 QualType T) override {
4042 return S.Diag(Loc, DiagID: diag::err_delete_operand) << T;
4043 }
4044
4045 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4046 QualType T) override {
4047 return S.Diag(Loc, DiagID: diag::err_delete_incomplete_class_type) << T;
4048 }
4049
4050 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4051 QualType T,
4052 QualType ConvTy) override {
4053 return S.Diag(Loc, DiagID: diag::err_delete_explicit_conversion) << T << ConvTy;
4054 }
4055
4056 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4057 QualType ConvTy) override {
4058 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_delete_conversion)
4059 << ConvTy;
4060 }
4061
4062 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4063 QualType T) override {
4064 return S.Diag(Loc, DiagID: diag::err_ambiguous_delete_operand) << T;
4065 }
4066
4067 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4068 QualType ConvTy) override {
4069 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_delete_conversion)
4070 << ConvTy;
4071 }
4072
4073 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
4074 QualType T,
4075 QualType ConvTy) override {
4076 llvm_unreachable("conversion functions are permitted");
4077 }
4078 } Converter;
4079
4080 Ex = PerformContextualImplicitConversion(Loc: StartLoc, FromE: Ex.get(), Converter);
4081 if (Ex.isInvalid())
4082 return ExprError();
4083 Type = Ex.get()->getType();
4084 if (!Converter.match(ConvType: Type))
4085 // FIXME: PerformContextualImplicitConversion should return ExprError
4086 // itself in this case.
4087 return ExprError();
4088
4089 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
4090 QualType PointeeElem = Context.getBaseElementType(QT: Pointee);
4091
4092 if (Pointee.getAddressSpace() != LangAS::Default &&
4093 !getLangOpts().OpenCLCPlusPlus)
4094 return Diag(Loc: Ex.get()->getBeginLoc(),
4095 DiagID: diag::err_address_space_qualified_delete)
4096 << Pointee.getUnqualifiedType()
4097 << Qualifiers::getAddrSpaceAsString(AS: Pointee.getAddressSpace());
4098
4099 CXXRecordDecl *PointeeRD = nullptr;
4100 if (Pointee->isVoidType() && !isSFINAEContext()) {
4101 // The C++ standard bans deleting a pointer to a non-object type, which
4102 // effectively bans deletion of "void*". However, most compilers support
4103 // this, so we treat it as a warning unless we're in a SFINAE context.
4104 // But we still prohibit this since C++26.
4105 Diag(Loc: StartLoc, DiagID: LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
4106 : diag::ext_delete_void_ptr_operand)
4107 << (LangOpts.CPlusPlus26 ? Pointee : Type)
4108 << Ex.get()->getSourceRange();
4109 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
4110 Pointee->isSizelessType()) {
4111 return ExprError(Diag(Loc: StartLoc, DiagID: diag::err_delete_operand)
4112 << Type << Ex.get()->getSourceRange());
4113 } else if (!Pointee->isDependentType()) {
4114 // FIXME: This can result in errors if the definition was imported from a
4115 // module but is hidden.
4116 if (Pointee->isEnumeralType() ||
4117 !RequireCompleteType(Loc: StartLoc, T: Pointee,
4118 DiagID: LangOpts.CPlusPlus26
4119 ? diag::err_delete_incomplete
4120 : diag::warn_delete_incomplete,
4121 Args: Ex.get())) {
4122 PointeeRD = PointeeElem->getAsCXXRecordDecl();
4123 }
4124 }
4125
4126 if (Pointee->isArrayType() && !ArrayForm) {
4127 Diag(Loc: StartLoc, DiagID: diag::warn_delete_array_type)
4128 << Type << Ex.get()->getSourceRange()
4129 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: StartLoc), Code: "[]");
4130 ArrayForm = true;
4131 }
4132
4133 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
4134 Op: ArrayForm ? OO_Array_Delete : OO_Delete);
4135
4136 if (PointeeRD) {
4137 ImplicitDeallocationParameters IDP = {
4138 Pointee, ShouldUseTypeAwareOperatorNewOrDelete(),
4139 AlignedAllocationMode::No, SizedDeallocationMode::No};
4140 if (!UseGlobal &&
4141 FindDeallocationFunction(StartLoc, RD: PointeeRD, Name: DeleteName,
4142 Operator&: OperatorDelete, IDP))
4143 return ExprError();
4144
4145 // If we're allocating an array of records, check whether the
4146 // usual operator delete[] has a size_t parameter.
4147 if (ArrayForm) {
4148 // If the user specifically asked to use the global allocator,
4149 // we'll need to do the lookup into the class.
4150 if (UseGlobal)
4151 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(
4152 S&: *this, loc: StartLoc, PassType: IDP.PassTypeIdentity, allocType: PointeeElem);
4153
4154 // Otherwise, the usual operator delete[] should be the
4155 // function we just found.
4156 else if (isa_and_nonnull<CXXMethodDecl>(Val: OperatorDelete)) {
4157 UsualDeallocFnInfo UDFI(
4158 *this, DeclAccessPair::make(D: OperatorDelete, AS: AS_public), Pointee,
4159 StartLoc);
4160 UsualArrayDeleteWantsSize = isSizedDeallocation(Mode: UDFI.IDP.PassSize);
4161 }
4162 }
4163
4164 if (!PointeeRD->hasIrrelevantDestructor()) {
4165 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: PointeeRD)) {
4166 if (Dtor->isCalledByDelete(OpDel: OperatorDelete)) {
4167 MarkFunctionReferenced(Loc: StartLoc, Func: Dtor);
4168 if (DiagnoseUseOfDecl(D: Dtor, Locs: StartLoc))
4169 return ExprError();
4170 }
4171 }
4172 }
4173
4174 CheckVirtualDtorCall(dtor: PointeeRD->getDestructor(), Loc: StartLoc,
4175 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
4176 /*WarnOnNonAbstractTypes=*/!ArrayForm,
4177 DtorLoc: SourceLocation());
4178 }
4179
4180 if (!OperatorDelete) {
4181 if (getLangOpts().OpenCLCPlusPlus) {
4182 Diag(Loc: StartLoc, DiagID: diag::err_openclcxx_not_supported) << "default delete";
4183 return ExprError();
4184 }
4185
4186 bool IsComplete = isCompleteType(Loc: StartLoc, T: Pointee);
4187 bool CanProvideSize =
4188 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
4189 Pointee.isDestructedType());
4190 bool Overaligned = hasNewExtendedAlignment(S&: *this, AllocType: Pointee);
4191
4192 // Look for a global declaration.
4193 ImplicitDeallocationParameters IDP = {
4194 Pointee, ShouldUseTypeAwareOperatorNewOrDelete(),
4195 alignedAllocationModeFromBool(IsAligned: Overaligned),
4196 sizedDeallocationModeFromBool(IsSized: CanProvideSize)};
4197 OperatorDelete = FindUsualDeallocationFunction(StartLoc, IDP, Name: DeleteName);
4198 if (!OperatorDelete)
4199 return ExprError();
4200 }
4201
4202 if (OperatorDelete->isInvalidDecl())
4203 return ExprError();
4204
4205 MarkFunctionReferenced(Loc: StartLoc, Func: OperatorDelete);
4206
4207 // Check access and ambiguity of destructor if we're going to call it.
4208 // Note that this is required even for a virtual delete.
4209 bool IsVirtualDelete = false;
4210 if (PointeeRD) {
4211 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: PointeeRD)) {
4212 if (Dtor->isCalledByDelete(OpDel: OperatorDelete))
4213 CheckDestructorAccess(Loc: Ex.get()->getExprLoc(), Dtor,
4214 PDiag: PDiag(DiagID: diag::err_access_dtor) << PointeeElem);
4215 IsVirtualDelete = Dtor->isVirtual();
4216 }
4217 }
4218
4219 DiagnoseUseOfDecl(D: OperatorDelete, Locs: StartLoc);
4220
4221 unsigned AddressParamIdx = 0;
4222 if (OperatorDelete->isTypeAwareOperatorNewOrDelete()) {
4223 QualType TypeIdentity = OperatorDelete->getParamDecl(i: 0)->getType();
4224 if (RequireCompleteType(Loc: StartLoc, T: TypeIdentity,
4225 DiagID: diag::err_incomplete_type))
4226 return ExprError();
4227 AddressParamIdx = 1;
4228 }
4229
4230 // Convert the operand to the type of the first parameter of operator
4231 // delete. This is only necessary if we selected a destroying operator
4232 // delete that we are going to call (non-virtually); converting to void*
4233 // is trivial and left to AST consumers to handle.
4234 QualType ParamType =
4235 OperatorDelete->getParamDecl(i: AddressParamIdx)->getType();
4236 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
4237 Qualifiers Qs = Pointee.getQualifiers();
4238 if (Qs.hasCVRQualifiers()) {
4239 // Qualifiers are irrelevant to this conversion; we're only looking
4240 // for access and ambiguity.
4241 Qs.removeCVRQualifiers();
4242 QualType Unqual = Context.getPointerType(
4243 T: Context.getQualifiedType(T: Pointee.getUnqualifiedType(), Qs));
4244 Ex = ImpCastExprToType(E: Ex.get(), Type: Unqual, CK: CK_NoOp);
4245 }
4246 Ex = PerformImplicitConversion(From: Ex.get(), ToType: ParamType,
4247 Action: AssignmentAction::Passing);
4248 if (Ex.isInvalid())
4249 return ExprError();
4250 }
4251 }
4252
4253 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
4254 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
4255 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
4256 AnalyzeDeleteExprMismatch(DE: Result);
4257 return Result;
4258}
4259
4260static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
4261 bool IsDelete,
4262 FunctionDecl *&Operator) {
4263
4264 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
4265 Op: IsDelete ? OO_Delete : OO_New);
4266
4267 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
4268 S.LookupQualifiedName(R, LookupCtx: S.Context.getTranslationUnitDecl());
4269 assert(!R.empty() && "implicitly declared allocation functions not found");
4270 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
4271
4272 // We do our own custom access checks below.
4273 R.suppressDiagnostics();
4274
4275 SmallVector<Expr *, 8> Args(TheCall->arguments());
4276 OverloadCandidateSet Candidates(R.getNameLoc(),
4277 OverloadCandidateSet::CSK_Normal);
4278 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
4279 FnOvl != FnOvlEnd; ++FnOvl) {
4280 // Even member operator new/delete are implicitly treated as
4281 // static, so don't use AddMemberCandidate.
4282 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
4283
4284 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(Val: D)) {
4285 S.AddTemplateOverloadCandidate(FunctionTemplate: FnTemplate, FoundDecl: FnOvl.getPair(),
4286 /*ExplicitTemplateArgs=*/nullptr, Args,
4287 CandidateSet&: Candidates,
4288 /*SuppressUserConversions=*/false);
4289 continue;
4290 }
4291
4292 FunctionDecl *Fn = cast<FunctionDecl>(Val: D);
4293 S.AddOverloadCandidate(Function: Fn, FoundDecl: FnOvl.getPair(), Args, CandidateSet&: Candidates,
4294 /*SuppressUserConversions=*/false);
4295 }
4296
4297 SourceRange Range = TheCall->getSourceRange();
4298
4299 // Do the resolution.
4300 OverloadCandidateSet::iterator Best;
4301 switch (Candidates.BestViableFunction(S, Loc: R.getNameLoc(), Best)) {
4302 case OR_Success: {
4303 // Got one!
4304 FunctionDecl *FnDecl = Best->Function;
4305 assert(R.getNamingClass() == nullptr &&
4306 "class members should not be considered");
4307
4308 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
4309 S.Diag(Loc: R.getNameLoc(), DiagID: diag::err_builtin_operator_new_delete_not_usual)
4310 << (IsDelete ? 1 : 0) << Range;
4311 S.Diag(Loc: FnDecl->getLocation(), DiagID: diag::note_non_usual_function_declared_here)
4312 << R.getLookupName() << FnDecl->getSourceRange();
4313 return true;
4314 }
4315
4316 Operator = FnDecl;
4317 return false;
4318 }
4319
4320 case OR_No_Viable_Function:
4321 Candidates.NoteCandidates(
4322 PA: PartialDiagnosticAt(R.getNameLoc(),
4323 S.PDiag(DiagID: diag::err_ovl_no_viable_function_in_call)
4324 << R.getLookupName() << Range),
4325 S, OCD: OCD_AllCandidates, Args);
4326 return true;
4327
4328 case OR_Ambiguous:
4329 Candidates.NoteCandidates(
4330 PA: PartialDiagnosticAt(R.getNameLoc(),
4331 S.PDiag(DiagID: diag::err_ovl_ambiguous_call)
4332 << R.getLookupName() << Range),
4333 S, OCD: OCD_AmbiguousCandidates, Args);
4334 return true;
4335
4336 case OR_Deleted:
4337 S.DiagnoseUseOfDeletedFunction(Loc: R.getNameLoc(), Range, Name: R.getLookupName(),
4338 CandidateSet&: Candidates, Fn: Best->Function, Args);
4339 return true;
4340 }
4341 llvm_unreachable("Unreachable, bad result from BestViableFunction");
4342}
4343
4344ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
4345 bool IsDelete) {
4346 CallExpr *TheCall = cast<CallExpr>(Val: TheCallResult.get());
4347 if (!getLangOpts().CPlusPlus) {
4348 Diag(Loc: TheCall->getExprLoc(), DiagID: diag::err_builtin_requires_language)
4349 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
4350 << "C++";
4351 return ExprError();
4352 }
4353 // CodeGen assumes it can find the global new and delete to call,
4354 // so ensure that they are declared.
4355 DeclareGlobalNewDelete();
4356
4357 FunctionDecl *OperatorNewOrDelete = nullptr;
4358 if (resolveBuiltinNewDeleteOverload(S&: *this, TheCall, IsDelete,
4359 Operator&: OperatorNewOrDelete))
4360 return ExprError();
4361 assert(OperatorNewOrDelete && "should be found");
4362
4363 DiagnoseUseOfDecl(D: OperatorNewOrDelete, Locs: TheCall->getExprLoc());
4364 MarkFunctionReferenced(Loc: TheCall->getExprLoc(), Func: OperatorNewOrDelete);
4365
4366 TheCall->setType(OperatorNewOrDelete->getReturnType());
4367 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4368 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
4369 InitializedEntity Entity =
4370 InitializedEntity::InitializeParameter(Context, Type: ParamTy, Consumed: false);
4371 ExprResult Arg = PerformCopyInitialization(
4372 Entity, EqualLoc: TheCall->getArg(Arg: i)->getBeginLoc(), Init: TheCall->getArg(Arg: i));
4373 if (Arg.isInvalid())
4374 return ExprError();
4375 TheCall->setArg(Arg: i, ArgExpr: Arg.get());
4376 }
4377 auto Callee = dyn_cast<ImplicitCastExpr>(Val: TheCall->getCallee());
4378 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
4379 "Callee expected to be implicit cast to a builtin function pointer");
4380 Callee->setType(OperatorNewOrDelete->getType());
4381
4382 return TheCallResult;
4383}
4384
4385void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
4386 bool IsDelete, bool CallCanBeVirtual,
4387 bool WarnOnNonAbstractTypes,
4388 SourceLocation DtorLoc) {
4389 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
4390 return;
4391
4392 // C++ [expr.delete]p3:
4393 // In the first alternative (delete object), if the static type of the
4394 // object to be deleted is different from its dynamic type, the static
4395 // type shall be a base class of the dynamic type of the object to be
4396 // deleted and the static type shall have a virtual destructor or the
4397 // behavior is undefined.
4398 //
4399 const CXXRecordDecl *PointeeRD = dtor->getParent();
4400 // Note: a final class cannot be derived from, no issue there
4401 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
4402 return;
4403
4404 // If the superclass is in a system header, there's nothing that can be done.
4405 // The `delete` (where we emit the warning) can be in a system header,
4406 // what matters for this warning is where the deleted type is defined.
4407 if (getSourceManager().isInSystemHeader(Loc: PointeeRD->getLocation()))
4408 return;
4409
4410 QualType ClassType = dtor->getFunctionObjectParameterType();
4411 if (PointeeRD->isAbstract()) {
4412 // If the class is abstract, we warn by default, because we're
4413 // sure the code has undefined behavior.
4414 Diag(Loc, DiagID: diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4415 << ClassType;
4416 } else if (WarnOnNonAbstractTypes) {
4417 // Otherwise, if this is not an array delete, it's a bit suspect,
4418 // but not necessarily wrong.
4419 Diag(Loc, DiagID: diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4420 << ClassType;
4421 }
4422 if (!IsDelete) {
4423 std::string TypeStr;
4424 ClassType.getAsStringInternal(Str&: TypeStr, Policy: getPrintingPolicy());
4425 Diag(Loc: DtorLoc, DiagID: diag::note_delete_non_virtual)
4426 << FixItHint::CreateInsertion(InsertionLoc: DtorLoc, Code: TypeStr + "::");
4427 }
4428}
4429
4430Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
4431 SourceLocation StmtLoc,
4432 ConditionKind CK) {
4433 ExprResult E =
4434 CheckConditionVariable(ConditionVar: cast<VarDecl>(Val: ConditionVar), StmtLoc, CK);
4435 if (E.isInvalid())
4436 return ConditionError();
4437 E = ActOnFinishFullExpr(Expr: E.get(), /*DiscardedValue*/ false);
4438 return ConditionResult(*this, ConditionVar, E,
4439 CK == ConditionKind::ConstexprIf);
4440}
4441
4442ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
4443 SourceLocation StmtLoc,
4444 ConditionKind CK) {
4445 if (ConditionVar->isInvalidDecl())
4446 return ExprError();
4447
4448 QualType T = ConditionVar->getType();
4449
4450 // C++ [stmt.select]p2:
4451 // The declarator shall not specify a function or an array.
4452 if (T->isFunctionType())
4453 return ExprError(Diag(Loc: ConditionVar->getLocation(),
4454 DiagID: diag::err_invalid_use_of_function_type)
4455 << ConditionVar->getSourceRange());
4456 else if (T->isArrayType())
4457 return ExprError(Diag(Loc: ConditionVar->getLocation(),
4458 DiagID: diag::err_invalid_use_of_array_type)
4459 << ConditionVar->getSourceRange());
4460
4461 ExprResult Condition = BuildDeclRefExpr(
4462 D: ConditionVar, Ty: ConditionVar->getType().getNonReferenceType(), VK: VK_LValue,
4463 Loc: ConditionVar->getLocation());
4464
4465 switch (CK) {
4466 case ConditionKind::Boolean:
4467 return CheckBooleanCondition(Loc: StmtLoc, E: Condition.get());
4468
4469 case ConditionKind::ConstexprIf:
4470 return CheckBooleanCondition(Loc: StmtLoc, E: Condition.get(), IsConstexpr: true);
4471
4472 case ConditionKind::Switch:
4473 return CheckSwitchCondition(SwitchLoc: StmtLoc, Cond: Condition.get());
4474 }
4475
4476 llvm_unreachable("unexpected condition kind");
4477}
4478
4479ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4480 // C++11 6.4p4:
4481 // The value of a condition that is an initialized declaration in a statement
4482 // other than a switch statement is the value of the declared variable
4483 // implicitly converted to type bool. If that conversion is ill-formed, the
4484 // program is ill-formed.
4485 // The value of a condition that is an expression is the value of the
4486 // expression, implicitly converted to bool.
4487 //
4488 // C++23 8.5.2p2
4489 // If the if statement is of the form if constexpr, the value of the condition
4490 // is contextually converted to bool and the converted expression shall be
4491 // a constant expression.
4492 //
4493
4494 ExprResult E = PerformContextuallyConvertToBool(From: CondExpr);
4495 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4496 return E;
4497
4498 E = ActOnFinishFullExpr(Expr: E.get(), CC: E.get()->getExprLoc(),
4499 /*DiscardedValue*/ false,
4500 /*IsConstexpr*/ true);
4501 if (E.isInvalid())
4502 return E;
4503
4504 // FIXME: Return this value to the caller so they don't need to recompute it.
4505 llvm::APSInt Cond;
4506 E = VerifyIntegerConstantExpression(
4507 E: E.get(), Result: &Cond,
4508 DiagID: diag::err_constexpr_if_condition_expression_is_not_constant);
4509 return E;
4510}
4511
4512bool
4513Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
4514 // Look inside the implicit cast, if it exists.
4515 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Val: From))
4516 From = Cast->getSubExpr();
4517
4518 // A string literal (2.13.4) that is not a wide string literal can
4519 // be converted to an rvalue of type "pointer to char"; a wide
4520 // string literal can be converted to an rvalue of type "pointer
4521 // to wchar_t" (C++ 4.2p2).
4522 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(Val: From->IgnoreParens()))
4523 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4524 if (const BuiltinType *ToPointeeType
4525 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4526 // This conversion is considered only when there is an
4527 // explicit appropriate pointer target type (C++ 4.2p2).
4528 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4529 switch (StrLit->getKind()) {
4530 case StringLiteralKind::UTF8:
4531 case StringLiteralKind::UTF16:
4532 case StringLiteralKind::UTF32:
4533 // We don't allow UTF literals to be implicitly converted
4534 break;
4535 case StringLiteralKind::Ordinary:
4536 case StringLiteralKind::Binary:
4537 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4538 ToPointeeType->getKind() == BuiltinType::Char_S);
4539 case StringLiteralKind::Wide:
4540 return Context.typesAreCompatible(T1: Context.getWideCharType(),
4541 T2: QualType(ToPointeeType, 0));
4542 case StringLiteralKind::Unevaluated:
4543 assert(false && "Unevaluated string literal in expression");
4544 break;
4545 }
4546 }
4547 }
4548
4549 return false;
4550}
4551
4552static ExprResult BuildCXXCastArgument(Sema &S,
4553 SourceLocation CastLoc,
4554 QualType Ty,
4555 CastKind Kind,
4556 CXXMethodDecl *Method,
4557 DeclAccessPair FoundDecl,
4558 bool HadMultipleCandidates,
4559 Expr *From) {
4560 switch (Kind) {
4561 default: llvm_unreachable("Unhandled cast kind!");
4562 case CK_ConstructorConversion: {
4563 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Method);
4564 SmallVector<Expr*, 8> ConstructorArgs;
4565
4566 if (S.RequireNonAbstractType(Loc: CastLoc, T: Ty,
4567 DiagID: diag::err_allocation_of_abstract_type))
4568 return ExprError();
4569
4570 if (S.CompleteConstructorCall(Constructor, DeclInitType: Ty, ArgsPtr: From, Loc: CastLoc,
4571 ConvertedArgs&: ConstructorArgs))
4572 return ExprError();
4573
4574 S.CheckConstructorAccess(Loc: CastLoc, D: Constructor, FoundDecl,
4575 Entity: InitializedEntity::InitializeTemporary(Type: Ty));
4576 if (S.DiagnoseUseOfDecl(D: Method, Locs: CastLoc))
4577 return ExprError();
4578
4579 ExprResult Result = S.BuildCXXConstructExpr(
4580 ConstructLoc: CastLoc, DeclInitType: Ty, FoundDecl, Constructor: cast<CXXConstructorDecl>(Val: Method),
4581 Exprs: ConstructorArgs, HadMultipleCandidates,
4582 /*ListInit*/ IsListInitialization: false, /*StdInitListInit*/ IsStdInitListInitialization: false, /*ZeroInit*/ RequiresZeroInit: false,
4583 ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange());
4584 if (Result.isInvalid())
4585 return ExprError();
4586
4587 return S.MaybeBindToTemporary(E: Result.getAs<Expr>());
4588 }
4589
4590 case CK_UserDefinedConversion: {
4591 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4592
4593 S.CheckMemberOperatorAccess(Loc: CastLoc, ObjectExpr: From, /*arg*/ ArgExpr: nullptr, FoundDecl);
4594 if (S.DiagnoseUseOfDecl(D: Method, Locs: CastLoc))
4595 return ExprError();
4596
4597 // Create an implicit call expr that calls it.
4598 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Val: Method);
4599 ExprResult Result = S.BuildCXXMemberCallExpr(Exp: From, FoundDecl, Method: Conv,
4600 HadMultipleCandidates);
4601 if (Result.isInvalid())
4602 return ExprError();
4603 // Record usage of conversion in an implicit cast.
4604 Result = ImplicitCastExpr::Create(Context: S.Context, T: Result.get()->getType(),
4605 Kind: CK_UserDefinedConversion, Operand: Result.get(),
4606 BasePath: nullptr, Cat: Result.get()->getValueKind(),
4607 FPO: S.CurFPFeatureOverrides());
4608
4609 return S.MaybeBindToTemporary(E: Result.get());
4610 }
4611 }
4612}
4613
4614ExprResult
4615Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4616 const ImplicitConversionSequence &ICS,
4617 AssignmentAction Action,
4618 CheckedConversionKind CCK) {
4619 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4620 if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp &&
4621 !From->getType()->isRecordType())
4622 return From;
4623
4624 switch (ICS.getKind()) {
4625 case ImplicitConversionSequence::StandardConversion: {
4626 ExprResult Res = PerformImplicitConversion(From, ToType, SCS: ICS.Standard,
4627 Action, CCK);
4628 if (Res.isInvalid())
4629 return ExprError();
4630 From = Res.get();
4631 break;
4632 }
4633
4634 case ImplicitConversionSequence::UserDefinedConversion: {
4635
4636 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
4637 CastKind CastKind;
4638 QualType BeforeToType;
4639 assert(FD && "no conversion function for user-defined conversion seq");
4640 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Val: FD)) {
4641 CastKind = CK_UserDefinedConversion;
4642
4643 // If the user-defined conversion is specified by a conversion function,
4644 // the initial standard conversion sequence converts the source type to
4645 // the implicit object parameter of the conversion function.
4646 BeforeToType = Context.getCanonicalTagType(TD: Conv->getParent());
4647 } else {
4648 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(Val: FD);
4649 CastKind = CK_ConstructorConversion;
4650 // Do no conversion if dealing with ... for the first conversion.
4651 if (!ICS.UserDefined.EllipsisConversion) {
4652 // If the user-defined conversion is specified by a constructor, the
4653 // initial standard conversion sequence converts the source type to
4654 // the type required by the argument of the constructor
4655 BeforeToType = Ctor->getParamDecl(i: 0)->getType().getNonReferenceType();
4656 }
4657 }
4658 // Watch out for ellipsis conversion.
4659 if (!ICS.UserDefined.EllipsisConversion) {
4660 ExprResult Res = PerformImplicitConversion(
4661 From, ToType: BeforeToType, SCS: ICS.UserDefined.Before,
4662 Action: AssignmentAction::Converting, CCK);
4663 if (Res.isInvalid())
4664 return ExprError();
4665 From = Res.get();
4666 }
4667
4668 ExprResult CastArg = BuildCXXCastArgument(
4669 S&: *this, CastLoc: From->getBeginLoc(), Ty: ToType.getNonReferenceType(), Kind: CastKind,
4670 Method: cast<CXXMethodDecl>(Val: FD), FoundDecl: ICS.UserDefined.FoundConversionFunction,
4671 HadMultipleCandidates: ICS.UserDefined.HadMultipleCandidates, From);
4672
4673 if (CastArg.isInvalid())
4674 return ExprError();
4675
4676 From = CastArg.get();
4677
4678 // C++ [over.match.oper]p7:
4679 // [...] the second standard conversion sequence of a user-defined
4680 // conversion sequence is not applied.
4681 if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp)
4682 return From;
4683
4684 return PerformImplicitConversion(From, ToType, SCS: ICS.UserDefined.After,
4685 Action: AssignmentAction::Converting, CCK);
4686 }
4687
4688 case ImplicitConversionSequence::AmbiguousConversion:
4689 ICS.DiagnoseAmbiguousConversion(S&: *this, CaretLoc: From->getExprLoc(),
4690 PDiag: PDiag(DiagID: diag::err_typecheck_ambiguous_condition)
4691 << From->getSourceRange());
4692 return ExprError();
4693
4694 case ImplicitConversionSequence::EllipsisConversion:
4695 case ImplicitConversionSequence::StaticObjectArgumentConversion:
4696 llvm_unreachable("bad conversion");
4697
4698 case ImplicitConversionSequence::BadConversion:
4699 AssignConvertType ConvTy =
4700 CheckAssignmentConstraints(Loc: From->getExprLoc(), LHSType: ToType, RHSType: From->getType());
4701 bool Diagnosed = DiagnoseAssignmentResult(
4702 ConvTy: ConvTy == AssignConvertType::Compatible
4703 ? AssignConvertType::Incompatible
4704 : ConvTy,
4705 Loc: From->getExprLoc(), DstType: ToType, SrcType: From->getType(), SrcExpr: From, Action);
4706 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4707 return ExprError();
4708 }
4709
4710 // Everything went well.
4711 return From;
4712}
4713
4714// adjustVectorOrConstantMatrixType - Compute the intermediate cast type casting
4715// elements of the from type to the elements of the to type without resizing the
4716// vector or matrix.
4717static QualType adjustVectorOrConstantMatrixType(ASTContext &Context,
4718 QualType FromTy,
4719 QualType ToType,
4720 QualType *ElTy = nullptr) {
4721 QualType ElType = ToType;
4722 if (auto *ToVec = ToType->getAs<VectorType>())
4723 ElType = ToVec->getElementType();
4724 else if (auto *ToMat = ToType->getAs<ConstantMatrixType>())
4725 ElType = ToMat->getElementType();
4726
4727 if (ElTy)
4728 *ElTy = ElType;
4729 if (FromTy->isVectorType()) {
4730 auto *FromVec = FromTy->castAs<VectorType>();
4731 return Context.getExtVectorType(VectorType: ElType, NumElts: FromVec->getNumElements());
4732 }
4733 if (FromTy->isConstantMatrixType()) {
4734 auto *FromMat = FromTy->castAs<ConstantMatrixType>();
4735 return Context.getConstantMatrixType(ElementType: ElType, NumRows: FromMat->getNumRows(),
4736 NumColumns: FromMat->getNumColumns());
4737 }
4738 return ElType;
4739}
4740
4741/// Check if an integral conversion involves incompatible overflow behavior
4742/// types. Returns true if the conversion is invalid.
4743static bool checkIncompatibleOBTConversion(Sema &S, QualType FromType,
4744 QualType ToType, Expr *From) {
4745 const auto *FromOBT = FromType->getAs<OverflowBehaviorType>();
4746 const auto *ToOBT = ToType->getAs<OverflowBehaviorType>();
4747
4748 if (FromOBT && ToOBT &&
4749 FromOBT->getBehaviorKind() != ToOBT->getBehaviorKind()) {
4750 S.Diag(Loc: From->getExprLoc(), DiagID: diag::err_incompatible_obt_kinds_assignment)
4751 << ToType << FromType
4752 << (ToOBT->getBehaviorKind() ==
4753 OverflowBehaviorType::OverflowBehaviorKind::Trap
4754 ? "__ob_trap"
4755 : "__ob_wrap")
4756 << (FromOBT->getBehaviorKind() ==
4757 OverflowBehaviorType::OverflowBehaviorKind::Trap
4758 ? "__ob_trap"
4759 : "__ob_wrap");
4760 return true;
4761 }
4762 return false;
4763}
4764
4765ExprResult
4766Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4767 const StandardConversionSequence& SCS,
4768 AssignmentAction Action,
4769 CheckedConversionKind CCK) {
4770 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4771 CCK == CheckedConversionKind::FunctionalCast);
4772
4773 // Overall FIXME: we are recomputing too many types here and doing far too
4774 // much extra work. What this means is that we need to keep track of more
4775 // information that is computed when we try the implicit conversion initially,
4776 // so that we don't need to recompute anything here.
4777 QualType FromType = From->getType();
4778
4779 if (SCS.CopyConstructor) {
4780 // FIXME: When can ToType be a reference type?
4781 assert(!ToType->isReferenceType());
4782 if (SCS.Second == ICK_Derived_To_Base) {
4783 SmallVector<Expr*, 8> ConstructorArgs;
4784 if (CompleteConstructorCall(
4785 Constructor: cast<CXXConstructorDecl>(Val: SCS.CopyConstructor), DeclInitType: ToType, ArgsPtr: From,
4786 /*FIXME:ConstructLoc*/ Loc: SourceLocation(), ConvertedArgs&: ConstructorArgs))
4787 return ExprError();
4788 return BuildCXXConstructExpr(
4789 /*FIXME:ConstructLoc*/ ConstructLoc: SourceLocation(), DeclInitType: ToType,
4790 FoundDecl: SCS.FoundCopyConstructor, Constructor: SCS.CopyConstructor, Exprs: ConstructorArgs,
4791 /*HadMultipleCandidates*/ false,
4792 /*ListInit*/ IsListInitialization: false, /*StdInitListInit*/ IsStdInitListInitialization: false, /*ZeroInit*/ RequiresZeroInit: false,
4793 ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange());
4794 }
4795 return BuildCXXConstructExpr(
4796 /*FIXME:ConstructLoc*/ ConstructLoc: SourceLocation(), DeclInitType: ToType,
4797 FoundDecl: SCS.FoundCopyConstructor, Constructor: SCS.CopyConstructor, Exprs: From,
4798 /*HadMultipleCandidates*/ false,
4799 /*ListInit*/ IsListInitialization: false, /*StdInitListInit*/ IsStdInitListInitialization: false, /*ZeroInit*/ RequiresZeroInit: false,
4800 ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange());
4801 }
4802
4803 // Resolve overloaded function references.
4804 if (Context.hasSameType(T1: FromType, T2: Context.OverloadTy)) {
4805 DeclAccessPair Found;
4806 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: From, TargetType: ToType,
4807 Complain: true, Found);
4808 if (!Fn)
4809 return ExprError();
4810
4811 if (DiagnoseUseOfDecl(D: Fn, Locs: From->getBeginLoc()))
4812 return ExprError();
4813
4814 ExprResult Res = FixOverloadedFunctionReference(E: From, FoundDecl: Found, Fn);
4815 if (Res.isInvalid())
4816 return ExprError();
4817
4818 // We might get back another placeholder expression if we resolved to a
4819 // builtin.
4820 Res = CheckPlaceholderExpr(E: Res.get());
4821 if (Res.isInvalid())
4822 return ExprError();
4823
4824 From = Res.get();
4825 FromType = From->getType();
4826 }
4827
4828 // If we're converting to an atomic type, first convert to the corresponding
4829 // non-atomic type.
4830 QualType ToAtomicType;
4831 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4832 ToAtomicType = ToType;
4833 ToType = ToAtomic->getValueType();
4834 }
4835
4836 QualType InitialFromType = FromType;
4837 // Perform the first implicit conversion.
4838 switch (SCS.First) {
4839 case ICK_Identity:
4840 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4841 FromType = FromAtomic->getValueType().getUnqualifiedType();
4842 From = ImplicitCastExpr::Create(Context, T: FromType, Kind: CK_AtomicToNonAtomic,
4843 Operand: From, /*BasePath=*/nullptr, Cat: VK_PRValue,
4844 FPO: FPOptionsOverride());
4845 }
4846 break;
4847
4848 case ICK_Lvalue_To_Rvalue: {
4849 assert(From->getObjectKind() != OK_ObjCProperty);
4850 ExprResult FromRes = DefaultLvalueConversion(E: From);
4851 if (FromRes.isInvalid())
4852 return ExprError();
4853
4854 From = FromRes.get();
4855 FromType = From->getType();
4856 break;
4857 }
4858
4859 case ICK_Array_To_Pointer:
4860 FromType = Context.getArrayDecayedType(T: FromType);
4861 From = ImpCastExprToType(E: From, Type: FromType, CK: CK_ArrayToPointerDecay, VK: VK_PRValue,
4862 /*BasePath=*/nullptr, CCK)
4863 .get();
4864 break;
4865
4866 case ICK_HLSL_Array_RValue:
4867 if (ToType->isArrayParameterType()) {
4868 FromType = Context.getArrayParameterType(Ty: FromType);
4869 } else if (FromType->isArrayParameterType()) {
4870 const ArrayParameterType *APT = cast<ArrayParameterType>(Val&: FromType);
4871 FromType = APT->getConstantArrayType(Ctx: Context);
4872 }
4873 From = ImpCastExprToType(E: From, Type: FromType, CK: CK_HLSLArrayRValue, VK: VK_PRValue,
4874 /*BasePath=*/nullptr, CCK)
4875 .get();
4876 break;
4877
4878 case ICK_Function_To_Pointer:
4879 FromType = Context.getPointerType(T: FromType);
4880 From = ImpCastExprToType(E: From, Type: FromType, CK: CK_FunctionToPointerDecay,
4881 VK: VK_PRValue, /*BasePath=*/nullptr, CCK)
4882 .get();
4883 break;
4884
4885 default:
4886 llvm_unreachable("Improper first standard conversion");
4887 }
4888
4889 // Perform the second implicit conversion
4890 switch (SCS.Second) {
4891 case ICK_Identity:
4892 // C++ [except.spec]p5:
4893 // [For] assignment to and initialization of pointers to functions,
4894 // pointers to member functions, and references to functions: the
4895 // target entity shall allow at least the exceptions allowed by the
4896 // source value in the assignment or initialization.
4897 switch (Action) {
4898 case AssignmentAction::Assigning:
4899 case AssignmentAction::Initializing:
4900 // Note, function argument passing and returning are initialization.
4901 case AssignmentAction::Passing:
4902 case AssignmentAction::Returning:
4903 case AssignmentAction::Sending:
4904 case AssignmentAction::Passing_CFAudited:
4905 if (CheckExceptionSpecCompatibility(From, ToType))
4906 return ExprError();
4907 break;
4908
4909 case AssignmentAction::Casting:
4910 case AssignmentAction::Converting:
4911 // Casts and implicit conversions are not initialization, so are not
4912 // checked for exception specification mismatches.
4913 break;
4914 }
4915 // Nothing else to do.
4916 break;
4917
4918 case ICK_Integral_Promotion:
4919 case ICK_Integral_Conversion: {
4920 QualType ElTy = ToType;
4921 QualType StepTy = ToType;
4922 if (FromType->isVectorType() || ToType->isVectorType() ||
4923 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
4924 StepTy =
4925 adjustVectorOrConstantMatrixType(Context, FromTy: FromType, ToType, ElTy: &ElTy);
4926
4927 // Check for incompatible OBT kinds before converting
4928 if (checkIncompatibleOBTConversion(S&: *this, FromType, ToType: StepTy, From))
4929 return ExprError();
4930
4931 if (ElTy->isBooleanType()) {
4932 assert(FromType->castAsEnumDecl()->isFixed() &&
4933 SCS.Second == ICK_Integral_Promotion &&
4934 "only enums with fixed underlying type can promote to bool");
4935 From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_IntegralToBoolean, VK: VK_PRValue,
4936 /*BasePath=*/nullptr, CCK)
4937 .get();
4938 } else {
4939 From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_IntegralCast, VK: VK_PRValue,
4940 /*BasePath=*/nullptr, CCK)
4941 .get();
4942 }
4943 break;
4944 }
4945
4946 case ICK_Floating_Promotion:
4947 case ICK_Floating_Conversion: {
4948 QualType StepTy = ToType;
4949 if (FromType->isVectorType() || ToType->isVectorType() ||
4950 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
4951 StepTy = adjustVectorOrConstantMatrixType(Context, FromTy: FromType, ToType);
4952 From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_FloatingCast, VK: VK_PRValue,
4953 /*BasePath=*/nullptr, CCK)
4954 .get();
4955 break;
4956 }
4957
4958 case ICK_Complex_Promotion:
4959 case ICK_Complex_Conversion: {
4960 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4961 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4962 CastKind CK;
4963 if (FromEl->isRealFloatingType()) {
4964 if (ToEl->isRealFloatingType())
4965 CK = CK_FloatingComplexCast;
4966 else
4967 CK = CK_FloatingComplexToIntegralComplex;
4968 } else if (ToEl->isRealFloatingType()) {
4969 CK = CK_IntegralComplexToFloatingComplex;
4970 } else {
4971 CK = CK_IntegralComplexCast;
4972 }
4973 From = ImpCastExprToType(E: From, Type: ToType, CK, VK: VK_PRValue, /*BasePath=*/nullptr,
4974 CCK)
4975 .get();
4976 break;
4977 }
4978
4979 case ICK_Floating_Integral: {
4980 QualType ElTy = ToType;
4981 QualType StepTy = ToType;
4982 if (FromType->isVectorType() || ToType->isVectorType() ||
4983 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
4984 StepTy =
4985 adjustVectorOrConstantMatrixType(Context, FromTy: FromType, ToType, ElTy: &ElTy);
4986 if (ElTy->isRealFloatingType())
4987 From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_IntegralToFloating, VK: VK_PRValue,
4988 /*BasePath=*/nullptr, CCK)
4989 .get();
4990 else
4991 From = ImpCastExprToType(E: From, Type: StepTy, CK: CK_FloatingToIntegral, VK: VK_PRValue,
4992 /*BasePath=*/nullptr, CCK)
4993 .get();
4994 break;
4995 }
4996
4997 case ICK_Fixed_Point_Conversion:
4998 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4999 "Attempting implicit fixed point conversion without a fixed "
5000 "point operand");
5001 if (FromType->isFloatingType())
5002 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FloatingToFixedPoint,
5003 VK: VK_PRValue,
5004 /*BasePath=*/nullptr, CCK).get();
5005 else if (ToType->isFloatingType())
5006 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointToFloating,
5007 VK: VK_PRValue,
5008 /*BasePath=*/nullptr, CCK).get();
5009 else if (FromType->isIntegralType(Ctx: Context))
5010 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_IntegralToFixedPoint,
5011 VK: VK_PRValue,
5012 /*BasePath=*/nullptr, CCK).get();
5013 else if (ToType->isIntegralType(Ctx: Context))
5014 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointToIntegral,
5015 VK: VK_PRValue,
5016 /*BasePath=*/nullptr, CCK).get();
5017 else if (ToType->isBooleanType())
5018 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointToBoolean,
5019 VK: VK_PRValue,
5020 /*BasePath=*/nullptr, CCK).get();
5021 else
5022 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_FixedPointCast,
5023 VK: VK_PRValue,
5024 /*BasePath=*/nullptr, CCK).get();
5025 break;
5026
5027 case ICK_Compatible_Conversion:
5028 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_NoOp, VK: From->getValueKind(),
5029 /*BasePath=*/nullptr, CCK).get();
5030 break;
5031
5032 case ICK_Writeback_Conversion:
5033 case ICK_Pointer_Conversion: {
5034 if (SCS.IncompatibleObjC && Action != AssignmentAction::Casting) {
5035 // Diagnose incompatible Objective-C conversions
5036 if (Action == AssignmentAction::Initializing ||
5037 Action == AssignmentAction::Assigning)
5038 Diag(Loc: From->getBeginLoc(),
5039 DiagID: diag::ext_typecheck_convert_incompatible_pointer)
5040 << ToType << From->getType() << Action << From->getSourceRange()
5041 << 0;
5042 else
5043 Diag(Loc: From->getBeginLoc(),
5044 DiagID: diag::ext_typecheck_convert_incompatible_pointer)
5045 << From->getType() << ToType << Action << From->getSourceRange()
5046 << 0;
5047
5048 if (From->getType()->isObjCObjectPointerType() &&
5049 ToType->isObjCObjectPointerType())
5050 ObjC().EmitRelatedResultTypeNote(E: From);
5051 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
5052 !ObjC().CheckObjCARCUnavailableWeakConversion(castType: ToType,
5053 ExprType: From->getType())) {
5054 if (Action == AssignmentAction::Initializing)
5055 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_arc_weak_unavailable_assign);
5056 else
5057 Diag(Loc: From->getBeginLoc(), DiagID: diag::err_arc_convesion_of_weak_unavailable)
5058 << (Action == AssignmentAction::Casting) << From->getType()
5059 << ToType << From->getSourceRange();
5060 }
5061
5062 // Defer address space conversion to the third conversion.
5063 QualType FromPteeType = From->getType()->getPointeeType();
5064 QualType ToPteeType = ToType->getPointeeType();
5065 QualType NewToType = ToType;
5066 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
5067 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
5068 NewToType = Context.removeAddrSpaceQualType(T: ToPteeType);
5069 NewToType = Context.getAddrSpaceQualType(T: NewToType,
5070 AddressSpace: FromPteeType.getAddressSpace());
5071 if (ToType->isObjCObjectPointerType())
5072 NewToType = Context.getObjCObjectPointerType(OIT: NewToType);
5073 else if (ToType->isBlockPointerType())
5074 NewToType = Context.getBlockPointerType(T: NewToType);
5075 else
5076 NewToType = Context.getPointerType(T: NewToType);
5077 }
5078
5079 CastKind Kind;
5080 CXXCastPath BasePath;
5081 if (CheckPointerConversion(From, ToType: NewToType, Kind, BasePath, IgnoreBaseAccess: CStyle))
5082 return ExprError();
5083
5084 // Make sure we extend blocks if necessary.
5085 // FIXME: doing this here is really ugly.
5086 if (Kind == CK_BlockPointerToObjCPointerCast) {
5087 ExprResult E = From;
5088 (void)ObjC().PrepareCastToObjCObjectPointer(E);
5089 From = E.get();
5090 }
5091 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
5092 ObjC().CheckObjCConversion(castRange: SourceRange(), castType: NewToType, op&: From, CCK);
5093 From = ImpCastExprToType(E: From, Type: NewToType, CK: Kind, VK: VK_PRValue, BasePath: &BasePath, CCK)
5094 .get();
5095 break;
5096 }
5097
5098 case ICK_Pointer_Member: {
5099 CastKind Kind;
5100 CXXCastPath BasePath;
5101 switch (CheckMemberPointerConversion(
5102 FromType: From->getType(), ToPtrType: ToType->castAs<MemberPointerType>(), Kind, BasePath,
5103 CheckLoc: From->getExprLoc(), OpRange: From->getSourceRange(), IgnoreBaseAccess: CStyle,
5104 Direction: MemberPointerConversionDirection::Downcast)) {
5105 case MemberPointerConversionResult::Success:
5106 assert((Kind != CK_NullToMemberPointer ||
5107 From->isNullPointerConstant(Context,
5108 Expr::NPC_ValueDependentIsNull)) &&
5109 "Expr must be null pointer constant!");
5110 break;
5111 case MemberPointerConversionResult::Inaccessible:
5112 break;
5113 case MemberPointerConversionResult::DifferentPointee:
5114 llvm_unreachable("unexpected result");
5115 case MemberPointerConversionResult::NotDerived:
5116 llvm_unreachable("Should not have been called if derivation isn't OK.");
5117 case MemberPointerConversionResult::Ambiguous:
5118 case MemberPointerConversionResult::Virtual:
5119 return ExprError();
5120 }
5121 if (CheckExceptionSpecCompatibility(From, ToType))
5122 return ExprError();
5123
5124 From =
5125 ImpCastExprToType(E: From, Type: ToType, CK: Kind, VK: VK_PRValue, BasePath: &BasePath, CCK).get();
5126 break;
5127 }
5128
5129 case ICK_Boolean_Conversion: {
5130 // Perform half-to-boolean conversion via float.
5131 if (From->getType()->isHalfType()) {
5132 From = ImpCastExprToType(E: From, Type: Context.FloatTy, CK: CK_FloatingCast).get();
5133 FromType = Context.FloatTy;
5134 }
5135 QualType ElTy = FromType;
5136 QualType StepTy = ToType;
5137 if (FromType->isVectorType())
5138 ElTy = FromType->castAs<VectorType>()->getElementType();
5139 else if (FromType->isConstantMatrixType())
5140 ElTy = FromType->castAs<ConstantMatrixType>()->getElementType();
5141 if (getLangOpts().HLSL) {
5142 if (FromType->isVectorType() || ToType->isVectorType() ||
5143 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
5144 StepTy = adjustVectorOrConstantMatrixType(Context, FromTy: FromType, ToType);
5145 }
5146
5147 From = ImpCastExprToType(E: From, Type: StepTy, CK: ScalarTypeToBooleanCastKind(ScalarTy: ElTy),
5148 VK: VK_PRValue,
5149 /*BasePath=*/nullptr, CCK)
5150 .get();
5151 break;
5152 }
5153
5154 case ICK_Derived_To_Base: {
5155 CXXCastPath BasePath;
5156 if (CheckDerivedToBaseConversion(
5157 Derived: From->getType(), Base: ToType.getNonReferenceType(), Loc: From->getBeginLoc(),
5158 Range: From->getSourceRange(), BasePath: &BasePath, IgnoreAccess: CStyle))
5159 return ExprError();
5160
5161 From = ImpCastExprToType(E: From, Type: ToType.getNonReferenceType(),
5162 CK: CK_DerivedToBase, VK: From->getValueKind(),
5163 BasePath: &BasePath, CCK).get();
5164 break;
5165 }
5166
5167 case ICK_Vector_Conversion:
5168 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_BitCast, VK: VK_PRValue,
5169 /*BasePath=*/nullptr, CCK)
5170 .get();
5171 break;
5172
5173 case ICK_SVE_Vector_Conversion:
5174 case ICK_RVV_Vector_Conversion:
5175 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_BitCast, VK: VK_PRValue,
5176 /*BasePath=*/nullptr, CCK)
5177 .get();
5178 break;
5179
5180 case ICK_Vector_Splat: {
5181 // Vector splat from any arithmetic type to a vector.
5182 Expr *Elem = prepareVectorSplat(VectorTy: ToType, SplattedExpr: From).get();
5183 From = ImpCastExprToType(E: Elem, Type: ToType, CK: CK_VectorSplat, VK: VK_PRValue,
5184 /*BasePath=*/nullptr, CCK)
5185 .get();
5186 break;
5187 }
5188
5189 case ICK_Complex_Real:
5190 // Case 1. x -> _Complex y
5191 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
5192 QualType ElType = ToComplex->getElementType();
5193 bool isFloatingComplex = ElType->isRealFloatingType();
5194
5195 // x -> y
5196 if (Context.hasSameUnqualifiedType(T1: ElType, T2: From->getType())) {
5197 // do nothing
5198 } else if (From->getType()->isRealFloatingType()) {
5199 From = ImpCastExprToType(E: From, Type: ElType,
5200 CK: isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
5201 } else {
5202 assert(From->getType()->isIntegerType());
5203 From = ImpCastExprToType(E: From, Type: ElType,
5204 CK: isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
5205 }
5206 // y -> _Complex y
5207 From = ImpCastExprToType(E: From, Type: ToType,
5208 CK: isFloatingComplex ? CK_FloatingRealToComplex
5209 : CK_IntegralRealToComplex).get();
5210
5211 // Case 2. _Complex x -> y
5212 } else {
5213 auto *FromComplex = From->getType()->castAs<ComplexType>();
5214 QualType ElType = FromComplex->getElementType();
5215 bool isFloatingComplex = ElType->isRealFloatingType();
5216
5217 // _Complex x -> x
5218 From = ImpCastExprToType(E: From, Type: ElType,
5219 CK: isFloatingComplex ? CK_FloatingComplexToReal
5220 : CK_IntegralComplexToReal,
5221 VK: VK_PRValue, /*BasePath=*/nullptr, CCK)
5222 .get();
5223
5224 // x -> y
5225 if (Context.hasSameUnqualifiedType(T1: ElType, T2: ToType)) {
5226 // do nothing
5227 } else if (ToType->isRealFloatingType()) {
5228 From = ImpCastExprToType(E: From, Type: ToType,
5229 CK: isFloatingComplex ? CK_FloatingCast
5230 : CK_IntegralToFloating,
5231 VK: VK_PRValue, /*BasePath=*/nullptr, CCK)
5232 .get();
5233 } else {
5234 assert(ToType->isIntegerType());
5235 From = ImpCastExprToType(E: From, Type: ToType,
5236 CK: isFloatingComplex ? CK_FloatingToIntegral
5237 : CK_IntegralCast,
5238 VK: VK_PRValue, /*BasePath=*/nullptr, CCK)
5239 .get();
5240 }
5241 }
5242 break;
5243
5244 case ICK_Block_Pointer_Conversion: {
5245 LangAS AddrSpaceL =
5246 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
5247 LangAS AddrSpaceR =
5248 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
5249 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR,
5250 getASTContext()) &&
5251 "Invalid cast");
5252 CastKind Kind =
5253 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
5254 From = ImpCastExprToType(E: From, Type: ToType.getUnqualifiedType(), CK: Kind,
5255 VK: VK_PRValue, /*BasePath=*/nullptr, CCK)
5256 .get();
5257 break;
5258 }
5259
5260 case ICK_TransparentUnionConversion: {
5261 ExprResult FromRes = From;
5262 AssignConvertType ConvTy =
5263 CheckTransparentUnionArgumentConstraints(ArgType: ToType, RHS&: FromRes);
5264 if (FromRes.isInvalid())
5265 return ExprError();
5266 From = FromRes.get();
5267 assert((ConvTy == AssignConvertType::Compatible) &&
5268 "Improper transparent union conversion");
5269 (void)ConvTy;
5270 break;
5271 }
5272
5273 case ICK_Zero_Event_Conversion:
5274 case ICK_Zero_Queue_Conversion:
5275 From = ImpCastExprToType(E: From, Type: ToType,
5276 CK: CK_ZeroToOCLOpaqueType,
5277 VK: From->getValueKind()).get();
5278 break;
5279
5280 case ICK_Lvalue_To_Rvalue:
5281 case ICK_Array_To_Pointer:
5282 case ICK_Function_To_Pointer:
5283 case ICK_Function_Conversion:
5284 case ICK_Qualification:
5285 case ICK_Num_Conversion_Kinds:
5286 case ICK_C_Only_Conversion:
5287 case ICK_Incompatible_Pointer_Conversion:
5288 case ICK_HLSL_Array_RValue:
5289 case ICK_HLSL_Vector_Truncation:
5290 case ICK_HLSL_Matrix_Truncation:
5291 case ICK_HLSL_Vector_Splat:
5292 case ICK_HLSL_Matrix_Splat:
5293 llvm_unreachable("Improper second standard conversion");
5294 }
5295
5296 if (SCS.Dimension != ICK_Identity) {
5297 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
5298 // vectors or matrices.
5299 assert(
5300 (ToType->isVectorType() || ToType->isConstantMatrixType() ||
5301 ToType->isBuiltinType()) &&
5302 "Dimension conversion output must be vector, matrix, or scalar type.");
5303 switch (SCS.Dimension) {
5304 case ICK_HLSL_Vector_Splat: {
5305 // Vector splat from any arithmetic type to a vector.
5306 Expr *Elem = prepareVectorSplat(VectorTy: ToType, SplattedExpr: From).get();
5307 From = ImpCastExprToType(E: Elem, Type: ToType, CK: CK_VectorSplat, VK: VK_PRValue,
5308 /*BasePath=*/nullptr, CCK)
5309 .get();
5310 break;
5311 }
5312 case ICK_HLSL_Matrix_Splat: {
5313 // Matrix splat from any arithmetic type to a matrix.
5314 Expr *Elem = prepareMatrixSplat(MatrixTy: ToType, SplattedExpr: From).get();
5315 From =
5316 ImpCastExprToType(E: Elem, Type: ToType, CK: CK_HLSLAggregateSplatCast, VK: VK_PRValue,
5317 /*BasePath=*/nullptr, CCK)
5318 .get();
5319 break;
5320 }
5321 case ICK_HLSL_Vector_Truncation: {
5322 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a
5323 // vector to a smaller vector or to a scalar, this can only operate on
5324 // arguments where the source type is an ExtVector and the destination
5325 // type is destination type is either an ExtVectorType or a builtin scalar
5326 // type.
5327 auto *FromVec = From->getType()->castAs<VectorType>();
5328 QualType TruncTy = FromVec->getElementType();
5329 if (auto *ToVec = ToType->getAs<VectorType>())
5330 TruncTy = Context.getExtVectorType(VectorType: TruncTy, NumElts: ToVec->getNumElements());
5331 From = ImpCastExprToType(E: From, Type: TruncTy, CK: CK_HLSLVectorTruncation,
5332 VK: From->getValueKind())
5333 .get();
5334
5335 break;
5336 }
5337 case ICK_HLSL_Matrix_Truncation: {
5338 auto *FromMat = From->getType()->castAs<ConstantMatrixType>();
5339 QualType TruncTy = FromMat->getElementType();
5340 if (auto *ToMat = ToType->getAs<ConstantMatrixType>())
5341 TruncTy = Context.getConstantMatrixType(ElementType: TruncTy, NumRows: ToMat->getNumRows(),
5342 NumColumns: ToMat->getNumColumns());
5343 From = ImpCastExprToType(E: From, Type: TruncTy, CK: CK_HLSLMatrixTruncation,
5344 VK: From->getValueKind())
5345 .get();
5346 break;
5347 }
5348 case ICK_Identity:
5349 default:
5350 llvm_unreachable("Improper element standard conversion");
5351 }
5352 }
5353
5354 switch (SCS.Third) {
5355 case ICK_Identity:
5356 // Nothing to do.
5357 break;
5358
5359 case ICK_Function_Conversion:
5360 // If both sides are functions (or pointers/references to them), there could
5361 // be incompatible exception declarations.
5362 if (CheckExceptionSpecCompatibility(From, ToType))
5363 return ExprError();
5364
5365 From = ImpCastExprToType(E: From, Type: ToType, CK: CK_NoOp, VK: VK_PRValue,
5366 /*BasePath=*/nullptr, CCK)
5367 .get();
5368 break;
5369
5370 case ICK_Qualification: {
5371 ExprValueKind VK = From->getValueKind();
5372 CastKind CK = CK_NoOp;
5373
5374 if (ToType->isReferenceType() &&
5375 ToType->getPointeeType().getAddressSpace() !=
5376 From->getType().getAddressSpace())
5377 CK = CK_AddressSpaceConversion;
5378
5379 if (ToType->isPointerType() &&
5380 ToType->getPointeeType().getAddressSpace() !=
5381 From->getType()->getPointeeType().getAddressSpace())
5382 CK = CK_AddressSpaceConversion;
5383
5384 if (!isCast(CCK) &&
5385 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
5386 From->getType()->getPointeeType().getQualifiers().hasUnaligned()) {
5387 Diag(Loc: From->getBeginLoc(), DiagID: diag::warn_imp_cast_drops_unaligned)
5388 << InitialFromType << ToType;
5389 }
5390
5391 From = ImpCastExprToType(E: From, Type: ToType.getNonLValueExprType(Context), CK, VK,
5392 /*BasePath=*/nullptr, CCK)
5393 .get();
5394
5395 if (SCS.DeprecatedStringLiteralToCharPtr &&
5396 !getLangOpts().WritableStrings) {
5397 Diag(Loc: From->getBeginLoc(),
5398 DiagID: getLangOpts().CPlusPlus11
5399 ? diag::ext_deprecated_string_literal_conversion
5400 : diag::warn_deprecated_string_literal_conversion)
5401 << ToType.getNonReferenceType();
5402 }
5403
5404 break;
5405 }
5406
5407 default:
5408 llvm_unreachable("Improper third standard conversion");
5409 }
5410
5411 // If this conversion sequence involved a scalar -> atomic conversion, perform
5412 // that conversion now.
5413 if (!ToAtomicType.isNull()) {
5414 assert(Context.hasSameType(
5415 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
5416 From = ImpCastExprToType(E: From, Type: ToAtomicType, CK: CK_NonAtomicToAtomic,
5417 VK: VK_PRValue, BasePath: nullptr, CCK)
5418 .get();
5419 }
5420
5421 // Materialize a temporary if we're implicitly converting to a reference
5422 // type. This is not required by the C++ rules but is necessary to maintain
5423 // AST invariants.
5424 if (ToType->isReferenceType() && From->isPRValue()) {
5425 ExprResult Res = TemporaryMaterializationConversion(E: From);
5426 if (Res.isInvalid())
5427 return ExprError();
5428 From = Res.get();
5429 }
5430
5431 // If this conversion sequence succeeded and involved implicitly converting a
5432 // _Nullable type to a _Nonnull one, complain.
5433 if (!isCast(CCK))
5434 diagnoseNullableToNonnullConversion(DstType: ToType, SrcType: InitialFromType,
5435 Loc: From->getBeginLoc());
5436
5437 return From;
5438}
5439
5440QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5441 ExprValueKind &VK,
5442 SourceLocation Loc,
5443 bool isIndirect) {
5444 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
5445 "placeholders should have been weeded out by now");
5446
5447 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5448 // temporary materialization conversion otherwise.
5449 if (isIndirect)
5450 LHS = DefaultLvalueConversion(E: LHS.get());
5451 else if (LHS.get()->isPRValue())
5452 LHS = TemporaryMaterializationConversion(E: LHS.get());
5453 if (LHS.isInvalid())
5454 return QualType();
5455
5456 // The RHS always undergoes lvalue conversions.
5457 RHS = DefaultLvalueConversion(E: RHS.get());
5458 if (RHS.isInvalid()) return QualType();
5459
5460 const char *OpSpelling = isIndirect ? "->*" : ".*";
5461 // C++ 5.5p2
5462 // The binary operator .* [p3: ->*] binds its second operand, which shall
5463 // be of type "pointer to member of T" (where T is a completely-defined
5464 // class type) [...]
5465 QualType RHSType = RHS.get()->getType();
5466 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5467 if (!MemPtr) {
5468 Diag(Loc, DiagID: diag::err_bad_memptr_rhs)
5469 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5470 return QualType();
5471 }
5472
5473 CXXRecordDecl *RHSClass = MemPtr->getMostRecentCXXRecordDecl();
5474
5475 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5476 // member pointer points must be completely-defined. However, there is no
5477 // reason for this semantic distinction, and the rule is not enforced by
5478 // other compilers. Therefore, we do not check this property, as it is
5479 // likely to be considered a defect.
5480
5481 // C++ 5.5p2
5482 // [...] to its first operand, which shall be of class T or of a class of
5483 // which T is an unambiguous and accessible base class. [p3: a pointer to
5484 // such a class]
5485 QualType LHSType = LHS.get()->getType();
5486 if (isIndirect) {
5487 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5488 LHSType = Ptr->getPointeeType();
5489 else {
5490 Diag(Loc, DiagID: diag::err_bad_memptr_lhs)
5491 << OpSpelling << 1 << LHSType
5492 << FixItHint::CreateReplacement(RemoveRange: SourceRange(Loc), Code: ".*");
5493 return QualType();
5494 }
5495 }
5496 CXXRecordDecl *LHSClass = LHSType->getAsCXXRecordDecl();
5497
5498 if (!declaresSameEntity(D1: LHSClass, D2: RHSClass)) {
5499 // If we want to check the hierarchy, we need a complete type.
5500 if (RequireCompleteType(Loc, T: LHSType, DiagID: diag::err_bad_memptr_lhs,
5501 Args: OpSpelling, Args: (int)isIndirect)) {
5502 return QualType();
5503 }
5504
5505 if (!IsDerivedFrom(Loc, Derived: LHSClass, Base: RHSClass)) {
5506 Diag(Loc, DiagID: diag::err_bad_memptr_lhs) << OpSpelling
5507 << (int)isIndirect << LHS.get()->getType();
5508 return QualType();
5509 }
5510
5511 // FIXME: use sugared type from member pointer.
5512 CanQualType RHSClassType = Context.getCanonicalTagType(TD: RHSClass);
5513 CXXCastPath BasePath;
5514 if (CheckDerivedToBaseConversion(
5515 Derived: LHSType, Base: RHSClassType, Loc,
5516 Range: SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5517 BasePath: &BasePath))
5518 return QualType();
5519
5520 // Cast LHS to type of use.
5521 QualType UseType =
5522 Context.getQualifiedType(T: RHSClassType, Qs: LHSType.getQualifiers());
5523 if (isIndirect)
5524 UseType = Context.getPointerType(T: UseType);
5525 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
5526 LHS = ImpCastExprToType(E: LHS.get(), Type: UseType, CK: CK_DerivedToBase, VK,
5527 BasePath: &BasePath);
5528 }
5529
5530 if (isa<CXXScalarValueInitExpr>(Val: RHS.get()->IgnoreParens())) {
5531 // Diagnose use of pointer-to-member type which when used as
5532 // the functional cast in a pointer-to-member expression.
5533 Diag(Loc, DiagID: diag::err_pointer_to_member_type) << isIndirect;
5534 return QualType();
5535 }
5536
5537 // C++ 5.5p2
5538 // The result is an object or a function of the type specified by the
5539 // second operand.
5540 // The cv qualifiers are the union of those in the pointer and the left side,
5541 // in accordance with 5.5p5 and 5.2.5.
5542 QualType Result = MemPtr->getPointeeType();
5543 Result = Context.getCVRQualifiedType(T: Result, CVR: LHSType.getCVRQualifiers());
5544
5545 // C++0x [expr.mptr.oper]p6:
5546 // In a .* expression whose object expression is an rvalue, the program is
5547 // ill-formed if the second operand is a pointer to member function with
5548 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5549 // expression is an lvalue, the program is ill-formed if the second operand
5550 // is a pointer to member function with ref-qualifier &&.
5551 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5552 switch (Proto->getRefQualifier()) {
5553 case RQ_None:
5554 // Do nothing
5555 break;
5556
5557 case RQ_LValue:
5558 if (!isIndirect && !LHS.get()->Classify(Ctx&: Context).isLValue()) {
5559 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5560 // is (exactly) 'const'.
5561 if (Proto->isConst() && !Proto->isVolatile())
5562 Diag(Loc, DiagID: getLangOpts().CPlusPlus20
5563 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5564 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5565 else
5566 Diag(Loc, DiagID: diag::err_pointer_to_member_oper_value_classify)
5567 << RHSType << 1 << LHS.get()->getSourceRange();
5568 }
5569 break;
5570
5571 case RQ_RValue:
5572 if (isIndirect || !LHS.get()->Classify(Ctx&: Context).isRValue())
5573 Diag(Loc, DiagID: diag::err_pointer_to_member_oper_value_classify)
5574 << RHSType << 0 << LHS.get()->getSourceRange();
5575 break;
5576 }
5577 }
5578
5579 // C++ [expr.mptr.oper]p6:
5580 // The result of a .* expression whose second operand is a pointer
5581 // to a data member is of the same value category as its
5582 // first operand. The result of a .* expression whose second
5583 // operand is a pointer to a member function is a prvalue. The
5584 // result of an ->* expression is an lvalue if its second operand
5585 // is a pointer to data member and a prvalue otherwise.
5586 if (Result->isFunctionType()) {
5587 VK = VK_PRValue;
5588 return Context.BoundMemberTy;
5589 } else if (isIndirect) {
5590 VK = VK_LValue;
5591 } else {
5592 VK = LHS.get()->getValueKind();
5593 }
5594
5595 return Result;
5596}
5597
5598/// Try to convert a type to another according to C++11 5.16p3.
5599///
5600/// This is part of the parameter validation for the ? operator. If either
5601/// value operand is a class type, the two operands are attempted to be
5602/// converted to each other. This function does the conversion in one direction.
5603/// It returns true if the program is ill-formed and has already been diagnosed
5604/// as such.
5605static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5606 SourceLocation QuestionLoc,
5607 bool &HaveConversion,
5608 QualType &ToType) {
5609 HaveConversion = false;
5610 ToType = To->getType();
5611
5612 InitializationKind Kind =
5613 InitializationKind::CreateCopy(InitLoc: To->getBeginLoc(), EqualLoc: SourceLocation());
5614 // C++11 5.16p3
5615 // The process for determining whether an operand expression E1 of type T1
5616 // can be converted to match an operand expression E2 of type T2 is defined
5617 // as follows:
5618 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5619 // implicitly converted to type "lvalue reference to T2", subject to the
5620 // constraint that in the conversion the reference must bind directly to
5621 // an lvalue.
5622 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5623 // implicitly converted to the type "rvalue reference to R2", subject to
5624 // the constraint that the reference must bind directly.
5625 if (To->isGLValue()) {
5626 QualType T = Self.Context.getReferenceQualifiedType(e: To);
5627 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: T);
5628
5629 InitializationSequence InitSeq(Self, Entity, Kind, From);
5630 if (InitSeq.isDirectReferenceBinding()) {
5631 ToType = T;
5632 HaveConversion = true;
5633 return false;
5634 }
5635
5636 if (InitSeq.isAmbiguous())
5637 return InitSeq.Diagnose(S&: Self, Entity, Kind, Args: From);
5638 }
5639
5640 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5641 // -- if E1 and E2 have class type, and the underlying class types are
5642 // the same or one is a base class of the other:
5643 QualType FTy = From->getType();
5644 QualType TTy = To->getType();
5645 const RecordType *FRec = FTy->getAsCanonical<RecordType>();
5646 const RecordType *TRec = TTy->getAsCanonical<RecordType>();
5647 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5648 Self.IsDerivedFrom(Loc: QuestionLoc, Derived: FTy, Base: TTy);
5649 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5650 Self.IsDerivedFrom(Loc: QuestionLoc, Derived: TTy, Base: FTy))) {
5651 // E1 can be converted to match E2 if the class of T2 is the
5652 // same type as, or a base class of, the class of T1, and
5653 // [cv2 > cv1].
5654 if (FRec == TRec || FDerivedFromT) {
5655 if (TTy.isAtLeastAsQualifiedAs(other: FTy, Ctx: Self.getASTContext())) {
5656 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: TTy);
5657 InitializationSequence InitSeq(Self, Entity, Kind, From);
5658 if (InitSeq) {
5659 HaveConversion = true;
5660 return false;
5661 }
5662
5663 if (InitSeq.isAmbiguous())
5664 return InitSeq.Diagnose(S&: Self, Entity, Kind, Args: From);
5665 }
5666 }
5667
5668 return false;
5669 }
5670
5671 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5672 // implicitly converted to the type that expression E2 would have
5673 // if E2 were converted to an rvalue (or the type it has, if E2 is
5674 // an rvalue).
5675 //
5676 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5677 // to the array-to-pointer or function-to-pointer conversions.
5678 TTy = TTy.getNonLValueExprType(Context: Self.Context);
5679
5680 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: TTy);
5681 InitializationSequence InitSeq(Self, Entity, Kind, From);
5682 HaveConversion = !InitSeq.Failed();
5683 ToType = TTy;
5684 if (InitSeq.isAmbiguous())
5685 return InitSeq.Diagnose(S&: Self, Entity, Kind, Args: From);
5686
5687 return false;
5688}
5689
5690/// Try to find a common type for two according to C++0x 5.16p5.
5691///
5692/// This is part of the parameter validation for the ? operator. If either
5693/// value operand is a class type, overload resolution is used to find a
5694/// conversion to a common type.
5695static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5696 SourceLocation QuestionLoc) {
5697 Expr *Args[2] = { LHS.get(), RHS.get() };
5698 OverloadCandidateSet CandidateSet(QuestionLoc,
5699 OverloadCandidateSet::CSK_Operator);
5700 Self.AddBuiltinOperatorCandidates(Op: OO_Conditional, OpLoc: QuestionLoc, Args,
5701 CandidateSet);
5702
5703 OverloadCandidateSet::iterator Best;
5704 switch (CandidateSet.BestViableFunction(S&: Self, Loc: QuestionLoc, Best)) {
5705 case OR_Success: {
5706 // We found a match. Perform the conversions on the arguments and move on.
5707 ExprResult LHSRes = Self.PerformImplicitConversion(
5708 From: LHS.get(), ToType: Best->BuiltinParamTypes[0], ICS: Best->Conversions[0],
5709 Action: AssignmentAction::Converting);
5710 if (LHSRes.isInvalid())
5711 break;
5712 LHS = LHSRes;
5713
5714 ExprResult RHSRes = Self.PerformImplicitConversion(
5715 From: RHS.get(), ToType: Best->BuiltinParamTypes[1], ICS: Best->Conversions[1],
5716 Action: AssignmentAction::Converting);
5717 if (RHSRes.isInvalid())
5718 break;
5719 RHS = RHSRes;
5720 if (Best->Function)
5721 Self.MarkFunctionReferenced(Loc: QuestionLoc, Func: Best->Function);
5722 return false;
5723 }
5724
5725 case OR_No_Viable_Function:
5726
5727 // Emit a better diagnostic if one of the expressions is a null pointer
5728 // constant and the other is a pointer type. In this case, the user most
5729 // likely forgot to take the address of the other expression.
5730 if (Self.DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
5731 return true;
5732
5733 Self.Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
5734 << LHS.get()->getType() << RHS.get()->getType()
5735 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5736 return true;
5737
5738 case OR_Ambiguous:
5739 Self.Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_ambiguous_ovl)
5740 << LHS.get()->getType() << RHS.get()->getType()
5741 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5742 // FIXME: Print the possible common types by printing the return types of
5743 // the viable candidates.
5744 break;
5745
5746 case OR_Deleted:
5747 llvm_unreachable("Conditional operator has only built-in overloads");
5748 }
5749 return true;
5750}
5751
5752/// Perform an "extended" implicit conversion as returned by
5753/// TryClassUnification.
5754static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5755 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: T);
5756 InitializationKind Kind =
5757 InitializationKind::CreateCopy(InitLoc: E.get()->getBeginLoc(), EqualLoc: SourceLocation());
5758 Expr *Arg = E.get();
5759 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5760 ExprResult Result = InitSeq.Perform(S&: Self, Entity, Kind, Args: Arg);
5761 if (Result.isInvalid())
5762 return true;
5763
5764 E = Result;
5765 return false;
5766}
5767
5768// Check the condition operand of ?: to see if it is valid for the GCC
5769// extension.
5770static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
5771 QualType CondTy) {
5772 bool IsSVEVectorType = CondTy->isSveVLSBuiltinType();
5773 if (!CondTy->isVectorType() && !CondTy->isExtVectorType() && !IsSVEVectorType)
5774 return false;
5775 const QualType EltTy =
5776 IsSVEVectorType
5777 ? cast<BuiltinType>(Val: CondTy.getCanonicalType())->getSveEltType(Ctx)
5778 : cast<VectorType>(Val: CondTy.getCanonicalType())->getElementType();
5779 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
5780 return EltTy->isIntegralType(Ctx);
5781}
5782
5783QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
5784 ExprResult &RHS,
5785 SourceLocation QuestionLoc) {
5786 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
5787 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
5788
5789 QualType CondType = Cond.get()->getType();
5790 QualType LHSType = LHS.get()->getType();
5791 QualType RHSType = RHS.get()->getType();
5792
5793 bool LHSSizelessVector = LHSType->isSizelessVectorType();
5794 bool RHSSizelessVector = RHSType->isSizelessVectorType();
5795 bool LHSIsVector = LHSType->isVectorType() || LHSSizelessVector;
5796 bool RHSIsVector = RHSType->isVectorType() || RHSSizelessVector;
5797
5798 auto GetVectorInfo =
5799 [&](QualType Type) -> std::pair<QualType, llvm::ElementCount> {
5800 if (const auto *VT = Type->getAs<VectorType>())
5801 return std::make_pair(x: VT->getElementType(),
5802 y: llvm::ElementCount::getFixed(MinVal: VT->getNumElements()));
5803 ASTContext::BuiltinVectorTypeInfo VectorInfo =
5804 Context.getBuiltinVectorTypeInfo(VecTy: Type->castAs<BuiltinType>());
5805 return std::make_pair(x&: VectorInfo.ElementType, y&: VectorInfo.EC);
5806 };
5807
5808 auto [CondElementTy, CondElementCount] = GetVectorInfo(CondType);
5809
5810 QualType ResultType;
5811 if (LHSIsVector && RHSIsVector) {
5812 if (CondType->isExtVectorType() != LHSType->isExtVectorType()) {
5813 Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_cond_result_mismatch)
5814 << /*isExtVectorNotSizeless=*/1;
5815 return {};
5816 }
5817
5818 // If both are vector types, they must be the same type.
5819 if (!Context.hasSameType(T1: LHSType, T2: RHSType)) {
5820 Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_mismatched)
5821 << LHSType << RHSType;
5822 return {};
5823 }
5824 ResultType = Context.getCommonSugaredType(X: LHSType, Y: RHSType);
5825 } else if (LHSIsVector || RHSIsVector) {
5826 bool ResultSizeless = LHSSizelessVector || RHSSizelessVector;
5827 if (ResultSizeless != CondType->isSizelessVectorType()) {
5828 Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_cond_result_mismatch)
5829 << /*isExtVectorNotSizeless=*/0;
5830 return {};
5831 }
5832 if (ResultSizeless)
5833 ResultType = CheckSizelessVectorOperands(LHS, RHS, Loc: QuestionLoc,
5834 /*IsCompAssign*/ false,
5835 OperationKind: ArithConvKind::Conditional);
5836 else
5837 ResultType = CheckVectorOperands(
5838 LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false, /*AllowBothBool*/ true,
5839 /*AllowBoolConversions*/ AllowBoolConversion: false,
5840 /*AllowBoolOperation*/ true,
5841 /*ReportInvalid*/ true);
5842 if (ResultType.isNull())
5843 return {};
5844 } else {
5845 // Both are scalar.
5846 LHSType = LHSType.getUnqualifiedType();
5847 RHSType = RHSType.getUnqualifiedType();
5848 QualType ResultElementTy =
5849 Context.hasSameType(T1: LHSType, T2: RHSType)
5850 ? Context.getCommonSugaredType(X: LHSType, Y: RHSType)
5851 : UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
5852 ACK: ArithConvKind::Conditional);
5853
5854 if (ResultElementTy->isEnumeralType()) {
5855 Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_operand_type)
5856 << ResultElementTy;
5857 return {};
5858 }
5859 if (CondType->isExtVectorType()) {
5860 ResultType = Context.getExtVectorType(VectorType: ResultElementTy,
5861 NumElts: CondElementCount.getFixedValue());
5862 } else if (CondType->isSizelessVectorType()) {
5863 ResultType = Context.getScalableVectorType(
5864 EltTy: ResultElementTy, NumElts: CondElementCount.getKnownMinValue());
5865 // There are not scalable vector type mappings for all element counts.
5866 if (ResultType.isNull()) {
5867 Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_scalar_type_unsupported)
5868 << ResultElementTy << CondType;
5869 return {};
5870 }
5871 } else {
5872 ResultType = Context.getVectorType(VectorType: ResultElementTy,
5873 NumElts: CondElementCount.getFixedValue(),
5874 VecKind: VectorKind::Generic);
5875 }
5876 LHS = ImpCastExprToType(E: LHS.get(), Type: ResultType, CK: CK_VectorSplat);
5877 RHS = ImpCastExprToType(E: RHS.get(), Type: ResultType, CK: CK_VectorSplat);
5878 }
5879
5880 assert(!ResultType.isNull() &&
5881 (ResultType->isVectorType() || ResultType->isSizelessVectorType()) &&
5882 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
5883 "Result should have been a vector type");
5884
5885 auto [ResultElementTy, ResultElementCount] = GetVectorInfo(ResultType);
5886 if (ResultElementCount != CondElementCount) {
5887 Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_size) << CondType
5888 << ResultType;
5889 return {};
5890 }
5891
5892 // Boolean vectors are permitted outside of OpenCL mode.
5893 if (Context.getTypeSize(T: ResultElementTy) !=
5894 Context.getTypeSize(T: CondElementTy) &&
5895 (!CondElementTy->isBooleanType() || LangOpts.OpenCL)) {
5896 Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_vector_element_size)
5897 << CondType << ResultType;
5898 return {};
5899 }
5900
5901 return ResultType;
5902}
5903
5904QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5905 ExprResult &RHS, ExprValueKind &VK,
5906 ExprObjectKind &OK,
5907 SourceLocation QuestionLoc) {
5908 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
5909 // pointers.
5910
5911 // Assume r-value.
5912 VK = VK_PRValue;
5913 OK = OK_Ordinary;
5914 bool IsVectorConditional =
5915 isValidVectorForConditionalCondition(Ctx&: Context, CondTy: Cond.get()->getType());
5916
5917 // C++11 [expr.cond]p1
5918 // The first expression is contextually converted to bool.
5919 if (!Cond.get()->isTypeDependent()) {
5920 ExprResult CondRes = IsVectorConditional
5921 ? DefaultFunctionArrayLvalueConversion(E: Cond.get())
5922 : CheckCXXBooleanCondition(CondExpr: Cond.get());
5923 if (CondRes.isInvalid())
5924 return QualType();
5925 Cond = CondRes;
5926 } else {
5927 // To implement C++, the first expression typically doesn't alter the result
5928 // type of the conditional, however the GCC compatible vector extension
5929 // changes the result type to be that of the conditional. Since we cannot
5930 // know if this is a vector extension here, delay the conversion of the
5931 // LHS/RHS below until later.
5932 return Context.DependentTy;
5933 }
5934
5935
5936 // Either of the arguments dependent?
5937 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5938 return Context.DependentTy;
5939
5940 // C++11 [expr.cond]p2
5941 // If either the second or the third operand has type (cv) void, ...
5942 QualType LTy = LHS.get()->getType();
5943 QualType RTy = RHS.get()->getType();
5944 bool LVoid = LTy->isVoidType();
5945 bool RVoid = RTy->isVoidType();
5946 if (LVoid || RVoid) {
5947 // ... one of the following shall hold:
5948 // -- The second or the third operand (but not both) is a (possibly
5949 // parenthesized) throw-expression; the result is of the type
5950 // and value category of the other.
5951 bool LThrow = isa<CXXThrowExpr>(Val: LHS.get()->IgnoreParenImpCasts());
5952 bool RThrow = isa<CXXThrowExpr>(Val: RHS.get()->IgnoreParenImpCasts());
5953
5954 // Void expressions aren't legal in the vector-conditional expressions.
5955 if (IsVectorConditional) {
5956 SourceRange DiagLoc =
5957 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
5958 bool IsThrow = LVoid ? LThrow : RThrow;
5959 Diag(Loc: DiagLoc.getBegin(), DiagID: diag::err_conditional_vector_has_void)
5960 << DiagLoc << IsThrow;
5961 return QualType();
5962 }
5963
5964 if (LThrow != RThrow) {
5965 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5966 VK = NonThrow->getValueKind();
5967 // DR (no number yet): the result is a bit-field if the
5968 // non-throw-expression operand is a bit-field.
5969 OK = NonThrow->getObjectKind();
5970 return NonThrow->getType();
5971 }
5972
5973 // -- Both the second and third operands have type void; the result is of
5974 // type void and is a prvalue.
5975 if (LVoid && RVoid)
5976 return Context.getCommonSugaredType(X: LTy, Y: RTy);
5977
5978 // Neither holds, error.
5979 Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_void_nonvoid)
5980 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5981 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5982 return QualType();
5983 }
5984
5985 // Neither is void.
5986 if (IsVectorConditional)
5987 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
5988
5989 // WebAssembly tables are not allowed as conditional LHS or RHS.
5990 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
5991 Diag(Loc: QuestionLoc, DiagID: diag::err_wasm_table_conditional_expression)
5992 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5993 return QualType();
5994 }
5995
5996 // C++11 [expr.cond]p3
5997 // Otherwise, if the second and third operand have different types, and
5998 // either has (cv) class type [...] an attempt is made to convert each of
5999 // those operands to the type of the other.
6000 if (!Context.hasSameType(T1: LTy, T2: RTy) &&
6001 (LTy->isRecordType() || RTy->isRecordType())) {
6002 // These return true if a single direction is already ambiguous.
6003 QualType L2RType, R2LType;
6004 bool HaveL2R, HaveR2L;
6005 if (TryClassUnification(Self&: *this, From: LHS.get(), To: RHS.get(), QuestionLoc, HaveConversion&: HaveL2R, ToType&: L2RType))
6006 return QualType();
6007 if (TryClassUnification(Self&: *this, From: RHS.get(), To: LHS.get(), QuestionLoc, HaveConversion&: HaveR2L, ToType&: R2LType))
6008 return QualType();
6009
6010 // If both can be converted, [...] the program is ill-formed.
6011 if (HaveL2R && HaveR2L) {
6012 Diag(Loc: QuestionLoc, DiagID: diag::err_conditional_ambiguous)
6013 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6014 return QualType();
6015 }
6016
6017 // If exactly one conversion is possible, that conversion is applied to
6018 // the chosen operand and the converted operands are used in place of the
6019 // original operands for the remainder of this section.
6020 if (HaveL2R) {
6021 if (ConvertForConditional(Self&: *this, E&: LHS, T: L2RType) || LHS.isInvalid())
6022 return QualType();
6023 LTy = LHS.get()->getType();
6024 } else if (HaveR2L) {
6025 if (ConvertForConditional(Self&: *this, E&: RHS, T: R2LType) || RHS.isInvalid())
6026 return QualType();
6027 RTy = RHS.get()->getType();
6028 }
6029 }
6030
6031 // C++11 [expr.cond]p3
6032 // if both are glvalues of the same value category and the same type except
6033 // for cv-qualification, an attempt is made to convert each of those
6034 // operands to the type of the other.
6035 // FIXME:
6036 // Resolving a defect in P0012R1: we extend this to cover all cases where
6037 // one of the operands is reference-compatible with the other, in order
6038 // to support conditionals between functions differing in noexcept. This
6039 // will similarly cover difference in array bounds after P0388R4.
6040 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6041 // that instead?
6042 ExprValueKind LVK = LHS.get()->getValueKind();
6043 ExprValueKind RVK = RHS.get()->getValueKind();
6044 if (!Context.hasSameType(T1: LTy, T2: RTy) && LVK == RVK && LVK != VK_PRValue) {
6045 // DerivedToBase was already handled by the class-specific case above.
6046 // FIXME: Should we allow ObjC conversions here?
6047 const ReferenceConversions AllowedConversions =
6048 ReferenceConversions::Qualification |
6049 ReferenceConversions::NestedQualification |
6050 ReferenceConversions::Function;
6051
6052 ReferenceConversions RefConv;
6053 if (CompareReferenceRelationship(Loc: QuestionLoc, T1: LTy, T2: RTy, Conv: &RefConv) ==
6054 Ref_Compatible &&
6055 !(RefConv & ~AllowedConversions) &&
6056 // [...] subject to the constraint that the reference must bind
6057 // directly [...]
6058 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6059 RHS = ImpCastExprToType(E: RHS.get(), Type: LTy, CK: CK_NoOp, VK: RVK);
6060 RTy = RHS.get()->getType();
6061 } else if (CompareReferenceRelationship(Loc: QuestionLoc, T1: RTy, T2: LTy, Conv: &RefConv) ==
6062 Ref_Compatible &&
6063 !(RefConv & ~AllowedConversions) &&
6064 !LHS.get()->refersToBitField() &&
6065 !LHS.get()->refersToVectorElement()) {
6066 LHS = ImpCastExprToType(E: LHS.get(), Type: RTy, CK: CK_NoOp, VK: LVK);
6067 LTy = LHS.get()->getType();
6068 }
6069 }
6070
6071 // C++11 [expr.cond]p4
6072 // If the second and third operands are glvalues of the same value
6073 // category and have the same type, the result is of that type and
6074 // value category and it is a bit-field if the second or the third
6075 // operand is a bit-field, or if both are bit-fields.
6076 // We only extend this to bitfields, not to the crazy other kinds of
6077 // l-values.
6078 bool Same = Context.hasSameType(T1: LTy, T2: RTy);
6079 if (Same && LVK == RVK && LVK != VK_PRValue &&
6080 LHS.get()->isOrdinaryOrBitFieldObject() &&
6081 RHS.get()->isOrdinaryOrBitFieldObject()) {
6082 VK = LHS.get()->getValueKind();
6083 if (LHS.get()->getObjectKind() == OK_BitField ||
6084 RHS.get()->getObjectKind() == OK_BitField)
6085 OK = OK_BitField;
6086 return Context.getCommonSugaredType(X: LTy, Y: RTy);
6087 }
6088
6089 // C++11 [expr.cond]p5
6090 // Otherwise, the result is a prvalue. If the second and third operands
6091 // do not have the same type, and either has (cv) class type, ...
6092 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6093 // ... overload resolution is used to determine the conversions (if any)
6094 // to be applied to the operands. If the overload resolution fails, the
6095 // program is ill-formed.
6096 if (FindConditionalOverload(Self&: *this, LHS, RHS, QuestionLoc))
6097 return QualType();
6098 }
6099
6100 // C++11 [expr.cond]p6
6101 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6102 // conversions are performed on the second and third operands.
6103 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
6104 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
6105 if (LHS.isInvalid() || RHS.isInvalid())
6106 return QualType();
6107 LTy = LHS.get()->getType();
6108 RTy = RHS.get()->getType();
6109
6110 // After those conversions, one of the following shall hold:
6111 // -- The second and third operands have the same type; the result
6112 // is of that type. If the operands have class type, the result
6113 // is a prvalue temporary of the result type, which is
6114 // copy-initialized from either the second operand or the third
6115 // operand depending on the value of the first operand.
6116 if (Context.hasSameType(T1: LTy, T2: RTy)) {
6117 if (LTy->isRecordType()) {
6118 // The operands have class type. Make a temporary copy.
6119 ExprResult LHSCopy = PerformCopyInitialization(
6120 Entity: InitializedEntity::InitializeTemporary(Type: LTy), EqualLoc: SourceLocation(), Init: LHS);
6121 if (LHSCopy.isInvalid())
6122 return QualType();
6123
6124 ExprResult RHSCopy = PerformCopyInitialization(
6125 Entity: InitializedEntity::InitializeTemporary(Type: RTy), EqualLoc: SourceLocation(), Init: RHS);
6126 if (RHSCopy.isInvalid())
6127 return QualType();
6128
6129 LHS = LHSCopy;
6130 RHS = RHSCopy;
6131 }
6132 return Context.getCommonSugaredType(X: LTy, Y: RTy);
6133 }
6134
6135 // Extension: conditional operator involving vector types.
6136 if (LTy->isVectorType() || RTy->isVectorType())
6137 return CheckVectorOperands(LHS, RHS, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
6138 /*AllowBothBool*/ true,
6139 /*AllowBoolConversions*/ AllowBoolConversion: false,
6140 /*AllowBoolOperation*/ false,
6141 /*ReportInvalid*/ true);
6142
6143 // -- The second and third operands have arithmetic or enumeration type;
6144 // the usual arithmetic conversions are performed to bring them to a
6145 // common type, and the result is of that type.
6146 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6147 QualType ResTy = UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc,
6148 ACK: ArithConvKind::Conditional);
6149 if (LHS.isInvalid() || RHS.isInvalid())
6150 return QualType();
6151 if (ResTy.isNull()) {
6152 Diag(Loc: QuestionLoc,
6153 DiagID: diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6154 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6155 return QualType();
6156 }
6157
6158 LHS = ImpCastExprToType(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(src&: LHS, destType: ResTy));
6159 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(src&: RHS, destType: ResTy));
6160
6161 return ResTy;
6162 }
6163
6164 // -- The second and third operands have pointer type, or one has pointer
6165 // type and the other is a null pointer constant, or both are null
6166 // pointer constants, at least one of which is non-integral; pointer
6167 // conversions and qualification conversions are performed to bring them
6168 // to their composite pointer type. The result is of the composite
6169 // pointer type.
6170 // -- The second and third operands have pointer to member type, or one has
6171 // pointer to member type and the other is a null pointer constant;
6172 // pointer to member conversions and qualification conversions are
6173 // performed to bring them to a common type, whose cv-qualification
6174 // shall match the cv-qualification of either the second or the third
6175 // operand. The result is of the common type.
6176 QualType Composite = FindCompositePointerType(Loc: QuestionLoc, E1&: LHS, E2&: RHS);
6177 if (!Composite.isNull())
6178 return Composite;
6179
6180 // Similarly, attempt to find composite type of two objective-c pointers.
6181 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6182 if (LHS.isInvalid() || RHS.isInvalid())
6183 return QualType();
6184 if (!Composite.isNull())
6185 return Composite;
6186
6187 // Check if we are using a null with a non-pointer type.
6188 if (DiagnoseConditionalForNull(LHSExpr: LHS.get(), RHSExpr: RHS.get(), QuestionLoc))
6189 return QualType();
6190
6191 Diag(Loc: QuestionLoc, DiagID: diag::err_typecheck_cond_incompatible_operands)
6192 << LHS.get()->getType() << RHS.get()->getType()
6193 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6194 return QualType();
6195}
6196
6197QualType Sema::FindCompositePointerType(SourceLocation Loc,
6198 Expr *&E1, Expr *&E2,
6199 bool ConvertArgs) {
6200 assert(getLangOpts().CPlusPlus && "This function assumes C++");
6201
6202 // C++1z [expr]p14:
6203 // The composite pointer type of two operands p1 and p2 having types T1
6204 // and T2
6205 QualType T1 = E1->getType(), T2 = E2->getType();
6206
6207 // where at least one is a pointer or pointer to member type or
6208 // std::nullptr_t is:
6209 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6210 T1->isNullPtrType();
6211 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6212 T2->isNullPtrType();
6213 if (!T1IsPointerLike && !T2IsPointerLike)
6214 return QualType();
6215
6216 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6217 // This can't actually happen, following the standard, but we also use this
6218 // to implement the end of [expr.conv], which hits this case.
6219 //
6220 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6221 if (T1IsPointerLike &&
6222 E2->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
6223 if (ConvertArgs)
6224 E2 = ImpCastExprToType(E: E2, Type: T1, CK: T1->isMemberPointerType()
6225 ? CK_NullToMemberPointer
6226 : CK_NullToPointer).get();
6227 return T1;
6228 }
6229 if (T2IsPointerLike &&
6230 E1->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
6231 if (ConvertArgs)
6232 E1 = ImpCastExprToType(E: E1, Type: T2, CK: T2->isMemberPointerType()
6233 ? CK_NullToMemberPointer
6234 : CK_NullToPointer).get();
6235 return T2;
6236 }
6237
6238 // Now both have to be pointers or member pointers.
6239 if (!T1IsPointerLike || !T2IsPointerLike)
6240 return QualType();
6241 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6242 "nullptr_t should be a null pointer constant");
6243
6244 struct Step {
6245 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6246 // Qualifiers to apply under the step kind.
6247 Qualifiers Quals;
6248 /// The class for a pointer-to-member; a constant array type with a bound
6249 /// (if any) for an array.
6250 /// FIXME: Store Qualifier for pointer-to-member.
6251 const Type *ClassOrBound;
6252
6253 Step(Kind K, const Type *ClassOrBound = nullptr)
6254 : K(K), ClassOrBound(ClassOrBound) {}
6255 QualType rebuild(ASTContext &Ctx, QualType T) const {
6256 T = Ctx.getQualifiedType(T, Qs: Quals);
6257 switch (K) {
6258 case Pointer:
6259 return Ctx.getPointerType(T);
6260 case MemberPointer:
6261 return Ctx.getMemberPointerType(T, /*Qualifier=*/std::nullopt,
6262 Cls: ClassOrBound->getAsCXXRecordDecl());
6263 case ObjCPointer:
6264 return Ctx.getObjCObjectPointerType(OIT: T);
6265 case Array:
6266 if (auto *CAT = cast_or_null<ConstantArrayType>(Val: ClassOrBound))
6267 return Ctx.getConstantArrayType(EltTy: T, ArySize: CAT->getSize(), SizeExpr: nullptr,
6268 ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6269 else
6270 return Ctx.getIncompleteArrayType(EltTy: T, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
6271 }
6272 llvm_unreachable("unknown step kind");
6273 }
6274 };
6275
6276 SmallVector<Step, 8> Steps;
6277
6278 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6279 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6280 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6281 // respectively;
6282 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6283 // to member of C2 of type cv2 U2" for some non-function type U, where
6284 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6285 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6286 // respectively;
6287 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6288 // T2;
6289 //
6290 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6291 // and to prepare to form the cv-combined type if so.
6292 QualType Composite1 = T1;
6293 QualType Composite2 = T2;
6294 unsigned NeedConstBefore = 0;
6295 while (true) {
6296 assert(!Composite1.isNull() && !Composite2.isNull());
6297
6298 Qualifiers Q1, Q2;
6299 Composite1 = Context.getUnqualifiedArrayType(T: Composite1, Quals&: Q1);
6300 Composite2 = Context.getUnqualifiedArrayType(T: Composite2, Quals&: Q2);
6301
6302 // Top-level qualifiers are ignored. Merge at all lower levels.
6303 if (!Steps.empty()) {
6304 // Find the qualifier union: (approximately) the unique minimal set of
6305 // qualifiers that is compatible with both types.
6306 Qualifiers Quals = Qualifiers::fromCVRUMask(CVRU: Q1.getCVRUQualifiers() |
6307 Q2.getCVRUQualifiers());
6308
6309 // Under one level of pointer or pointer-to-member, we can change to an
6310 // unambiguous compatible address space.
6311 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6312 Quals.setAddressSpace(Q1.getAddressSpace());
6313 } else if (Steps.size() == 1) {
6314 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(other: Q2, Ctx: getASTContext());
6315 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(other: Q1, Ctx: getASTContext());
6316 if (MaybeQ1 == MaybeQ2) {
6317 // Exception for ptr size address spaces. Should be able to choose
6318 // either address space during comparison.
6319 if (isPtrSizeAddressSpace(AS: Q1.getAddressSpace()) ||
6320 isPtrSizeAddressSpace(AS: Q2.getAddressSpace()))
6321 MaybeQ1 = true;
6322 else
6323 return QualType(); // No unique best address space.
6324 }
6325 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6326 : Q2.getAddressSpace());
6327 } else {
6328 return QualType();
6329 }
6330
6331 // FIXME: In C, we merge __strong and none to __strong at the top level.
6332 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6333 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6334 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6335 assert(Steps.size() == 1);
6336 else
6337 return QualType();
6338
6339 // Mismatched lifetime qualifiers never compatibly include each other.
6340 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6341 Quals.setObjCLifetime(Q1.getObjCLifetime());
6342 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6343 assert(Steps.size() == 1);
6344 else
6345 return QualType();
6346
6347 if (Q1.getPointerAuth().isEquivalent(Other: Q2.getPointerAuth()))
6348 Quals.setPointerAuth(Q1.getPointerAuth());
6349 else
6350 return QualType();
6351
6352 Steps.back().Quals = Quals;
6353 if (Q1 != Quals || Q2 != Quals)
6354 NeedConstBefore = Steps.size() - 1;
6355 }
6356
6357 // FIXME: Can we unify the following with UnwrapSimilarTypes?
6358
6359 const ArrayType *Arr1, *Arr2;
6360 if ((Arr1 = Context.getAsArrayType(T: Composite1)) &&
6361 (Arr2 = Context.getAsArrayType(T: Composite2))) {
6362 auto *CAT1 = dyn_cast<ConstantArrayType>(Val: Arr1);
6363 auto *CAT2 = dyn_cast<ConstantArrayType>(Val: Arr2);
6364 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
6365 Composite1 = Arr1->getElementType();
6366 Composite2 = Arr2->getElementType();
6367 Steps.emplace_back(Args: Step::Array, Args&: CAT1);
6368 continue;
6369 }
6370 bool IAT1 = isa<IncompleteArrayType>(Val: Arr1);
6371 bool IAT2 = isa<IncompleteArrayType>(Val: Arr2);
6372 if ((IAT1 && IAT2) ||
6373 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
6374 ((bool)CAT1 != (bool)CAT2) &&
6375 (Steps.empty() || Steps.back().K != Step::Array))) {
6376 // In C++20 onwards, we can unify an array of N T with an array of
6377 // a different or unknown bound. But we can't form an array whose
6378 // element type is an array of unknown bound by doing so.
6379 Composite1 = Arr1->getElementType();
6380 Composite2 = Arr2->getElementType();
6381 Steps.emplace_back(Args: Step::Array);
6382 if (CAT1 || CAT2)
6383 NeedConstBefore = Steps.size();
6384 continue;
6385 }
6386 }
6387
6388 const PointerType *Ptr1, *Ptr2;
6389 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6390 (Ptr2 = Composite2->getAs<PointerType>())) {
6391 Composite1 = Ptr1->getPointeeType();
6392 Composite2 = Ptr2->getPointeeType();
6393 Steps.emplace_back(Args: Step::Pointer);
6394 continue;
6395 }
6396
6397 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6398 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6399 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6400 Composite1 = ObjPtr1->getPointeeType();
6401 Composite2 = ObjPtr2->getPointeeType();
6402 Steps.emplace_back(Args: Step::ObjCPointer);
6403 continue;
6404 }
6405
6406 const MemberPointerType *MemPtr1, *MemPtr2;
6407 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6408 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6409 Composite1 = MemPtr1->getPointeeType();
6410 Composite2 = MemPtr2->getPointeeType();
6411
6412 // At the top level, we can perform a base-to-derived pointer-to-member
6413 // conversion:
6414 //
6415 // - [...] where C1 is reference-related to C2 or C2 is
6416 // reference-related to C1
6417 //
6418 // (Note that the only kinds of reference-relatedness in scope here are
6419 // "same type or derived from".) At any other level, the class must
6420 // exactly match.
6421 CXXRecordDecl *Cls = nullptr,
6422 *Cls1 = MemPtr1->getMostRecentCXXRecordDecl(),
6423 *Cls2 = MemPtr2->getMostRecentCXXRecordDecl();
6424 if (declaresSameEntity(D1: Cls1, D2: Cls2))
6425 Cls = Cls1;
6426 else if (Steps.empty())
6427 Cls = IsDerivedFrom(Loc, Derived: Cls1, Base: Cls2) ? Cls1
6428 : IsDerivedFrom(Loc, Derived: Cls2, Base: Cls1) ? Cls2
6429 : nullptr;
6430 if (!Cls)
6431 return QualType();
6432
6433 Steps.emplace_back(Args: Step::MemberPointer,
6434 Args: Context.getCanonicalTagType(TD: Cls).getTypePtr());
6435 continue;
6436 }
6437
6438 // Special case: at the top level, we can decompose an Objective-C pointer
6439 // and a 'cv void *'. Unify the qualifiers.
6440 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6441 Composite2->isObjCObjectPointerType()) ||
6442 (Composite1->isObjCObjectPointerType() &&
6443 Composite2->isVoidPointerType()))) {
6444 Composite1 = Composite1->getPointeeType();
6445 Composite2 = Composite2->getPointeeType();
6446 Steps.emplace_back(Args: Step::Pointer);
6447 continue;
6448 }
6449
6450 // FIXME: block pointer types?
6451
6452 // Cannot unwrap any more types.
6453 break;
6454 }
6455
6456 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6457 // "pointer to function", where the function types are otherwise the same,
6458 // "pointer to function";
6459 // - if T1 or T2 is "pointer to member of C1 of type function", the other
6460 // type is "pointer to member of C2 of type noexcept function", and C1
6461 // is reference-related to C2 or C2 is reference-related to C1, where
6462 // the function types are otherwise the same, "pointer to member of C2 of
6463 // type function" or "pointer to member of C1 of type function",
6464 // respectively;
6465 //
6466 // We also support 'noreturn' here, so as a Clang extension we generalize the
6467 // above to:
6468 //
6469 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6470 // "pointer to member function" and the pointee types can be unified
6471 // by a function pointer conversion, that conversion is applied
6472 // before checking the following rules.
6473 //
6474 // We've already unwrapped down to the function types, and we want to merge
6475 // rather than just convert, so do this ourselves rather than calling
6476 // IsFunctionConversion.
6477 //
6478 // FIXME: In order to match the standard wording as closely as possible, we
6479 // currently only do this under a single level of pointers. Ideally, we would
6480 // allow this in general, and set NeedConstBefore to the relevant depth on
6481 // the side(s) where we changed anything. If we permit that, we should also
6482 // consider this conversion when determining type similarity and model it as
6483 // a qualification conversion.
6484 if (Steps.size() == 1) {
6485 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6486 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6487 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6488 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6489
6490 // The result is noreturn if both operands are.
6491 bool Noreturn =
6492 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6493 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(noReturn: Noreturn);
6494 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(noReturn: Noreturn);
6495
6496 bool CFIUncheckedCallee =
6497 EPI1.CFIUncheckedCallee || EPI2.CFIUncheckedCallee;
6498 EPI1.CFIUncheckedCallee = CFIUncheckedCallee;
6499 EPI2.CFIUncheckedCallee = CFIUncheckedCallee;
6500
6501 // The result is nothrow if both operands are.
6502 SmallVector<QualType, 8> ExceptionTypeStorage;
6503 EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs(
6504 ESI1: EPI1.ExceptionSpec, ESI2: EPI2.ExceptionSpec, ExceptionTypeStorage,
6505 AcceptDependent: getLangOpts().CPlusPlus17);
6506
6507 Composite1 = Context.getFunctionType(ResultTy: FPT1->getReturnType(),
6508 Args: FPT1->getParamTypes(), EPI: EPI1);
6509 Composite2 = Context.getFunctionType(ResultTy: FPT2->getReturnType(),
6510 Args: FPT2->getParamTypes(), EPI: EPI2);
6511 }
6512 }
6513 }
6514
6515 // There are some more conversions we can perform under exactly one pointer.
6516 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6517 !Context.hasSameType(T1: Composite1, T2: Composite2)) {
6518 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6519 // "pointer to cv2 T", where T is an object type or void,
6520 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6521 if (Composite1->isVoidType() && Composite2->isObjectType())
6522 Composite2 = Composite1;
6523 else if (Composite2->isVoidType() && Composite1->isObjectType())
6524 Composite1 = Composite2;
6525 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6526 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6527 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6528 // T1, respectively;
6529 //
6530 // The "similar type" handling covers all of this except for the "T1 is a
6531 // base class of T2" case in the definition of reference-related.
6532 else if (IsDerivedFrom(Loc, Derived: Composite1, Base: Composite2))
6533 Composite1 = Composite2;
6534 else if (IsDerivedFrom(Loc, Derived: Composite2, Base: Composite1))
6535 Composite2 = Composite1;
6536 }
6537
6538 // At this point, either the inner types are the same or we have failed to
6539 // find a composite pointer type.
6540 if (!Context.hasSameType(T1: Composite1, T2: Composite2))
6541 return QualType();
6542
6543 // Per C++ [conv.qual]p3, add 'const' to every level before the last
6544 // differing qualifier.
6545 for (unsigned I = 0; I != NeedConstBefore; ++I)
6546 Steps[I].Quals.addConst();
6547
6548 // Rebuild the composite type.
6549 QualType Composite = Context.getCommonSugaredType(X: Composite1, Y: Composite2);
6550 for (auto &S : llvm::reverse(C&: Steps))
6551 Composite = S.rebuild(Ctx&: Context, T: Composite);
6552
6553 if (ConvertArgs) {
6554 // Convert the expressions to the composite pointer type.
6555 InitializedEntity Entity =
6556 InitializedEntity::InitializeTemporary(Type: Composite);
6557 InitializationKind Kind =
6558 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
6559
6560 InitializationSequence E1ToC(*this, Entity, Kind, E1);
6561 if (!E1ToC)
6562 return QualType();
6563
6564 InitializationSequence E2ToC(*this, Entity, Kind, E2);
6565 if (!E2ToC)
6566 return QualType();
6567
6568 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6569 ExprResult E1Result = E1ToC.Perform(S&: *this, Entity, Kind, Args: E1);
6570 if (E1Result.isInvalid())
6571 return QualType();
6572 E1 = E1Result.get();
6573
6574 ExprResult E2Result = E2ToC.Perform(S&: *this, Entity, Kind, Args: E2);
6575 if (E2Result.isInvalid())
6576 return QualType();
6577 E2 = E2Result.get();
6578 }
6579
6580 return Composite;
6581}
6582
6583ExprResult Sema::MaybeBindToTemporary(Expr *E) {
6584 if (!E)
6585 return ExprError();
6586
6587 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6588
6589 // If the result is a glvalue, we shouldn't bind it.
6590 if (E->isGLValue())
6591 return E;
6592
6593 // In ARC, calls that return a retainable type can return retained,
6594 // in which case we have to insert a consuming cast.
6595 if (getLangOpts().ObjCAutoRefCount &&
6596 E->getType()->isObjCRetainableType()) {
6597
6598 bool ReturnsRetained;
6599
6600 // For actual calls, we compute this by examining the type of the
6601 // called value.
6602 if (CallExpr *Call = dyn_cast<CallExpr>(Val: E)) {
6603 Expr *Callee = Call->getCallee()->IgnoreParens();
6604 QualType T = Callee->getType();
6605
6606 if (T == Context.BoundMemberTy) {
6607 // Handle pointer-to-members.
6608 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Val: Callee))
6609 T = BinOp->getRHS()->getType();
6610 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Val: Callee))
6611 T = Mem->getMemberDecl()->getType();
6612 }
6613
6614 if (const PointerType *Ptr = T->getAs<PointerType>())
6615 T = Ptr->getPointeeType();
6616 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6617 T = Ptr->getPointeeType();
6618 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6619 T = MemPtr->getPointeeType();
6620
6621 auto *FTy = T->castAs<FunctionType>();
6622 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6623
6624 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6625 // type always produce a +1 object.
6626 } else if (isa<StmtExpr>(Val: E)) {
6627 ReturnsRetained = true;
6628
6629 // We hit this case with the lambda conversion-to-block optimization;
6630 // we don't want any extra casts here.
6631 } else if (isa<CastExpr>(Val: E) &&
6632 isa<BlockExpr>(Val: cast<CastExpr>(Val: E)->getSubExpr())) {
6633 return E;
6634
6635 // For message sends and property references, we try to find an
6636 // actual method. FIXME: we should infer retention by selector in
6637 // cases where we don't have an actual method.
6638 } else {
6639 ObjCMethodDecl *D = nullptr;
6640 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(Val: E)) {
6641 D = Send->getMethodDecl();
6642 } else if (auto *OL = dyn_cast<ObjCObjectLiteral>(Val: E);
6643 OL && OL->isGlobalAllocation()) {
6644 return E;
6645 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(Val: E)) {
6646 D = BoxedExpr->getBoxingMethod();
6647 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(Val: E)) {
6648 // Don't do reclaims if we're using the zero-element array
6649 // constant.
6650 if (ArrayLit->getNumElements() == 0 &&
6651 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6652 return E;
6653
6654 D = ArrayLit->getArrayWithObjectsMethod();
6655 } else if (ObjCDictionaryLiteral *DictLit =
6656 dyn_cast<ObjCDictionaryLiteral>(Val: E)) {
6657 // Don't do reclaims if we're using the zero-element dictionary
6658 // constant.
6659 if (DictLit->getNumElements() == 0 &&
6660 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6661 return E;
6662
6663 D = DictLit->getDictWithObjectsMethod();
6664 }
6665
6666 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6667
6668 // Don't do reclaims on performSelector calls; despite their
6669 // return type, the invoked method doesn't necessarily actually
6670 // return an object.
6671 if (!ReturnsRetained &&
6672 D && D->getMethodFamily() == OMF_performSelector)
6673 return E;
6674 }
6675
6676 // Don't reclaim an object of Class type.
6677 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6678 return E;
6679
6680 Cleanup.setExprNeedsCleanups(true);
6681
6682 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6683 : CK_ARCReclaimReturnedObject);
6684 return ImplicitCastExpr::Create(Context, T: E->getType(), Kind: ck, Operand: E, BasePath: nullptr,
6685 Cat: VK_PRValue, FPO: FPOptionsOverride());
6686 }
6687
6688 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
6689 Cleanup.setExprNeedsCleanups(true);
6690
6691 if (!getLangOpts().CPlusPlus)
6692 return E;
6693
6694 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6695 // a fast path for the common case that the type is directly a RecordType.
6696 const Type *T = Context.getCanonicalType(T: E->getType().getTypePtr());
6697 const RecordType *RT = nullptr;
6698 while (!RT) {
6699 switch (T->getTypeClass()) {
6700 case Type::Record:
6701 RT = cast<RecordType>(Val: T);
6702 break;
6703 case Type::ConstantArray:
6704 case Type::IncompleteArray:
6705 case Type::VariableArray:
6706 case Type::DependentSizedArray:
6707 T = cast<ArrayType>(Val: T)->getElementType().getTypePtr();
6708 break;
6709 default:
6710 return E;
6711 }
6712 }
6713
6714 // That should be enough to guarantee that this type is complete, if we're
6715 // not processing a decltype expression.
6716 auto *RD = cast<CXXRecordDecl>(Val: RT->getDecl())->getDefinitionOrSelf();
6717 if (RD->isInvalidDecl() || RD->isDependentContext())
6718 return E;
6719
6720 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6721 ExpressionEvaluationContextRecord::EK_Decltype;
6722 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(Class: RD);
6723
6724 if (Destructor) {
6725 MarkFunctionReferenced(Loc: E->getExprLoc(), Func: Destructor);
6726 CheckDestructorAccess(Loc: E->getExprLoc(), Dtor: Destructor,
6727 PDiag: PDiag(DiagID: diag::err_access_dtor_temp)
6728 << E->getType());
6729 if (DiagnoseUseOfDecl(D: Destructor, Locs: E->getExprLoc()))
6730 return ExprError();
6731
6732 // If destructor is trivial, we can avoid the extra copy.
6733 if (Destructor->isTrivial())
6734 return E;
6735
6736 // We need a cleanup, but we don't need to remember the temporary.
6737 Cleanup.setExprNeedsCleanups(true);
6738 }
6739
6740 CXXTemporary *Temp = CXXTemporary::Create(C: Context, Destructor);
6741 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(C: Context, Temp, SubExpr: E);
6742
6743 if (IsDecltype)
6744 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Elt: Bind);
6745
6746 return Bind;
6747}
6748
6749ExprResult
6750Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6751 if (SubExpr.isInvalid())
6752 return ExprError();
6753
6754 return MaybeCreateExprWithCleanups(SubExpr: SubExpr.get());
6755}
6756
6757Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6758 assert(SubExpr && "subexpression can't be null!");
6759
6760 CleanupVarDeclMarking();
6761
6762 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6763 assert(ExprCleanupObjects.size() >= FirstCleanup);
6764 assert(Cleanup.exprNeedsCleanups() ||
6765 ExprCleanupObjects.size() == FirstCleanup);
6766 if (!Cleanup.exprNeedsCleanups())
6767 return SubExpr;
6768
6769 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6770 ExprCleanupObjects.size() - FirstCleanup);
6771
6772 auto *E = ExprWithCleanups::Create(
6773 C: Context, subexpr: SubExpr, CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: Cleanups);
6774 DiscardCleanupsInEvaluationContext();
6775
6776 return E;
6777}
6778
6779Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6780 assert(SubStmt && "sub-statement can't be null!");
6781
6782 CleanupVarDeclMarking();
6783
6784 if (!Cleanup.exprNeedsCleanups())
6785 return SubStmt;
6786
6787 // FIXME: In order to attach the temporaries, wrap the statement into
6788 // a StmtExpr; currently this is only used for asm statements.
6789 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6790 // a new AsmStmtWithTemporaries.
6791 CompoundStmt *CompStmt =
6792 CompoundStmt::Create(C: Context, Stmts: SubStmt, FPFeatures: FPOptionsOverride(),
6793 LB: SourceLocation(), RB: SourceLocation());
6794 Expr *E = new (Context)
6795 StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
6796 /*FIXME TemplateDepth=*/0);
6797 return MaybeCreateExprWithCleanups(SubExpr: E);
6798}
6799
6800ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6801 assert(ExprEvalContexts.back().ExprContext ==
6802 ExpressionEvaluationContextRecord::EK_Decltype &&
6803 "not in a decltype expression");
6804
6805 ExprResult Result = CheckPlaceholderExpr(E);
6806 if (Result.isInvalid())
6807 return ExprError();
6808 E = Result.get();
6809
6810 // C++11 [expr.call]p11:
6811 // If a function call is a prvalue of object type,
6812 // -- if the function call is either
6813 // -- the operand of a decltype-specifier, or
6814 // -- the right operand of a comma operator that is the operand of a
6815 // decltype-specifier,
6816 // a temporary object is not introduced for the prvalue.
6817
6818 // Recursively rebuild ParenExprs and comma expressions to strip out the
6819 // outermost CXXBindTemporaryExpr, if any.
6820 if (ParenExpr *PE = dyn_cast<ParenExpr>(Val: E)) {
6821 ExprResult SubExpr = ActOnDecltypeExpression(E: PE->getSubExpr());
6822 if (SubExpr.isInvalid())
6823 return ExprError();
6824 if (SubExpr.get() == PE->getSubExpr())
6825 return E;
6826 return ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: SubExpr.get());
6827 }
6828 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
6829 if (BO->getOpcode() == BO_Comma) {
6830 ExprResult RHS = ActOnDecltypeExpression(E: BO->getRHS());
6831 if (RHS.isInvalid())
6832 return ExprError();
6833 if (RHS.get() == BO->getRHS())
6834 return E;
6835 return BinaryOperator::Create(C: Context, lhs: BO->getLHS(), rhs: RHS.get(), opc: BO_Comma,
6836 ResTy: BO->getType(), VK: BO->getValueKind(),
6837 OK: BO->getObjectKind(), opLoc: BO->getOperatorLoc(),
6838 FPFeatures: BO->getFPFeatures());
6839 }
6840 }
6841
6842 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(Val: E);
6843 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(Val: TopBind->getSubExpr())
6844 : nullptr;
6845 if (TopCall)
6846 E = TopCall;
6847 else
6848 TopBind = nullptr;
6849
6850 // Disable the special decltype handling now.
6851 ExprEvalContexts.back().ExprContext =
6852 ExpressionEvaluationContextRecord::EK_Other;
6853
6854 Result = CheckUnevaluatedOperand(E);
6855 if (Result.isInvalid())
6856 return ExprError();
6857 E = Result.get();
6858
6859 // In MS mode, don't perform any extra checking of call return types within a
6860 // decltype expression.
6861 if (getLangOpts().MSVCCompat)
6862 return E;
6863
6864 // Perform the semantic checks we delayed until this point.
6865 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6866 I != N; ++I) {
6867 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6868 if (Call == TopCall)
6869 continue;
6870
6871 if (CheckCallReturnType(ReturnType: Call->getCallReturnType(Ctx: Context),
6872 Loc: Call->getBeginLoc(), CE: Call, FD: Call->getDirectCallee()))
6873 return ExprError();
6874 }
6875
6876 // Now all relevant types are complete, check the destructors are accessible
6877 // and non-deleted, and annotate them on the temporaries.
6878 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6879 I != N; ++I) {
6880 CXXBindTemporaryExpr *Bind =
6881 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6882 if (Bind == TopBind)
6883 continue;
6884
6885 CXXTemporary *Temp = Bind->getTemporary();
6886
6887 CXXRecordDecl *RD =
6888 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6889 CXXDestructorDecl *Destructor = LookupDestructor(Class: RD);
6890 Temp->setDestructor(Destructor);
6891
6892 MarkFunctionReferenced(Loc: Bind->getExprLoc(), Func: Destructor);
6893 CheckDestructorAccess(Loc: Bind->getExprLoc(), Dtor: Destructor,
6894 PDiag: PDiag(DiagID: diag::err_access_dtor_temp)
6895 << Bind->getType());
6896 if (DiagnoseUseOfDecl(D: Destructor, Locs: Bind->getExprLoc()))
6897 return ExprError();
6898
6899 // We need a cleanup, but we don't need to remember the temporary.
6900 Cleanup.setExprNeedsCleanups(true);
6901 }
6902
6903 // Possibly strip off the top CXXBindTemporaryExpr.
6904 return E;
6905}
6906
6907/// Note a set of 'operator->' functions that were used for a member access.
6908static void noteOperatorArrows(Sema &S,
6909 ArrayRef<FunctionDecl *> OperatorArrows) {
6910 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6911 // FIXME: Make this configurable?
6912 unsigned Limit = 9;
6913 if (OperatorArrows.size() > Limit) {
6914 // Produce Limit-1 normal notes and one 'skipping' note.
6915 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6916 SkipCount = OperatorArrows.size() - (Limit - 1);
6917 }
6918
6919 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6920 if (I == SkipStart) {
6921 S.Diag(Loc: OperatorArrows[I]->getLocation(),
6922 DiagID: diag::note_operator_arrows_suppressed)
6923 << SkipCount;
6924 I += SkipCount;
6925 } else {
6926 S.Diag(Loc: OperatorArrows[I]->getLocation(), DiagID: diag::note_operator_arrow_here)
6927 << OperatorArrows[I]->getCallResultType();
6928 ++I;
6929 }
6930 }
6931}
6932
6933ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6934 SourceLocation OpLoc,
6935 tok::TokenKind OpKind,
6936 ParsedType &ObjectType,
6937 bool &MayBePseudoDestructor) {
6938 // Since this might be a postfix expression, get rid of ParenListExprs.
6939 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Base);
6940 if (Result.isInvalid()) return ExprError();
6941 Base = Result.get();
6942
6943 Result = CheckPlaceholderExpr(E: Base);
6944 if (Result.isInvalid()) return ExprError();
6945 Base = Result.get();
6946
6947 QualType BaseType = Base->getType();
6948 MayBePseudoDestructor = false;
6949 if (BaseType->isDependentType()) {
6950 // If we have a pointer to a dependent type and are using the -> operator,
6951 // the object type is the type that the pointer points to. We might still
6952 // have enough information about that type to do something useful.
6953 if (OpKind == tok::arrow)
6954 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6955 BaseType = Ptr->getPointeeType();
6956
6957 ObjectType = ParsedType::make(P: BaseType);
6958 MayBePseudoDestructor = true;
6959 return Base;
6960 }
6961
6962 // C++ [over.match.oper]p8:
6963 // [...] When operator->returns, the operator-> is applied to the value
6964 // returned, with the original second operand.
6965 if (OpKind == tok::arrow) {
6966 QualType StartingType = BaseType;
6967 bool NoArrowOperatorFound = false;
6968 bool FirstIteration = true;
6969 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(Val: CurContext);
6970 // The set of types we've considered so far.
6971 llvm::SmallPtrSet<CanQualType,8> CTypes;
6972 SmallVector<FunctionDecl*, 8> OperatorArrows;
6973 CTypes.insert(Ptr: Context.getCanonicalType(T: BaseType));
6974
6975 while (BaseType->isRecordType()) {
6976 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6977 Diag(Loc: OpLoc, DiagID: diag::err_operator_arrow_depth_exceeded)
6978 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6979 noteOperatorArrows(S&: *this, OperatorArrows);
6980 Diag(Loc: OpLoc, DiagID: diag::note_operator_arrow_depth)
6981 << getLangOpts().ArrowDepth;
6982 return ExprError();
6983 }
6984
6985 Result = BuildOverloadedArrowExpr(
6986 S, Base, OpLoc,
6987 // When in a template specialization and on the first loop iteration,
6988 // potentially give the default diagnostic (with the fixit in a
6989 // separate note) instead of having the error reported back to here
6990 // and giving a diagnostic with a fixit attached to the error itself.
6991 NoArrowOperatorFound: (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6992 ? nullptr
6993 : &NoArrowOperatorFound);
6994 if (Result.isInvalid()) {
6995 if (NoArrowOperatorFound) {
6996 if (FirstIteration) {
6997 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_suggestion)
6998 << BaseType << 1 << Base->getSourceRange()
6999 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
7000 OpKind = tok::period;
7001 break;
7002 }
7003 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_arrow)
7004 << BaseType << Base->getSourceRange();
7005 CallExpr *CE = dyn_cast<CallExpr>(Val: Base);
7006 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7007 Diag(Loc: CD->getBeginLoc(),
7008 DiagID: diag::note_member_reference_arrow_from_operator_arrow);
7009 }
7010 }
7011 return ExprError();
7012 }
7013 Base = Result.get();
7014 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Val: Base))
7015 OperatorArrows.push_back(Elt: OpCall->getDirectCallee());
7016 BaseType = Base->getType();
7017 CanQualType CBaseType = Context.getCanonicalType(T: BaseType);
7018 if (!CTypes.insert(Ptr: CBaseType).second) {
7019 Diag(Loc: OpLoc, DiagID: diag::err_operator_arrow_circular) << StartingType;
7020 noteOperatorArrows(S&: *this, OperatorArrows);
7021 return ExprError();
7022 }
7023 FirstIteration = false;
7024 }
7025
7026 if (OpKind == tok::arrow) {
7027 if (BaseType->isPointerType())
7028 BaseType = BaseType->getPointeeType();
7029 else if (auto *AT = Context.getAsArrayType(T: BaseType))
7030 BaseType = AT->getElementType();
7031 }
7032 }
7033
7034 // Objective-C properties allow "." access on Objective-C pointer types,
7035 // so adjust the base type to the object type itself.
7036 if (BaseType->isObjCObjectPointerType())
7037 BaseType = BaseType->getPointeeType();
7038
7039 // C++ [basic.lookup.classref]p2:
7040 // [...] If the type of the object expression is of pointer to scalar
7041 // type, the unqualified-id is looked up in the context of the complete
7042 // postfix-expression.
7043 //
7044 // This also indicates that we could be parsing a pseudo-destructor-name.
7045 // Note that Objective-C class and object types can be pseudo-destructor
7046 // expressions or normal member (ivar or property) access expressions, and
7047 // it's legal for the type to be incomplete if this is a pseudo-destructor
7048 // call. We'll do more incomplete-type checks later in the lookup process,
7049 // so just skip this check for ObjC types.
7050 if (!BaseType->isRecordType()) {
7051 ObjectType = ParsedType::make(P: BaseType);
7052 MayBePseudoDestructor = true;
7053 return Base;
7054 }
7055
7056 // The object type must be complete (or dependent), or
7057 // C++11 [expr.prim.general]p3:
7058 // Unlike the object expression in other contexts, *this is not required to
7059 // be of complete type for purposes of class member access (5.2.5) outside
7060 // the member function body.
7061 if (!BaseType->isDependentType() &&
7062 !isThisOutsideMemberFunctionBody(BaseType) &&
7063 RequireCompleteType(Loc: OpLoc, T: BaseType,
7064 DiagID: diag::err_incomplete_member_access)) {
7065 return CreateRecoveryExpr(Begin: Base->getBeginLoc(), End: Base->getEndLoc(), SubExprs: {Base});
7066 }
7067
7068 // C++ [basic.lookup.classref]p2:
7069 // If the id-expression in a class member access (5.2.5) is an
7070 // unqualified-id, and the type of the object expression is of a class
7071 // type C (or of pointer to a class type C), the unqualified-id is looked
7072 // up in the scope of class C. [...]
7073 ObjectType = ParsedType::make(P: BaseType);
7074 return Base;
7075}
7076
7077static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7078 tok::TokenKind &OpKind, SourceLocation OpLoc) {
7079 if (Base->hasPlaceholderType()) {
7080 ExprResult result = S.CheckPlaceholderExpr(E: Base);
7081 if (result.isInvalid()) return true;
7082 Base = result.get();
7083 }
7084 ObjectType = Base->getType();
7085
7086 // C++ [expr.pseudo]p2:
7087 // The left-hand side of the dot operator shall be of scalar type. The
7088 // left-hand side of the arrow operator shall be of pointer to scalar type.
7089 // This scalar type is the object type.
7090 // Note that this is rather different from the normal handling for the
7091 // arrow operator.
7092 if (OpKind == tok::arrow) {
7093 // The operator requires a prvalue, so perform lvalue conversions.
7094 // Only do this if we might plausibly end with a pointer, as otherwise
7095 // this was likely to be intended to be a '.'.
7096 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7097 ObjectType->isFunctionType()) {
7098 ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(E: Base);
7099 if (BaseResult.isInvalid())
7100 return true;
7101 Base = BaseResult.get();
7102 ObjectType = Base->getType();
7103 }
7104
7105 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7106 ObjectType = Ptr->getPointeeType();
7107 } else if (!Base->isTypeDependent()) {
7108 // The user wrote "p->" when they probably meant "p."; fix it.
7109 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_suggestion)
7110 << ObjectType << true
7111 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
7112 if (S.isSFINAEContext())
7113 return true;
7114
7115 OpKind = tok::period;
7116 }
7117 }
7118
7119 return false;
7120}
7121
7122/// Check if it's ok to try and recover dot pseudo destructor calls on
7123/// pointer objects.
7124static bool
7125canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7126 QualType DestructedType) {
7127 // If this is a record type, check if its destructor is callable.
7128 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7129 if (RD->hasDefinition())
7130 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(Class: RD))
7131 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7132 return false;
7133 }
7134
7135 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7136 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7137 DestructedType->isVectorType();
7138}
7139
7140ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
7141 SourceLocation OpLoc,
7142 tok::TokenKind OpKind,
7143 const CXXScopeSpec &SS,
7144 TypeSourceInfo *ScopeTypeInfo,
7145 SourceLocation CCLoc,
7146 SourceLocation TildeLoc,
7147 PseudoDestructorTypeStorage Destructed) {
7148 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7149
7150 QualType ObjectType;
7151 if (CheckArrow(S&: *this, ObjectType, Base, OpKind, OpLoc))
7152 return ExprError();
7153
7154 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7155 !ObjectType->isVectorType() && !ObjectType->isMatrixType()) {
7156 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7157 Diag(Loc: OpLoc, DiagID: diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7158 else {
7159 Diag(Loc: OpLoc, DiagID: diag::err_pseudo_dtor_base_not_scalar)
7160 << ObjectType << Base->getSourceRange();
7161 return ExprError();
7162 }
7163 }
7164
7165 // C++ [expr.pseudo]p2:
7166 // [...] The cv-unqualified versions of the object type and of the type
7167 // designated by the pseudo-destructor-name shall be the same type.
7168 if (DestructedTypeInfo) {
7169 QualType DestructedType = DestructedTypeInfo->getType();
7170 SourceLocation DestructedTypeStart =
7171 DestructedTypeInfo->getTypeLoc().getBeginLoc();
7172 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7173 if (!Context.hasSameUnqualifiedType(T1: DestructedType, T2: ObjectType)) {
7174 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7175 // Foo *foo;
7176 // foo.~Foo();
7177 if (OpKind == tok::period && ObjectType->isPointerType() &&
7178 Context.hasSameUnqualifiedType(T1: DestructedType,
7179 T2: ObjectType->getPointeeType())) {
7180 auto Diagnostic =
7181 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_suggestion)
7182 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7183
7184 // Issue a fixit only when the destructor is valid.
7185 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7186 SemaRef&: *this, DestructedType))
7187 Diagnostic << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: "->");
7188
7189 // Recover by setting the object type to the destructed type and the
7190 // operator to '->'.
7191 ObjectType = DestructedType;
7192 OpKind = tok::arrow;
7193 } else {
7194 Diag(Loc: DestructedTypeStart, DiagID: diag::err_pseudo_dtor_type_mismatch)
7195 << ObjectType << DestructedType << Base->getSourceRange()
7196 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7197
7198 // Recover by setting the destructed type to the object type.
7199 DestructedType = ObjectType;
7200 DestructedTypeInfo =
7201 Context.getTrivialTypeSourceInfo(T: ObjectType, Loc: DestructedTypeStart);
7202 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7203 }
7204 } else if (DestructedType.getObjCLifetime() !=
7205 ObjectType.getObjCLifetime()) {
7206
7207 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7208 // Okay: just pretend that the user provided the correctly-qualified
7209 // type.
7210 } else {
7211 Diag(Loc: DestructedTypeStart, DiagID: diag::err_arc_pseudo_dtor_inconstant_quals)
7212 << ObjectType << DestructedType << Base->getSourceRange()
7213 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7214 }
7215
7216 // Recover by setting the destructed type to the object type.
7217 DestructedType = ObjectType;
7218 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(T: ObjectType,
7219 Loc: DestructedTypeStart);
7220 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7221 }
7222 }
7223 }
7224
7225 // C++ [expr.pseudo]p2:
7226 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7227 // form
7228 //
7229 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7230 //
7231 // shall designate the same scalar type.
7232 if (ScopeTypeInfo) {
7233 QualType ScopeType = ScopeTypeInfo->getType();
7234 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7235 !Context.hasSameUnqualifiedType(T1: ScopeType, T2: ObjectType)) {
7236
7237 Diag(Loc: ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
7238 DiagID: diag::err_pseudo_dtor_type_mismatch)
7239 << ObjectType << ScopeType << Base->getSourceRange()
7240 << ScopeTypeInfo->getTypeLoc().getSourceRange();
7241
7242 ScopeType = QualType();
7243 ScopeTypeInfo = nullptr;
7244 }
7245 }
7246
7247 Expr *Result
7248 = new (Context) CXXPseudoDestructorExpr(Context, Base,
7249 OpKind == tok::arrow, OpLoc,
7250 SS.getWithLocInContext(Context),
7251 ScopeTypeInfo,
7252 CCLoc,
7253 TildeLoc,
7254 Destructed);
7255
7256 return Result;
7257}
7258
7259ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7260 SourceLocation OpLoc,
7261 tok::TokenKind OpKind,
7262 CXXScopeSpec &SS,
7263 UnqualifiedId &FirstTypeName,
7264 SourceLocation CCLoc,
7265 SourceLocation TildeLoc,
7266 UnqualifiedId &SecondTypeName) {
7267 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7268 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7269 "Invalid first type name in pseudo-destructor");
7270 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7271 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7272 "Invalid second type name in pseudo-destructor");
7273
7274 QualType ObjectType;
7275 if (CheckArrow(S&: *this, ObjectType, Base, OpKind, OpLoc))
7276 return ExprError();
7277
7278 // Compute the object type that we should use for name lookup purposes. Only
7279 // record types and dependent types matter.
7280 ParsedType ObjectTypePtrForLookup;
7281 if (!SS.isSet()) {
7282 if (ObjectType->isRecordType())
7283 ObjectTypePtrForLookup = ParsedType::make(P: ObjectType);
7284 else if (ObjectType->isDependentType())
7285 ObjectTypePtrForLookup = ParsedType::make(P: Context.DependentTy);
7286 }
7287
7288 // Convert the name of the type being destructed (following the ~) into a
7289 // type (with source-location information).
7290 QualType DestructedType;
7291 TypeSourceInfo *DestructedTypeInfo = nullptr;
7292 PseudoDestructorTypeStorage Destructed;
7293 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7294 ParsedType T = getTypeName(II: *SecondTypeName.Identifier,
7295 NameLoc: SecondTypeName.StartLocation,
7296 S, SS: &SS, isClassName: true, HasTrailingDot: false, ObjectType: ObjectTypePtrForLookup,
7297 /*IsCtorOrDtorName*/true);
7298 if (!T &&
7299 ((SS.isSet() && !computeDeclContext(SS, EnteringContext: false)) ||
7300 (!SS.isSet() && ObjectType->isDependentType()))) {
7301 // The name of the type being destroyed is a dependent name, and we
7302 // couldn't find anything useful in scope. Just store the identifier and
7303 // it's location, and we'll perform (qualified) name lookup again at
7304 // template instantiation time.
7305 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7306 SecondTypeName.StartLocation);
7307 } else if (!T) {
7308 Diag(Loc: SecondTypeName.StartLocation,
7309 DiagID: diag::err_pseudo_dtor_destructor_non_type)
7310 << SecondTypeName.Identifier << ObjectType;
7311 if (isSFINAEContext())
7312 return ExprError();
7313
7314 // Recover by assuming we had the right type all along.
7315 DestructedType = ObjectType;
7316 } else
7317 DestructedType = GetTypeFromParser(Ty: T, TInfo: &DestructedTypeInfo);
7318 } else {
7319 // Resolve the template-id to a type.
7320 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7321 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7322 TemplateId->NumArgs);
7323 TypeResult T = ActOnTemplateIdType(
7324 S, ElaboratedKeyword: ElaboratedTypeKeyword::None,
7325 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
7326 TemplateKWLoc: TemplateId->TemplateKWLoc, Template: TemplateId->Template, TemplateII: TemplateId->Name,
7327 TemplateIILoc: TemplateId->TemplateNameLoc, LAngleLoc: TemplateId->LAngleLoc, TemplateArgs: TemplateArgsPtr,
7328 RAngleLoc: TemplateId->RAngleLoc,
7329 /*IsCtorOrDtorName*/ true);
7330 if (T.isInvalid() || !T.get()) {
7331 // Recover by assuming we had the right type all along.
7332 DestructedType = ObjectType;
7333 } else
7334 DestructedType = GetTypeFromParser(Ty: T.get(), TInfo: &DestructedTypeInfo);
7335 }
7336
7337 // If we've performed some kind of recovery, (re-)build the type source
7338 // information.
7339 if (!DestructedType.isNull()) {
7340 if (!DestructedTypeInfo)
7341 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(T: DestructedType,
7342 Loc: SecondTypeName.StartLocation);
7343 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7344 }
7345
7346 // Convert the name of the scope type (the type prior to '::') into a type.
7347 TypeSourceInfo *ScopeTypeInfo = nullptr;
7348 QualType ScopeType;
7349 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7350 FirstTypeName.Identifier) {
7351 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7352 ParsedType T = getTypeName(II: *FirstTypeName.Identifier,
7353 NameLoc: FirstTypeName.StartLocation,
7354 S, SS: &SS, isClassName: true, HasTrailingDot: false, ObjectType: ObjectTypePtrForLookup,
7355 /*IsCtorOrDtorName*/true);
7356 if (!T) {
7357 Diag(Loc: FirstTypeName.StartLocation,
7358 DiagID: diag::err_pseudo_dtor_destructor_non_type)
7359 << FirstTypeName.Identifier << ObjectType;
7360
7361 if (isSFINAEContext())
7362 return ExprError();
7363
7364 // Just drop this type. It's unnecessary anyway.
7365 ScopeType = QualType();
7366 } else
7367 ScopeType = GetTypeFromParser(Ty: T, TInfo: &ScopeTypeInfo);
7368 } else {
7369 // Resolve the template-id to a type.
7370 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7371 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7372 TemplateId->NumArgs);
7373 TypeResult T = ActOnTemplateIdType(
7374 S, ElaboratedKeyword: ElaboratedTypeKeyword::None,
7375 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
7376 TemplateKWLoc: TemplateId->TemplateKWLoc, Template: TemplateId->Template, TemplateII: TemplateId->Name,
7377 TemplateIILoc: TemplateId->TemplateNameLoc, LAngleLoc: TemplateId->LAngleLoc, TemplateArgs: TemplateArgsPtr,
7378 RAngleLoc: TemplateId->RAngleLoc,
7379 /*IsCtorOrDtorName*/ true);
7380 if (T.isInvalid() || !T.get()) {
7381 // Recover by dropping this type.
7382 ScopeType = QualType();
7383 } else
7384 ScopeType = GetTypeFromParser(Ty: T.get(), TInfo: &ScopeTypeInfo);
7385 }
7386 }
7387
7388 if (!ScopeType.isNull() && !ScopeTypeInfo)
7389 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(T: ScopeType,
7390 Loc: FirstTypeName.StartLocation);
7391
7392
7393 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7394 ScopeTypeInfo, CCLoc, TildeLoc,
7395 Destructed);
7396}
7397
7398ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7399 SourceLocation OpLoc,
7400 tok::TokenKind OpKind,
7401 SourceLocation TildeLoc,
7402 const DeclSpec& DS) {
7403 QualType ObjectType;
7404 QualType T;
7405 TypeLocBuilder TLB;
7406 if (CheckArrow(S&: *this, ObjectType, Base, OpKind, OpLoc) ||
7407 DS.getTypeSpecType() == DeclSpec::TST_error)
7408 return ExprError();
7409
7410 switch (DS.getTypeSpecType()) {
7411 case DeclSpec::TST_decltype_auto: {
7412 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
7413 return true;
7414 }
7415 case DeclSpec::TST_decltype: {
7416 T = BuildDecltypeType(E: DS.getRepAsExpr(), /*AsUnevaluated=*/false);
7417 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7418 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
7419 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
7420 break;
7421 }
7422 case DeclSpec::TST_typename_pack_indexing: {
7423 T = ActOnPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
7424 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
7425 TLB.pushTrivial(Context&: getASTContext(),
7426 T: cast<PackIndexingType>(Val: T.getTypePtr())->getPattern(),
7427 Loc: DS.getBeginLoc());
7428 PackIndexingTypeLoc PITL = TLB.push<PackIndexingTypeLoc>(T);
7429 PITL.setEllipsisLoc(DS.getEllipsisLoc());
7430 break;
7431 }
7432 default:
7433 llvm_unreachable("Unsupported type in pseudo destructor");
7434 }
7435 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7436 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7437
7438 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS: CXXScopeSpec(),
7439 ScopeTypeInfo: nullptr, CCLoc: SourceLocation(), TildeLoc,
7440 Destructed);
7441}
7442
7443ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7444 SourceLocation RParen) {
7445 // If the operand is an unresolved lookup expression, the expression is ill-
7446 // formed per [over.over]p1, because overloaded function names cannot be used
7447 // without arguments except in explicit contexts.
7448 ExprResult R = CheckPlaceholderExpr(E: Operand);
7449 if (R.isInvalid())
7450 return R;
7451
7452 R = CheckUnevaluatedOperand(E: R.get());
7453 if (R.isInvalid())
7454 return ExprError();
7455
7456 Operand = R.get();
7457
7458 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
7459 Operand->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) {
7460 // The expression operand for noexcept is in an unevaluated expression
7461 // context, so side effects could result in unintended consequences.
7462 Diag(Loc: Operand->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
7463 }
7464
7465 CanThrowResult CanThrow = canThrow(E: Operand);
7466 return new (Context)
7467 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7468}
7469
7470ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7471 Expr *Operand, SourceLocation RParen) {
7472 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7473}
7474
7475static void MaybeDecrementCount(
7476 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
7477 DeclRefExpr *LHS = nullptr;
7478 bool IsCompoundAssign = false;
7479 bool isIncrementDecrementUnaryOp = false;
7480 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
7481 if (BO->getLHS()->getType()->isDependentType() ||
7482 BO->getRHS()->getType()->isDependentType()) {
7483 if (BO->getOpcode() != BO_Assign)
7484 return;
7485 } else if (!BO->isAssignmentOp())
7486 return;
7487 else
7488 IsCompoundAssign = BO->isCompoundAssignmentOp();
7489 LHS = dyn_cast<DeclRefExpr>(Val: BO->getLHS());
7490 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
7491 if (COCE->getOperator() != OO_Equal)
7492 return;
7493 LHS = dyn_cast<DeclRefExpr>(Val: COCE->getArg(Arg: 0));
7494 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E)) {
7495 if (!UO->isIncrementDecrementOp())
7496 return;
7497 isIncrementDecrementUnaryOp = true;
7498 LHS = dyn_cast<DeclRefExpr>(Val: UO->getSubExpr());
7499 }
7500 if (!LHS)
7501 return;
7502 VarDecl *VD = dyn_cast<VarDecl>(Val: LHS->getDecl());
7503 if (!VD)
7504 return;
7505 // Don't decrement RefsMinusAssignments if volatile variable with compound
7506 // assignment (+=, ...) or increment/decrement unary operator to avoid
7507 // potential unused-but-set-variable warning.
7508 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
7509 VD->getType().isVolatileQualified())
7510 return;
7511 auto iter = RefsMinusAssignments.find(Val: VD->getCanonicalDecl());
7512 if (iter == RefsMinusAssignments.end())
7513 return;
7514 iter->getSecond()--;
7515}
7516
7517/// Perform the conversions required for an expression used in a
7518/// context that ignores the result.
7519ExprResult Sema::IgnoredValueConversions(Expr *E) {
7520 MaybeDecrementCount(E, RefsMinusAssignments);
7521
7522 if (E->hasPlaceholderType()) {
7523 ExprResult result = CheckPlaceholderExpr(E);
7524 if (result.isInvalid()) return E;
7525 E = result.get();
7526 }
7527
7528 if (getLangOpts().CPlusPlus) {
7529 // The C++11 standard defines the notion of a discarded-value expression;
7530 // normally, we don't need to do anything to handle it, but if it is a
7531 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7532 // conversion.
7533 if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {
7534 ExprResult Res = DefaultLvalueConversion(E);
7535 if (Res.isInvalid())
7536 return E;
7537 E = Res.get();
7538 } else {
7539 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7540 // it occurs as a discarded-value expression.
7541 CheckUnusedVolatileAssignment(E);
7542 }
7543
7544 // C++1z:
7545 // If the expression is a prvalue after this optional conversion, the
7546 // temporary materialization conversion is applied.
7547 //
7548 // We do not materialize temporaries by default in order to avoid creating
7549 // unnecessary temporary objects. If we skip this step, IR generation is
7550 // able to synthesize the storage for itself in the aggregate case, and
7551 // adding the extra node to the AST is just clutter.
7552 if (isInLifetimeExtendingContext() && getLangOpts().CPlusPlus17 &&
7553 E->isPRValue() && !E->getType()->isVoidType()) {
7554 ExprResult Res = TemporaryMaterializationConversion(E);
7555 if (Res.isInvalid())
7556 return E;
7557 E = Res.get();
7558 }
7559 return E;
7560 }
7561
7562 // C99 6.3.2.1:
7563 // [Except in specific positions,] an lvalue that does not have
7564 // array type is converted to the value stored in the
7565 // designated object (and is no longer an lvalue).
7566 if (E->isPRValue()) {
7567 // In C, function designators (i.e. expressions of function type)
7568 // are r-values, but we still want to do function-to-pointer decay
7569 // on them. This is both technically correct and convenient for
7570 // some clients.
7571 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7572 return DefaultFunctionArrayConversion(E);
7573
7574 return E;
7575 }
7576
7577 // GCC seems to also exclude expressions of incomplete enum type.
7578 if (const auto *ED = E->getType()->getAsEnumDecl(); ED && !ED->isComplete()) {
7579 // FIXME: stupid workaround for a codegen bug!
7580 E = ImpCastExprToType(E, Type: Context.VoidTy, CK: CK_ToVoid).get();
7581 return E;
7582 }
7583
7584 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7585 if (Res.isInvalid())
7586 return E;
7587 E = Res.get();
7588
7589 if (!E->getType()->isVoidType())
7590 RequireCompleteType(Loc: E->getExprLoc(), T: E->getType(),
7591 DiagID: diag::err_incomplete_type);
7592 return E;
7593}
7594
7595ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
7596 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7597 // it occurs as an unevaluated operand.
7598 CheckUnusedVolatileAssignment(E);
7599
7600 return E;
7601}
7602
7603// If we can unambiguously determine whether Var can never be used
7604// in a constant expression, return true.
7605// - if the variable and its initializer are non-dependent, then
7606// we can unambiguously check if the variable is a constant expression.
7607// - if the initializer is not value dependent - we can determine whether
7608// it can be used to initialize a constant expression. If Init can not
7609// be used to initialize a constant expression we conclude that Var can
7610// never be a constant expression.
7611// - FXIME: if the initializer is dependent, we can still do some analysis and
7612// identify certain cases unambiguously as non-const by using a Visitor:
7613// - such as those that involve odr-use of a ParmVarDecl, involve a new
7614// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7615static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7616 ASTContext &Context) {
7617 if (isa<ParmVarDecl>(Val: Var)) return true;
7618 const VarDecl *DefVD = nullptr;
7619
7620 // If there is no initializer - this can not be a constant expression.
7621 const Expr *Init = Var->getAnyInitializer(D&: DefVD);
7622 if (!Init)
7623 return true;
7624 assert(DefVD);
7625 if (DefVD->isWeak())
7626 return false;
7627
7628 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7629 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7630 // of value-dependent expressions, and use it here to determine whether the
7631 // initializer is a potential constant expression.
7632 return false;
7633 }
7634
7635 return !Var->isUsableInConstantExpressions(C: Context);
7636}
7637
7638/// Check if the current lambda has any potential captures
7639/// that must be captured by any of its enclosing lambdas that are ready to
7640/// capture. If there is a lambda that can capture a nested
7641/// potential-capture, go ahead and do so. Also, check to see if any
7642/// variables are uncaptureable or do not involve an odr-use so do not
7643/// need to be captured.
7644
7645static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7646 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7647
7648 assert(!S.isUnevaluatedContext());
7649 assert(S.CurContext->isDependentContext());
7650#ifndef NDEBUG
7651 DeclContext *DC = S.CurContext;
7652 while (isa_and_nonnull<CapturedDecl>(DC))
7653 DC = DC->getParent();
7654 assert(
7655 (CurrentLSI->CallOperator == DC || !CurrentLSI->AfterParameterList) &&
7656 "The current call operator must be synchronized with Sema's CurContext");
7657#endif // NDEBUG
7658
7659 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7660
7661 // All the potentially captureable variables in the current nested
7662 // lambda (within a generic outer lambda), must be captured by an
7663 // outer lambda that is enclosed within a non-dependent context.
7664 CurrentLSI->visitPotentialCaptures(Callback: [&](ValueDecl *Var, Expr *VarExpr) {
7665 // If the variable is clearly identified as non-odr-used and the full
7666 // expression is not instantiation dependent, only then do we not
7667 // need to check enclosing lambda's for speculative captures.
7668 // For e.g.:
7669 // Even though 'x' is not odr-used, it should be captured.
7670 // int test() {
7671 // const int x = 10;
7672 // auto L = [=](auto a) {
7673 // (void) +x + a;
7674 // };
7675 // }
7676 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(CapturingVarExpr: VarExpr) &&
7677 !IsFullExprInstantiationDependent)
7678 return;
7679
7680 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
7681 if (!UnderlyingVar)
7682 return;
7683
7684 // If we have a capture-capable lambda for the variable, go ahead and
7685 // capture the variable in that lambda (and all its enclosing lambdas).
7686 if (const UnsignedOrNone Index =
7687 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7688 FunctionScopes: S.FunctionScopes, VarToCapture: Var, S))
7689 S.MarkCaptureUsedInEnclosingContext(Capture: Var, Loc: VarExpr->getExprLoc(), CapturingScopeIndex: *Index);
7690 const bool IsVarNeverAConstantExpression =
7691 VariableCanNeverBeAConstantExpression(Var: UnderlyingVar, Context&: S.Context);
7692 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7693 // This full expression is not instantiation dependent or the variable
7694 // can not be used in a constant expression - which means
7695 // this variable must be odr-used here, so diagnose a
7696 // capture violation early, if the variable is un-captureable.
7697 // This is purely for diagnosing errors early. Otherwise, this
7698 // error would get diagnosed when the lambda becomes capture ready.
7699 QualType CaptureType, DeclRefType;
7700 SourceLocation ExprLoc = VarExpr->getExprLoc();
7701 if (S.tryCaptureVariable(Var, Loc: ExprLoc, Kind: TryCaptureKind::Implicit,
7702 /*EllipsisLoc*/ SourceLocation(),
7703 /*BuildAndDiagnose*/ false, CaptureType,
7704 DeclRefType, FunctionScopeIndexToStopAt: nullptr)) {
7705 // We will never be able to capture this variable, and we need
7706 // to be able to in any and all instantiations, so diagnose it.
7707 S.tryCaptureVariable(Var, Loc: ExprLoc, Kind: TryCaptureKind::Implicit,
7708 /*EllipsisLoc*/ SourceLocation(),
7709 /*BuildAndDiagnose*/ true, CaptureType,
7710 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
7711 }
7712 }
7713 });
7714
7715 // Check if 'this' needs to be captured.
7716 if (CurrentLSI->hasPotentialThisCapture()) {
7717 // If we have a capture-capable lambda for 'this', go ahead and capture
7718 // 'this' in that lambda (and all its enclosing lambdas).
7719 if (const UnsignedOrNone Index =
7720 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7721 FunctionScopes: S.FunctionScopes, /*0 is 'this'*/ VarToCapture: nullptr, S)) {
7722 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
7723 S.CheckCXXThisCapture(Loc: CurrentLSI->PotentialThisCaptureLocation,
7724 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7725 FunctionScopeIndexToStopAt: &FunctionScopeIndexOfCapturableLambda);
7726 }
7727 }
7728
7729 // Reset all the potential captures at the end of each full-expression.
7730 CurrentLSI->clearPotentialCaptures();
7731}
7732
7733ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
7734 bool DiscardedValue, bool IsConstexpr,
7735 bool IsTemplateArgument) {
7736 ExprResult FullExpr = FE;
7737
7738 if (!FullExpr.get())
7739 return ExprError();
7740
7741 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(E: FullExpr.get()))
7742 return ExprError();
7743
7744 if (DiscardedValue) {
7745 // Top-level expressions default to 'id' when we're in a debugger.
7746 if (getLangOpts().DebuggerCastResultToId &&
7747 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7748 FullExpr = forceUnknownAnyToType(E: FullExpr.get(), ToType: Context.getObjCIdType());
7749 if (FullExpr.isInvalid())
7750 return ExprError();
7751 }
7752
7753 FullExpr = CheckPlaceholderExpr(E: FullExpr.get());
7754 if (FullExpr.isInvalid())
7755 return ExprError();
7756
7757 FullExpr = IgnoredValueConversions(E: FullExpr.get());
7758 if (FullExpr.isInvalid())
7759 return ExprError();
7760
7761 DiagnoseUnusedExprResult(S: FullExpr.get(), DiagID: diag::warn_unused_expr);
7762 }
7763
7764 if (FullExpr.isInvalid())
7765 return ExprError();
7766
7767 CheckCompletedExpr(E: FullExpr.get(), CheckLoc: CC, IsConstexpr);
7768
7769 // At the end of this full expression (which could be a deeply nested
7770 // lambda), if there is a potential capture within the nested lambda,
7771 // have the outer capture-able lambda try and capture it.
7772 // Consider the following code:
7773 // void f(int, int);
7774 // void f(const int&, double);
7775 // void foo() {
7776 // const int x = 10, y = 20;
7777 // auto L = [=](auto a) {
7778 // auto M = [=](auto b) {
7779 // f(x, b); <-- requires x to be captured by L and M
7780 // f(y, a); <-- requires y to be captured by L, but not all Ms
7781 // };
7782 // };
7783 // }
7784
7785 // FIXME: Also consider what happens for something like this that involves
7786 // the gnu-extension statement-expressions or even lambda-init-captures:
7787 // void f() {
7788 // const int n = 0;
7789 // auto L = [&](auto a) {
7790 // +n + ({ 0; a; });
7791 // };
7792 // }
7793 //
7794 // Here, we see +n, and then the full-expression 0; ends, so we don't
7795 // capture n (and instead remove it from our list of potential captures),
7796 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7797 // for us to see that we need to capture n after all.
7798
7799 LambdaScopeInfo *const CurrentLSI =
7800 getCurLambda(/*IgnoreCapturedRegions=*/IgnoreNonLambdaCapturingScope: true);
7801 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7802 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7803 // for an example of the code that might cause this asynchrony.
7804 // By ensuring we are in the context of a lambda's call operator
7805 // we can fix the bug (we only need to check whether we need to capture
7806 // if we are within a lambda's body); but per the comments in that
7807 // PR, a proper fix would entail :
7808 // "Alternative suggestion:
7809 // - Add to Sema an integer holding the smallest (outermost) scope
7810 // index that we are *lexically* within, and save/restore/set to
7811 // FunctionScopes.size() in InstantiatingTemplate's
7812 // constructor/destructor.
7813 // - Teach the handful of places that iterate over FunctionScopes to
7814 // stop at the outermost enclosing lexical scope."
7815 DeclContext *DC = CurContext;
7816 while (isa_and_nonnull<CapturedDecl>(Val: DC))
7817 DC = DC->getParent();
7818 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7819 if (IsInLambdaDeclContext && CurrentLSI &&
7820 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7821 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7822 S&: *this);
7823 return MaybeCreateExprWithCleanups(SubExpr: FullExpr);
7824}
7825
7826StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7827 if (!FullStmt) return StmtError();
7828
7829 return MaybeCreateStmtWithCleanups(SubStmt: FullStmt);
7830}
7831
7832IfExistsResult
7833Sema::CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
7834 const DeclarationNameInfo &TargetNameInfo) {
7835 DeclarationName TargetName = TargetNameInfo.getName();
7836 if (!TargetName)
7837 return IfExistsResult::DoesNotExist;
7838
7839 // If the name itself is dependent, then the result is dependent.
7840 if (TargetName.isDependentName())
7841 return IfExistsResult::Dependent;
7842
7843 // Do the redeclaration lookup in the current scope.
7844 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7845 RedeclarationKind::NotForRedeclaration);
7846 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
7847 R.suppressDiagnostics();
7848
7849 switch (R.getResultKind()) {
7850 case LookupResultKind::Found:
7851 case LookupResultKind::FoundOverloaded:
7852 case LookupResultKind::FoundUnresolvedValue:
7853 case LookupResultKind::Ambiguous:
7854 return IfExistsResult::Exists;
7855
7856 case LookupResultKind::NotFound:
7857 return IfExistsResult::DoesNotExist;
7858
7859 case LookupResultKind::NotFoundInCurrentInstantiation:
7860 return IfExistsResult::Dependent;
7861 }
7862
7863 llvm_unreachable("Invalid LookupResult Kind!");
7864}
7865
7866IfExistsResult Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7867 SourceLocation KeywordLoc,
7868 bool IsIfExists,
7869 CXXScopeSpec &SS,
7870 UnqualifiedId &Name) {
7871 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7872
7873 // Check for an unexpanded parameter pack.
7874 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7875 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7876 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC))
7877 return IfExistsResult::Error;
7878
7879 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7880}
7881
7882concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
7883 return BuildExprRequirement(E, /*IsSimple=*/IsSatisfied: true,
7884 /*NoexceptLoc=*/SourceLocation(),
7885 /*ReturnTypeRequirement=*/{});
7886}
7887
7888concepts::Requirement *Sema::ActOnTypeRequirement(
7889 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7890 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
7891 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
7892 "Exactly one of TypeName and TemplateId must be specified.");
7893 TypeSourceInfo *TSI = nullptr;
7894 if (TypeName) {
7895 QualType T =
7896 CheckTypenameType(Keyword: ElaboratedTypeKeyword::Typename, KeywordLoc: TypenameKWLoc,
7897 QualifierLoc: SS.getWithLocInContext(Context), II: *TypeName, IILoc: NameLoc,
7898 TSI: &TSI, /*DeducedTSTContext=*/false);
7899 if (T.isNull())
7900 return nullptr;
7901 } else {
7902 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
7903 TemplateId->NumArgs);
7904 TypeResult T = ActOnTypenameType(S: CurScope, TypenameLoc: TypenameKWLoc, SS,
7905 TemplateLoc: TemplateId->TemplateKWLoc,
7906 TemplateName: TemplateId->Template, TemplateII: TemplateId->Name,
7907 TemplateIILoc: TemplateId->TemplateNameLoc,
7908 LAngleLoc: TemplateId->LAngleLoc, TemplateArgs: ArgsPtr,
7909 RAngleLoc: TemplateId->RAngleLoc);
7910 if (T.isInvalid())
7911 return nullptr;
7912 if (GetTypeFromParser(Ty: T.get(), TInfo: &TSI).isNull())
7913 return nullptr;
7914 }
7915 return BuildTypeRequirement(Type: TSI);
7916}
7917
7918concepts::Requirement *
7919Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
7920 return BuildExprRequirement(E, /*IsSimple=*/IsSatisfied: false, NoexceptLoc,
7921 /*ReturnTypeRequirement=*/{});
7922}
7923
7924concepts::Requirement *
7925Sema::ActOnCompoundRequirement(
7926 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7927 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
7928 // C++2a [expr.prim.req.compound] p1.3.3
7929 // [..] the expression is deduced against an invented function template
7930 // F [...] F is a void function template with a single type template
7931 // parameter T declared with the constrained-parameter. Form a new
7932 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
7933 // around the constrained-parameter. F has a single parameter whose
7934 // type-specifier is cv T followed by the abstract-declarator. [...]
7935 //
7936 // The cv part is done in the calling function - we get the concept with
7937 // arguments and the abstract declarator with the correct CV qualification and
7938 // have to synthesize T and the single parameter of F.
7939 auto &II = Context.Idents.get(Name: "expr-type");
7940 auto *TParam = TemplateTypeParmDecl::Create(C: Context, DC: CurContext,
7941 KeyLoc: SourceLocation(),
7942 NameLoc: SourceLocation(), D: Depth,
7943 /*Index=*/P: 0, Id: &II,
7944 /*Typename=*/true,
7945 /*ParameterPack=*/false,
7946 /*HasTypeConstraint=*/true);
7947
7948 if (BuildTypeConstraint(SS, TypeConstraint, ConstrainedParameter: TParam,
7949 /*EllipsisLoc=*/SourceLocation(),
7950 /*AllowUnexpandedPack=*/true))
7951 // Just produce a requirement with no type requirements.
7952 return BuildExprRequirement(E, /*IsSimple=*/IsSatisfied: false, NoexceptLoc, ReturnTypeRequirement: {});
7953
7954 auto *TPL = TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
7955 LAngleLoc: SourceLocation(),
7956 Params: ArrayRef<NamedDecl *>(TParam),
7957 RAngleLoc: SourceLocation(),
7958 /*RequiresClause=*/nullptr);
7959 return BuildExprRequirement(
7960 E, /*IsSimple=*/IsSatisfied: false, NoexceptLoc,
7961 ReturnTypeRequirement: concepts::ExprRequirement::ReturnTypeRequirement(TPL));
7962}
7963
7964concepts::ExprRequirement *
7965Sema::BuildExprRequirement(
7966 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
7967 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
7968 auto Status = concepts::ExprRequirement::SS_Satisfied;
7969 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
7970 if (E->isInstantiationDependent() || E->getType()->isPlaceholderType() ||
7971 ReturnTypeRequirement.isDependent())
7972 Status = concepts::ExprRequirement::SS_Dependent;
7973 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
7974 Status = concepts::ExprRequirement::SS_NoexceptNotMet;
7975 else if (ReturnTypeRequirement.isSubstitutionFailure())
7976 Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
7977 else if (ReturnTypeRequirement.isTypeConstraint()) {
7978 // C++2a [expr.prim.req]p1.3.3
7979 // The immediately-declared constraint ([temp]) of decltype((E)) shall
7980 // be satisfied.
7981 TemplateParameterList *TPL =
7982 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
7983 QualType MatchedType = Context.getReferenceQualifiedType(e: E);
7984 llvm::SmallVector<TemplateArgument, 1> Args;
7985 Args.push_back(Elt: TemplateArgument(MatchedType));
7986
7987 auto *Param = cast<TemplateTypeParmDecl>(Val: TPL->getParam(Idx: 0));
7988
7989 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/true);
7990 MLTAL.addOuterRetainedLevels(Num: TPL->getDepth());
7991 const TypeConstraint *TC = Param->getTypeConstraint();
7992 assert(TC && "Type Constraint cannot be null here");
7993 auto *IDC = TC->getImmediatelyDeclaredConstraint();
7994 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
7995 ExprResult Constraint = SubstExpr(E: IDC, TemplateArgs: MLTAL);
7996 bool HasError = Constraint.isInvalid();
7997 if (!HasError) {
7998 SubstitutedConstraintExpr =
7999 cast<ConceptSpecializationExpr>(Val: Constraint.get());
8000 if (SubstitutedConstraintExpr->getSatisfaction().ContainsErrors)
8001 HasError = true;
8002 }
8003 if (HasError) {
8004 return new (Context) concepts::ExprRequirement(
8005 createSubstDiagAt(Location: IDC->getExprLoc(),
8006 Printer: [&](llvm::raw_ostream &OS) {
8007 IDC->printPretty(OS, /*Helper=*/nullptr,
8008 Policy: getPrintingPolicy());
8009 }),
8010 IsSimple, NoexceptLoc, ReturnTypeRequirement);
8011 }
8012 if (!SubstitutedConstraintExpr->isSatisfied())
8013 Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
8014 }
8015 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
8016 ReturnTypeRequirement, Status,
8017 SubstitutedConstraintExpr);
8018}
8019
8020concepts::ExprRequirement *
8021Sema::BuildExprRequirement(
8022 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
8023 bool IsSimple, SourceLocation NoexceptLoc,
8024 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8025 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
8026 IsSimple, NoexceptLoc,
8027 ReturnTypeRequirement);
8028}
8029
8030concepts::TypeRequirement *
8031Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
8032 return new (Context) concepts::TypeRequirement(Type);
8033}
8034
8035concepts::TypeRequirement *
8036Sema::BuildTypeRequirement(
8037 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8038 return new (Context) concepts::TypeRequirement(SubstDiag);
8039}
8040
8041concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
8042 return BuildNestedRequirement(E: Constraint);
8043}
8044
8045concepts::NestedRequirement *
8046Sema::BuildNestedRequirement(Expr *Constraint) {
8047 ConstraintSatisfaction Satisfaction;
8048 LocalInstantiationScope Scope(*this);
8049 if (!Constraint->isInstantiationDependent() &&
8050 !Constraint->isValueDependent() &&
8051 CheckConstraintSatisfaction(Entity: nullptr, AssociatedConstraints: AssociatedConstraint(Constraint),
8052 /*TemplateArgs=*/TemplateArgLists: {},
8053 TemplateIDRange: Constraint->getSourceRange(), Satisfaction))
8054 return nullptr;
8055 return new (Context) concepts::NestedRequirement(Context, Constraint,
8056 Satisfaction);
8057}
8058
8059concepts::NestedRequirement *
8060Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
8061 const ASTConstraintSatisfaction &Satisfaction) {
8062 return new (Context) concepts::NestedRequirement(
8063 InvalidConstraintEntity,
8064 ASTConstraintSatisfaction::Rebuild(C: Context, Satisfaction));
8065}
8066
8067RequiresExprBodyDecl *
8068Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8069 ArrayRef<ParmVarDecl *> LocalParameters,
8070 Scope *BodyScope) {
8071 assert(BodyScope);
8072
8073 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(C&: Context, DC: CurContext,
8074 StartLoc: RequiresKWLoc);
8075
8076 PushDeclContext(S: BodyScope, DC: Body);
8077
8078 for (ParmVarDecl *Param : LocalParameters) {
8079 if (Param->getType()->isVoidType()) {
8080 if (LocalParameters.size() > 1) {
8081 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_void_only_param);
8082 Param->setType(Context.IntTy);
8083 } else if (Param->getIdentifier()) {
8084 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_param_with_void_type);
8085 Param->setType(Context.IntTy);
8086 } else if (Param->getType().hasQualifiers()) {
8087 Diag(Loc: Param->getBeginLoc(), DiagID: diag::err_void_param_qualified);
8088 }
8089 } else if (Param->hasDefaultArg()) {
8090 // C++2a [expr.prim.req] p4
8091 // [...] A local parameter of a requires-expression shall not have a
8092 // default argument. [...]
8093 Diag(Loc: Param->getDefaultArgRange().getBegin(),
8094 DiagID: diag::err_requires_expr_local_parameter_default_argument);
8095 // Ignore default argument and move on
8096 } else if (Param->isExplicitObjectParameter()) {
8097 // C++23 [dcl.fct]p6:
8098 // An explicit-object-parameter-declaration is a parameter-declaration
8099 // with a this specifier. An explicit-object-parameter-declaration
8100 // shall appear only as the first parameter-declaration of a
8101 // parameter-declaration-list of either:
8102 // - a member-declarator that declares a member function, or
8103 // - a lambda-declarator.
8104 //
8105 // The parameter-declaration-list of a requires-expression is not such
8106 // a context.
8107 Diag(Loc: Param->getExplicitObjectParamThisLoc(),
8108 DiagID: diag::err_requires_expr_explicit_object_parameter);
8109 Param->setExplicitObjectParameterLoc(SourceLocation());
8110 }
8111
8112 Param->setDeclContext(Body);
8113 // If this has an identifier, add it to the scope stack.
8114 if (Param->getIdentifier()) {
8115 CheckShadow(S: BodyScope, D: Param);
8116 PushOnScopeChains(D: Param, S: BodyScope);
8117 }
8118 }
8119 return Body;
8120}
8121
8122void Sema::ActOnFinishRequiresExpr() {
8123 assert(CurContext && "DeclContext imbalance!");
8124 CurContext = CurContext->getLexicalParent();
8125 assert(CurContext && "Popped translation unit!");
8126}
8127
8128ExprResult Sema::ActOnRequiresExpr(
8129 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
8130 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
8131 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
8132 SourceLocation ClosingBraceLoc) {
8133 auto *RE = RequiresExpr::Create(C&: Context, RequiresKWLoc, Body, LParenLoc,
8134 LocalParameters, RParenLoc, Requirements,
8135 RBraceLoc: ClosingBraceLoc);
8136 if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))
8137 return ExprError();
8138 return RE;
8139}
8140