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