Thanks to visit codestin.com
Credit goes to clang.llvm.org

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