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