clang 24.0.0git
SemaExprCXX.cpp
Go to the documentation of this file.
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Implements semantic analysis for C++ expressions.
11///
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
17#include "clang/AST/ASTLambda.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/Type.h"
27#include "clang/AST/TypeLoc.h"
34#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/Lookup.h"
39#include "clang/Sema/Scope.h"
41#include "clang/Sema/SemaCUDA.h"
42#include "clang/Sema/SemaHLSL.h"
44#include "clang/Sema/SemaObjC.h"
45#include "clang/Sema/SemaPPC.h"
46#include "clang/Sema/Template.h"
48#include "llvm/ADT/APInt.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/ADT/StringExtras.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/TypeSize.h"
53#include <optional>
54using namespace clang;
55using namespace sema;
56
58 SourceLocation NameLoc,
59 const IdentifierInfo &Name) {
61 QualType Type(NNS.getAsType(), 0);
62 if ([[maybe_unused]] const auto *DNT = dyn_cast<DependentNameType>(Type))
63 assert(DNT->getIdentifier() == &Name && "not a constructor name");
64
65 // This reference to the type is located entirely at the location of the
66 // final identifier in the qualified-id.
68 Context.getTrivialTypeSourceInfo(Type, NameLoc));
69}
70
72 SourceLocation NameLoc, Scope *S,
73 CXXScopeSpec &SS, bool EnteringContext) {
74 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
75 assert(CurClass && &II == CurClass->getIdentifier() &&
76 "not a constructor name");
77
78 // When naming a constructor as a member of a dependent context (eg, in a
79 // friend declaration or an inherited constructor declaration), form an
80 // unresolved "typename" type.
81 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
82 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
83 SS.getScopeRep(), &II);
84 return ParsedType::make(T);
85 }
86
87 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
88 return ParsedType();
89
90 // Find the injected-class-name declaration. Note that we make no attempt to
91 // diagnose cases where the injected-class-name is shadowed: the only
92 // declaration that can validly shadow the injected-class-name is a
93 // non-static data member, and if the class contains both a non-static data
94 // member and a constructor then it is ill-formed (we check that in
95 // CheckCompletedCXXClass).
96 CXXRecordDecl *InjectedClassName = nullptr;
97 for (NamedDecl *ND : CurClass->lookup(&II)) {
98 auto *RD = dyn_cast<CXXRecordDecl>(ND);
99 if (RD && RD->isInjectedClassName()) {
100 InjectedClassName = RD;
101 break;
102 }
103 }
104 if (!InjectedClassName) {
105 if (!CurClass->isInvalidDecl()) {
106 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
107 // properly. Work around it here for now.
109 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
110 }
111 return ParsedType();
112 }
113
115 InjectedClassName, /*OwnsTag=*/false);
116 return ParsedType::make(T);
117}
118
120 SourceLocation NameLoc, Scope *S,
121 CXXScopeSpec &SS, ParsedType ObjectTypePtr,
122 bool EnteringContext) {
123 // Determine where to perform name lookup.
124
125 // FIXME: This area of the standard is very messy, and the current
126 // wording is rather unclear about which scopes we search for the
127 // destructor name; see core issues 399 and 555. Issue 399 in
128 // particular shows where the current description of destructor name
129 // lookup is completely out of line with existing practice, e.g.,
130 // this appears to be ill-formed:
131 //
132 // namespace N {
133 // template <typename T> struct S {
134 // ~S();
135 // };
136 // }
137 //
138 // void f(N::S<int>* s) {
139 // s->N::S<int>::~S();
140 // }
141 //
142 // See also PR6358 and PR6359.
143 //
144 // For now, we accept all the cases in which the name given could plausibly
145 // be interpreted as a correct destructor name, issuing off-by-default
146 // extension diagnostics on the cases that don't strictly conform to the
147 // C++20 rules. This basically means we always consider looking in the
148 // nested-name-specifier prefix, the complete nested-name-specifier, and
149 // the scope, and accept if we find the expected type in any of the three
150 // places.
151
152 if (SS.isInvalid())
153 return nullptr;
154
155 // Whether we've failed with a diagnostic already.
156 bool Failed = false;
157
160
161 // If we have an object type, it's because we are in a
162 // pseudo-destructor-expression or a member access expression, and
163 // we know what type we're looking for.
164 QualType SearchType =
165 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
166
167 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
168 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
169 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
170 if (!Type)
171 return false;
172
173 if (SearchType.isNull() || SearchType->isDependentType())
174 return true;
175
176 CanQualType T = Context.getCanonicalTypeDeclType(Type);
177 return Context.hasSameUnqualifiedType(T, SearchType);
178 };
179
180 unsigned NumAcceptableResults = 0;
181 for (NamedDecl *D : Found) {
182 if (IsAcceptableResult(D))
183 ++NumAcceptableResults;
184
185 // Don't list a class twice in the lookup failure diagnostic if it's
186 // found by both its injected-class-name and by the name in the enclosing
187 // scope.
188 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
189 if (RD->isInjectedClassName())
190 D = cast<NamedDecl>(RD->getParent());
191
192 if (FoundDeclSet.insert(D).second)
193 FoundDecls.push_back(D);
194 }
195
196 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
197 // results, and all non-matching results if we have a search type. It's not
198 // clear what the right behavior is if destructor lookup hits an ambiguity,
199 // but other compilers do generally accept at least some kinds of
200 // ambiguity.
201 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
202 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
203 LookupResult::Filter F = Found.makeFilter();
204 while (F.hasNext()) {
205 NamedDecl *D = F.next();
206 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
207 Diag(D->getLocation(), diag::note_destructor_type_here)
208 << Context.getTypeDeclType(ElaboratedTypeKeyword::None,
209 /*Qualifier=*/std::nullopt, TD);
210 else
211 Diag(D->getLocation(), diag::note_destructor_nontype_here);
212
213 if (!IsAcceptableResult(D))
214 F.erase();
215 }
216 F.done();
217 }
218
219 if (Found.isAmbiguous())
220 Failed = true;
221
222 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
223 if (IsAcceptableResult(Type)) {
225 /*Qualifier=*/std::nullopt, Type);
226 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
227 return CreateParsedType(T,
228 Context.getTrivialTypeSourceInfo(T, NameLoc));
229 }
230 }
231
232 return nullptr;
233 };
234
235 bool IsDependent = false;
236
237 auto LookupInObjectType = [&]() -> ParsedType {
238 if (Failed || SearchType.isNull())
239 return nullptr;
240
241 IsDependent |= SearchType->isDependentType();
242
243 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
244 DeclContext *LookupCtx = computeDeclContext(SearchType);
245 if (!LookupCtx)
246 return nullptr;
247 LookupQualifiedName(Found, LookupCtx);
248 return CheckLookupResult(Found);
249 };
250
251 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
252 if (Failed)
253 return nullptr;
254
255 IsDependent |= isDependentScopeSpecifier(LookupSS);
256 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
257 if (!LookupCtx)
258 return nullptr;
259
260 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
261 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
262 Failed = true;
263 return nullptr;
264 }
265 LookupQualifiedName(Found, LookupCtx);
266 return CheckLookupResult(Found);
267 };
268
269 auto LookupInScope = [&]() -> ParsedType {
270 if (Failed || !S)
271 return nullptr;
272
273 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
274 LookupName(Found, S);
275 return CheckLookupResult(Found);
276 };
277
278 // C++2a [basic.lookup.qual]p6:
279 // In a qualified-id of the form
280 //
281 // nested-name-specifier[opt] type-name :: ~ type-name
282 //
283 // the second type-name is looked up in the same scope as the first.
284 //
285 // We interpret this as meaning that if you do a dual-scope lookup for the
286 // first name, you also do a dual-scope lookup for the second name, per
287 // C++ [basic.lookup.classref]p4:
288 //
289 // If the id-expression in a class member access is a qualified-id of the
290 // form
291 //
292 // class-name-or-namespace-name :: ...
293 //
294 // the class-name-or-namespace-name following the . or -> is first looked
295 // up in the class of the object expression and the name, if found, is used.
296 // Otherwise, it is looked up in the context of the entire
297 // postfix-expression.
298 //
299 // This looks in the same scopes as for an unqualified destructor name:
300 //
301 // C++ [basic.lookup.classref]p3:
302 // If the unqualified-id is ~ type-name, the type-name is looked up
303 // in the context of the entire postfix-expression. If the type T
304 // of the object expression is of a class type C, the type-name is
305 // also looked up in the scope of class C. At least one of the
306 // lookups shall find a name that refers to cv T.
307 //
308 // FIXME: The intent is unclear here. Should type-name::~type-name look in
309 // the scope anyway if it finds a non-matching name declared in the class?
310 // If both lookups succeed and find a dependent result, which result should
311 // we retain? (Same question for p->~type-name().)
312
313 auto Prefix = [&]() -> NestedNameSpecifierLoc {
315 if (!NNS)
316 return NestedNameSpecifierLoc();
317 if (auto TL = NNS.getAsTypeLoc())
318 return TL.getPrefix();
319 return NNS.getAsNamespaceAndPrefix().Prefix;
320 }();
321
322 if (Prefix) {
323 // This is
324 //
325 // nested-name-specifier type-name :: ~ type-name
326 //
327 // Look for the second type-name in the nested-name-specifier.
328 CXXScopeSpec PrefixSS;
329 PrefixSS.Adopt(Prefix);
330 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
331 return T;
332 } else {
333 // This is one of
334 //
335 // type-name :: ~ type-name
336 // ~ type-name
337 //
338 // Look in the scope and (if any) the object type.
339 if (ParsedType T = LookupInScope())
340 return T;
341 if (ParsedType T = LookupInObjectType())
342 return T;
343 }
344
345 if (Failed)
346 return nullptr;
347
348 if (IsDependent) {
349 // We didn't find our type, but that's OK: it's dependent anyway.
350
351 // FIXME: What if we have no nested-name-specifier?
352 TypeSourceInfo *TSI = nullptr;
353 QualType T =
355 SS.getWithLocInContext(Context), II, NameLoc, &TSI,
356 /*DeducedTSTContext=*/true);
357 if (T.isNull())
358 return ParsedType();
359 return CreateParsedType(T, TSI);
360 }
361
362 // The remaining cases are all non-standard extensions imitating the behavior
363 // of various other compilers.
364 unsigned NumNonExtensionDecls = FoundDecls.size();
365
366 if (SS.isSet()) {
367 // For compatibility with older broken C++ rules and existing code,
368 //
369 // nested-name-specifier :: ~ type-name
370 //
371 // also looks for type-name within the nested-name-specifier.
372 if (ParsedType T = LookupInNestedNameSpec(SS)) {
373 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
374 << SS.getRange()
376 ("::" + II.getName()).str());
377 return T;
378 }
379
380 // For compatibility with other compilers and older versions of Clang,
381 //
382 // nested-name-specifier type-name :: ~ type-name
383 //
384 // also looks for type-name in the scope. Unfortunately, we can't
385 // reasonably apply this fallback for dependent nested-name-specifiers.
386 if (Prefix) {
387 if (ParsedType T = LookupInScope()) {
388 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
390 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
392 return T;
393 }
394 }
395 }
396
397 // We didn't find anything matching; tell the user what we did find (if
398 // anything).
399
400 // Don't tell the user about declarations we shouldn't have found.
401 FoundDecls.resize(NumNonExtensionDecls);
402
403 // List types before non-types.
404 llvm::stable_sort(FoundDecls, [](NamedDecl *A, NamedDecl *B) {
405 return isa<TypeDecl>(A->getUnderlyingDecl()) >
407 });
408
409 // Suggest a fixit to properly name the destroyed type.
410 auto MakeFixItHint = [&]{
411 const CXXRecordDecl *Destroyed = nullptr;
412 // FIXME: If we have a scope specifier, suggest its last component?
413 if (!SearchType.isNull())
414 Destroyed = SearchType->getAsCXXRecordDecl();
415 else if (S)
416 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
417 if (Destroyed)
419 Destroyed->getNameAsString());
420 return FixItHint();
421 };
422
423 if (FoundDecls.empty()) {
424 // FIXME: Attempt typo-correction?
425 Diag(NameLoc, diag::err_undeclared_destructor_name)
426 << &II << MakeFixItHint();
427 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
428 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
429 assert(!SearchType.isNull() &&
430 "should only reject a type result if we have a search type");
431 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
432 << Context.getTypeDeclType(ElaboratedTypeKeyword::None,
433 /*Qualifier=*/std::nullopt, TD)
434 << SearchType << MakeFixItHint();
435 } else {
436 Diag(NameLoc, diag::err_destructor_expr_nontype)
437 << &II << MakeFixItHint();
438 }
439 } else {
440 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
441 : diag::err_destructor_expr_mismatch)
442 << &II << SearchType << MakeFixItHint();
443 }
444
445 for (NamedDecl *FoundD : FoundDecls) {
446 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
447 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
448 << Context.getTypeDeclType(ElaboratedTypeKeyword::None,
449 /*Qualifier=*/std::nullopt, TD);
450 else
451 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
452 << FoundD;
453 }
454
455 return nullptr;
456}
457
459 ParsedType ObjectType) {
461 return nullptr;
462
464 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
465 return nullptr;
466 }
467
469 "unexpected type in getDestructorType");
471
472 // If we know the type of the object, check that the correct destructor
473 // type was named now; we can give better diagnostics this way.
474 QualType SearchType = GetTypeFromParser(ObjectType);
475 if (!SearchType.isNull() && !SearchType->isDependentType() &&
476 !Context.hasSameUnqualifiedType(T, SearchType)) {
477 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
478 << T << SearchType;
479 return nullptr;
480 }
481
482 TypeLocBuilder TLB;
483 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
484 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
485 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
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 // If we're outside the body of a member function, then we'll have a specified
1491 // type for 'this'. Constraint substitution is the exception: a concept is
1492 // evaluated in its own declaration context (see GH#197215), so it loses the
1493 // enclosing '*this' even though it may legitimately name a member of the
1494 // class currently being instantiated.
1496 return false;
1497
1498 // Determine whether we're looking into a class that's currently being
1499 // defined.
1500 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1501 return Class && Class->isBeingDefined();
1502}
1503
1506 SourceLocation LParenOrBraceLoc,
1507 MultiExprArg exprs,
1508 SourceLocation RParenOrBraceLoc,
1509 bool ListInitialization) {
1510 if (!TypeRep)
1511 return ExprError();
1512
1513 TypeSourceInfo *TInfo;
1514 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1515 if (!TInfo)
1516 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1517
1518 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1519 RParenOrBraceLoc, ListInitialization);
1520 if (Result.isInvalid())
1522 RParenOrBraceLoc, exprs, Ty);
1523 return Result;
1524}
1525
1528 SourceLocation LParenOrBraceLoc,
1529 MultiExprArg Exprs,
1530 SourceLocation RParenOrBraceLoc,
1531 bool ListInitialization) {
1532 QualType Ty = TInfo->getType();
1533 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1534 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1535
1536 InitializedEntity Entity =
1538 InitializationKind Kind =
1539 Exprs.size()
1540 ? ListInitialization
1542 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1543 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1544 RParenOrBraceLoc)
1545 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1546 RParenOrBraceLoc);
1547
1548 // C++17 [expr.type.conv]p1:
1549 // If the type is a placeholder for a deduced class type, [...perform class
1550 // template argument deduction...]
1551 // C++23:
1552 // Otherwise, if the type contains a placeholder type, it is replaced by the
1553 // type determined by placeholder type deduction.
1554 DeducedType *Deduced = Ty->getContainedDeducedType();
1555 if (Deduced && !Deduced->isDeduced() &&
1558 Kind, Exprs);
1559 if (Ty.isNull())
1560 return ExprError();
1561 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1562 } else if (Deduced && !Deduced->isDeduced()) {
1563 MultiExprArg Inits = Exprs;
1564 if (ListInitialization) {
1565 auto *ILE = cast<InitListExpr>(Exprs[0]);
1566 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1567 }
1568
1569 if (Inits.empty())
1570 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1571 << Ty << FullRange);
1572 if (Inits.size() > 1) {
1573 Expr *FirstBad = Inits[1];
1574 return ExprError(Diag(FirstBad->getBeginLoc(),
1575 diag::err_auto_expr_init_multiple_expressions)
1576 << Ty << FullRange);
1577 }
1578 if (getLangOpts().CPlusPlus23) {
1579 if (Ty->getAs<AutoType>())
1580 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1581 }
1582 Expr *Deduce = Inits[0];
1583 if (isa<InitListExpr>(Deduce))
1584 return ExprError(
1585 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1586 << ListInitialization << Ty << FullRange);
1587 QualType DeducedType;
1588 TemplateDeductionInfo Info(Deduce->getExprLoc());
1590 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1593 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1594 << Ty << Deduce->getType() << FullRange
1595 << Deduce->getSourceRange());
1596 if (DeducedType.isNull()) {
1598 return ExprError();
1599 }
1600
1601 Ty = DeducedType;
1602 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1603 }
1604
1607 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1608 RParenOrBraceLoc, ListInitialization);
1609
1610 // C++ [expr.type.conv]p1:
1611 // If the expression list is a parenthesized single expression, the type
1612 // conversion expression is equivalent (in definedness, and if defined in
1613 // meaning) to the corresponding cast expression.
1614 if (Exprs.size() == 1 && !ListInitialization &&
1615 !isa<InitListExpr>(Exprs[0])) {
1616 Expr *Arg = Exprs[0];
1617 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1618 RParenOrBraceLoc);
1619 }
1620
1621 // For an expression of the form T(), T shall not be an array type.
1622 QualType ElemTy = Ty;
1623 if (Ty->isArrayType()) {
1624 if (!ListInitialization)
1625 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1626 << FullRange);
1627 ElemTy = Context.getBaseElementType(Ty);
1628 }
1629
1630 // Only construct objects with object types.
1631 // The standard doesn't explicitly forbid function types here, but that's an
1632 // obvious oversight, as there's no way to dynamically construct a function
1633 // in general.
1634 if (Ty->isFunctionType())
1635 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1636 << Ty << FullRange);
1637
1638 // C++17 [expr.type.conv]p2, per DR2351:
1639 // If the type is cv void and the initializer is () or {}, the expression is
1640 // a prvalue of the specified type that performs no initialization.
1641 if (Ty->isVoidType()) {
1642 if (Exprs.empty())
1643 return new (Context) CXXScalarValueInitExpr(
1644 Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd());
1645 if (ListInitialization &&
1646 cast<InitListExpr>(Exprs[0])->getNumInits() == 0) {
1648 Context, Ty.getUnqualifiedType(), VK_PRValue, TInfo, CK_ToVoid,
1649 Exprs[0], /*Path=*/nullptr, CurFPFeatureOverrides(),
1650 Exprs[0]->getBeginLoc(), Exprs[0]->getEndLoc());
1651 }
1652 } else if (RequireCompleteType(TyBeginLoc, ElemTy,
1653 diag::err_invalid_incomplete_type_use,
1654 FullRange))
1655 return ExprError();
1656
1657 // Otherwise, the expression is a prvalue of the specified type whose
1658 // result object is direct-initialized (11.6) with the initializer.
1659 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1660 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1661
1662 if (Result.isInvalid())
1663 return Result;
1664
1665 Expr *Inner = Result.get();
1666 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1667 Inner = BTE->getSubExpr();
1668 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1669 CE && CE->isImmediateInvocation())
1670 Inner = CE->getSubExpr();
1671 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1673 // If we created a CXXTemporaryObjectExpr, that node also represents the
1674 // functional cast. Otherwise, create an explicit cast to represent
1675 // the syntactic form of a functional-style cast that was used here.
1676 //
1677 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1678 // would give a more consistent AST representation than using a
1679 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1680 // is sometimes handled by initialization and sometimes not.
1681 QualType ResultType = Result.get()->getType();
1682 // In HLSL, vector/matrix constructors have their arguments wrapped into an
1683 // InitListExpr during initialization sequencing. Mark the resulting
1684 // CXXFunctionalCastExpr as list-initialization so that during template
1685 // re-instantiation, TreeTransform correctly passes the InitListExpr back
1686 // through BuildCXXTypeConstructExpr with ListInitialization=true as opposed
1687 // to false.
1688 bool IsListInit = ListInitialization ||
1689 (getLangOpts().HLSL && isa<InitListExpr>(Result.get()));
1690 SourceRange Locs = IsListInit
1691 ? SourceRange()
1692 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1694 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1695 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1696 Locs.getBegin(), Locs.getEnd());
1697 }
1698
1699 return Result;
1700}
1701
1703 // [CUDA] Ignore this function, if we can't call it.
1704 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1705 if (getLangOpts().CUDA) {
1706 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1707 // If it's not callable at all, it's not the right function.
1708 if (CallPreference < SemaCUDA::CFP_WrongSide)
1709 return false;
1710 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1711 // Maybe. We have to check if there are better alternatives.
1713 Method->getDeclContext()->lookup(Method->getDeclName());
1714 for (const auto *D : R) {
1715 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1716 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1717 return false;
1718 }
1719 }
1720 // We've found no better variants.
1721 }
1722 }
1723
1725 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1726
1727 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1728 return Result;
1729
1730 // In case of CUDA, return true if none of the 1-argument deallocator
1731 // functions are actually callable.
1732 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1733 assert(FD->getNumParams() == 1 &&
1734 "Only single-operand functions should be in PreventedBy");
1735 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1736 });
1737}
1738
1739/// Determine whether the given function is a non-placement
1740/// deallocation function.
1742 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1743 return S.isUsualDeallocationFunction(Method);
1744
1745 if (!FD->getDeclName().isAnyOperatorDelete())
1746 return false;
1747
1750 FD->getNumParams();
1751
1752 unsigned UsualParams = 1;
1753 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1755 FD->getParamDecl(UsualParams)->getType(),
1756 S.Context.getSizeType()))
1757 ++UsualParams;
1758
1759 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1761 FD->getParamDecl(UsualParams)->getType(),
1763 ++UsualParams;
1764
1765 return UsualParams == FD->getNumParams();
1766}
1767
1768namespace {
1769 struct UsualDeallocFnInfo {
1770 UsualDeallocFnInfo()
1771 : Found(), FD(nullptr),
1773 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found, QualType AllocType,
1774 SourceLocation Loc)
1775 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1776 Destroying(false),
1777 IDP({AllocType, TypeAwareAllocationMode::No,
1778 AlignedAllocationMode::No, SizedDeallocationMode::No}),
1779 CUDAPref(SemaCUDA::CFP_Native) {
1780 // A function template declaration is only a usual deallocation function
1781 // if it is a typed delete.
1782 if (!FD) {
1783 if (AllocType.isNull())
1784 return;
1785 auto *FTD = dyn_cast<FunctionTemplateDecl>(Found->getUnderlyingDecl());
1786 if (!FTD)
1787 return;
1788 FunctionDecl *InstantiatedDecl =
1789 S.BuildTypeAwareUsualDelete(FTD, AllocType, Loc);
1790 if (!InstantiatedDecl)
1791 return;
1792 FD = InstantiatedDecl;
1793 }
1794 unsigned NumBaseParams = 1;
1795 if (FD->isTypeAwareOperatorNewOrDelete()) {
1796 // If this is a type aware operator delete we instantiate an appropriate
1797 // specialization of std::type_identity<>. If we do not know the
1798 // type being deallocated, or if the type-identity parameter of the
1799 // deallocation function does not match the constructed type_identity
1800 // specialization we reject the declaration.
1801 if (AllocType.isNull()) {
1802 FD = nullptr;
1803 return;
1804 }
1805 QualType TypeIdentityTag = FD->getParamDecl(0)->getType();
1806 QualType ExpectedTypeIdentityTag =
1807 S.tryBuildStdTypeIdentity(AllocType, Loc);
1808 if (ExpectedTypeIdentityTag.isNull()) {
1809 FD = nullptr;
1810 return;
1811 }
1812 if (!S.Context.hasSameType(TypeIdentityTag, ExpectedTypeIdentityTag)) {
1813 FD = nullptr;
1814 return;
1815 }
1816 IDP.PassTypeIdentity = TypeAwareAllocationMode::Yes;
1817 ++NumBaseParams;
1818 }
1819
1820 if (FD->isDestroyingOperatorDelete()) {
1821 Destroying = true;
1822 ++NumBaseParams;
1823 }
1824
1825 if (NumBaseParams < FD->getNumParams() &&
1826 S.Context.hasSameUnqualifiedType(
1827 FD->getParamDecl(NumBaseParams)->getType(),
1828 S.Context.getSizeType())) {
1829 ++NumBaseParams;
1830 IDP.PassSize = SizedDeallocationMode::Yes;
1831 }
1832
1833 if (NumBaseParams < FD->getNumParams() &&
1834 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1835 ++NumBaseParams;
1836 IDP.PassAlignment = AlignedAllocationMode::Yes;
1837 }
1838
1839 // In CUDA, determine how much we'd like / dislike to call this.
1840 if (S.getLangOpts().CUDA)
1841 CUDAPref = S.CUDA().IdentifyPreference(
1842 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1843 }
1844
1845 explicit operator bool() const { return FD; }
1846
1847 int Compare(Sema &S, const UsualDeallocFnInfo &Other,
1848 ImplicitDeallocationParameters TargetIDP) const {
1849 assert(!TargetIDP.Type.isNull() ||
1850 !isTypeAwareAllocation(Other.IDP.PassTypeIdentity));
1851
1852 // C++ P0722:
1853 // A destroying operator delete is preferred over a non-destroying
1854 // operator delete.
1855 if (Destroying != Other.Destroying)
1856 return Destroying ? 1 : -1;
1857
1858 const ImplicitDeallocationParameters &OtherIDP = Other.IDP;
1859 // Selection for type awareness has priority over alignment and size
1860 if (IDP.PassTypeIdentity != OtherIDP.PassTypeIdentity)
1861 return IDP.PassTypeIdentity == TargetIDP.PassTypeIdentity ? 1 : -1;
1862
1863 // C++17 [expr.delete]p10:
1864 // If the type has new-extended alignment, a function with a parameter
1865 // of type std::align_val_t is preferred; otherwise a function without
1866 // such a parameter is preferred
1867 if (IDP.PassAlignment != OtherIDP.PassAlignment)
1868 return IDP.PassAlignment == TargetIDP.PassAlignment ? 1 : -1;
1869
1870 if (IDP.PassSize != OtherIDP.PassSize)
1871 return IDP.PassSize == TargetIDP.PassSize ? 1 : -1;
1872
1873 if (isTypeAwareAllocation(IDP.PassTypeIdentity)) {
1874 // Type aware allocation involves templates so we need to choose
1875 // the best type
1876 FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
1877 FunctionTemplateDecl *OtherPrimaryTemplate =
1878 Other.FD->getPrimaryTemplate();
1879 if ((!PrimaryTemplate) != (!OtherPrimaryTemplate))
1880 return OtherPrimaryTemplate ? 1 : -1;
1881
1882 if (PrimaryTemplate && OtherPrimaryTemplate) {
1883 const auto *DC = dyn_cast<CXXRecordDecl>(Found->getDeclContext());
1884 const auto *OtherDC =
1885 dyn_cast<CXXRecordDecl>(Other.Found->getDeclContext());
1886 unsigned ImplicitArgCount = Destroying + IDP.getNumImplicitArgs();
1887 if (FunctionTemplateDecl *Best = S.getMoreSpecializedTemplate(
1888 PrimaryTemplate, OtherPrimaryTemplate, SourceLocation(),
1889 TPOC_Call, ImplicitArgCount,
1890 DC ? S.Context.getCanonicalTagType(DC) : QualType{},
1891 OtherDC ? S.Context.getCanonicalTagType(OtherDC) : QualType{},
1892 false)) {
1893 return Best == PrimaryTemplate ? 1 : -1;
1894 }
1895 }
1896 }
1897
1898 // Use CUDA call preference as a tiebreaker.
1899 if (CUDAPref > Other.CUDAPref)
1900 return 1;
1901 if (CUDAPref == Other.CUDAPref)
1902 return 0;
1903 return -1;
1904 }
1905
1906 DeclAccessPair Found;
1907 FunctionDecl *FD;
1908 bool Destroying;
1909 ImplicitDeallocationParameters IDP;
1911 };
1912}
1913
1914/// Determine whether a type has new-extended alignment. This may be called when
1915/// the type is incomplete (for a delete-expression with an incomplete pointee
1916/// type), in which case it will conservatively return false if the alignment is
1917/// not known.
1918static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1919 return S.getLangOpts().AlignedAllocation &&
1920 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1922}
1923
1924static bool CheckDeleteOperator(Sema &S, SourceLocation StartLoc,
1925 SourceRange Range, bool Diagnose,
1926 CXXRecordDecl *NamingClass, DeclAccessPair Decl,
1927 FunctionDecl *Operator) {
1928 if (Operator->isTypeAwareOperatorNewOrDelete()) {
1929 QualType SelectedTypeIdentityParameter =
1930 Operator->getParamDecl(0)->getType();
1931 if (S.RequireCompleteType(StartLoc, SelectedTypeIdentityParameter,
1932 diag::err_incomplete_type))
1933 return true;
1934 }
1935
1936 // FIXME: DiagnoseUseOfDecl?
1937 if (Operator->isDeleted()) {
1938 if (Diagnose) {
1939 StringLiteral *Msg = Operator->getDeletedMessage();
1940 S.Diag(StartLoc, diag::err_deleted_function_use)
1941 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
1942 S.NoteDeletedFunction(Operator);
1943 }
1944 return true;
1945 }
1946 Sema::AccessResult Accessible =
1947 S.CheckAllocationAccess(StartLoc, Range, NamingClass, Decl, Diagnose);
1948 return Accessible == Sema::AR_inaccessible;
1949}
1950
1951/// Select the correct "usual" deallocation function to use from a selection of
1952/// deallocation functions (either global or class-scope).
1953static UsualDeallocFnInfo resolveDeallocationOverload(
1955 SourceLocation Loc,
1956 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1957
1958 UsualDeallocFnInfo Best;
1959 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1960 UsualDeallocFnInfo Info(S, I.getPair(), IDP.Type, Loc);
1961 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1962 Info.CUDAPref == SemaCUDA::CFP_Never)
1963 continue;
1964
1967 continue;
1968 if (!Best) {
1969 Best = Info;
1970 if (BestFns)
1971 BestFns->push_back(Info);
1972 continue;
1973 }
1974 int ComparisonResult = Best.Compare(S, Info, IDP);
1975 if (ComparisonResult > 0)
1976 continue;
1977
1978 // If more than one preferred function is found, all non-preferred
1979 // functions are eliminated from further consideration.
1980 if (BestFns && ComparisonResult < 0)
1981 BestFns->clear();
1982
1983 Best = Info;
1984 if (BestFns)
1985 BestFns->push_back(Info);
1986 }
1987
1988 return Best;
1989}
1990
1991/// Determine whether a given type is a class for which 'delete[]' would call
1992/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1993/// we need to store the array size (even if the type is
1994/// trivially-destructible).
1996 TypeAwareAllocationMode PassType,
1997 QualType allocType) {
1998 const auto *record =
1999 allocType->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>();
2000 if (!record) return false;
2001
2002 // Try to find an operator delete[] in class scope.
2003
2004 DeclarationName deleteName =
2005 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
2006 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
2007 S.LookupQualifiedName(ops, record->getDecl()->getDefinitionOrSelf());
2008
2009 // We're just doing this for information.
2010 ops.suppressDiagnostics();
2011
2012 // Very likely: there's no operator delete[].
2013 if (ops.empty()) return false;
2014
2015 // If it's ambiguous, it should be illegal to call operator delete[]
2016 // on this thing, so it doesn't matter if we allocate extra space or not.
2017 if (ops.isAmbiguous()) return false;
2018
2019 // C++17 [expr.delete]p10:
2020 // If the deallocation functions have class scope, the one without a
2021 // parameter of type std::size_t is selected.
2023 allocType, PassType,
2026 auto Best = resolveDeallocationOverload(S, ops, IDP, loc);
2027 return Best && isSizedDeallocation(Best.IDP.PassSize);
2028}
2029
2031Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
2032 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
2033 SourceLocation PlacementRParen, SourceRange TypeIdParens,
2035 std::optional<Expr *> ArraySize;
2036 // If the specified type is an array, unwrap it and save the expression.
2037 if (D.getNumTypeObjects() > 0 &&
2039 DeclaratorChunk &Chunk = D.getTypeObject(0);
2040 if (D.getDeclSpec().hasAutoTypeSpec())
2041 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
2042 << D.getSourceRange());
2043 if (Chunk.Arr.hasStatic)
2044 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
2045 << D.getSourceRange());
2046 if (!Chunk.Arr.NumElts && !Initializer)
2047 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
2048 << D.getSourceRange());
2049
2050 ArraySize = Chunk.Arr.NumElts;
2052 }
2053
2054 // Every dimension shall be of constant size.
2055 if (ArraySize) {
2056 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
2058 break;
2059
2061 if (Expr *NumElts = Array.NumElts) {
2062 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
2063 // FIXME: GCC permits constant folding here. We should either do so consistently
2064 // or not do so at all, rather than changing behavior in C++14 onwards.
2065 if (getLangOpts().CPlusPlus14) {
2066 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
2067 // shall be a converted constant expression (5.19) of type std::size_t
2068 // and shall evaluate to a strictly positive value.
2069 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
2070 Array.NumElts =
2071 CheckConvertedConstantExpression(NumElts, Context.getSizeType(),
2073 .get();
2074 } else {
2075 Array.NumElts = VerifyIntegerConstantExpression(
2076 NumElts, nullptr, diag::err_new_array_nonconst,
2078 .get();
2079 }
2080 if (!Array.NumElts)
2081 return ExprError();
2082 }
2083 }
2084 }
2085 }
2086
2088 QualType AllocType = TInfo->getType();
2089 if (D.isInvalidType())
2090 return ExprError();
2091
2092 SourceRange DirectInitRange;
2093 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
2094 DirectInitRange = List->getSourceRange();
2095
2096 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
2097 PlacementLParen, PlacementArgs, PlacementRParen,
2098 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
2099 Initializer);
2100}
2101
2103 Expr *Init, bool IsCPlusPlus20) {
2104 if (!Init)
2105 return true;
2106 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
2107 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
2109 return true;
2110 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
2111 return !CCE->isListInitialization() &&
2112 CCE->getConstructor()->isDefaultConstructor();
2113 else if (Style == CXXNewInitializationStyle::Braces) {
2114 assert(isa<InitListExpr>(Init) &&
2115 "Shouldn't create list CXXConstructExprs for arrays.");
2116 return true;
2117 }
2118 return false;
2119}
2120
2121bool
2123 if (!getLangOpts().AlignedAllocationUnavailable)
2124 return false;
2125 if (FD.isDefined())
2126 return false;
2127 UnsignedOrNone AlignmentParam = std::nullopt;
2128 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2129 AlignmentParam)
2130 return true;
2131 return false;
2132}
2133
2134// Emit a diagnostic if an aligned allocation/deallocation function that is not
2135// implemented in the standard library is selected.
2137 SourceLocation Loc) {
2139 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2140 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2141 getASTContext().getTargetInfo().getPlatformName());
2142 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2143
2144 bool IsDelete = FD.getDeclName().isAnyOperatorDelete();
2145 Diag(Loc, diag::err_aligned_allocation_unavailable)
2146 << IsDelete << FD.getType().getAsString() << OSName
2147 << OSVersion.getAsString() << OSVersion.empty();
2148 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2149 }
2150}
2151
2153 SourceLocation PlacementLParen,
2154 MultiExprArg PlacementArgs,
2155 SourceLocation PlacementRParen,
2156 SourceRange TypeIdParens, QualType AllocType,
2157 TypeSourceInfo *AllocTypeInfo,
2158 std::optional<Expr *> ArraySize,
2159 SourceRange DirectInitRange, Expr *Initializer) {
2160 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2161 SourceLocation StartLoc = Range.getBegin();
2162
2163 CXXNewInitializationStyle InitStyle;
2164 if (DirectInitRange.isValid()) {
2165 assert(Initializer && "Have parens but no initializer.");
2167 } else if (isa_and_nonnull<InitListExpr>(Initializer))
2169 else {
2172 "Initializer expression that cannot have been implicitly created.");
2174 }
2175
2176 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2177 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2178 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2179 "paren init for non-call init");
2180 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2181 } else if (auto *List = dyn_cast_or_null<CXXParenListInitExpr>(Initializer)) {
2182 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2183 "paren init for non-call init");
2184 Exprs = List->getInitExprs();
2185 }
2186
2187 // C++11 [expr.new]p15:
2188 // A new-expression that creates an object of type T initializes that
2189 // object as follows:
2190 InitializationKind Kind = [&] {
2191 switch (InitStyle) {
2192 // - If the new-initializer is omitted, the object is default-
2193 // initialized (8.5); if no initialization is performed,
2194 // the object has indeterminate value
2196 return InitializationKind::CreateDefault(TypeRange.getBegin());
2197 // - Otherwise, the new-initializer is interpreted according to the
2198 // initialization rules of 8.5 for direct-initialization.
2200 return InitializationKind::CreateDirect(TypeRange.getBegin(),
2201 DirectInitRange.getBegin(),
2202 DirectInitRange.getEnd());
2205 Initializer->getBeginLoc(),
2206 Initializer->getEndLoc());
2207 }
2208 llvm_unreachable("Unknown initialization kind");
2209 }();
2210
2211 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2212 auto *Deduced = AllocType->getContainedDeducedType();
2213 if (Deduced && !Deduced->isDeduced() &&
2215 if (ArraySize)
2216 return ExprError(
2217 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2218 diag::err_deduced_class_template_compound_type)
2219 << /*array*/ 2
2220 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2221
2225 AllocTypeInfo, Entity, Kind, Exprs);
2226 if (AllocType.isNull())
2227 return ExprError();
2228 } else if (Deduced && !Deduced->isDeduced()) {
2229 MultiExprArg Inits = Exprs;
2230 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2231 if (Braced) {
2232 auto *ILE = cast<InitListExpr>(Exprs[0]);
2233 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2234 }
2235
2236 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2237 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2238 << AllocType << TypeRange);
2239 if (Inits.size() > 1) {
2240 Expr *FirstBad = Inits[1];
2241 return ExprError(Diag(FirstBad->getBeginLoc(),
2242 diag::err_auto_new_ctor_multiple_expressions)
2243 << AllocType << TypeRange);
2244 }
2245 if (Braced && !getLangOpts().CPlusPlus17)
2246 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2247 << AllocType << TypeRange;
2248 Expr *Deduce = Inits[0];
2249 if (isa<InitListExpr>(Deduce))
2250 return ExprError(
2251 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2252 << Braced << AllocType << TypeRange);
2253 QualType DeducedType;
2254 TemplateDeductionInfo Info(Deduce->getExprLoc());
2256 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2259 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2260 << AllocType << Deduce->getType() << TypeRange
2261 << Deduce->getSourceRange());
2262 if (DeducedType.isNull()) {
2264 return ExprError();
2265 }
2266 AllocType = DeducedType;
2267 }
2268
2269 // Per C++0x [expr.new]p5, the type being constructed may be a
2270 // typedef of an array type.
2271 // Dependent case will be handled separately.
2272 if (!ArraySize && !AllocType->isDependentType()) {
2273 if (const ConstantArrayType *Array
2274 = Context.getAsConstantArrayType(AllocType)) {
2275 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2276 Context.getSizeType(),
2277 TypeRange.getEnd());
2278 AllocType = Array->getElementType();
2279 }
2280 }
2281
2282 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2283 return ExprError();
2284
2285 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2286 return ExprError();
2287
2288 // In ARC, infer 'retaining' for the allocated
2289 if (getLangOpts().ObjCAutoRefCount &&
2290 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2291 AllocType->isObjCLifetimeType()) {
2292 AllocType = Context.getLifetimeQualifiedType(AllocType,
2293 AllocType->getObjCARCImplicitLifetime());
2294 }
2295
2296 QualType ResultType = Context.getPointerType(AllocType);
2297
2298 if (ArraySize && *ArraySize &&
2299 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2300 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2301 if (result.isInvalid()) return ExprError();
2302 ArraySize = result.get();
2303 }
2304 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2305 // integral or enumeration type with a non-negative value."
2306 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2307 // enumeration type, or a class type for which a single non-explicit
2308 // conversion function to integral or unscoped enumeration type exists.
2309 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2310 // std::size_t.
2311 std::optional<uint64_t> KnownArraySize;
2312 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2313 ExprResult ConvertedSize;
2314 if (getLangOpts().CPlusPlus14) {
2315 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2316
2317 ConvertedSize = PerformImplicitConversion(
2318 *ArraySize, Context.getSizeType(), AssignmentAction::Converting);
2319
2320 if (!ConvertedSize.isInvalid() && (*ArraySize)->getType()->isRecordType())
2321 // Diagnose the compatibility of this conversion.
2322 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2323 << (*ArraySize)->getType() << 0 << "'size_t'";
2324 } else {
2325 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2326 protected:
2327 Expr *ArraySize;
2328
2329 public:
2330 SizeConvertDiagnoser(Expr *ArraySize)
2331 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2332 ArraySize(ArraySize) {}
2333
2334 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2335 QualType T) override {
2336 return S.Diag(Loc, diag::err_array_size_not_integral)
2337 << S.getLangOpts().CPlusPlus11 << T;
2338 }
2339
2340 SemaDiagnosticBuilder diagnoseIncomplete(
2341 Sema &S, SourceLocation Loc, QualType T) override {
2342 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2343 << T << ArraySize->getSourceRange();
2344 }
2345
2346 SemaDiagnosticBuilder diagnoseExplicitConv(
2347 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2348 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2349 }
2350
2351 SemaDiagnosticBuilder noteExplicitConv(
2352 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2353 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2354 << ConvTy->isEnumeralType() << ConvTy;
2355 }
2356
2357 SemaDiagnosticBuilder diagnoseAmbiguous(
2358 Sema &S, SourceLocation Loc, QualType T) override {
2359 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2360 }
2361
2362 SemaDiagnosticBuilder noteAmbiguous(
2363 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2364 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2365 << ConvTy->isEnumeralType() << ConvTy;
2366 }
2367
2368 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2369 QualType T,
2370 QualType ConvTy) override {
2371 return S.Diag(Loc,
2372 S.getLangOpts().CPlusPlus11
2373 ? diag::warn_cxx98_compat_array_size_conversion
2374 : diag::ext_array_size_conversion)
2375 << T << ConvTy->isEnumeralType() << ConvTy;
2376 }
2377 } SizeDiagnoser(*ArraySize);
2378
2379 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2380 SizeDiagnoser);
2381 }
2382 if (ConvertedSize.isInvalid())
2383 return ExprError();
2384
2385 ArraySize = ConvertedSize.get();
2386 QualType SizeType = (*ArraySize)->getType();
2387
2388 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2389 return ExprError();
2390
2391 // C++98 [expr.new]p7:
2392 // The expression in a direct-new-declarator shall have integral type
2393 // with a non-negative value.
2394 //
2395 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2396 // per CWG1464. Otherwise, if it's not a constant, we must have an
2397 // unparenthesized array type.
2398
2399 // We've already performed any required implicit conversion to integer or
2400 // unscoped enumeration type.
2401 // FIXME: Per CWG1464, we are required to check the value prior to
2402 // converting to size_t. This will never find a negative array size in
2403 // C++14 onwards, because Value is always unsigned here!
2404 if (std::optional<llvm::APSInt> Value =
2405 (*ArraySize)->getIntegerConstantExpr(Context)) {
2406 if (Value->isSigned() && Value->isNegative()) {
2407 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2408 diag::err_typecheck_negative_array_size)
2409 << (*ArraySize)->getSourceRange());
2410 }
2411
2412 if (!AllocType->isDependentType()) {
2413 unsigned ActiveSizeBits =
2415 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2416 return ExprError(
2417 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2418 << toString(*Value, 10, Value->isSigned(),
2419 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2420 /*InsertSeparators=*/true)
2421 << (*ArraySize)->getSourceRange());
2422 }
2423
2424 KnownArraySize = Value->getZExtValue();
2425 } else if (TypeIdParens.isValid()) {
2426 // Can't have dynamic array size when the type-id is in parentheses.
2427 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2428 << (*ArraySize)->getSourceRange()
2429 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2430 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2431
2432 TypeIdParens = SourceRange();
2433 }
2434
2435 // Note that we do *not* convert the argument in any way. It can
2436 // be signed, larger than size_t, whatever.
2437 }
2438
2439 FunctionDecl *OperatorNew = nullptr;
2440 FunctionDecl *OperatorDelete = nullptr;
2441 unsigned Alignment =
2442 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2443 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2446 alignedAllocationModeFromBool(getLangOpts().AlignedAllocation &&
2447 Alignment > NewAlignment)};
2448
2449 if (CheckArgsForPlaceholders(PlacementArgs))
2450 return ExprError();
2451
2454 SourceRange AllocationParameterRange = Range;
2455 if (PlacementLParen.isValid() && PlacementRParen.isValid())
2456 AllocationParameterRange = SourceRange(PlacementLParen, PlacementRParen);
2457 if (!AllocType->isDependentType() &&
2458 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2459 FindAllocationFunctions(StartLoc, AllocationParameterRange, Scope, Scope,
2460 AllocType, ArraySize.has_value(), IAP,
2461 PlacementArgs, OperatorNew, OperatorDelete))
2462 return ExprError();
2463
2464 // If this is an array allocation, compute whether the usual array
2465 // deallocation function for the type has a size_t parameter.
2466 bool UsualArrayDeleteWantsSize = false;
2467 if (ArraySize && !AllocType->isDependentType())
2468 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(
2469 *this, StartLoc, IAP.PassTypeIdentity, AllocType);
2470
2471 SmallVector<Expr *, 8> AllPlaceArgs;
2472 if (OperatorNew) {
2473 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2474 VariadicCallType CallType = Proto->isVariadic()
2477
2478 // We've already converted the placement args, just fill in any default
2479 // arguments. Skip the first parameter because we don't have a corresponding
2480 // argument. Skip the second parameter too if we're passing in the
2481 // alignment; we've already filled it in.
2482 unsigned NumImplicitArgs = 1;
2484 assert(OperatorNew->isTypeAwareOperatorNewOrDelete());
2485 NumImplicitArgs++;
2486 }
2488 NumImplicitArgs++;
2489 if (GatherArgumentsForCall(AllocationParameterRange.getBegin(), OperatorNew,
2490 Proto, NumImplicitArgs, PlacementArgs,
2491 AllPlaceArgs, CallType))
2492 return ExprError();
2493
2494 if (!AllPlaceArgs.empty())
2495 PlacementArgs = AllPlaceArgs;
2496
2497 // We would like to perform some checking on the given `operator new` call,
2498 // but the PlacementArgs does not contain the implicit arguments,
2499 // namely allocation size and maybe allocation alignment,
2500 // so we need to conjure them.
2501
2502 QualType SizeTy = Context.getSizeType();
2503 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2504
2505 llvm::APInt SingleEltSize(
2506 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2507
2508 // How many bytes do we want to allocate here?
2509 std::optional<llvm::APInt> AllocationSize;
2510 if (!ArraySize && !AllocType->isDependentType()) {
2511 // For non-array operator new, we only want to allocate one element.
2512 AllocationSize = SingleEltSize;
2513 } else if (KnownArraySize && !AllocType->isDependentType()) {
2514 // For array operator new, only deal with static array size case.
2515 bool Overflow;
2516 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2517 .umul_ov(SingleEltSize, Overflow);
2518 (void)Overflow;
2519 assert(
2520 !Overflow &&
2521 "Expected that all the overflows would have been handled already.");
2522 }
2523
2524 IntegerLiteral AllocationSizeLiteral(
2525 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2526 SizeTy, StartLoc);
2527 // Otherwise, if we failed to constant-fold the allocation size, we'll
2528 // just give up and pass-in something opaque, that isn't a null pointer.
2529 OpaqueValueExpr OpaqueAllocationSize(StartLoc, SizeTy, VK_PRValue,
2530 OK_Ordinary, /*SourceExpr=*/nullptr);
2531
2532 // Let's synthesize the alignment argument in case we will need it.
2533 // Since we *really* want to allocate these on stack, this is slightly ugly
2534 // because there might not be a `std::align_val_t` type.
2536 QualType AlignValT =
2537 StdAlignValT ? Context.getCanonicalTagType(StdAlignValT) : SizeTy;
2538 IntegerLiteral AlignmentLiteral(
2539 Context,
2540 llvm::APInt(Context.getTypeSize(SizeTy),
2541 Alignment / Context.getCharWidth()),
2542 SizeTy, StartLoc);
2543 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2544 CK_IntegralCast, &AlignmentLiteral,
2546
2547 // Adjust placement args by prepending conjured size and alignment exprs.
2549 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2550 CallArgs.emplace_back(AllocationSize
2551 ? static_cast<Expr *>(&AllocationSizeLiteral)
2552 : &OpaqueAllocationSize);
2554 CallArgs.emplace_back(&DesiredAlignment);
2555 llvm::append_range(CallArgs, PlacementArgs);
2556
2557 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2558
2559 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2560 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2561
2562 // Warn if the type is over-aligned and is being allocated by (unaligned)
2563 // global operator new.
2564 if (PlacementArgs.empty() && !isAlignedAllocation(IAP.PassAlignment) &&
2565 (OperatorNew->isImplicit() ||
2566 (OperatorNew->getBeginLoc().isValid() &&
2567 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2568 if (Alignment > NewAlignment)
2569 Diag(StartLoc, diag::warn_overaligned_type)
2570 << AllocType
2571 << unsigned(Alignment / Context.getCharWidth())
2572 << unsigned(NewAlignment / Context.getCharWidth());
2573 }
2574 }
2575
2576 // Array 'new' can't have any initializers except empty parentheses.
2577 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2578 // dialect distinction.
2579 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2581 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2582 Exprs.back()->getEndLoc());
2583 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2584 return ExprError();
2585 }
2586
2587 // If we can perform the initialization, and we've not already done so,
2588 // do it now.
2589 if (!AllocType->isDependentType() &&
2591 // The type we initialize is the complete type, including the array bound.
2592 QualType InitType;
2593 if (KnownArraySize)
2594 InitType = Context.getConstantArrayType(
2595 AllocType,
2596 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2597 *KnownArraySize),
2598 *ArraySize, ArraySizeModifier::Normal, 0);
2599 else if (ArraySize)
2600 InitType = Context.getIncompleteArrayType(AllocType,
2602 else
2603 InitType = AllocType;
2604
2605 bool VariableLengthArrayNew = ArraySize && *ArraySize && !KnownArraySize;
2607 StartLoc, InitType,
2608 VariableLengthArrayNew ? InitializedEntity::NewArrayKind::UnknownLength
2610 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2611 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2612 if (FullInit.isInvalid())
2613 return ExprError();
2614
2615 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2616 // we don't want the initialized object to be destructed.
2617 // FIXME: We should not create these in the first place.
2618 if (CXXBindTemporaryExpr *Binder =
2619 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2620 FullInit = Binder->getSubExpr();
2621
2622 Initializer = FullInit.get();
2623
2624 // FIXME: If we have a KnownArraySize, check that the array bound of the
2625 // initializer is no greater than that constant value.
2626
2627 if (ArraySize && !*ArraySize) {
2628 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2629 if (CAT) {
2630 // FIXME: Track that the array size was inferred rather than explicitly
2631 // specified.
2632 ArraySize = IntegerLiteral::Create(
2633 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2634 } else {
2635 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2636 << Initializer->getSourceRange();
2637 }
2638 }
2639 }
2640
2641 // Mark the new and delete operators as referenced.
2642 if (OperatorNew) {
2643 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2644 return ExprError();
2645 MarkFunctionReferenced(StartLoc, OperatorNew);
2646 }
2647 if (OperatorDelete) {
2648 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2649 return ExprError();
2650 MarkFunctionReferenced(StartLoc, OperatorDelete);
2651 }
2652
2653 // new[] will trigger vector deleting destructor emission if the class has
2654 // virtual destructor for MSVC compatibility. Perform necessary checks.
2655 if (Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts())) {
2656 if (const CXXConstructExpr *CCE =
2657 dyn_cast_or_null<CXXConstructExpr>(Initializer);
2658 CCE && ArraySize) {
2659 CXXRecordDecl *ClassDecl = CCE->getConstructor()->getParent();
2660 // We probably already did this for another new[] with this class so don't
2661 // do it twice.
2662 if (!Context.classMaybeNeedsVectorDeletingDestructor(ClassDecl)) {
2663 auto *Dtor = ClassDecl->getDestructor();
2664 if (Dtor && Dtor->isVirtual() && !Dtor->isDeleted()) {
2665 Context.setClassMaybeNeedsVectorDeletingDestructor(ClassDecl);
2666 if (!Dtor->isDefined() && !Dtor->isInvalidDecl()) {
2667 // Call CheckDestructor if destructor is not defined. This is
2668 // needed to find operators delete and delete[] for vector deleting
2669 // destructor body because new[] will trigger emission of vector
2670 // deleting destructor body even if destructor is defined in another
2671 // translation unit.
2672 ContextRAII SavedContext(*this, Dtor);
2673 CheckDestructor(Dtor);
2674 }
2675 }
2676 }
2677 }
2678 }
2679
2680 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2681 IAP, UsualArrayDeleteWantsSize, PlacementArgs,
2682 TypeIdParens, ArraySize, InitStyle, Initializer,
2683 ResultType, AllocTypeInfo, Range, DirectInitRange);
2684}
2685
2687 SourceRange R) {
2688 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2689 // abstract class type or array thereof.
2690 if (AllocType->isFunctionType())
2691 return Diag(Loc, diag::err_bad_new_type)
2692 << AllocType << 0 << R;
2693 else if (AllocType->isReferenceType())
2694 return Diag(Loc, diag::err_bad_new_type)
2695 << AllocType << 1 << R;
2696 else if (!AllocType->isDependentType() &&
2698 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2699 return true;
2700 else if (RequireNonAbstractType(Loc, AllocType,
2701 diag::err_allocation_of_abstract_type))
2702 return true;
2703 else if (AllocType->isVariablyModifiedType())
2704 return Diag(Loc, diag::err_variably_modified_new_type)
2705 << AllocType;
2706 else if (AllocType.getAddressSpace() != LangAS::Default &&
2707 !getLangOpts().OpenCLCPlusPlus)
2708 return Diag(Loc, diag::err_address_space_qualified_new)
2709 << AllocType.getUnqualifiedType()
2711
2712 else if (getLangOpts().ObjCAutoRefCount) {
2713 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2714 QualType BaseAllocType = Context.getBaseElementType(AT);
2715 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2716 BaseAllocType->isObjCLifetimeType())
2717 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2718 << BaseAllocType;
2719 }
2720 }
2721
2722 return false;
2723}
2724
2726 Sema &S, LookupResult &R, SourceRange Range, ArrayRef<Expr *> Args,
2727 OverloadCandidateSet &Candidates, OverloadCandidateSet *AlignedCandidates,
2728 Expr *AlignArg) {
2729 // If this is an allocation of the form 'new (p) X' for some object
2730 // pointer p (or an expression that will decay to such a pointer),
2731 // diagnose the reason for the error.
2732 if (!R.isClassLookup() && Args.size() == 2 &&
2733 (Args[1]->getType()->isObjectPointerType() ||
2734 Args[1]->getType()->isArrayType())) {
2735 const QualType Arg1Type = Args[1]->getType();
2736 QualType UnderlyingType = S.Context.getBaseElementType(Arg1Type);
2737 if (UnderlyingType->isPointerType())
2738 UnderlyingType = UnderlyingType->getPointeeType();
2739 if (UnderlyingType.isConstQualified()) {
2740 S.Diag(Args[1]->getExprLoc(),
2741 diag::err_placement_new_into_const_qualified_storage)
2742 << Arg1Type << Args[1]->getSourceRange();
2743 return;
2744 }
2745 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2746 << R.getLookupName() << Range;
2747 // Listing the candidates is unlikely to be useful; skip it.
2748 return;
2749 }
2750
2751 // Finish checking all candidates before we note any. This checking can
2752 // produce additional diagnostics so can't be interleaved with our
2753 // emission of notes.
2754 //
2755 // For an aligned allocation, separately check the aligned and unaligned
2756 // candidates with their respective argument lists.
2759 llvm::SmallVector<Expr *, 4> AlignedArgs;
2760 if (AlignedCandidates) {
2761 auto IsAligned = [](OverloadCandidate &C) {
2762 const unsigned AlignArgOffset = 1;
2763 return C.Function->getNumParams() > AlignArgOffset &&
2764 C.Function->getParamDecl(AlignArgOffset)->getType()->isAlignValT();
2765 };
2766 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2767
2768 AlignedArgs.reserve(Args.size() + 1);
2769 AlignedArgs.push_back(Args[0]);
2770 AlignedArgs.push_back(AlignArg);
2771 AlignedArgs.append(Args.begin() + 1, Args.end());
2772 AlignedCands = AlignedCandidates->CompleteCandidates(
2773 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2774
2775 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2776 R.getNameLoc(), IsUnaligned);
2777 } else {
2778 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2779 R.getNameLoc());
2780 }
2781
2782 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2783 << R.getLookupName() << Range;
2784 if (AlignedCandidates)
2785 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2786 R.getNameLoc());
2787 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2788}
2789
2790enum class ResolveMode { Typed, Untyped };
2792 Sema &S, LookupResult &R, SourceRange Range, ResolveMode Mode,
2793 SmallVectorImpl<Expr *> &Args, AlignedAllocationMode &PassAlignment,
2794 FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates,
2795 Expr *AlignArg, bool Diagnose) {
2796 unsigned NonTypeArgumentOffset = 0;
2797 if (Mode == ResolveMode::Typed) {
2798 ++NonTypeArgumentOffset;
2799 }
2800
2801 OverloadCandidateSet Candidates(R.getNameLoc(),
2803 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2804 Alloc != AllocEnd; ++Alloc) {
2805 // Even member operator new/delete are implicitly treated as
2806 // static, so don't use AddMemberCandidate.
2807 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2808 bool IsTypeAware = D->getAsFunction()->isTypeAwareOperatorNewOrDelete();
2809 if (IsTypeAware == (Mode != ResolveMode::Typed))
2810 continue;
2811
2812 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2813 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2814 /*ExplicitTemplateArgs=*/nullptr, Args,
2815 Candidates,
2816 /*SuppressUserConversions=*/false);
2817 continue;
2818 }
2819
2821 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2822 /*SuppressUserConversions=*/false);
2823 }
2824
2825 // Do the resolution.
2827 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2828 case OR_Success: {
2829 // Got one!
2830 FunctionDecl *FnDecl = Best->Function;
2831 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2832 Best->FoundDecl) == Sema::AR_inaccessible)
2833 return true;
2834
2835 Operator = FnDecl;
2836 return false;
2837 }
2838
2840 // C++17 [expr.new]p13:
2841 // If no matching function is found and the allocated object type has
2842 // new-extended alignment, the alignment argument is removed from the
2843 // argument list, and overload resolution is performed again.
2844 if (isAlignedAllocation(PassAlignment)) {
2845 PassAlignment = AlignedAllocationMode::No;
2846 AlignArg = Args[NonTypeArgumentOffset + 1];
2847 Args.erase(Args.begin() + NonTypeArgumentOffset + 1);
2848 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,
2849 PassAlignment, Operator,
2850 &Candidates, AlignArg, Diagnose);
2851 }
2852
2853 // MSVC will fall back on trying to find a matching global operator new
2854 // if operator new[] cannot be found. Also, MSVC will leak by not
2855 // generating a call to operator delete or operator delete[], but we
2856 // will not replicate that bug.
2857 // FIXME: Find out how this interacts with the std::align_val_t fallback
2858 // once MSVC implements it.
2859 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2860 S.Context.getLangOpts().MSVCCompat && Mode != ResolveMode::Typed) {
2861 R.clear();
2862 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2864 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2865 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,
2866 PassAlignment, Operator,
2867 /*Candidates=*/nullptr,
2868 /*AlignArg=*/nullptr, Diagnose);
2869 }
2870 if (Mode == ResolveMode::Typed) {
2871 // If we can't find a matching type aware operator we don't consider this
2872 // a failure.
2873 Operator = nullptr;
2874 return false;
2875 }
2876 if (Diagnose)
2878 S, R, Range, Args, Candidates, AlignedCandidates, AlignArg);
2879 return true;
2880
2881 case OR_Ambiguous:
2882 if (Diagnose) {
2883 Candidates.NoteCandidates(
2884 PartialDiagnosticAt(R.getNameLoc(),
2885 S.PDiag(diag::err_ovl_ambiguous_call)
2886 << R.getLookupName() << Range),
2887 S, OCD_AmbiguousCandidates, Args);
2888 }
2889 return true;
2890
2891 case OR_Deleted: {
2892 if (Diagnose)
2893 S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),
2894 Candidates, Best->Function, Args);
2895 return true;
2896 }
2897 }
2898 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2899}
2900
2902
2904 LookupResult &FoundDelete,
2905 DeallocLookupMode Mode,
2906 DeclarationName Name) {
2909 // We're going to remove either the typed or the non-typed
2910 bool RemoveTypedDecl = Mode == DeallocLookupMode::Untyped;
2911 LookupResult::Filter Filter = FoundDelete.makeFilter();
2912 while (Filter.hasNext()) {
2913 FunctionDecl *FD = Filter.next()->getUnderlyingDecl()->getAsFunction();
2914 if (FD->isTypeAwareOperatorNewOrDelete() == RemoveTypedDecl)
2915 Filter.erase();
2916 }
2917 Filter.done();
2918 }
2919}
2920
2924 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2925 Operator = nullptr;
2927 assert(S.isStdTypeIdentity(Args[0]->getType(), nullptr));
2928 // The internal overload resolution work mutates the argument list
2929 // in accordance with the spec. We may want to change that in future,
2930 // but for now we deal with this by making a copy of the non-type-identity
2931 // arguments.
2932 SmallVector<Expr *> UntypedParameters;
2933 UntypedParameters.reserve(Args.size() - 1);
2934 UntypedParameters.push_back(Args[1]);
2935 // Type aware allocation implicitly includes the alignment parameter so
2936 // only include it in the untyped parameter list if alignment was explicitly
2937 // requested
2939 UntypedParameters.push_back(Args[2]);
2940 UntypedParameters.append(Args.begin() + 3, Args.end());
2941
2942 AlignedAllocationMode InitialAlignmentMode = IAP.PassAlignment;
2945 S, R, Range, ResolveMode::Typed, Args, IAP.PassAlignment, Operator,
2946 AlignedCandidates, AlignArg, Diagnose))
2947 return true;
2948 if (Operator)
2949 return false;
2950
2951 // If we got to this point we could not find a matching typed operator
2952 // so we update the IAP flags, and revert to our stored copy of the
2953 // type-identity-less argument list.
2955 IAP.PassAlignment = InitialAlignmentMode;
2956 Args = std::move(UntypedParameters);
2957 }
2958 assert(!S.isStdTypeIdentity(Args[0]->getType(), nullptr));
2960 S, R, Range, ResolveMode::Untyped, Args, IAP.PassAlignment, Operator,
2961 AlignedCandidates, AlignArg, Diagnose);
2962}
2963
2965 SourceLocation StartLoc, SourceRange Range,
2967 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
2968 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
2969 FunctionDecl *&OperatorDelete, bool Diagnose) {
2970 // --- Choosing an allocation function ---
2971 // C++ 5.3.4p8 - 14 & 18
2972 // 1) If looking in AllocationFunctionScope::Global scope for allocation
2973 // functions, only look in
2974 // the global scope. Else, if AllocationFunctionScope::Class, only look in
2975 // the scope of the allocated class. If AllocationFunctionScope::Both, look
2976 // in both.
2977 // 2) If an array size is given, look for operator new[], else look for
2978 // operator new.
2979 // 3) The first argument is always size_t. Append the arguments from the
2980 // placement form.
2981
2982 SmallVector<Expr*, 8> AllocArgs;
2983 AllocArgs.reserve(IAP.getNumImplicitArgs() + PlaceArgs.size());
2984
2985 // C++ [expr.new]p8:
2986 // If the allocated type is a non-array type, the allocation
2987 // function's name is operator new and the deallocation function's
2988 // name is operator delete. If the allocated type is an array
2989 // type, the allocation function's name is operator new[] and the
2990 // deallocation function's name is operator delete[].
2991 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2992 IsArray ? OO_Array_New : OO_New);
2993
2994 QualType AllocElemType = Context.getBaseElementType(AllocType);
2995
2996 // We don't care about the actual value of these arguments.
2997 // FIXME: Should the Sema create the expression and embed it in the syntax
2998 // tree? Or should the consumer just recalculate the value?
2999 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
3000
3001 // We use size_t as a stand in so that we can construct the init
3002 // expr on the stack
3003 QualType TypeIdentity = Context.getSizeType();
3005 QualType SpecializedTypeIdentity =
3006 tryBuildStdTypeIdentity(IAP.Type, StartLoc);
3007 if (!SpecializedTypeIdentity.isNull()) {
3008 TypeIdentity = SpecializedTypeIdentity;
3009 if (RequireCompleteType(StartLoc, TypeIdentity,
3010 diag::err_incomplete_type))
3011 return true;
3012 } else
3014 }
3015 TypeAwareAllocationMode OriginalTypeAwareState = IAP.PassTypeIdentity;
3016
3017 CXXScalarValueInitExpr TypeIdentityParam(TypeIdentity, nullptr, StartLoc);
3019 AllocArgs.push_back(&TypeIdentityParam);
3020
3021 QualType SizeTy = Context.getSizeType();
3022 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
3023 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
3024 SourceLocation());
3025 AllocArgs.push_back(&Size);
3026
3027 QualType AlignValT = Context.VoidTy;
3028 bool IncludeAlignParam = isAlignedAllocation(IAP.PassAlignment) ||
3030 if (IncludeAlignParam) {
3032 AlignValT = Context.getCanonicalTagType(getStdAlignValT());
3033 }
3034 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
3035 if (IncludeAlignParam)
3036 AllocArgs.push_back(&Align);
3037
3038 llvm::append_range(AllocArgs, PlaceArgs);
3039
3040 // Find the allocation function.
3041 {
3042 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
3043
3044 // C++1z [expr.new]p9:
3045 // If the new-expression begins with a unary :: operator, the allocation
3046 // function's name is looked up in the global scope. Otherwise, if the
3047 // allocated type is a class type T or array thereof, the allocation
3048 // function's name is looked up in the scope of T.
3049 if (AllocElemType->isRecordType() &&
3051 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
3052
3053 // We can see ambiguity here if the allocation function is found in
3054 // multiple base classes.
3055 if (R.isAmbiguous())
3056 return true;
3057
3058 // If this lookup fails to find the name, or if the allocated type is not
3059 // a class type, the allocation function's name is looked up in the
3060 // global scope.
3061 if (R.empty()) {
3062 if (NewScope == AllocationFunctionScope::Class)
3063 return true;
3064
3065 LookupQualifiedName(R, Context.getTranslationUnitDecl());
3066 }
3067
3068 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
3069 if (PlaceArgs.empty()) {
3070 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
3071 } else {
3072 Diag(StartLoc, diag::err_openclcxx_placement_new);
3073 }
3074 return true;
3075 }
3076
3077 assert(!R.empty() && "implicitly declared allocation functions not found");
3078 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3079
3080 // We do our own custom access checks below.
3081 R.suppressDiagnostics();
3082
3083 if (resolveAllocationOverload(*this, R, Range, AllocArgs, IAP, OperatorNew,
3084 /*Candidates=*/nullptr,
3085 /*AlignArg=*/nullptr, Diagnose))
3086 return true;
3087 }
3088
3089 // We don't need an operator delete if we're running under -fno-exceptions.
3090 if (!getLangOpts().Exceptions) {
3091 OperatorDelete = nullptr;
3092 return false;
3093 }
3094
3095 // Note, the name of OperatorNew might have been changed from array to
3096 // non-array by resolveAllocationOverload.
3097 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3098 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
3099 ? OO_Array_Delete
3100 : OO_Delete);
3101
3102 // C++ [expr.new]p19:
3103 //
3104 // If the new-expression begins with a unary :: operator, the
3105 // deallocation function's name is looked up in the global
3106 // scope. Otherwise, if the allocated type is a class type T or an
3107 // array thereof, the deallocation function's name is looked up in
3108 // the scope of T. If this lookup fails to find the name, or if
3109 // the allocated type is not a class type or array thereof, the
3110 // deallocation function's name is looked up in the global scope.
3111 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
3112 if (AllocElemType->isRecordType() &&
3113 DeleteScope != AllocationFunctionScope::Global) {
3114 auto *RD = AllocElemType->castAsCXXRecordDecl();
3115 LookupQualifiedName(FoundDelete, RD);
3116 }
3117 if (FoundDelete.isAmbiguous())
3118 return true; // FIXME: clean up expressions?
3119
3120 // Filter out any destroying operator deletes. We can't possibly call such a
3121 // function in this context, because we're handling the case where the object
3122 // was not successfully constructed.
3123 // FIXME: This is not covered by the language rules yet.
3124 {
3125 LookupResult::Filter Filter = FoundDelete.makeFilter();
3126 while (Filter.hasNext()) {
3127 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
3128 if (FD && FD->isDestroyingOperatorDelete())
3129 Filter.erase();
3130 }
3131 Filter.done();
3132 }
3133
3134 auto GetRedeclContext = [](Decl *D) {
3135 return D->getDeclContext()->getRedeclContext();
3136 };
3137
3138 DeclContext *OperatorNewContext = GetRedeclContext(OperatorNew);
3139
3140 bool FoundGlobalDelete = FoundDelete.empty();
3141 bool IsClassScopedTypeAwareNew =
3143 OperatorNewContext->isRecord();
3144 auto DiagnoseMissingTypeAwareCleanupOperator = [&](bool IsPlacementOperator) {
3146 if (Diagnose) {
3147 Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator)
3148 << OperatorNew->getDeclName() << IsPlacementOperator << DeleteName;
3149 Diag(OperatorNew->getLocation(), diag::note_type_aware_operator_declared)
3150 << OperatorNew->isTypeAwareOperatorNewOrDelete()
3151 << OperatorNew->getDeclName() << OperatorNewContext;
3152 }
3153 };
3154 if (IsClassScopedTypeAwareNew && FoundDelete.empty()) {
3155 DiagnoseMissingTypeAwareCleanupOperator(/*isPlacementNew=*/false);
3156 return true;
3157 }
3158 if (FoundDelete.empty()) {
3159 FoundDelete.clear(LookupOrdinaryName);
3160
3161 if (DeleteScope == AllocationFunctionScope::Class)
3162 return true;
3163
3165 DeallocLookupMode LookupMode = isTypeAwareAllocation(OriginalTypeAwareState)
3168 LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete, LookupMode,
3169 DeleteName);
3170 }
3171
3172 FoundDelete.suppressDiagnostics();
3173
3175
3176 // Whether we're looking for a placement operator delete is dictated
3177 // by whether we selected a placement operator new, not by whether
3178 // we had explicit placement arguments. This matters for things like
3179 // struct A { void *operator new(size_t, int = 0); ... };
3180 // A *a = new A()
3181 //
3182 // We don't have any definition for what a "placement allocation function"
3183 // is, but we assume it's any allocation function whose
3184 // parameter-declaration-clause is anything other than (size_t).
3185 //
3186 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
3187 // This affects whether an exception from the constructor of an overaligned
3188 // type uses the sized or non-sized form of aligned operator delete.
3189
3190 unsigned NonPlacementNewArgCount = 1; // size parameter
3192 NonPlacementNewArgCount =
3193 /* type-identity */ 1 + /* size */ 1 + /* alignment */ 1;
3194 bool isPlacementNew = !PlaceArgs.empty() ||
3195 OperatorNew->param_size() != NonPlacementNewArgCount ||
3196 OperatorNew->isVariadic();
3197
3198 if (isPlacementNew) {
3199 // C++ [expr.new]p20:
3200 // A declaration of a placement deallocation function matches the
3201 // declaration of a placement allocation function if it has the
3202 // same number of parameters and, after parameter transformations
3203 // (8.3.5), all parameter types except the first are
3204 // identical. [...]
3205 //
3206 // To perform this comparison, we compute the function type that
3207 // the deallocation function should have, and use that type both
3208 // for template argument deduction and for comparison purposes.
3209 QualType ExpectedFunctionType;
3210 {
3211 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
3212
3213 SmallVector<QualType, 6> ArgTypes;
3214 int InitialParamOffset = 0;
3216 ArgTypes.push_back(TypeIdentity);
3217 InitialParamOffset = 1;
3218 }
3219 ArgTypes.push_back(Context.VoidPtrTy);
3220 for (unsigned I = ArgTypes.size() - InitialParamOffset,
3221 N = Proto->getNumParams();
3222 I < N; ++I)
3223 ArgTypes.push_back(Proto->getParamType(I));
3224
3226 // FIXME: This is not part of the standard's rule.
3227 EPI.Variadic = Proto->isVariadic();
3228
3229 ExpectedFunctionType
3230 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
3231 }
3232
3233 for (LookupResult::iterator D = FoundDelete.begin(),
3234 DEnd = FoundDelete.end();
3235 D != DEnd; ++D) {
3236 FunctionDecl *Fn = nullptr;
3237 if (FunctionTemplateDecl *FnTmpl =
3238 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
3239 // Perform template argument deduction to try to match the
3240 // expected function type.
3241 TemplateDeductionInfo Info(StartLoc);
3242 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
3244 continue;
3245 } else
3246 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
3247
3248 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
3249 ExpectedFunctionType,
3250 /*AdjustExcpetionSpec*/true),
3251 ExpectedFunctionType))
3252 Matches.push_back(std::make_pair(D.getPair(), Fn));
3253 }
3254
3255 if (getLangOpts().CUDA)
3256 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
3257 Matches);
3258 if (Matches.empty() && isTypeAwareAllocation(IAP.PassTypeIdentity)) {
3259 DiagnoseMissingTypeAwareCleanupOperator(isPlacementNew);
3260 return true;
3261 }
3262 } else {
3263 // C++1y [expr.new]p22:
3264 // For a non-placement allocation function, the normal deallocation
3265 // function lookup is used
3266 //
3267 // Per [expr.delete]p10, this lookup prefers a member operator delete
3268 // without a size_t argument, but prefers a non-member operator delete
3269 // with a size_t where possible (which it always is in this case).
3272 AllocElemType, OriginalTypeAwareState,
3274 hasNewExtendedAlignment(*this, AllocElemType)),
3275 sizedDeallocationModeFromBool(FoundGlobalDelete)};
3276 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
3277 *this, FoundDelete, IDP, StartLoc, &BestDeallocFns);
3278 if (Selected && BestDeallocFns.empty())
3279 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
3280 else {
3281 // If we failed to select an operator, all remaining functions are viable
3282 // but ambiguous.
3283 for (auto Fn : BestDeallocFns)
3284 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
3285 }
3286 }
3287
3288 // C++ [expr.new]p20:
3289 // [...] If the lookup finds a single matching deallocation
3290 // function, that function will be called; otherwise, no
3291 // deallocation function will be called.
3292 if (Matches.size() == 1) {
3293 OperatorDelete = Matches[0].second;
3294 DeclContext *OperatorDeleteContext = GetRedeclContext(OperatorDelete);
3295 bool FoundTypeAwareOperator =
3296 OperatorDelete->isTypeAwareOperatorNewOrDelete() ||
3297 OperatorNew->isTypeAwareOperatorNewOrDelete();
3298 if (Diagnose && FoundTypeAwareOperator) {
3299 bool MismatchedTypeAwareness =
3300 OperatorDelete->isTypeAwareOperatorNewOrDelete() !=
3301 OperatorNew->isTypeAwareOperatorNewOrDelete();
3302 bool MismatchedContext = OperatorDeleteContext != OperatorNewContext;
3303 if (MismatchedTypeAwareness || MismatchedContext) {
3304 FunctionDecl *Operators[] = {OperatorDelete, OperatorNew};
3305 bool TypeAwareOperatorIndex =
3306 OperatorNew->isTypeAwareOperatorNewOrDelete();
3307 Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator)
3308 << Operators[TypeAwareOperatorIndex]->getDeclName()
3309 << isPlacementNew
3310 << Operators[!TypeAwareOperatorIndex]->getDeclName()
3311 << GetRedeclContext(Operators[TypeAwareOperatorIndex]);
3312 Diag(OperatorNew->getLocation(),
3313 diag::note_type_aware_operator_declared)
3314 << OperatorNew->isTypeAwareOperatorNewOrDelete()
3315 << OperatorNew->getDeclName() << OperatorNewContext;
3316 Diag(OperatorDelete->getLocation(),
3317 diag::note_type_aware_operator_declared)
3318 << OperatorDelete->isTypeAwareOperatorNewOrDelete()
3319 << OperatorDelete->getDeclName() << OperatorDeleteContext;
3320 }
3321 }
3322
3323 // C++1z [expr.new]p23:
3324 // If the lookup finds a usual deallocation function (3.7.4.2)
3325 // with a parameter of type std::size_t and that function, considered
3326 // as a placement deallocation function, would have been
3327 // selected as a match for the allocation function, the program
3328 // is ill-formed.
3329 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
3330 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
3331 UsualDeallocFnInfo Info(*this,
3332 DeclAccessPair::make(OperatorDelete, AS_public),
3333 AllocElemType, StartLoc);
3334 // Core issue, per mail to core reflector, 2016-10-09:
3335 // If this is a member operator delete, and there is a corresponding
3336 // non-sized member operator delete, this isn't /really/ a sized
3337 // deallocation function, it just happens to have a size_t parameter.
3338 bool IsSizedDelete = isSizedDeallocation(Info.IDP.PassSize);
3339 if (IsSizedDelete && !FoundGlobalDelete) {
3340 ImplicitDeallocationParameters SizeTestingIDP = {
3341 AllocElemType, Info.IDP.PassTypeIdentity, Info.IDP.PassAlignment,
3343 auto NonSizedDelete = resolveDeallocationOverload(
3344 *this, FoundDelete, SizeTestingIDP, StartLoc);
3345 if (NonSizedDelete &&
3346 !isSizedDeallocation(NonSizedDelete.IDP.PassSize) &&
3347 NonSizedDelete.IDP.PassAlignment == Info.IDP.PassAlignment)
3348 IsSizedDelete = false;
3349 }
3350
3351 if (IsSizedDelete && !isTypeAwareAllocation(IAP.PassTypeIdentity)) {
3352 SourceRange R = PlaceArgs.empty()
3353 ? SourceRange()
3354 : SourceRange(PlaceArgs.front()->getBeginLoc(),
3355 PlaceArgs.back()->getEndLoc());
3356 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
3357 if (!OperatorDelete->isImplicit())
3358 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
3359 << DeleteName;
3360 }
3361 }
3362 if (CheckDeleteOperator(*this, StartLoc, Range, Diagnose,
3363 FoundDelete.getNamingClass(), Matches[0].first,
3364 Matches[0].second))
3365 return true;
3366
3367 } else if (!Matches.empty()) {
3368 // We found multiple suitable operators. Per [expr.new]p20, that means we
3369 // call no 'operator delete' function, but we should at least warn the user.
3370 // FIXME: Suppress this warning if the construction cannot throw.
3371 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
3372 << DeleteName << AllocElemType;
3373
3374 for (auto &Match : Matches)
3375 Diag(Match.second->getLocation(),
3376 diag::note_member_declared_here) << DeleteName;
3377 }
3378
3379 return false;
3380}
3381
3384 return;
3385
3386 // The implicitly declared new and delete operators
3387 // are not supported in OpenCL.
3388 if (getLangOpts().OpenCLCPlusPlus)
3389 return;
3390
3391 // C++ [basic.stc.dynamic.general]p2:
3392 // The library provides default definitions for the global allocation
3393 // and deallocation functions. Some global allocation and deallocation
3394 // functions are replaceable ([new.delete]); these are attached to the
3395 // global module ([module.unit]).
3396 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3397 PushGlobalModuleFragment(SourceLocation());
3398
3399 // C++ [basic.std.dynamic]p2:
3400 // [...] The following allocation and deallocation functions (18.4) are
3401 // implicitly declared in global scope in each translation unit of a
3402 // program
3403 //
3404 // C++03:
3405 // void* operator new(std::size_t) throw(std::bad_alloc);
3406 // void* operator new[](std::size_t) throw(std::bad_alloc);
3407 // void operator delete(void*) throw();
3408 // void operator delete[](void*) throw();
3409 // C++11:
3410 // void* operator new(std::size_t);
3411 // void* operator new[](std::size_t);
3412 // void operator delete(void*) noexcept;
3413 // void operator delete[](void*) noexcept;
3414 // C++1y:
3415 // void* operator new(std::size_t);
3416 // void* operator new[](std::size_t);
3417 // void operator delete(void*) noexcept;
3418 // void operator delete[](void*) noexcept;
3419 // void operator delete(void*, std::size_t) noexcept;
3420 // void operator delete[](void*, std::size_t) noexcept;
3421 //
3422 // These implicit declarations introduce only the function names operator
3423 // new, operator new[], operator delete, operator delete[].
3424 //
3425 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3426 // "std" or "bad_alloc" as necessary to form the exception specification.
3427 // However, we do not make these implicit declarations visible to name
3428 // lookup.
3429 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3430 // The "std::bad_alloc" class has not yet been declared, so build it
3431 // implicitly.
3435 &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3436 getStdBadAlloc()->setImplicit(true);
3437
3438 // The implicitly declared "std::bad_alloc" should live in global module
3439 // fragment.
3440 if (TheGlobalModuleFragment) {
3443 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3444 }
3445 }
3446 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3447 // The "std::align_val_t" enum class has not yet been declared, so build it
3448 // implicitly.
3449 auto *AlignValT = EnumDecl::Create(
3451 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3452
3453 // The implicitly declared "std::align_val_t" should live in global module
3454 // fragment.
3455 if (TheGlobalModuleFragment) {
3456 AlignValT->setModuleOwnershipKind(
3458 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3459 }
3460
3461 AlignValT->setIntegerType(Context.getSizeType());
3462 AlignValT->setPromotionType(Context.getSizeType());
3463 AlignValT->setImplicit(true);
3464
3465 // Add to the std namespace so that the module merger can find it via
3466 // noload_lookup and merge it with the module's explicit definition.
3467 // We want the created EnumDecl to be available for redeclaration lookups,
3468 // but not for regular name lookups (same pattern as
3469 // getOrCreateStdNamespace).
3470 getOrCreateStdNamespace()->addDecl(AlignValT);
3471
3472 StdAlignValT = AlignValT;
3473 }
3474
3476
3477 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
3478 QualType SizeT = Context.getSizeType();
3479
3480 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3481 QualType Return, QualType Param) {
3483 Params.push_back(Param);
3484
3485 // Create up to four variants of the function (sized/aligned).
3486 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3487 (Kind == OO_Delete || Kind == OO_Array_Delete);
3488 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3489
3490 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3491 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3492 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3493 if (Sized)
3494 Params.push_back(SizeT);
3495
3496 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3497 if (Aligned)
3498 Params.push_back(Context.getCanonicalTagType(getStdAlignValT()));
3499
3501 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3502
3503 if (Aligned)
3504 Params.pop_back();
3505 }
3506 }
3507 };
3508
3509 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3510 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3511 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3512 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3513
3514 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3515 PopGlobalModuleFragment();
3516}
3517
3518/// DeclareGlobalAllocationFunction - Declares a single implicit global
3519/// allocation function if it doesn't already exist.
3521 QualType Return,
3522 ArrayRef<QualType> Params) {
3523 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3524
3525 // Check if this function is already declared.
3526 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3527 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3528 Alloc != AllocEnd; ++Alloc) {
3529 // Only look at non-template functions, as it is the predefined,
3530 // non-templated allocation function we are trying to declare here.
3531 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3532 if (Func->getNumParams() == Params.size()) {
3533 if (std::equal(Func->param_begin(), Func->param_end(), Params.begin(),
3534 Params.end(), [&](ParmVarDecl *D, QualType RT) {
3535 return Context.hasSameUnqualifiedType(D->getType(),
3536 RT);
3537 })) {
3538 // Make the function visible to name lookup, even if we found it in
3539 // an unimported module. It either is an implicitly-declared global
3540 // allocation function, or is suppressing that function.
3541 Func->setVisibleDespiteOwningModule();
3542 return;
3543 }
3544 }
3545 }
3546 }
3547
3549 Context.getTargetInfo().getDefaultCallingConv());
3550
3551 QualType BadAllocType;
3552 bool HasBadAllocExceptionSpec = Name.isAnyOperatorNew();
3553 if (HasBadAllocExceptionSpec) {
3554 if (!getLangOpts().CPlusPlus11) {
3555 BadAllocType = Context.getCanonicalTagType(getStdBadAlloc());
3556 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3558 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3559 }
3560 if (getLangOpts().NewInfallible) {
3562 }
3563 } else {
3564 EPI.ExceptionSpec =
3566 }
3567
3568 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3569 // The MSVC STL has explicit cdecl on its (host-side) allocation function
3570 // specializations for the allocation, so in order to prevent a CC clash
3571 // we use the host's CC, if available, or CC_C as a fallback, for the
3572 // host-side implicit decls, knowing these do not get emitted when compiling
3573 // for device.
3574 if (getLangOpts().CUDAIsDevice && ExtraAttr &&
3575 isa<CUDAHostAttr>(ExtraAttr) &&
3576 Context.getTargetInfo().getTriple().isSPIRV()) {
3577 if (auto *ATI = Context.getAuxTargetInfo())
3578 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(ATI->getDefaultCallingConv());
3579 else
3581 }
3582 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3584 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3585 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3586 true);
3587 Alloc->setImplicit();
3588 // Global allocation functions should always be visible.
3589 Alloc->setVisibleDespiteOwningModule();
3590
3591 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3592 !getLangOpts().CheckNew)
3593 Alloc->addAttr(
3594 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3595
3596 // C++ [basic.stc.dynamic.general]p2:
3597 // The library provides default definitions for the global allocation
3598 // and deallocation functions. Some global allocation and deallocation
3599 // functions are replaceable ([new.delete]); these are attached to the
3600 // global module ([module.unit]).
3601 //
3602 // In the language wording, these functions are attched to the global
3603 // module all the time. But in the implementation, the global module
3604 // is only meaningful when we're in a module unit. So here we attach
3605 // these allocation functions to global module conditionally.
3606 if (TheGlobalModuleFragment) {
3607 Alloc->setModuleOwnershipKind(
3609 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3610 }
3611
3612 if (LangOpts.hasGlobalAllocationFunctionVisibility())
3613 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3614 Context, LangOpts.hasHiddenGlobalAllocationFunctionVisibility()
3615 ? VisibilityAttr::Hidden
3616 : LangOpts.hasProtectedGlobalAllocationFunctionVisibility()
3617 ? VisibilityAttr::Protected
3618 : VisibilityAttr::Default));
3619
3621 for (QualType T : Params) {
3622 ParamDecls.push_back(ParmVarDecl::Create(
3623 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3624 /*TInfo=*/nullptr, SC_None, nullptr));
3625 ParamDecls.back()->setImplicit();
3626 }
3627 Alloc->setParams(ParamDecls);
3628 if (ExtraAttr)
3629 Alloc->addAttr(ExtraAttr);
3631 Context.getTranslationUnitDecl()->addDecl(Alloc);
3632 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3633 };
3634
3635 if (!LangOpts.CUDA)
3636 CreateAllocationFunctionDecl(nullptr);
3637 else {
3638 // Host and device get their own declaration so each can be
3639 // defined or re-declared independently.
3640 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3641 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3642 }
3643}
3644
3648 DeclarationName Name, bool Diagnose) {
3650
3651 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3652 LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete,
3654
3655 // FIXME: It's possible for this to result in ambiguity, through a
3656 // user-declared variadic operator delete or the enable_if attribute. We
3657 // should probably not consider those cases to be usual deallocation
3658 // functions. But for now we just make an arbitrary choice in that case.
3659 auto Result = resolveDeallocationOverload(*this, FoundDelete, IDP, StartLoc);
3660 if (!Result)
3661 return nullptr;
3662
3663 if (CheckDeleteOperator(*this, StartLoc, StartLoc, Diagnose,
3664 FoundDelete.getNamingClass(), Result.Found,
3665 Result.FD))
3666 return nullptr;
3667
3668 assert(Result.FD && "operator delete missing from global scope?");
3669 return Result.FD;
3670}
3671
3673 SourceLocation Loc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal,
3674 DeclarationName Name) {
3675
3676 FunctionDecl *OperatorDelete = nullptr;
3677 CanQualType DeallocType = Context.getCanonicalTagType(RD);
3681
3682 if (!LookForGlobal) {
3683 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, IDP, Diagnose))
3684 return nullptr;
3685
3686 if (OperatorDelete)
3687 return OperatorDelete;
3688 }
3689
3690 // If there's no class-specific operator delete, look up the global
3691 // non-array delete.
3693 hasNewExtendedAlignment(*this, DeallocType));
3695 return FindUsualDeallocationFunction(Loc, IDP, Name, Diagnose);
3696}
3697
3699 DeclarationName Name,
3700 FunctionDecl *&Operator,
3702 bool Diagnose) {
3703 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3704 // Try to find operator delete/operator delete[] in class scope.
3706
3707 if (Found.isAmbiguous()) {
3708 if (!Diagnose)
3709 Found.suppressDiagnostics();
3710 return true;
3711 }
3712
3713 Found.suppressDiagnostics();
3714
3716 hasNewExtendedAlignment(*this, Context.getCanonicalTagType(RD)))
3718
3719 // C++17 [expr.delete]p10:
3720 // If the deallocation functions have class scope, the one without a
3721 // parameter of type std::size_t is selected.
3723 resolveDeallocationOverload(*this, Found, IDP, StartLoc, &Matches);
3724
3725 // If we could find an overload, use it.
3726 if (Matches.size() == 1) {
3727 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3728 return CheckDeleteOperator(*this, StartLoc, StartLoc, Diagnose,
3729 Found.getNamingClass(), Matches[0].Found,
3730 Operator);
3731 }
3732
3733 // We found multiple suitable operators; complain about the ambiguity.
3734 // FIXME: The standard doesn't say to do this; it appears that the intent
3735 // is that this should never happen.
3736 if (!Matches.empty()) {
3737 if (Diagnose) {
3738 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3739 << Name << RD;
3740 for (auto &Match : Matches)
3741 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3742 }
3743 return true;
3744 }
3745
3746 // We did find operator delete/operator delete[] declarations, but
3747 // none of them were suitable.
3748 if (!Found.empty()) {
3749 if (Diagnose) {
3750 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3751 << Name << RD;
3752
3753 for (NamedDecl *D : Found)
3754 Diag(D->getUnderlyingDecl()->getLocation(),
3755 diag::note_member_declared_here) << Name;
3756 }
3757 return true;
3758 }
3759
3760 Operator = nullptr;
3761 return false;
3762}
3763
3764namespace {
3765/// Checks whether delete-expression, and new-expression used for
3766/// initializing deletee have the same array form.
3767class MismatchingNewDeleteDetector {
3768public:
3769 enum MismatchResult {
3770 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3771 NoMismatch,
3772 /// Indicates that variable is initialized with mismatching form of \a new.
3773 VarInitMismatches,
3774 /// Indicates that member is initialized with mismatching form of \a new.
3775 MemberInitMismatches,
3776 /// Indicates that 1 or more constructors' definitions could not been
3777 /// analyzed, and they will be checked again at the end of translation unit.
3778 AnalyzeLater
3779 };
3780
3781 /// \param EndOfTU True, if this is the final analysis at the end of
3782 /// translation unit. False, if this is the initial analysis at the point
3783 /// delete-expression was encountered.
3784 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3785 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3786 HasUndefinedConstructors(false) {}
3787
3788 /// Checks whether pointee of a delete-expression is initialized with
3789 /// matching form of new-expression.
3790 ///
3791 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3792 /// point where delete-expression is encountered, then a warning will be
3793 /// issued immediately. If return value is \c AnalyzeLater at the point where
3794 /// delete-expression is seen, then member will be analyzed at the end of
3795 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3796 /// couldn't be analyzed. If at least one constructor initializes the member
3797 /// with matching type of new, the return value is \c NoMismatch.
3798 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3799 /// Analyzes a class member.
3800 /// \param Field Class member to analyze.
3801 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3802 /// for deleting the \p Field.
3803 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3804 FieldDecl *Field;
3805 /// List of mismatching new-expressions used for initialization of the pointee
3806 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3807 /// Indicates whether delete-expression was in array form.
3808 bool IsArrayForm;
3809
3810private:
3811 const bool EndOfTU;
3812 /// Indicates that there is at least one constructor without body.
3813 bool HasUndefinedConstructors;
3814 /// Returns \c CXXNewExpr from given initialization expression.
3815 /// \param E Expression used for initializing pointee in delete-expression.
3816 /// E can be a single-element \c InitListExpr consisting of new-expression.
3817 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3818 /// Returns whether member is initialized with mismatching form of
3819 /// \c new either by the member initializer or in-class initialization.
3820 ///
3821 /// If bodies of all constructors are not visible at the end of translation
3822 /// unit or at least one constructor initializes member with the matching
3823 /// form of \c new, mismatch cannot be proven, and this function will return
3824 /// \c NoMismatch.
3825 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3826 /// Returns whether variable is initialized with mismatching form of
3827 /// \c new.
3828 ///
3829 /// If variable is initialized with matching form of \c new or variable is not
3830 /// initialized with a \c new expression, this function will return true.
3831 /// If variable is initialized with mismatching form of \c new, returns false.
3832 /// \param D Variable to analyze.
3833 bool hasMatchingVarInit(const DeclRefExpr *D);
3834 /// Checks whether the constructor initializes pointee with mismatching
3835 /// form of \c new.
3836 ///
3837 /// Returns true, if member is initialized with matching form of \c new in
3838 /// member initializer list. Returns false, if member is initialized with the
3839 /// matching form of \c new in this constructor's initializer or given
3840 /// constructor isn't defined at the point where delete-expression is seen, or
3841 /// member isn't initialized by the constructor.
3842 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3843 /// Checks whether member is initialized with matching form of
3844 /// \c new in member initializer list.
3845 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3846 /// Checks whether member is initialized with mismatching form of \c new by
3847 /// in-class initializer.
3848 MismatchResult analyzeInClassInitializer();
3849};
3850}
3851
3852MismatchingNewDeleteDetector::MismatchResult
3853MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3854 NewExprs.clear();
3855 assert(DE && "Expected delete-expression");
3856 IsArrayForm = DE->isArrayForm();
3857 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3858 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3859 return analyzeMemberExpr(ME);
3860 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3861 if (!hasMatchingVarInit(D))
3862 return VarInitMismatches;
3863 }
3864 return NoMismatch;
3865}
3866
3867const CXXNewExpr *
3868MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3869 assert(E != nullptr && "Expected a valid initializer expression");
3870 E = E->IgnoreParenImpCasts();
3871 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3872 if (ILE->getNumInits() == 1)
3873 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3874 }
3875
3876 return dyn_cast_or_null<const CXXNewExpr>(E);
3877}
3878
3879bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3880 const CXXCtorInitializer *CI) {
3881 const CXXNewExpr *NE = nullptr;
3882 if (Field == CI->getMember() &&
3883 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3884 if (NE->isArray() == IsArrayForm)
3885 return true;
3886 else
3887 NewExprs.push_back(NE);
3888 }
3889 return false;
3890}
3891
3892bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3893 const CXXConstructorDecl *CD) {
3894 if (CD->isImplicit())
3895 return false;
3896 const FunctionDecl *Definition = CD;
3898 HasUndefinedConstructors = true;
3899 return EndOfTU;
3900 }
3901 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3902 if (hasMatchingNewInCtorInit(CI))
3903 return true;
3904 }
3905 return false;
3906}
3907
3908MismatchingNewDeleteDetector::MismatchResult
3909MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3910 assert(Field != nullptr && "This should be called only for members");
3911 const Expr *InitExpr = Field->getInClassInitializer();
3912 if (!InitExpr)
3913 return EndOfTU ? NoMismatch : AnalyzeLater;
3914 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3915 if (NE->isArray() != IsArrayForm) {
3916 NewExprs.push_back(NE);
3917 return MemberInitMismatches;
3918 }
3919 }
3920 return NoMismatch;
3921}
3922
3923MismatchingNewDeleteDetector::MismatchResult
3924MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3925 bool DeleteWasArrayForm) {
3926 assert(Field != nullptr && "Analysis requires a valid class member.");
3927 this->Field = Field;
3928 IsArrayForm = DeleteWasArrayForm;
3929 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3930 for (const auto *CD : RD->ctors()) {
3931 if (hasMatchingNewInCtor(CD))
3932 return NoMismatch;
3933 }
3934 if (HasUndefinedConstructors)
3935 return EndOfTU ? NoMismatch : AnalyzeLater;
3936 if (!NewExprs.empty())
3937 return MemberInitMismatches;
3938 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3939 : NoMismatch;
3940}
3941
3942MismatchingNewDeleteDetector::MismatchResult
3943MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3944 assert(ME != nullptr && "Expected a member expression");
3945 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3946 return analyzeField(F, IsArrayForm);
3947 return NoMismatch;
3948}
3949
3950bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3951 const CXXNewExpr *NE = nullptr;
3952 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3953 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3954 NE->isArray() != IsArrayForm) {
3955 NewExprs.push_back(NE);
3956 }
3957 }
3958 return NewExprs.empty();
3959}
3960
3961static void
3963 const MismatchingNewDeleteDetector &Detector) {
3964 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3965 FixItHint H;
3966 if (!Detector.IsArrayForm)
3967 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3968 else {
3970 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3971 SemaRef.getLangOpts(), true);
3972 if (RSquare.isValid())
3973 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3974 }
3975 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3976 << Detector.IsArrayForm << H;
3977
3978 for (const auto *NE : Detector.NewExprs)
3979 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3980 << Detector.IsArrayForm;
3981}
3982
3983void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3984 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3985 return;
3986 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3987 switch (Detector.analyzeDeleteExpr(DE)) {
3988 case MismatchingNewDeleteDetector::VarInitMismatches:
3989 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3990 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3991 break;
3992 }
3993 case MismatchingNewDeleteDetector::AnalyzeLater: {
3994 DeleteExprs[Detector.Field].push_back(
3995 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3996 break;
3997 }
3998 case MismatchingNewDeleteDetector::NoMismatch:
3999 break;
4000 }
4001}
4002
4003void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
4004 bool DeleteWasArrayForm) {
4005 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
4006 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
4007 case MismatchingNewDeleteDetector::VarInitMismatches:
4008 llvm_unreachable("This analysis should have been done for class members.");
4009 case MismatchingNewDeleteDetector::AnalyzeLater:
4010 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
4011 "translation unit.");
4012 case MismatchingNewDeleteDetector::MemberInitMismatches:
4013 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
4014 break;
4015 case MismatchingNewDeleteDetector::NoMismatch:
4016 break;
4017 }
4018}
4019
4021Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
4022 bool ArrayForm, Expr *ExE) {
4023 // C++ [expr.delete]p1:
4024 // The operand shall have a pointer type, or a class type having a single
4025 // non-explicit conversion function to a pointer type. The result has type
4026 // void.
4027 //
4028 // DR599 amends "pointer type" to "pointer to object type" in both cases.
4029
4030 ExprResult Ex = ExE;
4031 FunctionDecl *OperatorDelete = nullptr;
4032 bool ArrayFormAsWritten = ArrayForm;
4033 bool UsualArrayDeleteWantsSize = false;
4034
4035 if (!Ex.get()->isTypeDependent()) {
4036 // Perform lvalue-to-rvalue cast, if needed.
4037 Ex = DefaultLvalueConversion(Ex.get());
4038 if (Ex.isInvalid())
4039 return ExprError();
4040
4041 QualType Type = Ex.get()->getType();
4042
4043 class DeleteConverter : public ContextualImplicitConverter {
4044 public:
4045 DeleteConverter() : ContextualImplicitConverter(false, true) {}
4046
4047 bool match(QualType ConvType) override {
4048 // FIXME: If we have an operator T* and an operator void*, we must pick
4049 // the operator T*.
4050 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4051 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
4052 return true;
4053 return false;
4054 }
4055
4056 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
4057 QualType T) override {
4058 return S.Diag(Loc, diag::err_delete_operand) << T;
4059 }
4060
4061 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4062 QualType T) override {
4063 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
4064 }
4065
4066 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4067 QualType T,
4068 QualType ConvTy) override {
4069 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
4070 }
4071
4072 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4073 QualType ConvTy) override {
4074 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
4075 << ConvTy;
4076 }
4077
4078 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4079 QualType T) override {
4080 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
4081 }
4082
4083 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4084 QualType ConvTy) override {
4085 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
4086 << ConvTy;
4087 }
4088
4089 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
4090 QualType T,
4091 QualType ConvTy) override {
4092 llvm_unreachable("conversion functions are permitted");
4093 }
4094 } Converter;
4095
4096 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
4097 if (Ex.isInvalid())
4098 return ExprError();
4099 Type = Ex.get()->getType();
4100 if (!Converter.match(Type))
4101 // FIXME: PerformContextualImplicitConversion should return ExprError
4102 // itself in this case.
4103 return ExprError();
4104
4106 QualType PointeeElem = Context.getBaseElementType(Pointee);
4107
4108 if (Pointee.getAddressSpace() != LangAS::Default &&
4109 !getLangOpts().OpenCLCPlusPlus)
4110 return Diag(Ex.get()->getBeginLoc(),
4111 diag::err_address_space_qualified_delete)
4112 << Pointee.getUnqualifiedType()
4114
4115 CXXRecordDecl *PointeeRD = nullptr;
4116 if (Pointee->isVoidType() && !isSFINAEContext()) {
4117 // The C++ standard bans deleting a pointer to a non-object type, which
4118 // effectively bans deletion of "void*". However, most compilers support
4119 // this, so we treat it as a warning unless we're in a SFINAE context.
4120 // But we still prohibit this since C++26.
4121 Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
4122 : diag::ext_delete_void_ptr_operand)
4123 << (LangOpts.CPlusPlus26 ? Pointee : Type)
4124 << Ex.get()->getSourceRange();
4125 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
4126 Pointee->isSizelessType()) {
4127 return ExprError(Diag(StartLoc, diag::err_delete_operand)
4128 << Type << Ex.get()->getSourceRange());
4129 } else if (!Pointee->isDependentType()) {
4130 // FIXME: This can result in errors if the definition was imported from a
4131 // module but is hidden.
4132 if (Pointee->isEnumeralType() ||
4133 !RequireCompleteType(StartLoc, Pointee,
4134 LangOpts.CPlusPlus26
4135 ? diag::err_delete_incomplete
4136 : diag::warn_delete_incomplete,
4137 Ex.get())) {
4138 PointeeRD = PointeeElem->getAsCXXRecordDecl();
4139 }
4140 }
4141
4142 if (Pointee->isArrayType() && !ArrayForm) {
4143 Diag(StartLoc, diag::warn_delete_array_type)
4144 << Type << Ex.get()->getSourceRange()
4146 ArrayForm = true;
4147 }
4148
4149 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
4150 ArrayForm ? OO_Array_Delete : OO_Delete);
4151
4152 if (PointeeRD) {
4156 if (!UseGlobal &&
4157 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
4158 OperatorDelete, IDP))
4159 return ExprError();
4160
4161 // If we're allocating an array of records, check whether the
4162 // usual operator delete[] has a size_t parameter.
4163 if (ArrayForm) {
4164 // If the user specifically asked to use the global allocator,
4165 // we'll need to do the lookup into the class.
4166 if (UseGlobal)
4167 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(
4168 *this, StartLoc, IDP.PassTypeIdentity, PointeeElem);
4169
4170 // Otherwise, the usual operator delete[] should be the
4171 // function we just found.
4172 else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete)) {
4173 UsualDeallocFnInfo UDFI(
4174 *this, DeclAccessPair::make(OperatorDelete, AS_public), Pointee,
4175 StartLoc);
4176 UsualArrayDeleteWantsSize = isSizedDeallocation(UDFI.IDP.PassSize);
4177 }
4178 }
4179
4180 if (!PointeeRD->hasIrrelevantDestructor()) {
4181 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
4182 if (Dtor->isCalledByDelete(OperatorDelete)) {
4183 MarkFunctionReferenced(StartLoc, Dtor);
4184 if (DiagnoseUseOfDecl(Dtor, StartLoc))
4185 return ExprError();
4186 }
4187 }
4188 }
4189
4190 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
4191 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
4192 /*WarnOnNonAbstractTypes=*/!ArrayForm,
4193 SourceLocation());
4194 }
4195
4196 if (!OperatorDelete) {
4197 if (getLangOpts().OpenCLCPlusPlus) {
4198 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
4199 return ExprError();
4200 }
4201
4202 bool IsComplete = isCompleteType(StartLoc, Pointee);
4203 bool CanProvideSize =
4204 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
4205 Pointee.isDestructedType());
4206 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
4207
4208 // Look for a global declaration.
4211 alignedAllocationModeFromBool(Overaligned),
4212 sizedDeallocationModeFromBool(CanProvideSize)};
4213 OperatorDelete = FindUsualDeallocationFunction(StartLoc, IDP, DeleteName);
4214 if (!OperatorDelete)
4215 return ExprError();
4216 }
4217
4218 if (OperatorDelete->isInvalidDecl())
4219 return ExprError();
4220
4221 MarkFunctionReferenced(StartLoc, OperatorDelete);
4222
4223 // Check access and ambiguity of destructor if we're going to call it.
4224 // Note that this is required even for a virtual delete.
4225 bool IsVirtualDelete = false;
4226 if (PointeeRD) {
4227 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
4228 if (Dtor->isCalledByDelete(OperatorDelete))
4229 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
4230 PDiag(diag::err_access_dtor) << PointeeElem);
4231 IsVirtualDelete = Dtor->isVirtual();
4232 }
4233 }
4234
4235 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
4236
4237 unsigned AddressParamIdx = 0;
4238 if (OperatorDelete->isTypeAwareOperatorNewOrDelete()) {
4239 QualType TypeIdentity = OperatorDelete->getParamDecl(0)->getType();
4240 if (RequireCompleteType(StartLoc, TypeIdentity,
4241 diag::err_incomplete_type))
4242 return ExprError();
4243 AddressParamIdx = 1;
4244 }
4245
4246 // Convert the operand to the type of the first parameter of operator
4247 // delete. This is only necessary if we selected a destroying operator
4248 // delete that we are going to call (non-virtually); converting to void*
4249 // is trivial and left to AST consumers to handle.
4250 QualType ParamType =
4251 OperatorDelete->getParamDecl(AddressParamIdx)->getType();
4252 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
4253 Qualifiers Qs = Pointee.getQualifiers();
4254 if (Qs.hasCVRQualifiers()) {
4255 // Qualifiers are irrelevant to this conversion; we're only looking
4256 // for access and ambiguity.
4258 QualType Unqual = Context.getPointerType(
4259 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
4260 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
4261 }
4262 Ex = PerformImplicitConversion(Ex.get(), ParamType,
4264 if (Ex.isInvalid())
4265 return ExprError();
4266 }
4267 }
4268
4270 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
4271 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
4272 AnalyzeDeleteExprMismatch(Result);
4273 return Result;
4274}
4275
4277 bool IsDelete,
4278 FunctionDecl *&Operator) {
4279
4281 IsDelete ? OO_Delete : OO_New);
4282
4283 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
4285 assert(!R.empty() && "implicitly declared allocation functions not found");
4286 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
4287
4288 // We do our own custom access checks below.
4289 R.suppressDiagnostics();
4290
4291 SmallVector<Expr *, 8> Args(TheCall->arguments());
4292 OverloadCandidateSet Candidates(R.getNameLoc(),
4294 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
4295 FnOvl != FnOvlEnd; ++FnOvl) {
4296 // Even member operator new/delete are implicitly treated as
4297 // static, so don't use AddMemberCandidate.
4298 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
4299
4300 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
4301 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
4302 /*ExplicitTemplateArgs=*/nullptr, Args,
4303 Candidates,
4304 /*SuppressUserConversions=*/false);
4305 continue;
4306 }
4307
4309 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
4310 /*SuppressUserConversions=*/false);
4311 }
4312
4313 SourceRange Range = TheCall->getSourceRange();
4314
4315 // Do the resolution.
4317 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
4318 case OR_Success: {
4319 // Got one!
4320 FunctionDecl *FnDecl = Best->Function;
4321 assert(R.getNamingClass() == nullptr &&
4322 "class members should not be considered");
4323
4325 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
4326 << (IsDelete ? 1 : 0) << Range;
4327 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
4328 << R.getLookupName() << FnDecl->getSourceRange();
4329 return true;
4330 }
4331
4332 Operator = FnDecl;
4333 return false;
4334 }
4335
4337 Candidates.NoteCandidates(
4338 PartialDiagnosticAt(R.getNameLoc(),
4339 S.PDiag(diag::err_ovl_no_viable_function_in_call)
4340 << R.getLookupName() << Range),
4341 S, OCD_AllCandidates, Args);
4342 return true;
4343
4344 case OR_Ambiguous:
4345 Candidates.NoteCandidates(
4346 PartialDiagnosticAt(R.getNameLoc(),
4347 S.PDiag(diag::err_ovl_ambiguous_call)
4348 << R.getLookupName() << Range),
4349 S, OCD_AmbiguousCandidates, Args);
4350 return true;
4351
4352 case OR_Deleted:
4353 S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),
4354 Candidates, Best->Function, Args);
4355 return true;
4356 }
4357 llvm_unreachable("Unreachable, bad result from BestViableFunction");
4358}
4359
4360ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
4361 bool IsDelete) {
4362 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4363 if (!getLangOpts().CPlusPlus) {
4364 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
4365 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
4366 << "C++";
4367 return ExprError();
4368 }
4369 // CodeGen assumes it can find the global new and delete to call,
4370 // so ensure that they are declared.
4372
4373 FunctionDecl *OperatorNewOrDelete = nullptr;
4374 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
4375 OperatorNewOrDelete))
4376 return ExprError();
4377 assert(OperatorNewOrDelete && "should be found");
4378
4379 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
4380 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
4381
4382 TheCall->setType(OperatorNewOrDelete->getReturnType());
4383 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4384 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
4385 InitializedEntity Entity =
4388 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
4389 if (Arg.isInvalid())
4390 return ExprError();
4391 TheCall->setArg(i, Arg.get());
4392 }
4393 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
4394 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
4395 "Callee expected to be implicit cast to a builtin function pointer");
4396 Callee->setType(OperatorNewOrDelete->getType());
4397
4398 return TheCallResult;
4399}
4400
4402 bool IsDelete, bool CallCanBeVirtual,
4403 bool WarnOnNonAbstractTypes,
4404 SourceLocation DtorLoc) {
4405 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
4406 return;
4407
4408 // C++ [expr.delete]p3:
4409 // In the first alternative (delete object), if the static type of the
4410 // object to be deleted is different from its dynamic type, the static
4411 // type shall be a base class of the dynamic type of the object to be
4412 // deleted and the static type shall have a virtual destructor or the
4413 // behavior is undefined.
4414 //
4415 const CXXRecordDecl *PointeeRD = dtor->getParent();
4416 // Note: a final class cannot be derived from, no issue there
4417 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
4418 return;
4419
4420 // If the superclass is in a system header, there's nothing that can be done.
4421 // The `delete` (where we emit the warning) can be in a system header,
4422 // what matters for this warning is where the deleted type is defined.
4423 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4424 return;
4425
4426 QualType ClassType = dtor->getFunctionObjectParameterType();
4427 if (PointeeRD->isAbstract()) {
4428 // If the class is abstract, we warn by default, because we're
4429 // sure the code has undefined behavior.
4430 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4431 << ClassType;
4432 } else if (WarnOnNonAbstractTypes) {
4433 // Otherwise, if this is not an array delete, it's a bit suspect,
4434 // but not necessarily wrong.
4435 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4436 << ClassType;
4437 }
4438 if (!IsDelete) {
4439 std::string TypeStr;
4440 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4441 Diag(DtorLoc, diag::note_delete_non_virtual)
4442 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4443 }
4444}
4445
4447 SourceLocation StmtLoc,
4448 ConditionKind CK) {
4449 ExprResult E =
4450 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4451 if (E.isInvalid())
4452 return ConditionError();
4453 E = ActOnFinishFullExpr(E.get(), /*DiscardedValue*/ false);
4454 return ConditionResult(*this, ConditionVar, E,
4456}
4457
4459 SourceLocation StmtLoc,
4460 ConditionKind CK) {
4461 if (ConditionVar->isInvalidDecl())
4462 return ExprError();
4463
4464 QualType T = ConditionVar->getType();
4465
4466 // C++ [stmt.select]p2:
4467 // The declarator shall not specify a function or an array.
4468 if (T->isFunctionType())
4469 return ExprError(Diag(ConditionVar->getLocation(),
4470 diag::err_invalid_use_of_function_type)
4471 << ConditionVar->getSourceRange());
4472 else if (T->isArrayType())
4473 return ExprError(Diag(ConditionVar->getLocation(),
4474 diag::err_invalid_use_of_array_type)
4475 << ConditionVar->getSourceRange());
4476
4478 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4479 ConditionVar->getLocation());
4480
4481 switch (CK) {
4483 return CheckBooleanCondition(StmtLoc, Condition.get());
4484
4486 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4487
4489 return CheckSwitchCondition(StmtLoc, Condition.get());
4490 }
4491
4492 llvm_unreachable("unexpected condition kind");
4493}
4494
4495ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4496 // C++11 6.4p4:
4497 // The value of a condition that is an initialized declaration in a statement
4498 // other than a switch statement is the value of the declared variable
4499 // implicitly converted to type bool. If that conversion is ill-formed, the
4500 // program is ill-formed.
4501 // The value of a condition that is an expression is the value of the
4502 // expression, implicitly converted to bool.
4503 //
4504 // C++23 8.5.2p2
4505 // If the if statement is of the form if constexpr, the value of the condition
4506 // is contextually converted to bool and the converted expression shall be
4507 // a constant expression.
4508 //
4509
4511 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4512 return E;
4513
4514 E = ActOnFinishFullExpr(E.get(), E.get()->getExprLoc(),
4515 /*DiscardedValue*/ false,
4516 /*IsConstexpr*/ true);
4517 if (E.isInvalid())
4518 return E;
4519
4520 // FIXME: Return this value to the caller so they don't need to recompute it.
4521 llvm::APSInt Cond;
4523 E.get(), &Cond,
4524 diag::err_constexpr_if_condition_expression_is_not_constant);
4525 return E;
4526}
4527
4528bool
4530 // Look inside the implicit cast, if it exists.
4531 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4532 From = Cast->getSubExpr();
4533
4534 // A string literal (2.13.4) that is not a wide string literal can
4535 // be converted to an rvalue of type "pointer to char"; a wide
4536 // string literal can be converted to an rvalue of type "pointer
4537 // to wchar_t" (C++ 4.2p2).
4538 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4539 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4540 if (const BuiltinType *ToPointeeType
4541 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4542 // This conversion is considered only when there is an
4543 // explicit appropriate pointer target type (C++ 4.2p2).
4544 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4545 switch (StrLit->getKind()) {
4549 // We don't allow UTF literals to be implicitly converted
4550 break;
4553 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4554 ToPointeeType->getKind() == BuiltinType::Char_S);
4556 return Context.typesAreCompatible(Context.getWideCharType(),
4557 QualType(ToPointeeType, 0));
4559 assert(false && "Unevaluated string literal in expression");
4560 break;
4561 }
4562 }
4563 }
4564
4565 return false;
4566}
4567
4569 SourceLocation CastLoc,
4570 QualType Ty,
4571 CastKind Kind,
4572 CXXMethodDecl *Method,
4573 DeclAccessPair FoundDecl,
4574 bool HadMultipleCandidates,
4575 Expr *From) {
4576 switch (Kind) {
4577 default: llvm_unreachable("Unhandled cast kind!");
4578 case CK_ConstructorConversion: {
4580 SmallVector<Expr*, 8> ConstructorArgs;
4581
4582 if (S.RequireNonAbstractType(CastLoc, Ty,
4583 diag::err_allocation_of_abstract_type))
4584 return ExprError();
4585
4586 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4587 ConstructorArgs))
4588 return ExprError();
4589
4590 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4592 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4593 return ExprError();
4594
4596 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4597 ConstructorArgs, HadMultipleCandidates,
4598 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4600 if (Result.isInvalid())
4601 return ExprError();
4602
4603 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4604 }
4605
4606 case CK_UserDefinedConversion: {
4607 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4608
4609 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4610 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4611 return ExprError();
4612
4613 // Create an implicit call expr that calls it.
4615 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4616 HadMultipleCandidates);
4617 if (Result.isInvalid())
4618 return ExprError();
4619 // Record usage of conversion in an implicit cast.
4620 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4621 CK_UserDefinedConversion, Result.get(),
4622 nullptr, Result.get()->getValueKind(),
4624
4625 return S.MaybeBindToTemporary(Result.get());
4626 }
4627 }
4628}
4629
4632 const ImplicitConversionSequence &ICS,
4633 AssignmentAction Action,
4635 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4637 !From->getType()->isRecordType())
4638 return From;
4639
4640 switch (ICS.getKind()) {
4642 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4643 Action, CCK);
4644 if (Res.isInvalid())
4645 return ExprError();
4646 From = Res.get();
4647 break;
4648 }
4649
4651
4654 QualType BeforeToType;
4655 assert(FD && "no conversion function for user-defined conversion seq");
4656 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4657 CastKind = CK_UserDefinedConversion;
4658
4659 // If the user-defined conversion is specified by a conversion function,
4660 // the initial standard conversion sequence converts the source type to
4661 // the implicit object parameter of the conversion function.
4662 BeforeToType = Context.getCanonicalTagType(Conv->getParent());
4663 } else {
4665 CastKind = CK_ConstructorConversion;
4666 // Do no conversion if dealing with ... for the first conversion.
4668 // If the user-defined conversion is specified by a constructor, the
4669 // initial standard conversion sequence converts the source type to
4670 // the type required by the argument of the constructor
4671 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4672 }
4673 }
4674 // Watch out for ellipsis conversion.
4677 From, BeforeToType, ICS.UserDefined.Before,
4679 if (Res.isInvalid())
4680 return ExprError();
4681 From = Res.get();
4682 }
4683
4685 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4688
4689 if (CastArg.isInvalid())
4690 return ExprError();
4691
4692 From = CastArg.get();
4693
4694 // C++ [over.match.oper]p7:
4695 // [...] the second standard conversion sequence of a user-defined
4696 // conversion sequence is not applied.
4698 return From;
4699
4700 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4702 }
4703
4705 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4706 PDiag(diag::err_typecheck_ambiguous_condition)
4707 << From->getSourceRange());
4708 return ExprError();
4709
4712 llvm_unreachable("bad conversion");
4713
4715 AssignConvertType ConvTy =
4716 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4717 bool Diagnosed = DiagnoseAssignmentResult(
4720 : ConvTy,
4721 From->getExprLoc(), ToType, From->getType(), From, Action);
4722 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4723 return ExprError();
4724 }
4725
4726 // Everything went well.
4727 return From;
4728}
4729
4730// adjustVectorOrConstantMatrixType - Compute the intermediate cast type casting
4731// elements of the from type to the elements of the to type without resizing the
4732// vector or matrix.
4734 QualType FromTy,
4735 QualType ToType,
4736 QualType *ElTy = nullptr) {
4737 QualType ElType = ToType;
4738 if (auto *ToVec = ToType->getAs<VectorType>())
4739 ElType = ToVec->getElementType();
4740 else if (auto *ToMat = ToType->getAs<ConstantMatrixType>())
4741 ElType = ToMat->getElementType();
4742
4743 if (ElTy)
4744 *ElTy = ElType;
4745 if (FromTy->isVectorType()) {
4746 auto *FromVec = FromTy->castAs<VectorType>();
4747 return Context.getExtVectorType(ElType, FromVec->getNumElements());
4748 }
4749 if (FromTy->isConstantMatrixType()) {
4750 auto *FromMat = FromTy->castAs<ConstantMatrixType>();
4751 return Context.getConstantMatrixType(ElType, FromMat->getNumRows(),
4752 FromMat->getNumColumns());
4753 }
4754 return ElType;
4755}
4756
4757/// Check if an integral conversion involves incompatible overflow behavior
4758/// types. Returns true if the conversion is invalid.
4760 QualType ToType, Expr *From) {
4761 const auto *FromOBT = FromType->getAs<OverflowBehaviorType>();
4762 const auto *ToOBT = ToType->getAs<OverflowBehaviorType>();
4763
4764 if (FromOBT && ToOBT &&
4765 FromOBT->getBehaviorKind() != ToOBT->getBehaviorKind()) {
4766 S.Diag(From->getExprLoc(), diag::err_incompatible_obt_kinds_assignment)
4767 << ToType << FromType
4768 << (ToOBT->getBehaviorKind() ==
4769 OverflowBehaviorType::OverflowBehaviorKind::Trap
4770 ? "__ob_trap"
4771 : "__ob_wrap")
4772 << (FromOBT->getBehaviorKind() ==
4773 OverflowBehaviorType::OverflowBehaviorKind::Trap
4774 ? "__ob_trap"
4775 : "__ob_wrap");
4776 return true;
4777 }
4778 return false;
4779}
4780
4783 const StandardConversionSequence& SCS,
4784 AssignmentAction Action,
4786 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4788
4789 // Overall FIXME: we are recomputing too many types here and doing far too
4790 // much extra work. What this means is that we need to keep track of more
4791 // information that is computed when we try the implicit conversion initially,
4792 // so that we don't need to recompute anything here.
4793 QualType FromType = From->getType();
4794
4795 if (SCS.CopyConstructor) {
4796 // FIXME: When can ToType be a reference type?
4797 assert(!ToType->isReferenceType());
4798 if (SCS.Second == ICK_Derived_To_Base) {
4799 SmallVector<Expr*, 8> ConstructorArgs;
4801 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4802 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4803 return ExprError();
4804 return BuildCXXConstructExpr(
4805 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4806 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4807 /*HadMultipleCandidates*/ false,
4808 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4810 }
4811 return BuildCXXConstructExpr(
4812 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4814 /*HadMultipleCandidates*/ false,
4815 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4817 }
4818
4819 // Resolve overloaded function references.
4820 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4823 true, Found);
4824 if (!Fn)
4825 return ExprError();
4826
4827 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4828 return ExprError();
4829
4831 if (Res.isInvalid())
4832 return ExprError();
4833
4834 // We might get back another placeholder expression if we resolved to a
4835 // builtin.
4836 Res = CheckPlaceholderExpr(Res.get());
4837 if (Res.isInvalid())
4838 return ExprError();
4839
4840 From = Res.get();
4841 FromType = From->getType();
4842 }
4843
4844 // If we're converting to an atomic type, first convert to the corresponding
4845 // non-atomic type.
4846 QualType ToAtomicType;
4847 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4848 ToAtomicType = ToType;
4849 ToType = ToAtomic->getValueType();
4850 }
4851
4852 QualType InitialFromType = FromType;
4853 // Perform the first implicit conversion.
4854 switch (SCS.First) {
4855 case ICK_Identity:
4856 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4857 FromType = FromAtomic->getValueType().getUnqualifiedType();
4858 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4859 From, /*BasePath=*/nullptr, VK_PRValue,
4861 }
4862 break;
4863
4864 case ICK_Lvalue_To_Rvalue: {
4865 assert(From->getObjectKind() != OK_ObjCProperty);
4866 ExprResult FromRes = DefaultLvalueConversion(From);
4867 if (FromRes.isInvalid())
4868 return ExprError();
4869
4870 From = FromRes.get();
4871 FromType = From->getType();
4872 break;
4873 }
4874
4876 FromType = Context.getArrayDecayedType(FromType);
4877 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4878 /*BasePath=*/nullptr, CCK)
4879 .get();
4880 break;
4881
4883 if (ToType->isArrayParameterType()) {
4884 FromType = Context.getArrayParameterType(FromType);
4885 } else if (FromType->isArrayParameterType()) {
4886 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
4887 FromType = APT->getConstantArrayType(Context);
4888 }
4889 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4890 /*BasePath=*/nullptr, CCK)
4891 .get();
4892 break;
4893
4895 FromType = Context.getPointerType(FromType);
4896 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4897 VK_PRValue, /*BasePath=*/nullptr, CCK)
4898 .get();
4899 break;
4900
4901 default:
4902 llvm_unreachable("Improper first standard conversion");
4903 }
4904
4905 // Perform the second implicit conversion
4906 switch (SCS.Second) {
4907 case ICK_Identity:
4908 // C++ [except.spec]p5:
4909 // [For] assignment to and initialization of pointers to functions,
4910 // pointers to member functions, and references to functions: the
4911 // target entity shall allow at least the exceptions allowed by the
4912 // source value in the assignment or initialization.
4913 switch (Action) {
4916 // Note, function argument passing and returning are initialization.
4921 if (CheckExceptionSpecCompatibility(From, ToType))
4922 return ExprError();
4923 break;
4924
4927 // Casts and implicit conversions are not initialization, so are not
4928 // checked for exception specification mismatches.
4929 break;
4930 }
4931 // Nothing else to do.
4932 break;
4933
4936 QualType ElTy = ToType;
4937 QualType StepTy = ToType;
4938 if (FromType->isVectorType() || ToType->isVectorType() ||
4939 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
4940 StepTy =
4941 adjustVectorOrConstantMatrixType(Context, FromType, ToType, &ElTy);
4942
4943 // Check for incompatible OBT kinds before converting
4944 if (checkIncompatibleOBTConversion(*this, FromType, StepTy, From))
4945 return ExprError();
4946
4947 if (ElTy->isBooleanType()) {
4948 assert(FromType->castAsEnumDecl()->isFixed() &&
4950 "only enums with fixed underlying type can promote to bool");
4951 From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,
4952 /*BasePath=*/nullptr, CCK)
4953 .get();
4954 } else {
4955 From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,
4956 /*BasePath=*/nullptr, CCK)
4957 .get();
4958 }
4959 break;
4960 }
4961
4964 QualType StepTy = ToType;
4965 if (FromType->isVectorType() || ToType->isVectorType() ||
4966 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
4967 StepTy = adjustVectorOrConstantMatrixType(Context, FromType, ToType);
4968 From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,
4969 /*BasePath=*/nullptr, CCK)
4970 .get();
4971 break;
4972 }
4973
4976 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4977 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4978 CastKind CK;
4979 if (FromEl->isRealFloatingType()) {
4980 if (ToEl->isRealFloatingType())
4981 CK = CK_FloatingComplexCast;
4982 else
4983 CK = CK_FloatingComplexToIntegralComplex;
4984 } else if (ToEl->isRealFloatingType()) {
4985 CK = CK_IntegralComplexToFloatingComplex;
4986 } else {
4987 CK = CK_IntegralComplexCast;
4988 }
4989 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4990 CCK)
4991 .get();
4992 break;
4993 }
4994
4995 case ICK_Floating_Integral: {
4996 QualType ElTy = ToType;
4997 QualType StepTy = ToType;
4998 if (FromType->isVectorType() || ToType->isVectorType() ||
4999 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
5000 StepTy =
5001 adjustVectorOrConstantMatrixType(Context, FromType, ToType, &ElTy);
5002 if (ElTy->isRealFloatingType())
5003 From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,
5004 /*BasePath=*/nullptr, CCK)
5005 .get();
5006 else
5007 From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,
5008 /*BasePath=*/nullptr, CCK)
5009 .get();
5010 break;
5011 }
5012
5014 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
5015 "Attempting implicit fixed point conversion without a fixed "
5016 "point operand");
5017 if (FromType->isFloatingType())
5018 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
5019 VK_PRValue,
5020 /*BasePath=*/nullptr, CCK).get();
5021 else if (ToType->isFloatingType())
5022 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
5023 VK_PRValue,
5024 /*BasePath=*/nullptr, CCK).get();
5025 else if (FromType->isIntegralType(Context))
5026 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
5027 VK_PRValue,
5028 /*BasePath=*/nullptr, CCK).get();
5029 else if (ToType->isIntegralType(Context))
5030 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
5031 VK_PRValue,
5032 /*BasePath=*/nullptr, CCK).get();
5033 else if (ToType->isBooleanType())
5034 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
5035 VK_PRValue,
5036 /*BasePath=*/nullptr, CCK).get();
5037 else
5038 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
5039 VK_PRValue,
5040 /*BasePath=*/nullptr, CCK).get();
5041 break;
5042
5044 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
5045 /*BasePath=*/nullptr, CCK).get();
5046 break;
5047
5050 if (SCS.IncompatibleObjC && Action != AssignmentAction::Casting) {
5051 // Diagnose incompatible Objective-C conversions
5052 if (Action == AssignmentAction::Initializing ||
5054 Diag(From->getBeginLoc(),
5055 diag::ext_typecheck_convert_incompatible_pointer)
5056 << ToType << From->getType() << Action << From->getSourceRange()
5057 << 0;
5058 else
5059 Diag(From->getBeginLoc(),
5060 diag::ext_typecheck_convert_incompatible_pointer)
5061 << From->getType() << ToType << Action << From->getSourceRange()
5062 << 0;
5063
5064 if (From->getType()->isObjCObjectPointerType() &&
5065 ToType->isObjCObjectPointerType())
5067 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
5068 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
5069 From->getType())) {
5070 if (Action == AssignmentAction::Initializing)
5071 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
5072 else
5073 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
5074 << (Action == AssignmentAction::Casting) << From->getType()
5075 << ToType << From->getSourceRange();
5076 }
5077
5078 // Defer address space conversion to the third conversion.
5079 QualType FromPteeType = From->getType()->getPointeeType();
5080 QualType ToPteeType = ToType->getPointeeType();
5081 QualType NewToType = ToType;
5082 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
5083 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
5084 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
5085 NewToType = Context.getAddrSpaceQualType(NewToType,
5086 FromPteeType.getAddressSpace());
5087 if (ToType->isObjCObjectPointerType())
5088 NewToType = Context.getObjCObjectPointerType(NewToType);
5089 else if (ToType->isBlockPointerType())
5090 NewToType = Context.getBlockPointerType(NewToType);
5091 else
5092 NewToType = Context.getPointerType(NewToType);
5093 }
5094
5095 CastKind Kind;
5096 CXXCastPath BasePath;
5097 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
5098 return ExprError();
5099
5100 // Make sure we extend blocks if necessary.
5101 // FIXME: doing this here is really ugly.
5102 if (Kind == CK_BlockPointerToObjCPointerCast) {
5103 ExprResult E = From;
5105 From = E.get();
5106 }
5107 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
5108 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
5109 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
5110 .get();
5111 break;
5112 }
5113
5114 case ICK_Pointer_Member: {
5115 CastKind Kind;
5116 CXXCastPath BasePath;
5118 From->getType(), ToType->castAs<MemberPointerType>(), Kind, BasePath,
5119 From->getExprLoc(), From->getSourceRange(), CStyle,
5122 assert((Kind != CK_NullToMemberPointer ||
5125 "Expr must be null pointer constant!");
5126 break;
5128 break;
5130 llvm_unreachable("unexpected result");
5132 llvm_unreachable("Should not have been called if derivation isn't OK.");
5135 return ExprError();
5136 }
5137 if (CheckExceptionSpecCompatibility(From, ToType))
5138 return ExprError();
5139
5140 From =
5141 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
5142 break;
5143 }
5144
5146 // Perform half-to-boolean conversion via float.
5147 if (From->getType()->isHalfType()) {
5148 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
5149 FromType = Context.FloatTy;
5150 }
5151 QualType ElTy = FromType;
5152 QualType StepTy = ToType;
5153 if (FromType->isVectorType())
5154 ElTy = FromType->castAs<VectorType>()->getElementType();
5155 else if (FromType->isConstantMatrixType())
5156 ElTy = FromType->castAs<ConstantMatrixType>()->getElementType();
5157 if (getLangOpts().HLSL) {
5158 if (FromType->isVectorType() || ToType->isVectorType() ||
5159 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
5160 StepTy = adjustVectorOrConstantMatrixType(Context, FromType, ToType);
5161 }
5162
5163 From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),
5164 VK_PRValue,
5165 /*BasePath=*/nullptr, CCK)
5166 .get();
5167 break;
5168 }
5169
5170 case ICK_Derived_To_Base: {
5171 CXXCastPath BasePath;
5173 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
5174 From->getSourceRange(), &BasePath, CStyle))
5175 return ExprError();
5176
5177 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
5178 CK_DerivedToBase, From->getValueKind(),
5179 &BasePath, CCK).get();
5180 break;
5181 }
5182
5184 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
5185 /*BasePath=*/nullptr, CCK)
5186 .get();
5187 break;
5188
5191 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
5192 /*BasePath=*/nullptr, CCK)
5193 .get();
5194 break;
5195
5196 case ICK_Vector_Splat: {
5197 // Vector splat from any arithmetic type to a vector.
5198 Expr *Elem = prepareVectorSplat(ToType, From).get();
5199 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
5200 /*BasePath=*/nullptr, CCK)
5201 .get();
5202 break;
5203 }
5204
5205 case ICK_Complex_Real:
5206 // Case 1. x -> _Complex y
5207 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
5208 QualType ElType = ToComplex->getElementType();
5209 bool isFloatingComplex = ElType->isRealFloatingType();
5210
5211 // x -> y
5212 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
5213 // do nothing
5214 } else if (From->getType()->isRealFloatingType()) {
5215 From = ImpCastExprToType(From, ElType,
5216 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
5217 } else {
5218 assert(From->getType()->isIntegerType());
5219 From = ImpCastExprToType(From, ElType,
5220 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
5221 }
5222 // y -> _Complex y
5223 From = ImpCastExprToType(From, ToType,
5224 isFloatingComplex ? CK_FloatingRealToComplex
5225 : CK_IntegralRealToComplex).get();
5226
5227 // Case 2. _Complex x -> y
5228 } else {
5229 auto *FromComplex = From->getType()->castAs<ComplexType>();
5230 QualType ElType = FromComplex->getElementType();
5231 bool isFloatingComplex = ElType->isRealFloatingType();
5232
5233 // _Complex x -> x
5234 From = ImpCastExprToType(From, ElType,
5235 isFloatingComplex ? CK_FloatingComplexToReal
5236 : CK_IntegralComplexToReal,
5237 VK_PRValue, /*BasePath=*/nullptr, CCK)
5238 .get();
5239
5240 // x -> y
5241 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
5242 // do nothing
5243 } else if (ToType->isRealFloatingType()) {
5244 From = ImpCastExprToType(From, ToType,
5245 isFloatingComplex ? CK_FloatingCast
5246 : CK_IntegralToFloating,
5247 VK_PRValue, /*BasePath=*/nullptr, CCK)
5248 .get();
5249 } else {
5250 assert(ToType->isIntegerType());
5251 From = ImpCastExprToType(From, ToType,
5252 isFloatingComplex ? CK_FloatingToIntegral
5253 : CK_IntegralCast,
5254 VK_PRValue, /*BasePath=*/nullptr, CCK)
5255 .get();
5256 }
5257 }
5258 break;
5259
5261 LangAS AddrSpaceL =
5263 LangAS AddrSpaceR =
5265 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR,
5266 getASTContext()) &&
5267 "Invalid cast");
5268 CastKind Kind =
5269 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
5270 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
5271 VK_PRValue, /*BasePath=*/nullptr, CCK)
5272 .get();
5273 break;
5274 }
5275
5277 ExprResult FromRes = From;
5278 AssignConvertType ConvTy =
5280 if (FromRes.isInvalid())
5281 return ExprError();
5282 From = FromRes.get();
5283 assert((ConvTy == AssignConvertType::Compatible) &&
5284 "Improper transparent union conversion");
5285 (void)ConvTy;
5286 break;
5287 }
5288
5291 From = ImpCastExprToType(From, ToType,
5292 CK_ZeroToOCLOpaqueType,
5293 From->getValueKind()).get();
5294 break;
5295
5300 case ICK_Qualification:
5309 llvm_unreachable("Improper second standard conversion");
5310 }
5311
5312 if (SCS.Dimension != ICK_Identity) {
5313 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
5314 // vectors or matrices.
5315 assert(
5316 (ToType->isVectorType() || ToType->isConstantMatrixType() ||
5317 ToType->isBuiltinType()) &&
5318 "Dimension conversion output must be vector, matrix, or scalar type.");
5319 switch (SCS.Dimension) {
5320 case ICK_HLSL_Vector_Splat: {
5321 // Vector splat from any arithmetic type to a vector.
5322 Expr *Elem = prepareVectorSplat(ToType, From).get();
5323 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
5324 /*BasePath=*/nullptr, CCK)
5325 .get();
5326 break;
5327 }
5328 case ICK_HLSL_Matrix_Splat: {
5329 // Matrix splat from any arithmetic type to a matrix.
5330 Expr *Elem = prepareMatrixSplat(ToType, From).get();
5331 From =
5332 ImpCastExprToType(Elem, ToType, CK_HLSLAggregateSplatCast, VK_PRValue,
5333 /*BasePath=*/nullptr, CCK)
5334 .get();
5335 break;
5336 }
5338 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a
5339 // vector to a smaller vector or to a scalar, this can only operate on
5340 // arguments where the source type is an ExtVector and the destination
5341 // type is destination type is either an ExtVectorType or a builtin scalar
5342 // type.
5343 auto *FromVec = From->getType()->castAs<VectorType>();
5344 QualType TruncTy = FromVec->getElementType();
5345 if (auto *ToVec = ToType->getAs<VectorType>())
5346 TruncTy = Context.getExtVectorType(TruncTy, ToVec->getNumElements());
5347 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
5348 From->getValueKind())
5349 .get();
5350
5351 break;
5352 }
5354 auto *FromMat = From->getType()->castAs<ConstantMatrixType>();
5355 QualType TruncTy = FromMat->getElementType();
5356 // Preserve any sugar (e.g. `row_major`/`column_major` HLSL TypeAttrs) on
5357 // `ToType` so that downstream CodeGen can query the destination layout
5358 // from the cast node itself rather than falling back to the TU default.
5359 if (ToType->getAs<ConstantMatrixType>())
5360 TruncTy = ToType;
5361 From = ImpCastExprToType(From, TruncTy, CK_HLSLMatrixTruncation,
5362 From->getValueKind())
5363 .get();
5364 break;
5365 }
5366 case ICK_Identity:
5367 default:
5368 llvm_unreachable("Improper element standard conversion");
5369 }
5370 }
5371
5372 switch (SCS.Third) {
5373 case ICK_Identity:
5374 // Nothing to do.
5375 break;
5376
5378 // If both sides are functions (or pointers/references to them), there could
5379 // be incompatible exception declarations.
5380 if (CheckExceptionSpecCompatibility(From, ToType))
5381 return ExprError();
5382
5383 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
5384 /*BasePath=*/nullptr, CCK)
5385 .get();
5386 break;
5387
5388 case ICK_Qualification: {
5389 ExprValueKind VK = From->getValueKind();
5390 CastKind CK = CK_NoOp;
5391
5392 if (ToType->isReferenceType() &&
5393 ToType->getPointeeType().getAddressSpace() !=
5394 From->getType().getAddressSpace())
5395 CK = CK_AddressSpaceConversion;
5396
5397 if (ToType->isPointerType() &&
5398 ToType->getPointeeType().getAddressSpace() !=
5400 CK = CK_AddressSpaceConversion;
5401
5402 if (!isCast(CCK) &&
5403 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
5405 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
5406 << InitialFromType << ToType;
5407 }
5408
5409 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
5410 /*BasePath=*/nullptr, CCK)
5411 .get();
5412
5414 !getLangOpts().WritableStrings) {
5415 Diag(From->getBeginLoc(),
5417 ? diag::ext_deprecated_string_literal_conversion
5418 : diag::warn_deprecated_string_literal_conversion)
5419 << ToType.getNonReferenceType();
5420 }
5421
5422 break;
5423 }
5424
5425 default:
5426 llvm_unreachable("Improper third standard conversion");
5427 }
5428
5429 // If this conversion sequence involved a scalar -> atomic conversion, perform
5430 // that conversion now.
5431 if (!ToAtomicType.isNull()) {
5432 assert(Context.hasSameType(
5433 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
5434 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
5435 VK_PRValue, nullptr, CCK)
5436 .get();
5437 }
5438
5439 // Materialize a temporary if we're implicitly converting to a reference
5440 // type. This is not required by the C++ rules but is necessary to maintain
5441 // AST invariants.
5442 if (ToType->isReferenceType() && From->isPRValue()) {
5444 if (Res.isInvalid())
5445 return ExprError();
5446 From = Res.get();
5447 }
5448
5449 // If this conversion sequence succeeded and involved implicitly converting a
5450 // _Nullable type to a _Nonnull one, complain.
5451 if (!isCast(CCK))
5452 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
5453 From->getBeginLoc());
5454
5455 return From;
5456}
5457
5460 SourceLocation Loc,
5461 bool isIndirect) {
5462 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
5463 "placeholders should have been weeded out by now");
5464
5465 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5466 // temporary materialization conversion otherwise.
5467 if (isIndirect)
5468 LHS = DefaultLvalueConversion(LHS.get());
5469 else if (LHS.get()->isPRValue())
5471 if (LHS.isInvalid())
5472 return QualType();
5473
5474 // The RHS always undergoes lvalue conversions.
5475 RHS = DefaultLvalueConversion(RHS.get());
5476 if (RHS.isInvalid()) return QualType();
5477
5478 const char *OpSpelling = isIndirect ? "->*" : ".*";
5479 // C++ 5.5p2
5480 // The binary operator .* [p3: ->*] binds its second operand, which shall
5481 // be of type "pointer to member of T" (where T is a completely-defined
5482 // class type) [...]
5483 QualType RHSType = RHS.get()->getType();
5484 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5485 if (!MemPtr) {
5486 Diag(Loc, diag::err_bad_memptr_rhs)
5487 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5488 return QualType();
5489 }
5490
5491 CXXRecordDecl *RHSClass = MemPtr->getMostRecentCXXRecordDecl();
5492
5493 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5494 // member pointer points must be completely-defined. However, there is no
5495 // reason for this semantic distinction, and the rule is not enforced by
5496 // other compilers. Therefore, we do not check this property, as it is
5497 // likely to be considered a defect.
5498
5499 // C++ 5.5p2
5500 // [...] to its first operand, which shall be of class T or of a class of
5501 // which T is an unambiguous and accessible base class. [p3: a pointer to
5502 // such a class]
5503 QualType LHSType = LHS.get()->getType();
5504 if (isIndirect) {
5505 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5506 LHSType = Ptr->getPointeeType();
5507 else {
5508 Diag(Loc, diag::err_bad_memptr_lhs)
5509 << OpSpelling << 1 << LHSType
5511 return QualType();
5512 }
5513 }
5514 CXXRecordDecl *LHSClass = LHSType->getAsCXXRecordDecl();
5515
5516 if (!declaresSameEntity(LHSClass, RHSClass)) {
5517 // If we want to check the hierarchy, we need a complete type.
5518 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5519 OpSpelling, (int)isIndirect)) {
5520 return QualType();
5521 }
5522
5523 if (!IsDerivedFrom(Loc, LHSClass, RHSClass)) {
5524 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5525 << (int)isIndirect << LHS.get()->getType();
5526 return QualType();
5527 }
5528
5529 // FIXME: use sugared type from member pointer.
5530 CanQualType RHSClassType = Context.getCanonicalTagType(RHSClass);
5531 CXXCastPath BasePath;
5533 LHSType, RHSClassType, Loc,
5534 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5535 &BasePath))
5536 return QualType();
5537
5538 // Cast LHS to type of use.
5539 QualType UseType =
5540 Context.getQualifiedType(RHSClassType, LHSType.getQualifiers());
5541 if (isIndirect)
5542 UseType = Context.getPointerType(UseType);
5543 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
5544 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5545 &BasePath);
5546 }
5547
5549 // Diagnose use of pointer-to-member type which when used as
5550 // the functional cast in a pointer-to-member expression.
5551 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5552 return QualType();
5553 }
5554
5555 // C++ 5.5p2
5556 // The result is an object or a function of the type specified by the
5557 // second operand.
5558 // The cv qualifiers are the union of those in the pointer and the left side,
5559 // in accordance with 5.5p5 and 5.2.5.
5560 QualType Result = MemPtr->getPointeeType();
5561 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5562
5563 // C++0x [expr.mptr.oper]p6:
5564 // In a .* expression whose object expression is an rvalue, the program is
5565 // ill-formed if the second operand is a pointer to member function with
5566 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5567 // expression is an lvalue, the program is ill-formed if the second operand
5568 // is a pointer to member function with ref-qualifier &&.
5569 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5570 switch (Proto->getRefQualifier()) {
5571 case RQ_None:
5572 // Do nothing
5573 break;
5574
5575 case RQ_LValue:
5576 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5577 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5578 // is (exactly) 'const'.
5579 if (Proto->isConst() && !Proto->isVolatile())
5581 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5582 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5583 else
5584 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5585 << RHSType << 1 << LHS.get()->getSourceRange();
5586 }
5587 break;
5588
5589 case RQ_RValue:
5590 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5591 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5592 << RHSType << 0 << LHS.get()->getSourceRange();
5593 break;
5594 }
5595 }
5596
5597 // C++ [expr.mptr.oper]p6:
5598 // The result of a .* expression whose second operand is a pointer
5599 // to a data member is of the same value category as its
5600 // first operand. The result of a .* expression whose second
5601 // operand is a pointer to a member function is a prvalue. The
5602 // result of an ->* expression is an lvalue if its second operand
5603 // is a pointer to data member and a prvalue otherwise.
5604 if (Result->isFunctionType()) {
5605 VK = VK_PRValue;
5606 return Context.BoundMemberTy;
5607 } else if (isIndirect) {
5608 VK = VK_LValue;
5609 } else {
5610 VK = LHS.get()->getValueKind();
5611 }
5612
5613 return Result;
5614}
5615
5616/// Try to convert a type to another according to C++11 5.16p3.
5617///
5618/// This is part of the parameter validation for the ? operator. If either
5619/// value operand is a class type, the two operands are attempted to be
5620/// converted to each other. This function does the conversion in one direction.
5621/// It returns true if the program is ill-formed and has already been diagnosed
5622/// as such.
5623static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5624 SourceLocation QuestionLoc,
5625 bool &HaveConversion,
5626 QualType &ToType) {
5627 HaveConversion = false;
5628 ToType = To->getType();
5629
5630 InitializationKind Kind =
5632 // C++11 5.16p3
5633 // The process for determining whether an operand expression E1 of type T1
5634 // can be converted to match an operand expression E2 of type T2 is defined
5635 // as follows:
5636 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5637 // implicitly converted to type "lvalue reference to T2", subject to the
5638 // constraint that in the conversion the reference must bind directly to
5639 // an lvalue.
5640 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5641 // implicitly converted to the type "rvalue reference to R2", subject to
5642 // the constraint that the reference must bind directly.
5643 if (To->isGLValue()) {
5644 QualType T = Self.Context.getReferenceQualifiedType(To);
5646
5647 InitializationSequence InitSeq(Self, Entity, Kind, From);
5648 if (InitSeq.isDirectReferenceBinding()) {
5649 ToType = T;
5650 HaveConversion = true;
5651 return false;
5652 }
5653
5654 if (InitSeq.isAmbiguous())
5655 return InitSeq.Diagnose(Self, Entity, Kind, From);
5656 }
5657
5658 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5659 // -- if E1 and E2 have class type, and the underlying class types are
5660 // the same or one is a base class of the other:
5661 QualType FTy = From->getType();
5662 QualType TTy = To->getType();
5663 const RecordType *FRec = FTy->getAsCanonical<RecordType>();
5664 const RecordType *TRec = TTy->getAsCanonical<RecordType>();
5665 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5666 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5667 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5668 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5669 // E1 can be converted to match E2 if the class of T2 is the
5670 // same type as, or a base class of, the class of T1, and
5671 // [cv2 > cv1].
5672 if (FRec == TRec || FDerivedFromT) {
5673 if (TTy.isAtLeastAsQualifiedAs(FTy, Self.getASTContext())) {
5675 InitializationSequence InitSeq(Self, Entity, Kind, From);
5676 if (InitSeq) {
5677 HaveConversion = true;
5678 return false;
5679 }
5680
5681 if (InitSeq.isAmbiguous())
5682 return InitSeq.Diagnose(Self, Entity, Kind, From);
5683 }
5684 }
5685
5686 return false;
5687 }
5688
5689 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5690 // implicitly converted to the type that expression E2 would have
5691 // if E2 were converted to an rvalue (or the type it has, if E2 is
5692 // an rvalue).
5693 //
5694 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5695 // to the array-to-pointer or function-to-pointer conversions.
5696 TTy = TTy.getNonLValueExprType(Self.Context);
5697
5699 InitializationSequence InitSeq(Self, Entity, Kind, From);
5700 HaveConversion = !InitSeq.Failed();
5701 ToType = TTy;
5702 if (InitSeq.isAmbiguous())
5703 return InitSeq.Diagnose(Self, Entity, Kind, From);
5704
5705 return false;
5706}
5707
5708/// Try to find a common type for two according to C++0x 5.16p5.
5709///
5710/// This is part of the parameter validation for the ? operator. If either
5711/// value operand is a class type, overload resolution is used to find a
5712/// conversion to a common type.
5714 SourceLocation QuestionLoc) {
5715 Expr *Args[2] = { LHS.get(), RHS.get() };
5716 OverloadCandidateSet CandidateSet(QuestionLoc,
5718 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5719 CandidateSet);
5720
5722 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5723 case OR_Success: {
5724 // We found a match. Perform the conversions on the arguments and move on.
5725 ExprResult LHSRes = Self.PerformImplicitConversion(
5726 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5728 if (LHSRes.isInvalid())
5729 break;
5730 LHS = LHSRes;
5731
5732 ExprResult RHSRes = Self.PerformImplicitConversion(
5733 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5735 if (RHSRes.isInvalid())
5736 break;
5737 RHS = RHSRes;
5738 if (Best->Function)
5739 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5740 return false;
5741 }
5742
5744
5745 // Emit a better diagnostic if one of the expressions is a null pointer
5746 // constant and the other is a pointer type. In this case, the user most
5747 // likely forgot to take the address of the other expression.
5748 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5749 return true;
5750
5751 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5752 << LHS.get()->getType() << RHS.get()->getType()
5753 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5754 return true;
5755
5756 case OR_Ambiguous:
5757 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5758 << LHS.get()->getType() << RHS.get()->getType()
5759 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5760 // FIXME: Print the possible common types by printing the return types of
5761 // the viable candidates.
5762 break;
5763
5764 case OR_Deleted:
5765 llvm_unreachable("Conditional operator has only built-in overloads");
5766 }
5767 return true;
5768}
5769
5770/// Perform an "extended" implicit conversion as returned by
5771/// TryClassUnification.
5774 InitializationKind Kind =
5776 Expr *Arg = E.get();
5777 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5778 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5779 if (Result.isInvalid())
5780 return true;
5781
5782 E = Result;
5783 return false;
5784}
5785
5786// Check the condition operand of ?: to see if it is valid for the GCC
5787// extension.
5789 QualType CondTy) {
5790 bool IsSVEVectorType = CondTy->isSveVLSBuiltinType();
5791 if (!CondTy->isVectorType() && !CondTy->isExtVectorType() && !IsSVEVectorType)
5792 return false;
5793 const QualType EltTy =
5794 IsSVEVectorType
5795 ? cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx)
5796 : cast<VectorType>(CondTy.getCanonicalType())->getElementType();
5797 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
5798 return EltTy->isIntegralType(Ctx);
5799}
5800
5802 ExprResult &RHS,
5803 SourceLocation QuestionLoc) {
5806
5807 QualType CondType = Cond.get()->getType();
5808 QualType LHSType = LHS.get()->getType();
5809 QualType RHSType = RHS.get()->getType();
5810
5811 bool LHSSizelessVector = LHSType->isSizelessVectorType();
5812 bool RHSSizelessVector = RHSType->isSizelessVectorType();
5813 bool LHSIsVector = LHSType->isVectorType() || LHSSizelessVector;
5814 bool RHSIsVector = RHSType->isVectorType() || RHSSizelessVector;
5815
5816 auto GetVectorInfo =
5817 [&](QualType Type) -> std::pair<QualType, llvm::ElementCount> {
5818 if (const auto *VT = Type->getAs<VectorType>())
5819 return std::make_pair(VT->getElementType(),
5820 llvm::ElementCount::getFixed(VT->getNumElements()));
5822 Context.getBuiltinVectorTypeInfo(Type->castAs<BuiltinType>());
5823 return std::make_pair(VectorInfo.ElementType, VectorInfo.EC);
5824 };
5825
5826 auto [CondElementTy, CondElementCount] = GetVectorInfo(CondType);
5827
5828 QualType ResultType;
5829 if (LHSIsVector && RHSIsVector) {
5830 if (CondType->isExtVectorType() != LHSType->isExtVectorType()) {
5831 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
5832 << /*isExtVectorNotSizeless=*/1;
5833 return {};
5834 }
5835
5836 // If both are vector types, they must be the same type.
5837 if (!Context.hasSameType(LHSType, RHSType)) {
5838 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
5839 << LHSType << RHSType;
5840 return {};
5841 }
5842 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
5843 } else if (LHSIsVector || RHSIsVector) {
5844 bool ResultSizeless = LHSSizelessVector || RHSSizelessVector;
5845 if (ResultSizeless != CondType->isSizelessVectorType()) {
5846 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
5847 << /*isExtVectorNotSizeless=*/0;
5848 return {};
5849 }
5850 if (ResultSizeless)
5851 ResultType = CheckSizelessVectorOperands(LHS, RHS, QuestionLoc,
5852 /*IsCompAssign*/ false,
5854 else
5855 ResultType = CheckVectorOperands(
5856 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
5857 /*AllowBoolConversions*/ false,
5858 /*AllowBoolOperation*/ true,
5859 /*ReportInvalid*/ true);
5860 if (ResultType.isNull())
5861 return {};
5862 } else {
5863 // Both are scalar.
5864 LHSType = LHSType.getUnqualifiedType();
5865 RHSType = RHSType.getUnqualifiedType();
5866 QualType ResultElementTy =
5867 Context.hasSameType(LHSType, RHSType)
5868 ? Context.getCommonSugaredType(LHSType, RHSType)
5869 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
5871
5872 if (ResultElementTy->isEnumeralType()) {
5873 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5874 << ResultElementTy;
5875 return {};
5876 }
5877 if (CondType->isExtVectorType()) {
5878 ResultType = Context.getExtVectorType(ResultElementTy,
5879 CondElementCount.getFixedValue());
5880 } else if (CondType->isSizelessVectorType()) {
5881 ResultType = Context.getScalableVectorType(
5882 ResultElementTy, CondElementCount.getKnownMinValue());
5883 // There are not scalable vector type mappings for all element counts.
5884 if (ResultType.isNull()) {
5885 Diag(QuestionLoc, diag::err_conditional_vector_scalar_type_unsupported)
5886 << ResultElementTy << CondType;
5887 return {};
5888 }
5889 } else {
5890 ResultType = Context.getVectorType(ResultElementTy,
5891 CondElementCount.getFixedValue(),
5893 }
5894 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
5895 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
5896 }
5897
5898 assert(!ResultType.isNull() &&
5899 (ResultType->isVectorType() || ResultType->isSizelessVectorType()) &&
5900 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
5901 "Result should have been a vector type");
5902
5903 auto [ResultElementTy, ResultElementCount] = GetVectorInfo(ResultType);
5904 if (ResultElementCount != CondElementCount) {
5905 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
5906 << ResultType;
5907 return {};
5908 }
5909
5910 // Boolean vectors are permitted outside of OpenCL mode.
5911 if (Context.getTypeSize(ResultElementTy) !=
5912 Context.getTypeSize(CondElementTy) &&
5913 (!CondElementTy->isBooleanType() || LangOpts.OpenCL)) {
5914 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
5915 << CondType << ResultType;
5916 return {};
5917 }
5918
5919 return ResultType;
5920}
5921
5924 ExprObjectKind &OK,
5925 SourceLocation QuestionLoc) {
5926 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
5927 // pointers.
5928
5929 // Assume r-value.
5930 VK = VK_PRValue;
5931 OK = OK_Ordinary;
5932 bool IsVectorConditional =
5934
5935 // C++11 [expr.cond]p1
5936 // The first expression is contextually converted to bool.
5937 if (!Cond.get()->isTypeDependent()) {
5938 ExprResult CondRes = IsVectorConditional
5941 if (CondRes.isInvalid())
5942 return QualType();
5943 Cond = CondRes;
5944 } else {
5945 // To implement C++, the first expression typically doesn't alter the result
5946 // type of the conditional, however the GCC compatible vector extension
5947 // changes the result type to be that of the conditional. Since we cannot
5948 // know if this is a vector extension here, delay the conversion of the
5949 // LHS/RHS below until later.
5950 return Context.DependentTy;
5951 }
5952
5953
5954 // Either of the arguments dependent?
5955 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5956 return Context.DependentTy;
5957
5958 // C++11 [expr.cond]p2
5959 // If either the second or the third operand has type (cv) void, ...
5960 QualType LTy = LHS.get()->getType();
5961 QualType RTy = RHS.get()->getType();
5962 bool LVoid = LTy->isVoidType();
5963 bool RVoid = RTy->isVoidType();
5964 if (LVoid || RVoid) {
5965 // ... one of the following shall hold:
5966 // -- The second or the third operand (but not both) is a (possibly
5967 // parenthesized) throw-expression; the result is of the type
5968 // and value category of the other.
5969 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5970 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5971
5972 // Void expressions aren't legal in the vector-conditional expressions.
5973 if (IsVectorConditional) {
5974 SourceRange DiagLoc =
5975 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
5976 bool IsThrow = LVoid ? LThrow : RThrow;
5977 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
5978 << DiagLoc << IsThrow;
5979 return QualType();
5980 }
5981
5982 if (LThrow != RThrow) {
5983 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5984 VK = NonThrow->getValueKind();
5985 // DR (no number yet): the result is a bit-field if the
5986 // non-throw-expression operand is a bit-field.
5987 OK = NonThrow->getObjectKind();
5988 return NonThrow->getType();
5989 }
5990
5991 // -- Both the second and third operands have type void; the result is of
5992 // type void and is a prvalue.
5993 if (LVoid && RVoid)
5994 return Context.getCommonSugaredType(LTy, RTy);
5995
5996 // Neither holds, error.
5997 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5998 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5999 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6000 return QualType();
6001 }
6002
6003 // Neither is void.
6004 if (IsVectorConditional)
6005 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6006
6007 // WebAssembly tables are not allowed as conditional LHS or RHS.
6008 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
6009 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
6010 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6011 return QualType();
6012 }
6013
6014 // C++11 [expr.cond]p3
6015 // Otherwise, if the second and third operand have different types, and
6016 // either has (cv) class type [...] an attempt is made to convert each of
6017 // those operands to the type of the other.
6018 if (!Context.hasSameType(LTy, RTy) &&
6019 (LTy->isRecordType() || RTy->isRecordType())) {
6020 // These return true if a single direction is already ambiguous.
6021 QualType L2RType, R2LType;
6022 bool HaveL2R, HaveR2L;
6023 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6024 return QualType();
6025 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6026 return QualType();
6027
6028 // If both can be converted, [...] the program is ill-formed.
6029 if (HaveL2R && HaveR2L) {
6030 Diag(QuestionLoc, diag::err_conditional_ambiguous)
6031 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6032 return QualType();
6033 }
6034
6035 // If exactly one conversion is possible, that conversion is applied to
6036 // the chosen operand and the converted operands are used in place of the
6037 // original operands for the remainder of this section.
6038 if (HaveL2R) {
6039 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6040 return QualType();
6041 LTy = LHS.get()->getType();
6042 } else if (HaveR2L) {
6043 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6044 return QualType();
6045 RTy = RHS.get()->getType();
6046 }
6047 }
6048
6049 // C++11 [expr.cond]p3
6050 // if both are glvalues of the same value category and the same type except
6051 // for cv-qualification, an attempt is made to convert each of those
6052 // operands to the type of the other.
6053 // FIXME:
6054 // Resolving a defect in P0012R1: we extend this to cover all cases where
6055 // one of the operands is reference-compatible with the other, in order
6056 // to support conditionals between functions differing in noexcept. This
6057 // will similarly cover difference in array bounds after P0388R4.
6058 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6059 // that instead?
6060 ExprValueKind LVK = LHS.get()->getValueKind();
6061 ExprValueKind RVK = RHS.get()->getValueKind();
6062 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6063 // DerivedToBase was already handled by the class-specific case above.
6064 // FIXME: Should we allow ObjC conversions here?
6065 const ReferenceConversions AllowedConversions =
6066 ReferenceConversions::Qualification |
6067 ReferenceConversions::NestedQualification |
6068 ReferenceConversions::Function;
6069
6070 ReferenceConversions RefConv;
6071 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6073 !(RefConv & ~AllowedConversions) &&
6074 // [...] subject to the constraint that the reference must bind
6075 // directly [...]
6076 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6077 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6078 RTy = RHS.get()->getType();
6079 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6081 !(RefConv & ~AllowedConversions) &&
6082 !LHS.get()->refersToBitField() &&
6083 !LHS.get()->refersToVectorElement()) {
6084 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6085 LTy = LHS.get()->getType();
6086 }
6087 }
6088
6089 // C++11 [expr.cond]p4
6090 // If the second and third operands are glvalues of the same value
6091 // category and have the same type, the result is of that type and
6092 // value category and it is a bit-field if the second or the third
6093 // operand is a bit-field, or if both are bit-fields.
6094 // We only extend this to bitfields, not to the crazy other kinds of
6095 // l-values.
6096 bool Same = Context.hasSameType(LTy, RTy);
6097 if (Same && LVK == RVK && LVK != VK_PRValue &&
6100 VK = LHS.get()->getValueKind();
6101 if (LHS.get()->getObjectKind() == OK_BitField ||
6102 RHS.get()->getObjectKind() == OK_BitField)
6103 OK = OK_BitField;
6104 return Context.getCommonSugaredType(LTy, RTy);
6105 }
6106
6107 // C++11 [expr.cond]p5
6108 // Otherwise, the result is a prvalue. If the second and third operands
6109 // do not have the same type, and either has (cv) class type, ...
6110 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6111 // ... overload resolution is used to determine the conversions (if any)
6112 // to be applied to the operands. If the overload resolution fails, the
6113 // program is ill-formed.
6114 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6115 return QualType();
6116 }
6117
6118 // C++11 [expr.cond]p6
6119 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6120 // conversions are performed on the second and third operands.
6123 if (LHS.isInvalid() || RHS.isInvalid())
6124 return QualType();
6125 LTy = LHS.get()->getType();
6126 RTy = RHS.get()->getType();
6127
6128 // After those conversions, one of the following shall hold:
6129 // -- The second and third operands have the same type; the result
6130 // is of that type. If the operands have class type, the result
6131 // is a prvalue temporary of the result type, which is
6132 // copy-initialized from either the second operand or the third
6133 // operand depending on the value of the first operand.
6134 if (Context.hasSameType(LTy, RTy)) {
6135 if (LTy->isRecordType()) {
6136 // The operands have class type. Make a temporary copy.
6139 if (LHSCopy.isInvalid())
6140 return QualType();
6141
6144 if (RHSCopy.isInvalid())
6145 return QualType();
6146
6147 LHS = LHSCopy;
6148 RHS = RHSCopy;
6149 }
6150 return Context.getCommonSugaredType(LTy, RTy);
6151 }
6152
6153 // Extension: conditional operator involving vector types.
6154 if (LTy->isVectorType() || RTy->isVectorType())
6155 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
6156 /*AllowBothBool*/ true,
6157 /*AllowBoolConversions*/ false,
6158 /*AllowBoolOperation*/ false,
6159 /*ReportInvalid*/ true);
6160
6161 // -- The second and third operands have arithmetic or enumeration type;
6162 // the usual arithmetic conversions are performed to bring them to a
6163 // common type, and the result is of that type.
6164 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6165 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6167 if (LHS.isInvalid() || RHS.isInvalid())
6168 return QualType();
6169 if (ResTy.isNull()) {
6170 Diag(QuestionLoc,
6171 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6172 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6173 return QualType();
6174 }
6175
6176 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6177 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6178
6179 return ResTy;
6180 }
6181
6182 // -- The second and third operands have pointer type, or one has pointer
6183 // type and the other is a null pointer constant, or both are null
6184 // pointer constants, at least one of which is non-integral; pointer
6185 // conversions and qualification conversions are performed to bring them
6186 // to their composite pointer type. The result is of the composite
6187 // pointer type.
6188 // -- The second and third operands have pointer to member type, or one has
6189 // pointer to member type and the other is a null pointer constant;
6190 // pointer to member conversions and qualification conversions are
6191 // performed to bring them to a common type, whose cv-qualification
6192 // shall match the cv-qualification of either the second or the third
6193 // operand. The result is of the common type.
6194 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6195 if (!Composite.isNull())
6196 return Composite;
6197
6198 // Similarly, attempt to find composite type of two objective-c pointers.
6199 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6200 if (LHS.isInvalid() || RHS.isInvalid())
6201 return QualType();
6202 if (!Composite.isNull())
6203 return Composite;
6204
6205 // Check if we are using a null with a non-pointer type.
6206 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6207 return QualType();
6208
6209 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6210 << LHS.get()->getType() << RHS.get()->getType()
6211 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6212 return QualType();
6213}
6214
6216 Expr *&E1, Expr *&E2,
6217 bool ConvertArgs) {
6218 assert(getLangOpts().CPlusPlus && "This function assumes C++");
6219
6220 // C++1z [expr]p14:
6221 // The composite pointer type of two operands p1 and p2 having types T1
6222 // and T2
6223 QualType T1 = E1->getType(), T2 = E2->getType();
6224
6225 // where at least one is a pointer or pointer to member type or
6226 // std::nullptr_t is:
6227 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6228 T1->isNullPtrType();
6229 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6230 T2->isNullPtrType();
6231 if (!T1IsPointerLike && !T2IsPointerLike)
6232 return QualType();
6233
6234 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6235 // This can't actually happen, following the standard, but we also use this
6236 // to implement the end of [expr.conv], which hits this case.
6237 //
6238 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6239 if (T1IsPointerLike &&
6241 if (ConvertArgs)
6242 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6243 ? CK_NullToMemberPointer
6244 : CK_NullToPointer).get();
6245 return T1;
6246 }
6247 if (T2IsPointerLike &&
6249 if (ConvertArgs)
6250 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6251 ? CK_NullToMemberPointer
6252 : CK_NullToPointer).get();
6253 return T2;
6254 }
6255
6256 // Now both have to be pointers or member pointers.
6257 if (!T1IsPointerLike || !T2IsPointerLike)
6258 return QualType();
6259 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6260 "nullptr_t should be a null pointer constant");
6261
6262 struct Step {
6263 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6264 // Qualifiers to apply under the step kind.
6265 Qualifiers Quals;
6266 /// The class for a pointer-to-member; a constant array type with a bound
6267 /// (if any) for an array.
6268 /// FIXME: Store Qualifier for pointer-to-member.
6269 const Type *ClassOrBound;
6270
6271 Step(Kind K, const Type *ClassOrBound = nullptr)
6272 : K(K), ClassOrBound(ClassOrBound) {}
6273 QualType rebuild(ASTContext &Ctx, QualType T) const {
6274 T = Ctx.getQualifiedType(T, Quals);
6275 switch (K) {
6276 case Pointer:
6277 return Ctx.getPointerType(T);
6278 case MemberPointer:
6279 return Ctx.getMemberPointerType(T, /*Qualifier=*/std::nullopt,
6280 ClassOrBound->getAsCXXRecordDecl());
6281 case ObjCPointer:
6282 return Ctx.getObjCObjectPointerType(T);
6283 case Array:
6284 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6285 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6287 else
6289 }
6290 llvm_unreachable("unknown step kind");
6291 }
6292 };
6293
6295
6296 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6297 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6298 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6299 // respectively;
6300 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6301 // to member of C2 of type cv2 U2" for some non-function type U, where
6302 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6303 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6304 // respectively;
6305 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6306 // T2;
6307 //
6308 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6309 // and to prepare to form the cv-combined type if so.
6310 QualType Composite1 = T1;
6311 QualType Composite2 = T2;
6312 unsigned NeedConstBefore = 0;
6313 while (true) {
6314 assert(!Composite1.isNull() && !Composite2.isNull());
6315
6316 Qualifiers Q1, Q2;
6317 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6318 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6319
6320 // Top-level qualifiers are ignored. Merge at all lower levels.
6321 if (!Steps.empty()) {
6322 // Find the qualifier union: (approximately) the unique minimal set of
6323 // qualifiers that is compatible with both types.
6325 Q2.getCVRUQualifiers());
6326
6327 // Under one level of pointer or pointer-to-member, we can change to an
6328 // unambiguous compatible address space.
6329 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6330 Quals.setAddressSpace(Q1.getAddressSpace());
6331 } else if (Steps.size() == 1) {
6332 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2, getASTContext());
6333 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1, getASTContext());
6334 if (MaybeQ1 == MaybeQ2) {
6335 // Exception for ptr size address spaces. Should be able to choose
6336 // either address space during comparison.
6339 MaybeQ1 = true;
6340 else
6341 return QualType(); // No unique best address space.
6342 }
6343 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6344 : Q2.getAddressSpace());
6345 } else {
6346 return QualType();
6347 }
6348
6349 // FIXME: In C, we merge __strong and none to __strong at the top level.
6350 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6351 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6352 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6353 assert(Steps.size() == 1);
6354 else
6355 return QualType();
6356
6357 // Mismatched lifetime qualifiers never compatibly include each other.
6358 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6359 Quals.setObjCLifetime(Q1.getObjCLifetime());
6360 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6361 assert(Steps.size() == 1);
6362 else
6363 return QualType();
6364
6366 Quals.setPointerAuth(Q1.getPointerAuth());
6367 else
6368 return QualType();
6369
6370 Steps.back().Quals = Quals;
6371 if (Q1 != Quals || Q2 != Quals)
6372 NeedConstBefore = Steps.size() - 1;
6373 }
6374
6375 // FIXME: Can we unify the following with UnwrapSimilarTypes?
6376
6377 const ArrayType *Arr1, *Arr2;
6378 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
6379 (Arr2 = Context.getAsArrayType(Composite2))) {
6380 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
6381 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
6382 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
6383 Composite1 = Arr1->getElementType();
6384 Composite2 = Arr2->getElementType();
6385 Steps.emplace_back(Step::Array, CAT1);
6386 continue;
6387 }
6388 bool IAT1 = isa<IncompleteArrayType>(Arr1);
6389 bool IAT2 = isa<IncompleteArrayType>(Arr2);
6390 if ((IAT1 && IAT2) ||
6391 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
6392 ((bool)CAT1 != (bool)CAT2) &&
6393 (Steps.empty() || Steps.back().K != Step::Array))) {
6394 // In C++20 onwards, we can unify an array of N T with an array of
6395 // a different or unknown bound. But we can't form an array whose
6396 // element type is an array of unknown bound by doing so.
6397 Composite1 = Arr1->getElementType();
6398 Composite2 = Arr2->getElementType();
6399 Steps.emplace_back(Step::Array);
6400 if (CAT1 || CAT2)
6401 NeedConstBefore = Steps.size();
6402 continue;
6403 }
6404 }
6405
6406 const PointerType *Ptr1, *Ptr2;
6407 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6408 (Ptr2 = Composite2->getAs<PointerType>())) {
6409 Composite1 = Ptr1->getPointeeType();
6410 Composite2 = Ptr2->getPointeeType();
6411 Steps.emplace_back(Step::Pointer);
6412 continue;
6413 }
6414
6415 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6416 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6417 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6418 Composite1 = ObjPtr1->getPointeeType();
6419 Composite2 = ObjPtr2->getPointeeType();
6420 Steps.emplace_back(Step::ObjCPointer);
6421 continue;
6422 }
6423
6424 const MemberPointerType *MemPtr1, *MemPtr2;
6425 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6426 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6427 Composite1 = MemPtr1->getPointeeType();
6428 Composite2 = MemPtr2->getPointeeType();
6429
6430 // At the top level, we can perform a base-to-derived pointer-to-member
6431 // conversion:
6432 //
6433 // - [...] where C1 is reference-related to C2 or C2 is
6434 // reference-related to C1
6435 //
6436 // (Note that the only kinds of reference-relatedness in scope here are
6437 // "same type or derived from".) At any other level, the class must
6438 // exactly match.
6439 CXXRecordDecl *Cls = nullptr,
6440 *Cls1 = MemPtr1->getMostRecentCXXRecordDecl(),
6441 *Cls2 = MemPtr2->getMostRecentCXXRecordDecl();
6442 if (declaresSameEntity(Cls1, Cls2))
6443 Cls = Cls1;
6444 else if (Steps.empty())
6445 Cls = IsDerivedFrom(Loc, Cls1, Cls2) ? Cls1
6446 : IsDerivedFrom(Loc, Cls2, Cls1) ? Cls2
6447 : nullptr;
6448 if (!Cls)
6449 return QualType();
6450
6451 Steps.emplace_back(Step::MemberPointer,
6452 Context.getCanonicalTagType(Cls).getTypePtr());
6453 continue;
6454 }
6455
6456 // Special case: at the top level, we can decompose an Objective-C pointer
6457 // and a 'cv void *'. Unify the qualifiers.
6458 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6459 Composite2->isObjCObjectPointerType()) ||
6460 (Composite1->isObjCObjectPointerType() &&
6461 Composite2->isVoidPointerType()))) {
6462 Composite1 = Composite1->getPointeeType();
6463 Composite2 = Composite2->getPointeeType();
6464 Steps.emplace_back(Step::Pointer);
6465 continue;
6466 }
6467
6468 // FIXME: block pointer types?
6469
6470 // Cannot unwrap any more types.
6471 break;
6472 }
6473
6474 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6475 // "pointer to function", where the function types are otherwise the same,
6476 // "pointer to function";
6477 // - if T1 or T2 is "pointer to member of C1 of type function", the other
6478 // type is "pointer to member of C2 of type noexcept function", and C1
6479 // is reference-related to C2 or C2 is reference-related to C1, where
6480 // the function types are otherwise the same, "pointer to member of C2 of
6481 // type function" or "pointer to member of C1 of type function",
6482 // respectively;
6483 //
6484 // We also support 'noreturn' here, so as a Clang extension we generalize the
6485 // above to:
6486 //
6487 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6488 // "pointer to member function" and the pointee types can be unified
6489 // by a function pointer conversion, that conversion is applied
6490 // before checking the following rules.
6491 //
6492 // We've already unwrapped down to the function types, and we want to merge
6493 // rather than just convert, so do this ourselves rather than calling
6494 // IsFunctionConversion.
6495 //
6496 // FIXME: In order to match the standard wording as closely as possible, we
6497 // currently only do this under a single level of pointers. Ideally, we would
6498 // allow this in general, and set NeedConstBefore to the relevant depth on
6499 // the side(s) where we changed anything. If we permit that, we should also
6500 // consider this conversion when determining type similarity and model it as
6501 // a qualification conversion.
6502 if (Steps.size() == 1) {
6503 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6504 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6505 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6506 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6507
6508 // The result is noreturn if both operands are.
6509 bool Noreturn =
6510 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6511 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6512 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6513
6514 bool CFIUncheckedCallee =
6516 EPI1.CFIUncheckedCallee = CFIUncheckedCallee;
6517 EPI2.CFIUncheckedCallee = CFIUncheckedCallee;
6518
6519 // The result is nothrow if both operands are.
6520 SmallVector<QualType, 8> ExceptionTypeStorage;
6521 EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs(
6522 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
6524
6525 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6526 FPT1->getParamTypes(), EPI1);
6527 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6528 FPT2->getParamTypes(), EPI2);
6529 }
6530 }
6531 }
6532
6533 // There are some more conversions we can perform under exactly one pointer.
6534 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6535 !Context.hasSameType(Composite1, Composite2)) {
6536 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6537 // "pointer to cv2 T", where T is an object type or void,
6538 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6539 if (Composite1->isVoidType() && Composite2->isObjectType())
6540 Composite2 = Composite1;
6541 else if (Composite2->isVoidType() && Composite1->isObjectType())
6542 Composite1 = Composite2;
6543 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6544 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6545 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6546 // T1, respectively;
6547 //
6548 // The "similar type" handling covers all of this except for the "T1 is a
6549 // base class of T2" case in the definition of reference-related.
6550 else if (IsDerivedFrom(Loc, Composite1, Composite2))
6551 Composite1 = Composite2;
6552 else if (IsDerivedFrom(Loc, Composite2, Composite1))
6553 Composite2 = Composite1;
6554 }
6555
6556 // At this point, either the inner types are the same or we have failed to
6557 // find a composite pointer type.
6558 if (!Context.hasSameType(Composite1, Composite2))
6559 return QualType();
6560
6561 // Per C++ [conv.qual]p3, add 'const' to every level before the last
6562 // differing qualifier.
6563 for (unsigned I = 0; I != NeedConstBefore; ++I)
6564 Steps[I].Quals.addConst();
6565
6566 // Rebuild the composite type.
6567 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
6568 for (auto &S : llvm::reverse(Steps))
6569 Composite = S.rebuild(Context, Composite);
6570
6571 if (ConvertArgs) {
6572 // Convert the expressions to the composite pointer type.
6573 InitializedEntity Entity =
6575 InitializationKind Kind =
6577
6578 InitializationSequence E1ToC(*this, Entity, Kind, E1);
6579 if (!E1ToC)
6580 return QualType();
6581
6582 InitializationSequence E2ToC(*this, Entity, Kind, E2);
6583 if (!E2ToC)
6584 return QualType();
6585
6586 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6587 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
6588 if (E1Result.isInvalid())
6589 return QualType();
6590 E1 = E1Result.get();
6591
6592 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
6593 if (E2Result.isInvalid())
6594 return QualType();
6595 E2 = E2Result.get();
6596 }
6597
6598 return Composite;
6599}
6600
6602 if (!E)
6603 return ExprError();
6604
6605 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6606
6607 // If the result is a glvalue, we shouldn't bind it.
6608 if (E->isGLValue())
6609 return E;
6610
6611 // In ARC, calls that return a retainable type can return retained,
6612 // in which case we have to insert a consuming cast.
6613 if (getLangOpts().ObjCAutoRefCount &&
6614 E->getType()->isObjCRetainableType()) {
6615
6616 bool ReturnsRetained;
6617
6618 // For actual calls, we compute this by examining the type of the
6619 // called value.
6620 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6621 Expr *Callee = Call->getCallee()->IgnoreParens();
6622 QualType T = Callee->getType();
6623
6624 if (T == Context.BoundMemberTy) {
6625 // Handle pointer-to-members.
6626 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6627 T = BinOp->getRHS()->getType();
6628 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6629 T = Mem->getMemberDecl()->getType();
6630 }
6631
6632 if (const PointerType *Ptr = T->getAs<PointerType>())
6633 T = Ptr->getPointeeType();
6634 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6635 T = Ptr->getPointeeType();
6636 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6637 T = MemPtr->getPointeeType();
6638
6639 auto *FTy = T->castAs<FunctionType>();
6640 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6641
6642 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6643 // type always produce a +1 object.
6644 } else if (isa<StmtExpr>(E)) {
6645 ReturnsRetained = true;
6646
6647 // We hit this case with the lambda conversion-to-block optimization;
6648 // we don't want any extra casts here.
6649 } else if (isa<CastExpr>(E) &&
6650 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6651 return E;
6652
6653 // For message sends and property references, we try to find an
6654 // actual method. FIXME: we should infer retention by selector in
6655 // cases where we don't have an actual method.
6656 } else {
6657 ObjCMethodDecl *D = nullptr;
6658 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6659 D = Send->getMethodDecl();
6660 } else if (auto *OL = dyn_cast<ObjCObjectLiteral>(E);
6661 OL && OL->isGlobalAllocation()) {
6662 return E;
6663 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6664 D = BoxedExpr->getBoxingMethod();
6665 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6666 // Don't do reclaims if we're using the zero-element array
6667 // constant.
6668 if (ArrayLit->getNumElements() == 0 &&
6669 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6670 return E;
6671
6672 D = ArrayLit->getArrayWithObjectsMethod();
6673 } else if (ObjCDictionaryLiteral *DictLit =
6674 dyn_cast<ObjCDictionaryLiteral>(E)) {
6675 // Don't do reclaims if we're using the zero-element dictionary
6676 // constant.
6677 if (DictLit->getNumElements() == 0 &&
6678 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6679 return E;
6680
6681 D = DictLit->getDictWithObjectsMethod();
6682 }
6683
6684 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6685
6686 // Don't do reclaims on performSelector calls; despite their
6687 // return type, the invoked method doesn't necessarily actually
6688 // return an object.
6689 if (!ReturnsRetained &&
6691 return E;
6692 }
6693
6694 // Don't reclaim an object of Class type.
6695 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6696 return E;
6697
6698 Cleanup.setExprNeedsCleanups(true);
6699
6700 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6701 : CK_ARCReclaimReturnedObject);
6702 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6704 }
6705
6707 Cleanup.setExprNeedsCleanups(true);
6708
6709 if (!getLangOpts().CPlusPlus)
6710 return E;
6711
6712 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6713 // a fast path for the common case that the type is directly a RecordType.
6714 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6715 const RecordType *RT = nullptr;
6716 while (!RT) {
6717 switch (T->getTypeClass()) {
6718 case Type::Record:
6719 RT = cast<RecordType>(T);
6720 break;
6721 case Type::ConstantArray:
6722 case Type::IncompleteArray:
6723 case Type::VariableArray:
6724 case Type::DependentSizedArray:
6725 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6726 break;
6727 default:
6728 return E;
6729 }
6730 }
6731
6732 // That should be enough to guarantee that this type is complete, if we're
6733 // not processing a decltype expression.
6734 auto *RD = cast<CXXRecordDecl>(RT->getDecl())->getDefinitionOrSelf();
6735 if (RD->isInvalidDecl() || RD->isDependentContext())
6736 return E;
6737
6738 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6741
6742 if (Destructor) {
6745 PDiag(diag::err_access_dtor_temp)
6746 << E->getType());
6748 return ExprError();
6749
6750 // If destructor is trivial, we can avoid the extra copy.
6751 if (Destructor->isTrivial())
6752 return E;
6753
6754 // We need a cleanup, but we don't need to remember the temporary.
6755 Cleanup.setExprNeedsCleanups(true);
6756 }
6757
6760
6761 if (IsDecltype)
6762 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6763
6764 return Bind;
6765}
6766
6769 if (SubExpr.isInvalid())
6770 return ExprError();
6771
6772 return MaybeCreateExprWithCleanups(SubExpr.get());
6773}
6774
6776 assert(SubExpr && "subexpression can't be null!");
6777
6779
6780 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6781 assert(ExprCleanupObjects.size() >= FirstCleanup);
6782 assert(Cleanup.exprNeedsCleanups() ||
6783 ExprCleanupObjects.size() == FirstCleanup);
6784 if (!Cleanup.exprNeedsCleanups())
6785 return SubExpr;
6786
6787 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6788 ExprCleanupObjects.size() - FirstCleanup);
6789
6790 auto *E = ExprWithCleanups::Create(
6791 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6793
6794 return E;
6795}
6796
6798 assert(SubStmt && "sub-statement can't be null!");
6799
6801
6802 if (!Cleanup.exprNeedsCleanups())
6803 return SubStmt;
6804
6805 // FIXME: In order to attach the temporaries, wrap the statement into
6806 // a StmtExpr; currently this is only used for asm statements.
6807 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6808 // a new AsmStmtWithTemporaries.
6809 CompoundStmt *CompStmt =
6812 Expr *E = new (Context)
6813 StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
6814 /*FIXME TemplateDepth=*/0);
6816}
6817
6819 assert(ExprEvalContexts.back().ExprContext ==
6821 "not in a decltype expression");
6822
6824 if (Result.isInvalid())
6825 return ExprError();
6826 E = Result.get();
6827
6828 // C++11 [expr.call]p11:
6829 // If a function call is a prvalue of object type,
6830 // -- if the function call is either
6831 // -- the operand of a decltype-specifier, or
6832 // -- the right operand of a comma operator that is the operand of a
6833 // decltype-specifier,
6834 // a temporary object is not introduced for the prvalue.
6835
6836 // Recursively rebuild ParenExprs and comma expressions to strip out the
6837 // outermost CXXBindTemporaryExpr, if any.
6838 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6839 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6840 if (SubExpr.isInvalid())
6841 return ExprError();
6842 if (SubExpr.get() == PE->getSubExpr())
6843 return E;
6844 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6845 }
6846 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6847 if (BO->getOpcode() == BO_Comma) {
6848 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6849 if (RHS.isInvalid())
6850 return ExprError();
6851 if (RHS.get() == BO->getRHS())
6852 return E;
6853 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
6854 BO->getType(), BO->getValueKind(),
6855 BO->getObjectKind(), BO->getOperatorLoc(),
6856 BO->getFPFeatures());
6857 }
6858 }
6859
6860 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6861 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6862 : nullptr;
6863 if (TopCall)
6864 E = TopCall;
6865 else
6866 TopBind = nullptr;
6867
6868 // Disable the special decltype handling now.
6869 ExprEvalContexts.back().ExprContext =
6871
6873 if (Result.isInvalid())
6874 return ExprError();
6875 E = Result.get();
6876
6877 // In MS mode, don't perform any extra checking of call return types within a
6878 // decltype expression.
6879 if (getLangOpts().MSVCCompat)
6880 return E;
6881
6882 // Perform the semantic checks we delayed until this point.
6883 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6884 I != N; ++I) {
6885 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6886 if (Call == TopCall)
6887 continue;
6888
6889 if (CheckCallReturnType(Call->getCallReturnType(Context),
6890 Call->getBeginLoc(), Call, Call->getDirectCallee()))
6891 return ExprError();
6892 }
6893
6894 // Now all relevant types are complete, check the destructors are accessible
6895 // and non-deleted, and annotate them on the temporaries.
6896 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6897 I != N; ++I) {
6899 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6900 if (Bind == TopBind)
6901 continue;
6902
6903 CXXTemporary *Temp = Bind->getTemporary();
6904
6905 CXXRecordDecl *RD =
6906 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6909
6910 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6911 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6912 PDiag(diag::err_access_dtor_temp)
6913 << Bind->getType());
6914 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6915 return ExprError();
6916
6917 // We need a cleanup, but we don't need to remember the temporary.
6918 Cleanup.setExprNeedsCleanups(true);
6919 }
6920
6921 // Possibly strip off the top CXXBindTemporaryExpr.
6922 return E;
6923}
6924
6925/// Note a set of 'operator->' functions that were used for a member access.
6927 ArrayRef<FunctionDecl *> OperatorArrows) {
6928 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6929 // FIXME: Make this configurable?
6930 unsigned Limit = 9;
6931 if (OperatorArrows.size() > Limit) {
6932 // Produce Limit-1 normal notes and one 'skipping' note.
6933 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6934 SkipCount = OperatorArrows.size() - (Limit - 1);
6935 }
6936
6937 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6938 if (I == SkipStart) {
6939 S.Diag(OperatorArrows[I]->getLocation(),
6940 diag::note_operator_arrows_suppressed)
6941 << SkipCount;
6942 I += SkipCount;
6943 } else {
6944 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6945 << OperatorArrows[I]->getCallResultType();
6946 ++I;
6947 }
6948 }
6949}
6950
6952 SourceLocation OpLoc,
6953 tok::TokenKind OpKind,
6954 ParsedType &ObjectType,
6955 bool &MayBePseudoDestructor) {
6956 // Since this might be a postfix expression, get rid of ParenListExprs.
6958 if (Result.isInvalid()) return ExprError();
6959 Base = Result.get();
6960
6962 if (Result.isInvalid()) return ExprError();
6963 Base = Result.get();
6964
6965 QualType BaseType = Base->getType();
6966 MayBePseudoDestructor = false;
6967 if (BaseType->isDependentType()) {
6968 // If we have a pointer to a dependent type and are using the -> operator,
6969 // the object type is the type that the pointer points to. We might still
6970 // have enough information about that type to do something useful.
6971 if (OpKind == tok::arrow)
6972 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6973 BaseType = Ptr->getPointeeType();
6974
6975 ObjectType = ParsedType::make(BaseType);
6976 MayBePseudoDestructor = true;
6977 return Base;
6978 }
6979
6980 // C++ [over.match.oper]p8:
6981 // [...] When operator->returns, the operator-> is applied to the value
6982 // returned, with the original second operand.
6983 if (OpKind == tok::arrow) {
6984 QualType StartingType = BaseType;
6985 bool NoArrowOperatorFound = false;
6986 bool FirstIteration = true;
6987 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6988 // The set of types we've considered so far.
6990 SmallVector<FunctionDecl*, 8> OperatorArrows;
6991 CTypes.insert(Context.getCanonicalType(BaseType));
6992
6993 while (BaseType->isRecordType()) {
6994 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6995 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6996 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6997 noteOperatorArrows(*this, OperatorArrows);
6998 Diag(OpLoc, diag::note_operator_arrow_depth)
6999 << getLangOpts().ArrowDepth;
7000 return ExprError();
7001 }
7002
7004 S, Base, OpLoc,
7005 // When in a template specialization and on the first loop iteration,
7006 // potentially give the default diagnostic (with the fixit in a
7007 // separate note) instead of having the error reported back to here
7008 // and giving a diagnostic with a fixit attached to the error itself.
7009 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7010 ? nullptr
7011 : &NoArrowOperatorFound);
7012 if (Result.isInvalid()) {
7013 if (NoArrowOperatorFound) {
7014 if (FirstIteration) {
7015 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7016 << BaseType << 1 << Base->getSourceRange()
7017 << FixItHint::CreateReplacement(OpLoc, ".");
7018 OpKind = tok::period;
7019 break;
7020 }
7021 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7022 << BaseType << Base->getSourceRange();
7023 CallExpr *CE = dyn_cast<CallExpr>(Base);
7024 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7025 Diag(CD->getBeginLoc(),
7026 diag::note_member_reference_arrow_from_operator_arrow);
7027 }
7028 }
7029 return ExprError();
7030 }
7031 Base = Result.get();
7032 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7033 OperatorArrows.push_back(OpCall->getDirectCallee());
7034 BaseType = Base->getType();
7035 CanQualType CBaseType = Context.getCanonicalType(BaseType);
7036 if (!CTypes.insert(CBaseType).second) {
7037 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7038 noteOperatorArrows(*this, OperatorArrows);
7039 return ExprError();
7040 }
7041 FirstIteration = false;
7042 }
7043
7044 if (OpKind == tok::arrow) {
7045 if (BaseType->isPointerType())
7046 BaseType = BaseType->getPointeeType();
7047 else if (auto *AT = Context.getAsArrayType(BaseType))
7048 BaseType = AT->getElementType();
7049 }
7050 }
7051
7052 // Objective-C properties allow "." access on Objective-C pointer types,
7053 // so adjust the base type to the object type itself.
7054 if (BaseType->isObjCObjectPointerType())
7055 BaseType = BaseType->getPointeeType();
7056
7057 // C++ [basic.lookup.classref]p2:
7058 // [...] If the type of the object expression is of pointer to scalar
7059 // type, the unqualified-id is looked up in the context of the complete
7060 // postfix-expression.
7061 //
7062 // This also indicates that we could be parsing a pseudo-destructor-name.
7063 // Note that Objective-C class and object types can be pseudo-destructor
7064 // expressions or normal member (ivar or property) access expressions, and
7065 // it's legal for the type to be incomplete if this is a pseudo-destructor
7066 // call. We'll do more incomplete-type checks later in the lookup process,
7067 // so just skip this check for ObjC types.
7068 if (!BaseType->isRecordType()) {
7069 ObjectType = ParsedType::make(BaseType);
7070 MayBePseudoDestructor = true;
7071 return Base;
7072 }
7073
7074 // The object type must be complete (or dependent), or
7075 // C++11 [expr.prim.general]p3:
7076 // Unlike the object expression in other contexts, *this is not required to
7077 // be of complete type for purposes of class member access (5.2.5) outside
7078 // the member function body.
7079 if (!BaseType->isDependentType() &&
7081 RequireCompleteType(OpLoc, BaseType,
7082 diag::err_incomplete_member_access)) {
7083 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7084 }
7085
7086 // C++ [basic.lookup.classref]p2:
7087 // If the id-expression in a class member access (5.2.5) is an
7088 // unqualified-id, and the type of the object expression is of a class
7089 // type C (or of pointer to a class type C), the unqualified-id is looked
7090 // up in the scope of class C. [...]
7091 ObjectType = ParsedType::make(BaseType);
7092 return Base;
7093}
7094
7095static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7096 tok::TokenKind &OpKind, SourceLocation OpLoc) {
7097 if (Base->hasPlaceholderType()) {
7099 if (result.isInvalid()) return true;
7100 Base = result.get();
7101 }
7102 ObjectType = Base->getType();
7103
7104 // C++ [expr.pseudo]p2:
7105 // The left-hand side of the dot operator shall be of scalar type. The
7106 // left-hand side of the arrow operator shall be of pointer to scalar type.
7107 // This scalar type is the object type.
7108 // Note that this is rather different from the normal handling for the
7109 // arrow operator.
7110 if (OpKind == tok::arrow) {
7111 // The operator requires a prvalue, so perform lvalue conversions.
7112 // Only do this if we might plausibly end with a pointer, as otherwise
7113 // this was likely to be intended to be a '.'.
7114 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7115 ObjectType->isFunctionType()) {
7117 if (BaseResult.isInvalid())
7118 return true;
7119 Base = BaseResult.get();
7120 ObjectType = Base->getType();
7121 }
7122
7123 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7124 ObjectType = Ptr->getPointeeType();
7125 } else if (!Base->isTypeDependent()) {
7126 // The user wrote "p->" when they probably meant "p."; fix it.
7127 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7128 << ObjectType << true
7129 << FixItHint::CreateReplacement(OpLoc, ".");
7130 if (S.isSFINAEContext())
7131 return true;
7132
7133 OpKind = tok::period;
7134 }
7135 }
7136
7137 return false;
7138}
7139
7140/// Check if it's ok to try and recover dot pseudo destructor calls on
7141/// pointer objects.
7142static bool
7144 QualType DestructedType) {
7145 // If this is a record type, check if its destructor is callable.
7146 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7147 if (RD->hasDefinition())
7149 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7150 return false;
7151 }
7152
7153 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7154 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7155 DestructedType->isVectorType();
7156}
7157
7159 SourceLocation OpLoc,
7160 tok::TokenKind OpKind,
7161 const CXXScopeSpec &SS,
7162 TypeSourceInfo *ScopeTypeInfo,
7163 SourceLocation CCLoc,
7164 SourceLocation TildeLoc,
7165 PseudoDestructorTypeStorage Destructed) {
7166 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7167
7168 QualType ObjectType;
7169 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7170 return ExprError();
7171
7172 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7173 !ObjectType->isVectorType() && !ObjectType->isMatrixType()) {
7174 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7175 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7176 else {
7177 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7178 << ObjectType << Base->getSourceRange();
7179 return ExprError();
7180 }
7181 }
7182
7183 // C++ [expr.pseudo]p2:
7184 // [...] The cv-unqualified versions of the object type and of the type
7185 // designated by the pseudo-destructor-name shall be the same type.
7186 if (DestructedTypeInfo) {
7187 QualType DestructedType = DestructedTypeInfo->getType();
7188 SourceLocation DestructedTypeStart =
7189 DestructedTypeInfo->getTypeLoc().getBeginLoc();
7190 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7191 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7192 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7193 // Foo *foo;
7194 // foo.~Foo();
7195 if (OpKind == tok::period && ObjectType->isPointerType() &&
7196 Context.hasSameUnqualifiedType(DestructedType,
7197 ObjectType->getPointeeType())) {
7198 auto Diagnostic =
7199 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7200 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7201
7202 // Issue a fixit only when the destructor is valid.
7204 *this, DestructedType))
7206
7207 // Recover by setting the object type to the destructed type and the
7208 // operator to '->'.
7209 ObjectType = DestructedType;
7210 OpKind = tok::arrow;
7211 } else {
7212 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7213 << ObjectType << DestructedType << Base->getSourceRange()
7214 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7215
7216 // Recover by setting the destructed type to the object type.
7217 DestructedType = ObjectType;
7218 DestructedTypeInfo =
7219 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7220 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7221 }
7222 } else if (DestructedType.getObjCLifetime() !=
7223 ObjectType.getObjCLifetime()) {
7224
7225 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7226 // Okay: just pretend that the user provided the correctly-qualified
7227 // type.
7228 } else {
7229 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7230 << ObjectType << DestructedType << Base->getSourceRange()
7231 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7232 }
7233
7234 // Recover by setting the destructed type to the object type.
7235 DestructedType = ObjectType;
7236 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7237 DestructedTypeStart);
7238 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7239 }
7240 }
7241 }
7242
7243 // C++ [expr.pseudo]p2:
7244 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7245 // form
7246 //
7247 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7248 //
7249 // shall designate the same scalar type.
7250 if (ScopeTypeInfo) {
7251 QualType ScopeType = ScopeTypeInfo->getType();
7252 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7253 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7254
7255 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
7256 diag::err_pseudo_dtor_type_mismatch)
7257 << ObjectType << ScopeType << Base->getSourceRange()
7258 << ScopeTypeInfo->getTypeLoc().getSourceRange();
7259
7260 ScopeType = QualType();
7261 ScopeTypeInfo = nullptr;
7262 }
7263 }
7264
7265 Expr *Result
7267 OpKind == tok::arrow, OpLoc,
7269 ScopeTypeInfo,
7270 CCLoc,
7271 TildeLoc,
7272 Destructed);
7273
7274 return Result;
7275}
7276
7278 SourceLocation OpLoc,
7279 tok::TokenKind OpKind,
7280 CXXScopeSpec &SS,
7281 UnqualifiedId &FirstTypeName,
7282 SourceLocation CCLoc,
7283 SourceLocation TildeLoc,
7284 UnqualifiedId &SecondTypeName) {
7285 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7286 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7287 "Invalid first type name in pseudo-destructor");
7288 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7289 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7290 "Invalid second type name in pseudo-destructor");
7291
7292 QualType ObjectType;
7293 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7294 return ExprError();
7295
7296 // Compute the object type that we should use for name lookup purposes. Only
7297 // record types and dependent types matter.
7298 ParsedType ObjectTypePtrForLookup;
7299 if (!SS.isSet()) {
7300 if (ObjectType->isRecordType())
7301 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7302 else if (ObjectType->isDependentType())
7303 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7304 }
7305
7306 // Convert the name of the type being destructed (following the ~) into a
7307 // type (with source-location information).
7308 QualType DestructedType;
7309 TypeSourceInfo *DestructedTypeInfo = nullptr;
7310 PseudoDestructorTypeStorage Destructed;
7311 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7312 ParsedType T = getTypeName(*SecondTypeName.Identifier,
7313 SecondTypeName.StartLocation,
7314 S, &SS, true, false, ObjectTypePtrForLookup,
7315 /*IsCtorOrDtorName*/true);
7316 if (!T &&
7317 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7318 (!SS.isSet() && ObjectType->isDependentType()))) {
7319 // The name of the type being destroyed is a dependent name, and we
7320 // couldn't find anything useful in scope. Just store the identifier and
7321 // it's location, and we'll perform (qualified) name lookup again at
7322 // template instantiation time.
7323 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7324 SecondTypeName.StartLocation);
7325 } else if (!T) {
7326 Diag(SecondTypeName.StartLocation,
7327 diag::err_pseudo_dtor_destructor_non_type)
7328 << SecondTypeName.Identifier << ObjectType;
7329 if (isSFINAEContext())
7330 return ExprError();
7331
7332 // Recover by assuming we had the right type all along.
7333 DestructedType = ObjectType;
7334 } else
7335 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7336 } else {
7337 // Resolve the template-id to a type.
7338 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7339 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7340 TemplateId->NumArgs);
7343 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
7344 TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name,
7345 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
7346 TemplateId->RAngleLoc,
7347 /*IsCtorOrDtorName*/ true);
7348 if (T.isInvalid() || !T.get()) {
7349 // Recover by assuming we had the right type all along.
7350 DestructedType = ObjectType;
7351 } else
7352 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7353 }
7354
7355 // If we've performed some kind of recovery, (re-)build the type source
7356 // information.
7357 if (!DestructedType.isNull()) {
7358 if (!DestructedTypeInfo)
7359 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7360 SecondTypeName.StartLocation);
7361 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7362 }
7363
7364 // Convert the name of the scope type (the type prior to '::') into a type.
7365 TypeSourceInfo *ScopeTypeInfo = nullptr;
7366 QualType ScopeType;
7367 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7368 FirstTypeName.Identifier) {
7369 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7370 ParsedType T = getTypeName(*FirstTypeName.Identifier,
7371 FirstTypeName.StartLocation,
7372 S, &SS, true, false, ObjectTypePtrForLookup,
7373 /*IsCtorOrDtorName*/true);
7374 if (!T) {
7375 Diag(FirstTypeName.StartLocation,
7376 diag::err_pseudo_dtor_destructor_non_type)
7377 << FirstTypeName.Identifier << ObjectType;
7378
7379 if (isSFINAEContext())
7380 return ExprError();
7381
7382 // Just drop this type. It's unnecessary anyway.
7383 ScopeType = QualType();
7384 } else
7385 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7386 } else {
7387 // Resolve the template-id to a type.
7388 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7389 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7390 TemplateId->NumArgs);
7393 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
7394 TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name,
7395 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
7396 TemplateId->RAngleLoc,
7397 /*IsCtorOrDtorName*/ true);
7398 if (T.isInvalid() || !T.get()) {
7399 // Recover by dropping this type.
7400 ScopeType = QualType();
7401 } else
7402 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7403 }
7404 }
7405
7406 if (!ScopeType.isNull() && !ScopeTypeInfo)
7407 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7408 FirstTypeName.StartLocation);
7409
7410
7411 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7412 ScopeTypeInfo, CCLoc, TildeLoc,
7413 Destructed);
7414}
7415
7417 SourceLocation OpLoc,
7418 tok::TokenKind OpKind,
7419 SourceLocation TildeLoc,
7420 const DeclSpec& DS) {
7421 QualType ObjectType;
7422 QualType T;
7423 TypeLocBuilder TLB;
7424 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc) ||
7426 return ExprError();
7427
7428 switch (DS.getTypeSpecType()) {
7430 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
7431 return true;
7432 }
7434 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
7435 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7436 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
7437 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
7438 break;
7439 }
7442 DS.getBeginLoc(), DS.getEllipsisLoc());
7444 cast<PackIndexingType>(T.getTypePtr())->getPattern(),
7445 DS.getBeginLoc());
7447 PITL.setEllipsisLoc(DS.getEllipsisLoc());
7448 break;
7449 }
7450 default:
7451 llvm_unreachable("Unsupported type in pseudo destructor");
7452 }
7453 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7454 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7455
7456 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7457 nullptr, SourceLocation(), TildeLoc,
7458 Destructed);
7459}
7460
7462 SourceLocation RParen) {
7463 // If the operand is an unresolved lookup expression, the expression is ill-
7464 // formed per [over.over]p1, because overloaded function names cannot be used
7465 // without arguments except in explicit contexts.
7466 ExprResult R = CheckPlaceholderExpr(Operand);
7467 if (R.isInvalid())
7468 return R;
7469
7470 R = CheckUnevaluatedOperand(R.get());
7471 if (R.isInvalid())
7472 return ExprError();
7473
7474 Operand = R.get();
7475
7476 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
7477 Operand->HasSideEffects(Context, false)) {
7478 // The expression operand for noexcept is in an unevaluated expression
7479 // context, so side effects could result in unintended consequences.
7480 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7481 }
7482
7483 CanThrowResult CanThrow = canThrow(Operand);
7484 return new (Context)
7485 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7486}
7487
7489 Expr *Operand, SourceLocation RParen) {
7490 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7491}
7492
7494 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
7495 DeclRefExpr *LHS = nullptr;
7496 bool IsCompoundAssign = false;
7497 bool isIncrementDecrementUnaryOp = false;
7498 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7499 if (BO->getLHS()->getType()->isDependentType() ||
7500 BO->getRHS()->getType()->isDependentType()) {
7501 if (BO->getOpcode() != BO_Assign)
7502 return;
7503 } else if (!BO->isAssignmentOp())
7504 return;
7505 else
7506 IsCompoundAssign = BO->isCompoundAssignmentOp();
7507 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
7508 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7509 if (COCE->getOperator() != OO_Equal)
7510 return;
7511 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
7512 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7513 if (!UO->isIncrementDecrementOp())
7514 return;
7515 isIncrementDecrementUnaryOp = true;
7516 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
7517 }
7518 if (!LHS)
7519 return;
7520 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
7521 if (!VD)
7522 return;
7523 // Don't decrement RefsMinusAssignments if volatile variable with compound
7524 // assignment (+=, ...) or increment/decrement unary operator to avoid
7525 // potential unused-but-set-variable warning.
7526 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
7528 return;
7529 auto iter = RefsMinusAssignments.find(VD->getCanonicalDecl());
7530 if (iter == RefsMinusAssignments.end())
7531 return;
7532 iter->getSecond()--;
7533}
7534
7535/// Perform the conversions required for an expression used in a
7536/// context that ignores the result.
7539
7540 if (E->hasPlaceholderType()) {
7541 ExprResult result = CheckPlaceholderExpr(E);
7542 if (result.isInvalid()) return E;
7543 E = result.get();
7544 }
7545
7546 if (getLangOpts().CPlusPlus) {
7547 // The C++11 standard defines the notion of a discarded-value expression;
7548 // normally, we don't need to do anything to handle it, but if it is a
7549 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7550 // conversion.
7553 if (Res.isInvalid())
7554 return E;
7555 E = Res.get();
7556 } else {
7557 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7558 // it occurs as a discarded-value expression.
7560 }
7561
7562 // C++1z:
7563 // If the expression is a prvalue after this optional conversion, the
7564 // temporary materialization conversion is applied.
7565 //
7566 // We do not materialize temporaries by default in order to avoid creating
7567 // unnecessary temporary objects. If we skip this step, IR generation is
7568 // able to synthesize the storage for itself in the aggregate case, and
7569 // adding the extra node to the AST is just clutter.
7571 E->isPRValue() && !E->getType()->isVoidType()) {
7573 if (Res.isInvalid())
7574 return E;
7575 E = Res.get();
7576 }
7577 return E;
7578 }
7579
7580 // C99 6.3.2.1:
7581 // [Except in specific positions,] an lvalue that does not have
7582 // array type is converted to the value stored in the
7583 // designated object (and is no longer an lvalue).
7584 if (E->isPRValue()) {
7585 // In C, function designators (i.e. expressions of function type)
7586 // are r-values, but we still want to do function-to-pointer decay
7587 // on them. This is both technically correct and convenient for
7588 // some clients.
7589 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7591
7592 return E;
7593 }
7594
7595 // GCC seems to also exclude expressions of incomplete enum type.
7596 if (const auto *ED = E->getType()->getAsEnumDecl(); ED && !ED->isComplete()) {
7597 // FIXME: stupid workaround for a codegen bug!
7598 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7599 return E;
7600 }
7601
7603 if (Res.isInvalid())
7604 return E;
7605 E = Res.get();
7606
7607 if (!E->getType()->isVoidType())
7609 diag::err_incomplete_type);
7610 return E;
7611}
7612
7614 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7615 // it occurs as an unevaluated operand.
7617
7618 return E;
7619}
7620
7621// If we can unambiguously determine whether Var can never be used
7622// in a constant expression, return true.
7623// - if the variable and its initializer are non-dependent, then
7624// we can unambiguously check if the variable is a constant expression.
7625// - if the initializer is not value dependent - we can determine whether
7626// it can be used to initialize a constant expression. If Init can not
7627// be used to initialize a constant expression we conclude that Var can
7628// never be a constant expression.
7629// - FXIME: if the initializer is dependent, we can still do some analysis and
7630// identify certain cases unambiguously as non-const by using a Visitor:
7631// - such as those that involve odr-use of a ParmVarDecl, involve a new
7632// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7634 ASTContext &Context) {
7635 if (isa<ParmVarDecl>(Var)) return true;
7636 const VarDecl *DefVD = nullptr;
7637
7638 // If there is no initializer - this can not be a constant expression.
7639 const Expr *Init = Var->getAnyInitializer(DefVD);
7640 if (!Init)
7641 return true;
7642 assert(DefVD);
7643 if (DefVD->isWeak())
7644 return false;
7645
7646 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7647 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7648 // of value-dependent expressions, and use it here to determine whether the
7649 // initializer is a potential constant expression.
7650 return false;
7651 }
7652
7653 return !Var->isUsableInConstantExpressions(Context);
7654}
7655
7656/// Check if the current lambda has any potential captures
7657/// that must be captured by any of its enclosing lambdas that are ready to
7658/// capture. If there is a lambda that can capture a nested
7659/// potential-capture, go ahead and do so. Also, check to see if any
7660/// variables are uncaptureable or do not involve an odr-use so do not
7661/// need to be captured.
7662
7664 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7665
7666 assert(!S.isUnevaluatedContext());
7667#ifndef NDEBUG
7668 DeclContext *DC = S.CurContext;
7669 while (isa_and_nonnull<CapturedDecl>(DC))
7670 DC = DC->getParent();
7671 assert(
7672 (CurrentLSI->CallOperator == DC || !CurrentLSI->AfterParameterList) &&
7673 "The current call operator must be synchronized with Sema's CurContext");
7674#endif // NDEBUG
7675
7676 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7677
7678 // All the potentially captureable variables in the current nested
7679 // lambda (within a generic outer lambda), must be captured by an
7680 // outer lambda that is enclosed within a non-dependent context.
7681 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
7682 // If the variable is clearly identified as non-odr-used and the full
7683 // expression is not instantiation dependent, only then do we not
7684 // need to check enclosing lambda's for speculative captures.
7685 // For e.g.:
7686 // Even though 'x' is not odr-used, it should be captured.
7687 // int test() {
7688 // const int x = 10;
7689 // auto L = [=](auto a) {
7690 // (void) +x + a;
7691 // };
7692 // }
7693 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7694 !IsFullExprInstantiationDependent)
7695 return;
7696
7697 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
7698 if (!UnderlyingVar)
7699 return;
7700
7701 // If we have a capture-capable lambda for the variable, go ahead and
7702 // capture the variable in that lambda (and all its enclosing lambdas).
7703 if (const UnsignedOrNone Index =
7705 S.FunctionScopes, Var, S))
7706 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
7707 const bool IsVarNeverAConstantExpression =
7709 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7710 // This full expression is not instantiation dependent or the variable
7711 // can not be used in a constant expression - which means
7712 // this variable must be odr-used here, so diagnose a
7713 // capture violation early, if the variable is un-captureable.
7714 // This is purely for diagnosing errors early. Otherwise, this
7715 // error would get diagnosed when the lambda becomes capture ready.
7716 QualType CaptureType, DeclRefType;
7717 SourceLocation ExprLoc = VarExpr->getExprLoc();
7718 if (S.tryCaptureVariable(Var, ExprLoc, TryCaptureKind::Implicit,
7719 /*EllipsisLoc*/ SourceLocation(),
7720 /*BuildAndDiagnose*/ false, CaptureType,
7721 DeclRefType, nullptr)) {
7722 // We will never be able to capture this variable, and we need
7723 // to be able to in any and all instantiations, so diagnose it.
7725 /*EllipsisLoc*/ SourceLocation(),
7726 /*BuildAndDiagnose*/ true, CaptureType,
7727 DeclRefType, nullptr);
7728 }
7729 }
7730 });
7731
7732 // Check if 'this' needs to be captured.
7733 if (CurrentLSI->hasPotentialThisCapture()) {
7734 // If we have a capture-capable lambda for 'this', go ahead and capture
7735 // 'this' in that lambda (and all its enclosing lambdas).
7736 if (const UnsignedOrNone Index =
7738 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
7739 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
7741 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7742 &FunctionScopeIndexOfCapturableLambda);
7743 }
7744 }
7745
7746 // Reset all the potential captures at the end of each full-expression.
7747 CurrentLSI->clearPotentialCaptures();
7748}
7749
7751 bool DiscardedValue, bool IsConstexpr,
7752 bool IsTemplateArgument) {
7753 ExprResult FullExpr = FE;
7754
7755 if (!FullExpr.get())
7756 return ExprError();
7757
7758 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
7759 return ExprError();
7760
7761 if (DiscardedValue) {
7762 // Top-level expressions default to 'id' when we're in a debugger.
7763 if (getLangOpts().DebuggerCastResultToId &&
7764 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7765 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7766 if (FullExpr.isInvalid())
7767 return ExprError();
7768 }
7769
7771 if (FullExpr.isInvalid())
7772 return ExprError();
7773
7775 if (FullExpr.isInvalid())
7776 return ExprError();
7777
7778 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
7779 }
7780
7781 if (FullExpr.isInvalid())
7782 return ExprError();
7783
7784 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7785
7786 // At the end of this full expression (which could be a deeply nested
7787 // lambda), if there is a potential capture within the nested lambda,
7788 // have the outer capture-able lambda try and capture it.
7789 // Consider the following code:
7790 // void f(int, int);
7791 // void f(const int&, double);
7792 // void foo() {
7793 // const int x = 10, y = 20;
7794 // auto L = [=](auto a) {
7795 // auto M = [=](auto b) {
7796 // f(x, b); <-- requires x to be captured by L and M
7797 // f(y, a); <-- requires y to be captured by L, but not all Ms
7798 // };
7799 // };
7800 // }
7801
7802 // FIXME: Also consider what happens for something like this that involves
7803 // the gnu-extension statement-expressions or even lambda-init-captures:
7804 // void f() {
7805 // const int n = 0;
7806 // auto L = [&](auto a) {
7807 // +n + ({ 0; a; });
7808 // };
7809 // }
7810 //
7811 // Here, we see +n, and then the full-expression 0; ends, so we don't
7812 // capture n (and instead remove it from our list of potential captures),
7813 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7814 // for us to see that we need to capture n after all.
7815
7816 LambdaScopeInfo *const CurrentLSI =
7817 getCurLambda(/*IgnoreCapturedRegions=*/true);
7818 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7819 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7820 // for an example of the code that might cause this asynchrony.
7821 // By ensuring we are in the context of a lambda's call operator
7822 // we can fix the bug (we only need to check whether we need to capture
7823 // if we are within a lambda's body); but per the comments in that
7824 // PR, a proper fix would entail :
7825 // "Alternative suggestion:
7826 // - Add to Sema an integer holding the smallest (outermost) scope
7827 // index that we are *lexically* within, and save/restore/set to
7828 // FunctionScopes.size() in InstantiatingTemplate's
7829 // constructor/destructor.
7830 // - Teach the handful of places that iterate over FunctionScopes to
7831 // stop at the outermost enclosing lexical scope."
7832 DeclContext *DC = CurContext;
7833 while (isa_and_nonnull<CapturedDecl>(DC))
7834 DC = DC->getParent();
7835 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7836 if (IsInLambdaDeclContext && CurrentLSI &&
7837 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7839 *this);
7841}
7842
7844 if (!FullStmt) return StmtError();
7845
7846 return MaybeCreateStmtWithCleanups(FullStmt);
7847}
7848
7851 const DeclarationNameInfo &TargetNameInfo) {
7852 DeclarationName TargetName = TargetNameInfo.getName();
7853 if (!TargetName)
7855
7856 // If the name itself is dependent, then the result is dependent.
7857 if (TargetName.isDependentName())
7859
7860 // Do the redeclaration lookup in the current scope.
7861 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7863 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
7864 R.suppressDiagnostics();
7865
7866 switch (R.getResultKind()) {
7872
7875
7878 }
7879
7880 llvm_unreachable("Invalid LookupResult Kind!");
7881}
7882
7884 SourceLocation KeywordLoc,
7885 bool IsIfExists,
7886 CXXScopeSpec &SS,
7887 UnqualifiedId &Name) {
7888 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7889
7890 // Check for an unexpanded parameter pack.
7891 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7892 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7893 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7894 return IfExistsResult::Error;
7895
7896 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7897}
7898
7900 return BuildExprRequirement(E, /*IsSimple=*/true,
7901 /*NoexceptLoc=*/SourceLocation(),
7902 /*ReturnTypeRequirement=*/{});
7903}
7904
7906 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7907 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
7908 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
7909 "Exactly one of TypeName and TemplateId must be specified.");
7910 TypeSourceInfo *TSI = nullptr;
7911 if (TypeName) {
7912 QualType T =
7914 SS.getWithLocInContext(Context), *TypeName, NameLoc,
7915 &TSI, /*DeducedTSTContext=*/false);
7916 if (T.isNull())
7917 return nullptr;
7918 } else {
7919 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
7920 TemplateId->NumArgs);
7921 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
7922 TemplateId->TemplateKWLoc,
7923 TemplateId->Template, TemplateId->Name,
7924 TemplateId->TemplateNameLoc,
7925 TemplateId->LAngleLoc, ArgsPtr,
7926 TemplateId->RAngleLoc);
7927 if (T.isInvalid())
7928 return nullptr;
7929 if (GetTypeFromParser(T.get(), &TSI).isNull())
7930 return nullptr;
7931 }
7932 return BuildTypeRequirement(TSI);
7933}
7934
7937 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
7938 /*ReturnTypeRequirement=*/{});
7939}
7940
7943 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7944 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
7945 // C++2a [expr.prim.req.compound] p1.3.3
7946 // [..] the expression is deduced against an invented function template
7947 // F [...] F is a void function template with a single type template
7948 // parameter T declared with the constrained-parameter. Form a new
7949 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
7950 // around the constrained-parameter. F has a single parameter whose
7951 // type-specifier is cv T followed by the abstract-declarator. [...]
7952 //
7953 // The cv part is done in the calling function - we get the concept with
7954 // arguments and the abstract declarator with the correct CV qualification and
7955 // have to synthesize T and the single parameter of F.
7956 auto &II = Context.Idents.get("expr-type");
7959 SourceLocation(), Depth,
7960 /*Index=*/0, &II,
7961 /*Typename=*/true,
7962 /*ParameterPack=*/false,
7963 /*HasTypeConstraint=*/true);
7964
7965 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
7966 /*EllipsisLoc=*/SourceLocation(),
7967 /*AllowUnexpandedPack=*/true))
7968 // Just produce a requirement with no type requirements.
7969 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
7970
7973 ArrayRef<NamedDecl *>(TParam),
7975 /*RequiresClause=*/nullptr);
7976 return BuildExprRequirement(
7977 E, /*IsSimple=*/false, NoexceptLoc,
7979}
7980
7983 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
7986 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
7988 ReturnTypeRequirement.isDependent())
7990 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
7992 else if (ReturnTypeRequirement.isSubstitutionFailure())
7994 else if (ReturnTypeRequirement.isTypeConstraint()) {
7995 // C++2a [expr.prim.req]p1.3.3
7996 // The immediately-declared constraint ([temp]) of decltype((E)) shall
7997 // be satisfied.
7999 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
8000 QualType MatchedType = Context.getReferenceQualifiedType(E);
8002 Args.push_back(TemplateArgument(MatchedType));
8003
8004 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
8005
8006 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/true);
8007 MLTAL.addOuterRetainedLevels(TPL->getDepth());
8008 const TypeConstraint *TC = Param->getTypeConstraint();
8009 assert(TC && "Type Constraint cannot be null here");
8010 auto *IDC = TC->getImmediatelyDeclaredConstraint();
8011 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
8012
8013 SFINAETrap Trap(*this);
8014 ExprResult Constraint = SubstExpr(IDC, MLTAL);
8015 bool HasError = Constraint.isInvalid();
8016 if (!HasError) {
8017 SubstitutedConstraintExpr =
8019 if (SubstitutedConstraintExpr->getSatisfaction().ContainsErrors)
8020 HasError = true;
8021 }
8022 if (HasError) {
8023 // FIXME: Capture diagnostics from the SFINAE trap and store them in the
8024 // requirement.
8026 createSubstDiagAt(IDC->getExprLoc(),
8027 [&](llvm::raw_ostream &OS) {
8028 IDC->printPretty(OS, /*Helper=*/nullptr,
8029 getPrintingPolicy());
8030 }),
8031 IsSimple, NoexceptLoc, ReturnTypeRequirement);
8032 }
8033 if (!SubstitutedConstraintExpr->isSatisfied())
8035 }
8036 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
8037 ReturnTypeRequirement, Status,
8038 SubstitutedConstraintExpr);
8039}
8040
8043 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
8044 bool IsSimple, SourceLocation NoexceptLoc,
8046 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
8047 IsSimple, NoexceptLoc,
8048 ReturnTypeRequirement);
8049}
8050
8055
8061
8065
8068 ConstraintSatisfaction Satisfaction;
8070 if (!Constraint->isInstantiationDependent() &&
8071 !Constraint->isValueDependent() &&
8073 /*TemplateArgs=*/{},
8074 Constraint->getSourceRange(), Satisfaction))
8075 return nullptr;
8076 return new (Context) concepts::NestedRequirement(Context, Constraint,
8077 Satisfaction);
8078}
8079
8081Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
8082 const ASTConstraintSatisfaction &Satisfaction) {
8084 InvalidConstraintEntity,
8086}
8087
8090 ArrayRef<ParmVarDecl *> LocalParameters,
8091 Scope *BodyScope) {
8092 assert(BodyScope);
8093
8095 RequiresKWLoc);
8096
8097 PushDeclContext(BodyScope, Body);
8098
8099 for (ParmVarDecl *Param : LocalParameters) {
8100 if (Param->getType()->isVoidType()) {
8101 if (LocalParameters.size() > 1) {
8102 Diag(Param->getBeginLoc(), diag::err_void_only_param);
8103 Param->setType(Context.IntTy);
8104 } else if (Param->getIdentifier()) {
8105 Diag(Param->getBeginLoc(), diag::err_param_with_void_type);
8106 Param->setType(Context.IntTy);
8107 } else if (Param->getType().hasQualifiers()) {
8108 Diag(Param->getBeginLoc(), diag::err_void_param_qualified);
8109 }
8110 } else if (Param->hasDefaultArg()) {
8111 // C++2a [expr.prim.req] p4
8112 // [...] A local parameter of a requires-expression shall not have a
8113 // default argument. [...]
8114 Diag(Param->getDefaultArgRange().getBegin(),
8115 diag::err_requires_expr_local_parameter_default_argument);
8116 // Ignore default argument and move on
8117 } else if (Param->isExplicitObjectParameter()) {
8118 // C++23 [dcl.fct]p6:
8119 // An explicit-object-parameter-declaration is a parameter-declaration
8120 // with a this specifier. An explicit-object-parameter-declaration
8121 // shall appear only as the first parameter-declaration of a
8122 // parameter-declaration-list of either:
8123 // - a member-declarator that declares a member function, or
8124 // - a lambda-declarator.
8125 //
8126 // The parameter-declaration-list of a requires-expression is not such
8127 // a context.
8128 Diag(Param->getExplicitObjectParamThisLoc(),
8129 diag::err_requires_expr_explicit_object_parameter);
8130 Param->setExplicitObjectParameterLoc(SourceLocation());
8131 }
8132
8133 Param->setDeclContext(Body);
8134 // If this has an identifier, add it to the scope stack.
8135 if (Param->getIdentifier()) {
8136 CheckShadow(BodyScope, Param);
8137 PushOnScopeChains(Param, BodyScope);
8138 }
8139 }
8140 return Body;
8141}
8142
8144 assert(CurContext && "DeclContext imbalance!");
8145 CurContext = CurContext->getLexicalParent();
8146 assert(CurContext && "Popped translation unit!");
8147}
8148
8150 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
8151 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
8152 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
8153 SourceLocation ClosingBraceLoc) {
8154 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
8155 LocalParameters, RParenLoc, Requirements,
8156 ClosingBraceLoc);
8158 return ExprError();
8159 return RE;
8160}
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:2852
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition Darwin.cpp:3826
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:812
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:965
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:927
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:3991
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:3821
QualType getElementType() const
Definition TypeBase.h:3833
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8288
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:5107
Pointer to a block type.
Definition TypeBase.h:3641
This class is used for builtin types like 'int'.
Definition TypeBase.h:3229
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1496
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition ExprCXX.cpp:1125
const Expr * getSubExpr() const
Definition ExprCXX.h:1518
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:726
Represents a call to a C++ constructor.
Definition ExprCXX.h:1551
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:2629
bool isArrayForm() const
Definition ExprCXX.h:2655
SourceLocation getBeginLoc() const
Definition ExprCXX.h:2679
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:4308
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:771
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2748
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:2129
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2199
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:1462
void setDestructor(const CXXDestructorDecl *Dtor)
Definition ExprCXX.h:1475
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition ExprCXX.cpp:1120
Represents the this expression in C++.
Definition ExprCXX.h:1157
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:1211
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:851
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:1071
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:3340
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1749
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:3859
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:4486
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:2608
DeclContextLookupResult lookup_result
Definition DeclBase.h:2607
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:629
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:594
TST getTypeSpecType() const
Definition DeclSpec.h:568
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:609
static const TST TST_typename_pack_indexing
Definition DeclSpec.h:286
ParsedType getRepAsType() const
Definition DeclSpec.h:581
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:658
Expr * getRepAsExpr() const
Definition DeclSpec.h:589
static const TST TST_decltype
Definition DeclSpec.h:284
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:616
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:626
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:2001
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2499
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2148
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2185
void DropFirstTypeObject()
Definition DeclSpec.h:2516
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2495
bool isInvalidType() const
Definition DeclSpec.h:2815
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2183
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2322
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2319
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:604
Represents an enum.
Definition Decl.h:4055
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4287
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5074
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4282
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:2576
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:4295
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:3101
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
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:3350
@ 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:3699
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:4080
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:2029
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2682
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:2225
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2837
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4185
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2350
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition Decl.h:2798
QualType getReturnType() const
Definition Decl.h:2885
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2413
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions:
Definition Decl.h:2632
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2576
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3539
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4549
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3806
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:3226
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5406
QualType getParamType(unsigned i) const
Definition TypeBase.h:5686
Declaration of a template function.
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4825
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4784
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4602
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:2081
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:1432
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
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:4424
MSGuidDeclParts Parts
Definition DeclCXX.h:4426
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:3752
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:3770
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
void addOuterRetainedLevels(unsigned Num)
Definition Template.h:272
This represents a decl that may have a name.
Definition Decl.h: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:973
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:8107
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8119
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:2347
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
Represents a parameter to a function.
Definition Decl.h:1819
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:2936
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3393
QualType getPointeeType() const
Definition TypeBase.h:3403
Stores the type being destroyed by a pseudo-destructor expression.
Definition ExprCXX.h:2697
TypeSourceInfo * getTypeSourceInfo() const
Definition ExprCXX.h:2713
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8573
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:1175
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8489
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8615
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8529
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8674
QualType getCanonicalType() const
Definition TypeBase.h:8541
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8583
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:8562
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8535
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8654
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
GC getObjCGCAttr() const
Definition TypeBase.h:520
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
bool hasCVRQualifiers() const
Definition TypeBase.h:488
bool hasUnaligned() const
Definition TypeBase.h:512
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:709
void setAddressSpace(LangAS space)
Definition TypeBase.h:592
unsigned getCVRUQualifiers() const
Definition TypeBase.h:490
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
void setObjCGCAttr(GC type)
Definition TypeBase.h:521
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition TypeBase.h:442
LangAS getAddressSpace() const
Definition TypeBase.h:572
void setPointerAuth(PointerAuthQualifier Q)
Definition TypeBase.h:607
static std::string getAddrSpaceAsString(LangAS AS)
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:549
Represents a struct/union/class.
Definition Decl.h:4369
Represents the body of a requires-expression.
Definition DeclCXX.h:2114
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition DeclCXX.cpp:2405
static RequiresExpr * Create(ASTContext &C, SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, SourceLocation LParenLoc, ArrayRef< ParmVarDecl * > LocalParameters, SourceLocation RParenLoc, ArrayRef< concepts::Requirement * > Requirements, SourceLocation RBraceLoc)
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:384
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
@ BlockScope
This is a scope that corresponds to a block/closure object.
Definition Scope.h:75
@ ClassScope
The scope of a struct/union/class definition.
Definition Scope.h:69
@ TryScope
This is the scope of a C++ try statement.
Definition Scope.h:105
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition Scope.h:51
@ ObjCMethodScope
This scope corresponds to an Objective-C method body.
Definition Scope.h:99
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder 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:10411
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12600
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
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:8330
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition Sema.h:9435
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9423
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9465
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:7924
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7926
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7925
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:10503
@ 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:1748
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:693
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:763
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:769
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:8448
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:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
@ UPPC_IfExists
Microsoft __if_exists.
Definition Sema.h:14590
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition Sema.h:14593
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:2696
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:7058
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:876
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10522
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:7055
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
void MarkThisReferenced(CXXThisExpr *This)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:647
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8271
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9948
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:8263
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1727
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:8459
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:14088
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:8530
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves=false)
Perform the initialization of a potentially-movable value, which is the result of return value.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
bool inConstraintSubstitution() const
Determine whether we are currently performing constraint substitution.
Definition Sema.h:14093
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:13836
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:15602
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:8455
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:7062
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:8466
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:8403
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:523
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:2242
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:8452
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6510
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:7910
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:8748
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:85
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:770
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:3557
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:8460
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:8471
The base class of the type hierarchy.
Definition TypeBase.h:1876
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:8746
bool isVoidType() const
Definition TypeBase.h:9092
bool isBooleanType() const
Definition TypeBase.h:9229
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:9068
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:8825
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2426
bool isConstantMatrixType() const
Definition TypeBase.h:8893
bool isPointerType() const
Definition TypeBase.h:8726
bool isArrayParameterType() const
Definition TypeBase.h:8841
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9136
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isReferenceType() const
Definition TypeBase.h:8750
bool isEnumeralType() const
Definition TypeBase.h:8857
bool isScalarType() const
Definition TypeBase.h:9198
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:8869
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:8849
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2847
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9152
bool isHalfType() const
Definition TypeBase.h:9096
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:9272
bool isMemberPointerType() const
Definition TypeBase.h:8807
bool isMatrixType() const
Definition TypeBase.h:8889
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:2865
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:2571
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isPointerOrReferenceType() const
Definition TypeBase.h:8730
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:8722
bool isObjCObjectPointerType() const
Definition TypeBase.h:8905
bool isVectorType() const
Definition TypeBase.h:8865
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:2986
bool isFloatingType() const
Definition Type.cpp:2393
bool isAnyPointerType() const
Definition TypeBase.h:8734
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
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:9129
bool isRecordType() const
Definition TypeBase.h:8853
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:1088
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1300
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1297
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:1301
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1146
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1116
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1170
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1140
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:5581
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3695
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:2171
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2238
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2509
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1381
Represents a GCC generic vector type.
Definition TypeBase.h:4274
TemplateParameterList * getTypeConstraintTemplateParameterList() const
A requires-expression requirement which queries the validity and properties of an expression ('simple...
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
A static requirement that can be used in a requires-expression to check properties of types and expre...
A requires-expression requirement which queries the existence of a type name or type template special...
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:709
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:759
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:756
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1099
SourceLocation PotentialThisCaptureLocation
Definition ScopeInfo.h:953
bool hasPotentialThisCapture() const
Definition ScopeInfo.h:1005
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:887
bool lambdaCaptureShouldBeConst() const
bool hasPotentialCaptures() const
Definition ScopeInfo.h:1071
bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const
Definition ScopeInfo.h:1054
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:872
void visitPotentialCaptures(llvm::function_ref< void(ValueDecl *, Expr *)> Callback) const
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:895
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:880
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:875
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1511
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:33
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:829
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:512
CanThrowResult
Possible results from evaluation of a noexcept expression.
AllocationFunctionScope
The scope in which to find allocation functions.
Definition Sema.h:790
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition Sema.h:798
@ Global
Only look for allocation functions in the global scope.
Definition Sema.h:792
@ Class
Only look for allocation functions in the scope of the allocated class.
Definition Sema.h:795
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:2272
@ Conditional
A conditional (?:) operator.
Definition Sema.h:668
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1798
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1801
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1804
@ 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:1080
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1072
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1066
@ 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:251
Expr * Cond
};
bool isAlignedAllocation(AlignedAllocationMode Mode)
Definition ExprCXX.h:2268
@ OMF_performSelector
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
AlignedAllocationMode
Definition ExprCXX.h:2266
StmtResult StmtError()
Definition Ownership.h:266
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h: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:688
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:786
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:690
@ Class
The "class" keyword.
Definition TypeBase.h:6041
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:563
bool isTypeAwareAllocation(TypeAwareAllocationMode Mode)
Definition ExprCXX.h:2256
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:2282
AssignmentAction
Definition Sema.h:215
@ Deduced
The normal deduced case.
Definition TypeBase.h:1815
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:2276
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:2278
TypeAwareAllocationMode
Definition ExprCXX.h:2254
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition Sema.h:802
@ Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
Definition Sema.h:811
@ Exists
The symbol exists.
Definition Sema.h:804
@ Error
An error occurred.
Definition Sema.h:814
@ DoesNotExist
The symbol does not exist.
Definition Sema.h:807
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:312
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:368
@ Success
Template argument deduction was successful.
Definition Sema.h:370
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:422
@ Generic
not a target-specific vector type
Definition TypeBase.h:4235
U cast(CodeGen::Address addr)
Definition Address.h:327
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:843
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:6026
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6016
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:6023
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1774
CXXNewInitializationStyle
Definition ExprCXX.h:2243
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2248
@ None
New-expression has no initializer as written.
Definition ExprCXX.h:2245
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2251
@ EST_BasicNoexcept
noexcept
@ EST_Dynamic
throw(T1, T2)
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:437
@ CStyleCast
A C-style cast.
Definition Sema.h:441
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:447
@ FunctionalCast
A functional-style cast.
Definition Sema.h:443
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:1405
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1414
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1336
ArrayTypeInfo Arr
Definition DeclSpec.h:1734
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1344
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5465
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5468
Extra information about a function prototype.
Definition TypeBase.h:5491
AlignedAllocationMode PassAlignment
Definition ExprCXX.h:2310
TypeAwareAllocationMode PassTypeIdentity
Definition ExprCXX.h:2309
unsigned getNumImplicitArgs() const
Definition ExprCXX.h:2299
TypeAwareAllocationMode PassTypeIdentity
Definition ExprCXX.h:2341
SizedDeallocationMode PassSize
Definition ExprCXX.h:2343
AlignedAllocationMode PassAlignment
Definition ExprCXX.h:2342
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