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