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