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