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