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