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