clang 20.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/DeclObjC.h"
21#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
25#include "clang/AST/Type.h"
26#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"
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/STLForwardCompat.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/TypeSize.h"
54#include <optional>
55using namespace clang;
56using namespace sema;
57
59 SourceLocation NameLoc,
60 const IdentifierInfo &Name) {
62
63 // Convert the nested-name-specifier into a type.
65 switch (NNS->getKind()) {
68 Type = QualType(NNS->getAsType(), 0);
69 break;
70
72 // Strip off the last layer of the nested-name-specifier and build a
73 // typename type for it.
74 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
77 break;
78
83 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
84 }
85
86 // This reference to the type is located entirely at the location of the
87 // final identifier in the qualified-id.
90}
91
93 SourceLocation NameLoc, Scope *S,
94 CXXScopeSpec &SS, bool EnteringContext) {
95 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
96 assert(CurClass && &II == CurClass->getIdentifier() &&
97 "not a constructor name");
98
99 // When naming a constructor as a member of a dependent context (eg, in a
100 // friend declaration or an inherited constructor declaration), form an
101 // unresolved "typename" type.
102 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
104 SS.getScopeRep(), &II);
105 return ParsedType::make(T);
106 }
107
108 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
109 return ParsedType();
110
111 // Find the injected-class-name declaration. Note that we make no attempt to
112 // diagnose cases where the injected-class-name is shadowed: the only
113 // declaration that can validly shadow the injected-class-name is a
114 // non-static data member, and if the class contains both a non-static data
115 // member and a constructor then it is ill-formed (we check that in
116 // CheckCompletedCXXClass).
117 CXXRecordDecl *InjectedClassName = nullptr;
118 for (NamedDecl *ND : CurClass->lookup(&II)) {
119 auto *RD = dyn_cast<CXXRecordDecl>(ND);
120 if (RD && RD->isInjectedClassName()) {
121 InjectedClassName = RD;
122 break;
123 }
124 }
125 if (!InjectedClassName) {
126 if (!CurClass->isInvalidDecl()) {
127 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
128 // properly. Work around it here for now.
130 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
131 }
132 return ParsedType();
133 }
134
135 QualType T = Context.getTypeDeclType(InjectedClassName);
136 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
137 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
138
139 return ParsedType::make(T);
140}
141
143 SourceLocation NameLoc, Scope *S,
144 CXXScopeSpec &SS, ParsedType ObjectTypePtr,
145 bool EnteringContext) {
146 // Determine where to perform name lookup.
147
148 // FIXME: This area of the standard is very messy, and the current
149 // wording is rather unclear about which scopes we search for the
150 // destructor name; see core issues 399 and 555. Issue 399 in
151 // particular shows where the current description of destructor name
152 // lookup is completely out of line with existing practice, e.g.,
153 // this appears to be ill-formed:
154 //
155 // namespace N {
156 // template <typename T> struct S {
157 // ~S();
158 // };
159 // }
160 //
161 // void f(N::S<int>* s) {
162 // s->N::S<int>::~S();
163 // }
164 //
165 // See also PR6358 and PR6359.
166 //
167 // For now, we accept all the cases in which the name given could plausibly
168 // be interpreted as a correct destructor name, issuing off-by-default
169 // extension diagnostics on the cases that don't strictly conform to the
170 // C++20 rules. This basically means we always consider looking in the
171 // nested-name-specifier prefix, the complete nested-name-specifier, and
172 // the scope, and accept if we find the expected type in any of the three
173 // places.
174
175 if (SS.isInvalid())
176 return nullptr;
177
178 // Whether we've failed with a diagnostic already.
179 bool Failed = false;
180
183
184 // If we have an object type, it's because we are in a
185 // pseudo-destructor-expression or a member access expression, and
186 // we know what type we're looking for.
187 QualType SearchType =
188 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
189
190 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
191 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
192 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
193 if (!Type)
194 return false;
195
196 if (SearchType.isNull() || SearchType->isDependentType())
197 return true;
198
200 return Context.hasSameUnqualifiedType(T, SearchType);
201 };
202
203 unsigned NumAcceptableResults = 0;
204 for (NamedDecl *D : Found) {
205 if (IsAcceptableResult(D))
206 ++NumAcceptableResults;
207
208 // Don't list a class twice in the lookup failure diagnostic if it's
209 // found by both its injected-class-name and by the name in the enclosing
210 // scope.
211 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
212 if (RD->isInjectedClassName())
213 D = cast<NamedDecl>(RD->getParent());
214
215 if (FoundDeclSet.insert(D).second)
216 FoundDecls.push_back(D);
217 }
218
219 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
220 // results, and all non-matching results if we have a search type. It's not
221 // clear what the right behavior is if destructor lookup hits an ambiguity,
222 // but other compilers do generally accept at least some kinds of
223 // ambiguity.
224 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
225 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
226 LookupResult::Filter F = Found.makeFilter();
227 while (F.hasNext()) {
228 NamedDecl *D = F.next();
229 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
230 Diag(D->getLocation(), diag::note_destructor_type_here)
232 else
233 Diag(D->getLocation(), diag::note_destructor_nontype_here);
234
235 if (!IsAcceptableResult(D))
236 F.erase();
237 }
238 F.done();
239 }
240
241 if (Found.isAmbiguous())
242 Failed = true;
243
244 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
245 if (IsAcceptableResult(Type)) {
247 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
248 return CreateParsedType(
251 }
252 }
253
254 return nullptr;
255 };
256
257 bool IsDependent = false;
258
259 auto LookupInObjectType = [&]() -> ParsedType {
260 if (Failed || SearchType.isNull())
261 return nullptr;
262
263 IsDependent |= SearchType->isDependentType();
264
265 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
266 DeclContext *LookupCtx = computeDeclContext(SearchType);
267 if (!LookupCtx)
268 return nullptr;
269 LookupQualifiedName(Found, LookupCtx);
270 return CheckLookupResult(Found);
271 };
272
273 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
274 if (Failed)
275 return nullptr;
276
277 IsDependent |= isDependentScopeSpecifier(LookupSS);
278 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
279 if (!LookupCtx)
280 return nullptr;
281
282 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
283 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
284 Failed = true;
285 return nullptr;
286 }
287 LookupQualifiedName(Found, LookupCtx);
288 return CheckLookupResult(Found);
289 };
290
291 auto LookupInScope = [&]() -> ParsedType {
292 if (Failed || !S)
293 return nullptr;
294
295 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
296 LookupName(Found, S);
297 return CheckLookupResult(Found);
298 };
299
300 // C++2a [basic.lookup.qual]p6:
301 // In a qualified-id of the form
302 //
303 // nested-name-specifier[opt] type-name :: ~ type-name
304 //
305 // the second type-name is looked up in the same scope as the first.
306 //
307 // We interpret this as meaning that if you do a dual-scope lookup for the
308 // first name, you also do a dual-scope lookup for the second name, per
309 // C++ [basic.lookup.classref]p4:
310 //
311 // If the id-expression in a class member access is a qualified-id of the
312 // form
313 //
314 // class-name-or-namespace-name :: ...
315 //
316 // the class-name-or-namespace-name following the . or -> is first looked
317 // up in the class of the object expression and the name, if found, is used.
318 // Otherwise, it is looked up in the context of the entire
319 // postfix-expression.
320 //
321 // This looks in the same scopes as for an unqualified destructor name:
322 //
323 // C++ [basic.lookup.classref]p3:
324 // If the unqualified-id is ~ type-name, the type-name is looked up
325 // in the context of the entire postfix-expression. If the type T
326 // of the object expression is of a class type C, the type-name is
327 // also looked up in the scope of class C. At least one of the
328 // lookups shall find a name that refers to cv T.
329 //
330 // FIXME: The intent is unclear here. Should type-name::~type-name look in
331 // the scope anyway if it finds a non-matching name declared in the class?
332 // If both lookups succeed and find a dependent result, which result should
333 // we retain? (Same question for p->~type-name().)
334
335 if (NestedNameSpecifier *Prefix =
336 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
337 // This is
338 //
339 // nested-name-specifier type-name :: ~ type-name
340 //
341 // Look for the second type-name in the nested-name-specifier.
342 CXXScopeSpec PrefixSS;
343 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
344 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
345 return T;
346 } else {
347 // This is one of
348 //
349 // type-name :: ~ type-name
350 // ~ type-name
351 //
352 // Look in the scope and (if any) the object type.
353 if (ParsedType T = LookupInScope())
354 return T;
355 if (ParsedType T = LookupInObjectType())
356 return T;
357 }
358
359 if (Failed)
360 return nullptr;
361
362 if (IsDependent) {
363 // We didn't find our type, but that's OK: it's dependent anyway.
364
365 // FIXME: What if we have no nested-name-specifier?
366 QualType T =
368 SS.getWithLocInContext(Context), II, NameLoc);
369 return ParsedType::make(T);
370 }
371
372 // The remaining cases are all non-standard extensions imitating the behavior
373 // of various other compilers.
374 unsigned NumNonExtensionDecls = FoundDecls.size();
375
376 if (SS.isSet()) {
377 // For compatibility with older broken C++ rules and existing code,
378 //
379 // nested-name-specifier :: ~ type-name
380 //
381 // also looks for type-name within the nested-name-specifier.
382 if (ParsedType T = LookupInNestedNameSpec(SS)) {
383 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
384 << SS.getRange()
386 ("::" + II.getName()).str());
387 return T;
388 }
389
390 // For compatibility with other compilers and older versions of Clang,
391 //
392 // nested-name-specifier type-name :: ~ type-name
393 //
394 // also looks for type-name in the scope. Unfortunately, we can't
395 // reasonably apply this fallback for dependent nested-name-specifiers.
396 if (SS.isValid() && SS.getScopeRep()->getPrefix()) {
397 if (ParsedType T = LookupInScope()) {
398 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
400 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
402 return T;
403 }
404 }
405 }
406
407 // We didn't find anything matching; tell the user what we did find (if
408 // anything).
409
410 // Don't tell the user about declarations we shouldn't have found.
411 FoundDecls.resize(NumNonExtensionDecls);
412
413 // List types before non-types.
414 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
415 [](NamedDecl *A, NamedDecl *B) {
416 return isa<TypeDecl>(A->getUnderlyingDecl()) >
417 isa<TypeDecl>(B->getUnderlyingDecl());
418 });
419
420 // Suggest a fixit to properly name the destroyed type.
421 auto MakeFixItHint = [&]{
422 const CXXRecordDecl *Destroyed = nullptr;
423 // FIXME: If we have a scope specifier, suggest its last component?
424 if (!SearchType.isNull())
425 Destroyed = SearchType->getAsCXXRecordDecl();
426 else if (S)
427 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
428 if (Destroyed)
430 Destroyed->getNameAsString());
431 return FixItHint();
432 };
433
434 if (FoundDecls.empty()) {
435 // FIXME: Attempt typo-correction?
436 Diag(NameLoc, diag::err_undeclared_destructor_name)
437 << &II << MakeFixItHint();
438 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
439 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
440 assert(!SearchType.isNull() &&
441 "should only reject a type result if we have a search type");
443 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
444 << T << SearchType << MakeFixItHint();
445 } else {
446 Diag(NameLoc, diag::err_destructor_expr_nontype)
447 << &II << MakeFixItHint();
448 }
449 } else {
450 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
451 : diag::err_destructor_expr_mismatch)
452 << &II << SearchType << MakeFixItHint();
453 }
454
455 for (NamedDecl *FoundD : FoundDecls) {
456 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
457 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
459 else
460 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
461 << FoundD;
462 }
463
464 return nullptr;
465}
466
468 ParsedType ObjectType) {
470 return nullptr;
471
473 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
474 return nullptr;
475 }
476
478 "unexpected type in getDestructorType");
480
481 // If we know the type of the object, check that the correct destructor
482 // type was named now; we can give better diagnostics this way.
483 QualType SearchType = GetTypeFromParser(ObjectType);
484 if (!SearchType.isNull() && !SearchType->isDependentType() &&
485 !Context.hasSameUnqualifiedType(T, SearchType)) {
486 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
487 << T << SearchType;
488 return nullptr;
489 }
490
491 return ParsedType::make(T);
492}
493
495 const UnqualifiedId &Name, bool IsUDSuffix) {
496 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
497 if (!IsUDSuffix) {
498 // [over.literal] p8
499 //
500 // double operator""_Bq(long double); // OK: not a reserved identifier
501 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
502 const IdentifierInfo *II = Name.Identifier;
504 SourceLocation Loc = Name.getEndLoc();
506 if (auto Hint = FixItHint::CreateReplacement(
507 Name.getSourceRange(),
508 (StringRef("operator\"\"") + II->getName()).str());
509 isReservedInAllContexts(Status)) {
510 Diag(Loc, diag::warn_reserved_extern_symbol)
511 << II << static_cast<int>(Status) << Hint;
512 } else {
513 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
514 }
515 }
516 }
517
518 if (!SS.isValid())
519 return false;
520
521 switch (SS.getScopeRep()->getKind()) {
525 // Per C++11 [over.literal]p2, literal operators can only be declared at
526 // namespace scope. Therefore, this unqualified-id cannot name anything.
527 // Reject it early, because we have no AST representation for this in the
528 // case where the scope is dependent.
529 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
530 << SS.getScopeRep();
531 return true;
532
537 return false;
538 }
539
540 llvm_unreachable("unknown nested name specifier kind");
541}
542
544 SourceLocation TypeidLoc,
545 TypeSourceInfo *Operand,
546 SourceLocation RParenLoc) {
547 // C++ [expr.typeid]p4:
548 // The top-level cv-qualifiers of the lvalue expression or the type-id
549 // that is the operand of typeid are always ignored.
550 // If the type of the type-id is a class type or a reference to a class
551 // type, the class shall be completely-defined.
552 Qualifiers Quals;
553 QualType T
554 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
555 Quals);
556 if (T->getAs<RecordType>() &&
557 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
558 return ExprError();
559
561 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
562
563 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
564 return ExprError();
565
566 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
567 SourceRange(TypeidLoc, RParenLoc));
568}
569
571 SourceLocation TypeidLoc,
572 Expr *E,
573 SourceLocation RParenLoc) {
574 bool WasEvaluated = false;
575 if (E && !E->isTypeDependent()) {
576 if (E->hasPlaceholderType()) {
578 if (result.isInvalid()) return ExprError();
579 E = result.get();
580 }
581
582 QualType T = E->getType();
583 if (const RecordType *RecordT = T->getAs<RecordType>()) {
584 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
585 // C++ [expr.typeid]p3:
586 // [...] If the type of the expression is a class type, the class
587 // shall be completely-defined.
588 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
589 return ExprError();
590
591 // C++ [expr.typeid]p3:
592 // When typeid is applied to an expression other than an glvalue of a
593 // polymorphic class type [...] [the] expression is an unevaluated
594 // operand. [...]
595 if (RecordD->isPolymorphic() && E->isGLValue()) {
596 if (isUnevaluatedContext()) {
597 // The operand was processed in unevaluated context, switch the
598 // context and recheck the subexpression.
600 if (Result.isInvalid())
601 return ExprError();
602 E = Result.get();
603 }
604
605 // We require a vtable to query the type at run time.
606 MarkVTableUsed(TypeidLoc, RecordD);
607 WasEvaluated = true;
608 }
609 }
610
612 if (Result.isInvalid())
613 return ExprError();
614 E = Result.get();
615
616 // C++ [expr.typeid]p4:
617 // [...] If the type of the type-id is a reference to a possibly
618 // cv-qualified type, the result of the typeid expression refers to a
619 // std::type_info object representing the cv-unqualified referenced
620 // type.
621 Qualifiers Quals;
622 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
623 if (!Context.hasSameType(T, UnqualT)) {
624 T = UnqualT;
625 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
626 }
627 }
628
630 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
631 << E->getType());
632 else if (!inTemplateInstantiation() &&
633 E->HasSideEffects(Context, WasEvaluated)) {
634 // The expression operand for typeid is in an unevaluated expression
635 // context, so side effects could result in unintended consequences.
636 Diag(E->getExprLoc(), WasEvaluated
637 ? diag::warn_side_effects_typeid
638 : diag::warn_side_effects_unevaluated_context);
639 }
640
641 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
642 SourceRange(TypeidLoc, RParenLoc));
643}
644
645/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
648 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
649 // typeid is not supported in OpenCL.
650 if (getLangOpts().OpenCLCPlusPlus) {
651 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
652 << "typeid");
653 }
654
655 // Find the std::type_info type.
656 if (!getStdNamespace())
657 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
658
659 if (!CXXTypeInfoDecl) {
660 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
661 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
664 // Microsoft's typeinfo doesn't have type_info in std but in the global
665 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
666 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
669 }
670 if (!CXXTypeInfoDecl)
671 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
672 }
673
674 if (!getLangOpts().RTTI) {
675 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
676 }
677
679
680 if (isType) {
681 // The operand is a type; handle it as such.
682 TypeSourceInfo *TInfo = nullptr;
684 &TInfo);
685 if (T.isNull())
686 return ExprError();
687
688 if (!TInfo)
689 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
690
691 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
692 }
693
694 // The operand is an expression.
696 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
697
698 if (!getLangOpts().RTTIData && !Result.isInvalid())
699 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
700 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
701 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
702 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
704 return Result;
705}
706
707/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
708/// a single GUID.
709static void
712 // Optionally remove one level of pointer, reference or array indirection.
713 const Type *Ty = QT.getTypePtr();
714 if (QT->isPointerOrReferenceType())
715 Ty = QT->getPointeeType().getTypePtr();
716 else if (QT->isArrayType())
717 Ty = Ty->getBaseElementTypeUnsafe();
718
719 const auto *TD = Ty->getAsTagDecl();
720 if (!TD)
721 return;
722
723 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
724 UuidAttrs.insert(Uuid);
725 return;
726 }
727
728 // __uuidof can grab UUIDs from template arguments.
729 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
730 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
731 for (const TemplateArgument &TA : TAL.asArray()) {
732 const UuidAttr *UuidForTA = nullptr;
733 if (TA.getKind() == TemplateArgument::Type)
734 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
735 else if (TA.getKind() == TemplateArgument::Declaration)
736 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
737
738 if (UuidForTA)
739 UuidAttrs.insert(UuidForTA);
740 }
741 }
742}
743
745 SourceLocation TypeidLoc,
746 TypeSourceInfo *Operand,
747 SourceLocation RParenLoc) {
748 MSGuidDecl *Guid = nullptr;
749 if (!Operand->getType()->isDependentType()) {
751 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
752 if (UuidAttrs.empty())
753 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
754 if (UuidAttrs.size() > 1)
755 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
756 Guid = UuidAttrs.back()->getGuidDecl();
757 }
758
759 return new (Context)
760 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
761}
762
764 Expr *E, SourceLocation RParenLoc) {
765 MSGuidDecl *Guid = nullptr;
766 if (!E->getType()->isDependentType()) {
768 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
770 } else {
772 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
773 if (UuidAttrs.empty())
774 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
775 if (UuidAttrs.size() > 1)
776 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
777 Guid = UuidAttrs.back()->getGuidDecl();
778 }
779 }
780
781 return new (Context)
782 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
783}
784
785/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
788 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
789 QualType GuidType = Context.getMSGuidType();
790 GuidType.addConst();
791
792 if (isType) {
793 // The operand is a type; handle it as such.
794 TypeSourceInfo *TInfo = nullptr;
796 &TInfo);
797 if (T.isNull())
798 return ExprError();
799
800 if (!TInfo)
801 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
802
803 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
804 }
805
806 // The operand is an expression.
807 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
808}
809
812 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
813 "Unknown C++ Boolean value!");
814 return new (Context)
815 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
816}
817
821}
822
825 bool IsThrownVarInScope = false;
826 if (Ex) {
827 // C++0x [class.copymove]p31:
828 // When certain criteria are met, an implementation is allowed to omit the
829 // copy/move construction of a class object [...]
830 //
831 // - in a throw-expression, when the operand is the name of a
832 // non-volatile automatic object (other than a function or catch-
833 // clause parameter) whose scope does not extend beyond the end of the
834 // innermost enclosing try-block (if there is one), the copy/move
835 // operation from the operand to the exception object (15.1) can be
836 // omitted by constructing the automatic object directly into the
837 // exception object
838 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
839 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());
840 Var && Var->hasLocalStorage() &&
841 !Var->getType().isVolatileQualified()) {
842 for (; S; S = S->getParent()) {
843 if (S->isDeclScope(Var)) {
844 IsThrownVarInScope = true;
845 break;
846 }
847
848 // FIXME: Many of the scope checks here seem incorrect.
849 if (S->getFlags() &
852 break;
853 }
854 }
855 }
856
857 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
858}
859
861 bool IsThrownVarInScope) {
862 const llvm::Triple &T = Context.getTargetInfo().getTriple();
863 const bool IsOpenMPGPUTarget =
864 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
865 // Don't report an error if 'throw' is used in system headers or in an OpenMP
866 // target region compiled for a GPU architecture.
867 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
868 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
869 // Delay error emission for the OpenMP device code.
870 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
871 }
872
873 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
874 if (IsOpenMPGPUTarget)
875 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
876
877 // Exceptions aren't allowed in CUDA device code.
878 if (getLangOpts().CUDA)
879 CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
880 << "throw" << llvm::to_underlying(CUDA().CurrentTarget());
881
882 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
883 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
884
885 // Exceptions that escape a compute construct are ill-formed.
886 if (getLangOpts().OpenACC && getCurScope() &&
887 getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))
888 Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)
889 << /*throw*/ 2 << /*out of*/ 0;
890
891 if (Ex && !Ex->isTypeDependent()) {
892 // Initialize the exception result. This implicitly weeds out
893 // abstract types or types with inaccessible copy constructors.
894
895 // C++0x [class.copymove]p31:
896 // When certain criteria are met, an implementation is allowed to omit the
897 // copy/move construction of a class object [...]
898 //
899 // - in a throw-expression, when the operand is the name of a
900 // non-volatile automatic object (other than a function or
901 // catch-clause
902 // parameter) whose scope does not extend beyond the end of the
903 // innermost enclosing try-block (if there is one), the copy/move
904 // operation from the operand to the exception object (15.1) can be
905 // omitted by constructing the automatic object directly into the
906 // exception object
907 NamedReturnInfo NRInfo =
908 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
909
910 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
911 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
912 return ExprError();
913
914 InitializedEntity Entity =
915 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
916 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
917 if (Res.isInvalid())
918 return ExprError();
919 Ex = Res.get();
920 }
921
922 // PPC MMA non-pointer types are not allowed as throw expr types.
923 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
924 PPC().CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
925
926 return new (Context)
927 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
928}
929
930static void
932 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
933 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
934 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
935 bool ParentIsPublic) {
936 for (const CXXBaseSpecifier &BS : RD->bases()) {
937 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
938 bool NewSubobject;
939 // Virtual bases constitute the same subobject. Non-virtual bases are
940 // always distinct subobjects.
941 if (BS.isVirtual())
942 NewSubobject = VBases.insert(BaseDecl).second;
943 else
944 NewSubobject = true;
945
946 if (NewSubobject)
947 ++SubobjectsSeen[BaseDecl];
948
949 // Only add subobjects which have public access throughout the entire chain.
950 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
951 if (PublicPath)
952 PublicSubobjectsSeen.insert(BaseDecl);
953
954 // Recurse on to each base subobject.
955 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
956 PublicPath);
957 }
958}
959
962 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
963 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
964 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
965 SubobjectsSeen[RD] = 1;
966 PublicSubobjectsSeen.insert(RD);
967 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
968 /*ParentIsPublic=*/true);
969
970 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
971 // Skip ambiguous objects.
972 if (SubobjectsSeen[PublicSubobject] > 1)
973 continue;
974
975 Objects.push_back(PublicSubobject);
976 }
977}
978
980 QualType ExceptionObjectTy, Expr *E) {
981 // If the type of the exception would be an incomplete type or a pointer
982 // to an incomplete type other than (cv) void the program is ill-formed.
983 QualType Ty = ExceptionObjectTy;
984 bool isPointer = false;
985 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
986 Ty = Ptr->getPointeeType();
987 isPointer = true;
988 }
989
990 // Cannot throw WebAssembly reference type.
992 Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
993 return true;
994 }
995
996 // Cannot throw WebAssembly table.
997 if (isPointer && Ty.isWebAssemblyReferenceType()) {
998 Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();
999 return true;
1000 }
1001
1002 if (!isPointer || !Ty->isVoidType()) {
1003 if (RequireCompleteType(ThrowLoc, Ty,
1004 isPointer ? diag::err_throw_incomplete_ptr
1005 : diag::err_throw_incomplete,
1006 E->getSourceRange()))
1007 return true;
1008
1009 if (!isPointer && Ty->isSizelessType()) {
1010 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
1011 return true;
1012 }
1013
1014 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
1015 diag::err_throw_abstract_type, E))
1016 return true;
1017 }
1018
1019 // If the exception has class type, we need additional handling.
1021 if (!RD)
1022 return false;
1023
1024 // If we are throwing a polymorphic class type or pointer thereof,
1025 // exception handling will make use of the vtable.
1026 MarkVTableUsed(ThrowLoc, RD);
1027
1028 // If a pointer is thrown, the referenced object will not be destroyed.
1029 if (isPointer)
1030 return false;
1031
1032 // If the class has a destructor, we must be able to call it.
1033 if (!RD->hasIrrelevantDestructor()) {
1037 PDiag(diag::err_access_dtor_exception) << Ty);
1039 return true;
1040 }
1041 }
1042
1043 // The MSVC ABI creates a list of all types which can catch the exception
1044 // object. This list also references the appropriate copy constructor to call
1045 // if the object is caught by value and has a non-trivial copy constructor.
1047 // We are only interested in the public, unambiguous bases contained within
1048 // the exception object. Bases which are ambiguous or otherwise
1049 // inaccessible are not catchable types.
1050 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1051 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1052
1053 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1054 // Attempt to lookup the copy constructor. Various pieces of machinery
1055 // will spring into action, like template instantiation, which means this
1056 // cannot be a simple walk of the class's decls. Instead, we must perform
1057 // lookup and overload resolution.
1058 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1059 if (!CD || CD->isDeleted())
1060 continue;
1061
1062 // Mark the constructor referenced as it is used by this throw expression.
1064
1065 // Skip this copy constructor if it is trivial, we don't need to record it
1066 // in the catchable type data.
1067 if (CD->isTrivial())
1068 continue;
1069
1070 // The copy constructor is non-trivial, create a mapping from this class
1071 // type to this constructor.
1072 // N.B. The selection of copy constructor is not sensitive to this
1073 // particular throw-site. Lookup will be performed at the catch-site to
1074 // ensure that the copy constructor is, in fact, accessible (via
1075 // friendship or any other means).
1077
1078 // We don't keep the instantiated default argument expressions around so
1079 // we must rebuild them here.
1080 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1081 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1082 return true;
1083 }
1084 }
1085 }
1086
1087 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1088 // the runtime with no ability for the compiler to request additional
1089 // alignment. Warn if the exception type requires alignment beyond the minimum
1090 // guaranteed by the target C++ runtime.
1092 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1093 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1094 if (ExnObjAlign < TypeAlign) {
1095 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1096 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1097 << Ty << (unsigned)TypeAlign.getQuantity()
1098 << (unsigned)ExnObjAlign.getQuantity();
1099 }
1100 }
1101 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1102 if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1103 auto Ty = Dtor->getType();
1104 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1105 if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&
1106 !FT->isNothrow())
1107 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1108 }
1109 }
1110 }
1111
1112 return false;
1113}
1114
1116 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1117 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1118
1119 QualType ClassType = ThisTy->getPointeeType();
1120 LambdaScopeInfo *CurLSI = nullptr;
1121 DeclContext *CurDC = CurSemaContext;
1122
1123 // Iterate through the stack of lambdas starting from the innermost lambda to
1124 // the outermost lambda, checking if '*this' is ever captured by copy - since
1125 // that could change the cv-qualifiers of the '*this' object.
1126 // The object referred to by '*this' starts out with the cv-qualifiers of its
1127 // member function. We then start with the innermost lambda and iterate
1128 // outward checking to see if any lambda performs a by-copy capture of '*this'
1129 // - and if so, any nested lambda must respect the 'constness' of that
1130 // capturing lamdbda's call operator.
1131 //
1132
1133 // Since the FunctionScopeInfo stack is representative of the lexical
1134 // nesting of the lambda expressions during initial parsing (and is the best
1135 // place for querying information about captures about lambdas that are
1136 // partially processed) and perhaps during instantiation of function templates
1137 // that contain lambda expressions that need to be transformed BUT not
1138 // necessarily during instantiation of a nested generic lambda's function call
1139 // operator (which might even be instantiated at the end of the TU) - at which
1140 // time the DeclContext tree is mature enough to query capture information
1141 // reliably - we use a two pronged approach to walk through all the lexically
1142 // enclosing lambda expressions:
1143 //
1144 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1145 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1146 // enclosed by the call-operator of the LSI below it on the stack (while
1147 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1148 // the stack represents the innermost lambda.
1149 //
1150 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1151 // represents a lambda's call operator. If it does, we must be instantiating
1152 // a generic lambda's call operator (represented by the Current LSI, and
1153 // should be the only scenario where an inconsistency between the LSI and the
1154 // DeclContext should occur), so climb out the DeclContexts if they
1155 // represent lambdas, while querying the corresponding closure types
1156 // regarding capture information.
1157
1158 // 1) Climb down the function scope info stack.
1159 for (int I = FunctionScopes.size();
1160 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1161 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1162 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1163 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1164 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1165
1166 if (!CurLSI->isCXXThisCaptured())
1167 continue;
1168
1169 auto C = CurLSI->getCXXThisCapture();
1170
1171 if (C.isCopyCapture()) {
1172 if (CurLSI->lambdaCaptureShouldBeConst())
1173 ClassType.addConst();
1174 return ASTCtx.getPointerType(ClassType);
1175 }
1176 }
1177
1178 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1179 // can happen during instantiation of its nested generic lambda call
1180 // operator); 2. if we're in a lambda scope (lambda body).
1181 if (CurLSI && isLambdaCallOperator(CurDC)) {
1183 "While computing 'this' capture-type for a generic lambda, when we "
1184 "run out of enclosing LSI's, yet the enclosing DC is a "
1185 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1186 "lambda call oeprator");
1187 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1188
1189 auto IsThisCaptured =
1190 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1191 IsConst = false;
1192 IsByCopy = false;
1193 for (auto &&C : Closure->captures()) {
1194 if (C.capturesThis()) {
1195 if (C.getCaptureKind() == LCK_StarThis)
1196 IsByCopy = true;
1197 if (Closure->getLambdaCallOperator()->isConst())
1198 IsConst = true;
1199 return true;
1200 }
1201 }
1202 return false;
1203 };
1204
1205 bool IsByCopyCapture = false;
1206 bool IsConstCapture = false;
1207 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1208 while (Closure &&
1209 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1210 if (IsByCopyCapture) {
1211 if (IsConstCapture)
1212 ClassType.addConst();
1213 return ASTCtx.getPointerType(ClassType);
1214 }
1215 Closure = isLambdaCallOperator(Closure->getParent())
1216 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1217 : nullptr;
1218 }
1219 }
1220 return ThisTy;
1221}
1222
1226
1227 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1228 if (method && method->isImplicitObjectMemberFunction())
1229 ThisTy = method->getThisType().getNonReferenceType();
1230 }
1231
1233 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1234
1235 // This is a lambda call operator that is being instantiated as a default
1236 // initializer. DC must point to the enclosing class type, so we can recover
1237 // the 'this' type from it.
1238 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1239 // There are no cv-qualifiers for 'this' within default initializers,
1240 // per [expr.prim.general]p4.
1241 ThisTy = Context.getPointerType(ClassTy);
1242 }
1243
1244 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1245 // might need to be adjusted if the lambda or any of its enclosing lambda's
1246 // captures '*this' by copy.
1247 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1250 return ThisTy;
1251}
1252
1254 Decl *ContextDecl,
1255 Qualifiers CXXThisTypeQuals,
1256 bool Enabled)
1257 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1258{
1259 if (!Enabled || !ContextDecl)
1260 return;
1261
1262 CXXRecordDecl *Record = nullptr;
1263 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1264 Record = Template->getTemplatedDecl();
1265 else
1266 Record = cast<CXXRecordDecl>(ContextDecl);
1267
1269 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1270
1272 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1273
1274 this->Enabled = true;
1275}
1276
1277
1279 if (Enabled) {
1280 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1281 }
1282}
1283
1285 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1286 assert(!LSI->isCXXThisCaptured());
1287 // [=, this] {}; // until C++20: Error: this when = is the default
1289 !Sema.getLangOpts().CPlusPlus20)
1290 return;
1291 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1293 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1294}
1295
1297 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1298 const bool ByCopy) {
1299 // We don't need to capture this in an unevaluated context.
1300 if (isUnevaluatedContext() && !Explicit)
1301 return true;
1302
1303 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1304
1305 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1306 ? *FunctionScopeIndexToStopAt
1307 : FunctionScopes.size() - 1;
1308
1309 // Check that we can capture the *enclosing object* (referred to by '*this')
1310 // by the capturing-entity/closure (lambda/block/etc) at
1311 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1312
1313 // Note: The *enclosing object* can only be captured by-value by a
1314 // closure that is a lambda, using the explicit notation:
1315 // [*this] { ... }.
1316 // Every other capture of the *enclosing object* results in its by-reference
1317 // capture.
1318
1319 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1320 // stack), we can capture the *enclosing object* only if:
1321 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1322 // - or, 'L' has an implicit capture.
1323 // AND
1324 // -- there is no enclosing closure
1325 // -- or, there is some enclosing closure 'E' that has already captured the
1326 // *enclosing object*, and every intervening closure (if any) between 'E'
1327 // and 'L' can implicitly capture the *enclosing object*.
1328 // -- or, every enclosing closure can implicitly capture the
1329 // *enclosing object*
1330
1331
1332 unsigned NumCapturingClosures = 0;
1333 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1334 if (CapturingScopeInfo *CSI =
1335 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1336 if (CSI->CXXThisCaptureIndex != 0) {
1337 // 'this' is already being captured; there isn't anything more to do.
1338 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1339 break;
1340 }
1341 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1343 // This context can't implicitly capture 'this'; fail out.
1344 if (BuildAndDiagnose) {
1346 Diag(Loc, diag::err_this_capture)
1347 << (Explicit && idx == MaxFunctionScopesIndex);
1348 if (!Explicit)
1349 buildLambdaThisCaptureFixit(*this, LSI);
1350 }
1351 return true;
1352 }
1353 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1354 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1355 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1356 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1357 (Explicit && idx == MaxFunctionScopesIndex)) {
1358 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1359 // iteration through can be an explicit capture, all enclosing closures,
1360 // if any, must perform implicit captures.
1361
1362 // This closure can capture 'this'; continue looking upwards.
1363 NumCapturingClosures++;
1364 continue;
1365 }
1366 // This context can't implicitly capture 'this'; fail out.
1367 if (BuildAndDiagnose) {
1369 Diag(Loc, diag::err_this_capture)
1370 << (Explicit && idx == MaxFunctionScopesIndex);
1371 }
1372 if (!Explicit)
1373 buildLambdaThisCaptureFixit(*this, LSI);
1374 return true;
1375 }
1376 break;
1377 }
1378 if (!BuildAndDiagnose) return false;
1379
1380 // If we got here, then the closure at MaxFunctionScopesIndex on the
1381 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1382 // (including implicit by-reference captures in any enclosing closures).
1383
1384 // In the loop below, respect the ByCopy flag only for the closure requesting
1385 // the capture (i.e. first iteration through the loop below). Ignore it for
1386 // all enclosing closure's up to NumCapturingClosures (since they must be
1387 // implicitly capturing the *enclosing object* by reference (see loop
1388 // above)).
1389 assert((!ByCopy ||
1390 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1391 "Only a lambda can capture the enclosing object (referred to by "
1392 "*this) by copy");
1393 QualType ThisTy = getCurrentThisType();
1394 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1395 --idx, --NumCapturingClosures) {
1396 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1397
1398 // The type of the corresponding data member (not a 'this' pointer if 'by
1399 // copy').
1400 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1401
1402 bool isNested = NumCapturingClosures > 1;
1403 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1404 }
1405 return false;
1406}
1407
1409 // C++20 [expr.prim.this]p1:
1410 // The keyword this names a pointer to the object for which an
1411 // implicit object member function is invoked or a non-static
1412 // data member's initializer is evaluated.
1413 QualType ThisTy = getCurrentThisType();
1414
1415 if (CheckCXXThisType(Loc, ThisTy))
1416 return ExprError();
1417
1418 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1419}
1420
1422 if (!Type.isNull())
1423 return false;
1424
1425 // C++20 [expr.prim.this]p3:
1426 // If a declaration declares a member function or member function template
1427 // of a class X, the expression this is a prvalue of type
1428 // "pointer to cv-qualifier-seq X" wherever X is the current class between
1429 // the optional cv-qualifier-seq and the end of the function-definition,
1430 // member-declarator, or declarator. It shall not appear within the
1431 // declaration of either a static member function or an explicit object
1432 // member function of the current class (although its type and value
1433 // category are defined within such member functions as they are within
1434 // an implicit object member function).
1436 const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1437 if (Method && Method->isExplicitObjectMemberFunction()) {
1438 Diag(Loc, diag::err_invalid_this_use) << 1;
1440 Diag(Loc, diag::err_invalid_this_use) << 1;
1441 } else {
1442 Diag(Loc, diag::err_invalid_this_use) << 0;
1443 }
1444 return true;
1445}
1446
1448 bool IsImplicit) {
1449 auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);
1450 MarkThisReferenced(This);
1451 return This;
1452}
1453
1455 CheckCXXThisCapture(This->getExprLoc());
1456 if (This->isTypeDependent())
1457 return;
1458
1459 // Check if 'this' is captured by value in a lambda with a dependent explicit
1460 // object parameter, and mark it as type-dependent as well if so.
1461 auto IsDependent = [&]() {
1462 for (auto *Scope : llvm::reverse(FunctionScopes)) {
1463 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
1464 if (!LSI)
1465 continue;
1466
1467 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
1468 LSI->AfterParameterList)
1469 return false;
1470
1471 // If this lambda captures 'this' by value, then 'this' is dependent iff
1472 // this lambda has a dependent explicit object parameter. If we can't
1473 // determine whether it does (e.g. because the CXXMethodDecl's type is
1474 // null), assume it doesn't.
1475 if (LSI->isCXXThisCaptured()) {
1476 if (!LSI->getCXXThisCapture().isCopyCapture())
1477 continue;
1478
1479 const auto *MD = LSI->CallOperator;
1480 if (MD->getType().isNull())
1481 return false;
1482
1483 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
1484 return Ty && MD->isExplicitObjectMemberFunction() &&
1485 Ty->getParamType(0)->isDependentType();
1486 }
1487 }
1488 return false;
1489 }();
1490
1491 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);
1492}
1493
1495 // If we're outside the body of a member function, then we'll have a specified
1496 // type for 'this'.
1498 return false;
1499
1500 // Determine whether we're looking into a class that's currently being
1501 // defined.
1502 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1503 return Class && Class->isBeingDefined();
1504}
1505
1508 SourceLocation LParenOrBraceLoc,
1509 MultiExprArg exprs,
1510 SourceLocation RParenOrBraceLoc,
1511 bool ListInitialization) {
1512 if (!TypeRep)
1513 return ExprError();
1514
1515 TypeSourceInfo *TInfo;
1516 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1517 if (!TInfo)
1519
1520 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1521 RParenOrBraceLoc, ListInitialization);
1522 // Avoid creating a non-type-dependent expression that contains typos.
1523 // Non-type-dependent expressions are liable to be discarded without
1524 // checking for embedded typos.
1525 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1526 !Result.get()->isTypeDependent())
1528 else if (Result.isInvalid())
1530 RParenOrBraceLoc, exprs, Ty);
1531 return Result;
1532}
1533
1536 SourceLocation LParenOrBraceLoc,
1537 MultiExprArg Exprs,
1538 SourceLocation RParenOrBraceLoc,
1539 bool ListInitialization) {
1540 QualType Ty = TInfo->getType();
1541 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1542
1543 assert((!ListInitialization || Exprs.size() == 1) &&
1544 "List initialization must have exactly one expression.");
1545 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1546
1547 InitializedEntity Entity =
1549 InitializationKind Kind =
1550 Exprs.size()
1551 ? ListInitialization
1553 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1554 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1555 RParenOrBraceLoc)
1556 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1557 RParenOrBraceLoc);
1558
1559 // C++17 [expr.type.conv]p1:
1560 // If the type is a placeholder for a deduced class type, [...perform class
1561 // template argument deduction...]
1562 // C++23:
1563 // Otherwise, if the type contains a placeholder type, it is replaced by the
1564 // type determined by placeholder type deduction.
1565 DeducedType *Deduced = Ty->getContainedDeducedType();
1566 if (Deduced && !Deduced->isDeduced() &&
1567 isa<DeducedTemplateSpecializationType>(Deduced)) {
1569 Kind, Exprs);
1570 if (Ty.isNull())
1571 return ExprError();
1572 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1573 } else if (Deduced && !Deduced->isDeduced()) {
1574 MultiExprArg Inits = Exprs;
1575 if (ListInitialization) {
1576 auto *ILE = cast<InitListExpr>(Exprs[0]);
1577 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1578 }
1579
1580 if (Inits.empty())
1581 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1582 << Ty << FullRange);
1583 if (Inits.size() > 1) {
1584 Expr *FirstBad = Inits[1];
1585 return ExprError(Diag(FirstBad->getBeginLoc(),
1586 diag::err_auto_expr_init_multiple_expressions)
1587 << Ty << FullRange);
1588 }
1589 if (getLangOpts().CPlusPlus23) {
1590 if (Ty->getAs<AutoType>())
1591 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1592 }
1593 Expr *Deduce = Inits[0];
1594 if (isa<InitListExpr>(Deduce))
1595 return ExprError(
1596 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1597 << ListInitialization << Ty << FullRange);
1599 TemplateDeductionInfo Info(Deduce->getExprLoc());
1601 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1604 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1605 << Ty << Deduce->getType() << FullRange
1606 << Deduce->getSourceRange());
1607 if (DeducedType.isNull()) {
1609 return ExprError();
1610 }
1611
1612 Ty = DeducedType;
1613 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1614 }
1615
1618 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1619 RParenOrBraceLoc, ListInitialization);
1620
1621 // C++ [expr.type.conv]p1:
1622 // If the expression list is a parenthesized single expression, the type
1623 // conversion expression is equivalent (in definedness, and if defined in
1624 // meaning) to the corresponding cast expression.
1625 if (Exprs.size() == 1 && !ListInitialization &&
1626 !isa<InitListExpr>(Exprs[0])) {
1627 Expr *Arg = Exprs[0];
1628 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1629 RParenOrBraceLoc);
1630 }
1631
1632 // For an expression of the form T(), T shall not be an array type.
1633 QualType ElemTy = Ty;
1634 if (Ty->isArrayType()) {
1635 if (!ListInitialization)
1636 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1637 << FullRange);
1638 ElemTy = Context.getBaseElementType(Ty);
1639 }
1640
1641 // Only construct objects with object types.
1642 // The standard doesn't explicitly forbid function types here, but that's an
1643 // obvious oversight, as there's no way to dynamically construct a function
1644 // in general.
1645 if (Ty->isFunctionType())
1646 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1647 << Ty << FullRange);
1648
1649 // C++17 [expr.type.conv]p2, per DR2351:
1650 // If the type is cv void and the initializer is () or {}, the expression is
1651 // a prvalue of the specified type that performs no initialization.
1652 if (Ty->isVoidType()) {
1653 if (Exprs.empty())
1654 return new (Context) CXXScalarValueInitExpr(
1655 Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd());
1656 if (ListInitialization &&
1657 cast<InitListExpr>(Exprs[0])->getNumInits() == 0) {
1659 Context, Ty.getUnqualifiedType(), VK_PRValue, TInfo, CK_ToVoid,
1660 Exprs[0], /*Path=*/nullptr, CurFPFeatureOverrides(),
1661 Exprs[0]->getBeginLoc(), Exprs[0]->getEndLoc());
1662 }
1663 } else if (RequireCompleteType(TyBeginLoc, ElemTy,
1664 diag::err_invalid_incomplete_type_use,
1665 FullRange))
1666 return ExprError();
1667
1668 // Otherwise, the expression is a prvalue of the specified type whose
1669 // result object is direct-initialized (11.6) with the initializer.
1670 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1671 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1672
1673 if (Result.isInvalid())
1674 return Result;
1675
1676 Expr *Inner = Result.get();
1677 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1678 Inner = BTE->getSubExpr();
1679 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1680 CE && CE->isImmediateInvocation())
1681 Inner = CE->getSubExpr();
1682 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1683 !isa<CXXScalarValueInitExpr>(Inner)) {
1684 // If we created a CXXTemporaryObjectExpr, that node also represents the
1685 // functional cast. Otherwise, create an explicit cast to represent
1686 // the syntactic form of a functional-style cast that was used here.
1687 //
1688 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1689 // would give a more consistent AST representation than using a
1690 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1691 // is sometimes handled by initialization and sometimes not.
1692 QualType ResultType = Result.get()->getType();
1693 SourceRange Locs = ListInitialization
1694 ? SourceRange()
1695 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1697 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1698 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1699 Locs.getBegin(), Locs.getEnd());
1700 }
1701
1702 return Result;
1703}
1704
1706 // [CUDA] Ignore this function, if we can't call it.
1707 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1708 if (getLangOpts().CUDA) {
1709 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1710 // If it's not callable at all, it's not the right function.
1711 if (CallPreference < SemaCUDA::CFP_WrongSide)
1712 return false;
1713 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1714 // Maybe. We have to check if there are better alternatives.
1716 Method->getDeclContext()->lookup(Method->getDeclName());
1717 for (const auto *D : R) {
1718 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1719 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1720 return false;
1721 }
1722 }
1723 // We've found no better variants.
1724 }
1725 }
1726
1728 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1729
1730 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1731 return Result;
1732
1733 // In case of CUDA, return true if none of the 1-argument deallocator
1734 // functions are actually callable.
1735 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1736 assert(FD->getNumParams() == 1 &&
1737 "Only single-operand functions should be in PreventedBy");
1738 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1739 });
1740}
1741
1742/// Determine whether the given function is a non-placement
1743/// deallocation function.
1745 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1746 return S.isUsualDeallocationFunction(Method);
1747
1748 if (FD->getOverloadedOperator() != OO_Delete &&
1749 FD->getOverloadedOperator() != OO_Array_Delete)
1750 return false;
1751
1752 unsigned UsualParams = 1;
1753
1754 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1756 FD->getParamDecl(UsualParams)->getType(),
1757 S.Context.getSizeType()))
1758 ++UsualParams;
1759
1760 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1762 FD->getParamDecl(UsualParams)->getType(),
1764 ++UsualParams;
1765
1766 return UsualParams == FD->getNumParams();
1767}
1768
1769namespace {
1770 struct UsualDeallocFnInfo {
1771 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1772 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1773 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1774 Destroying(false), HasSizeT(false), HasAlignValT(false),
1775 CUDAPref(SemaCUDA::CFP_Native) {
1776 // A function template declaration is never a usual deallocation function.
1777 if (!FD)
1778 return;
1779 unsigned NumBaseParams = 1;
1780 if (FD->isDestroyingOperatorDelete()) {
1781 Destroying = true;
1782 ++NumBaseParams;
1783 }
1784
1785 if (NumBaseParams < FD->getNumParams() &&
1787 FD->getParamDecl(NumBaseParams)->getType(),
1788 S.Context.getSizeType())) {
1789 ++NumBaseParams;
1790 HasSizeT = true;
1791 }
1792
1793 if (NumBaseParams < FD->getNumParams() &&
1794 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1795 ++NumBaseParams;
1796 HasAlignValT = true;
1797 }
1798
1799 // In CUDA, determine how much we'd like / dislike to call this.
1800 if (S.getLangOpts().CUDA)
1801 CUDAPref = S.CUDA().IdentifyPreference(
1802 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1803 }
1804
1805 explicit operator bool() const { return FD; }
1806
1807 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1808 bool WantAlign) const {
1809 // C++ P0722:
1810 // A destroying operator delete is preferred over a non-destroying
1811 // operator delete.
1812 if (Destroying != Other.Destroying)
1813 return Destroying;
1814
1815 // C++17 [expr.delete]p10:
1816 // If the type has new-extended alignment, a function with a parameter
1817 // of type std::align_val_t is preferred; otherwise a function without
1818 // such a parameter is preferred
1819 if (HasAlignValT != Other.HasAlignValT)
1820 return HasAlignValT == WantAlign;
1821
1822 if (HasSizeT != Other.HasSizeT)
1823 return HasSizeT == WantSize;
1824
1825 // Use CUDA call preference as a tiebreaker.
1826 return CUDAPref > Other.CUDAPref;
1827 }
1828
1830 FunctionDecl *FD;
1831 bool Destroying, HasSizeT, HasAlignValT;
1833 };
1834}
1835
1836/// Determine whether a type has new-extended alignment. This may be called when
1837/// the type is incomplete (for a delete-expression with an incomplete pointee
1838/// type), in which case it will conservatively return false if the alignment is
1839/// not known.
1840static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1841 return S.getLangOpts().AlignedAllocation &&
1842 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1844}
1845
1846/// Select the correct "usual" deallocation function to use from a selection of
1847/// deallocation functions (either global or class-scope).
1848static UsualDeallocFnInfo resolveDeallocationOverload(
1849 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1850 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1851 UsualDeallocFnInfo Best;
1852
1853 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1854 UsualDeallocFnInfo Info(S, I.getPair());
1855 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1856 Info.CUDAPref == SemaCUDA::CFP_Never)
1857 continue;
1858
1859 if (!Best) {
1860 Best = Info;
1861 if (BestFns)
1862 BestFns->push_back(Info);
1863 continue;
1864 }
1865
1866 if (Best.isBetterThan(Info, WantSize, WantAlign))
1867 continue;
1868
1869 // If more than one preferred function is found, all non-preferred
1870 // functions are eliminated from further consideration.
1871 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1872 BestFns->clear();
1873
1874 Best = Info;
1875 if (BestFns)
1876 BestFns->push_back(Info);
1877 }
1878
1879 return Best;
1880}
1881
1882/// Determine whether a given type is a class for which 'delete[]' would call
1883/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1884/// we need to store the array size (even if the type is
1885/// trivially-destructible).
1887 QualType allocType) {
1888 const RecordType *record =
1889 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1890 if (!record) return false;
1891
1892 // Try to find an operator delete[] in class scope.
1893
1894 DeclarationName deleteName =
1895 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1896 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1897 S.LookupQualifiedName(ops, record->getDecl());
1898
1899 // We're just doing this for information.
1900 ops.suppressDiagnostics();
1901
1902 // Very likely: there's no operator delete[].
1903 if (ops.empty()) return false;
1904
1905 // If it's ambiguous, it should be illegal to call operator delete[]
1906 // on this thing, so it doesn't matter if we allocate extra space or not.
1907 if (ops.isAmbiguous()) return false;
1908
1909 // C++17 [expr.delete]p10:
1910 // If the deallocation functions have class scope, the one without a
1911 // parameter of type std::size_t is selected.
1912 auto Best = resolveDeallocationOverload(
1913 S, ops, /*WantSize*/false,
1914 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1915 return Best && Best.HasSizeT;
1916}
1917
1919Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1920 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1921 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1923 std::optional<Expr *> ArraySize;
1924 // If the specified type is an array, unwrap it and save the expression.
1925 if (D.getNumTypeObjects() > 0 &&
1926 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1927 DeclaratorChunk &Chunk = D.getTypeObject(0);
1928 if (D.getDeclSpec().hasAutoTypeSpec())
1929 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1930 << D.getSourceRange());
1931 if (Chunk.Arr.hasStatic)
1932 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1933 << D.getSourceRange());
1934 if (!Chunk.Arr.NumElts && !Initializer)
1935 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1936 << D.getSourceRange());
1937
1938 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1939 D.DropFirstTypeObject();
1940 }
1941
1942 // Every dimension shall be of constant size.
1943 if (ArraySize) {
1944 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1945 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1946 break;
1947
1948 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1949 if (Expr *NumElts = (Expr *)Array.NumElts) {
1950 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1951 // FIXME: GCC permits constant folding here. We should either do so consistently
1952 // or not do so at all, rather than changing behavior in C++14 onwards.
1953 if (getLangOpts().CPlusPlus14) {
1954 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1955 // shall be a converted constant expression (5.19) of type std::size_t
1956 // and shall evaluate to a strictly positive value.
1957 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1958 Array.NumElts
1961 .get();
1962 } else {
1963 Array.NumElts =
1965 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1966 .get();
1967 }
1968 if (!Array.NumElts)
1969 return ExprError();
1970 }
1971 }
1972 }
1973 }
1974
1976 QualType AllocType = TInfo->getType();
1977 if (D.isInvalidType())
1978 return ExprError();
1979
1980 SourceRange DirectInitRange;
1981 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1982 DirectInitRange = List->getSourceRange();
1983
1984 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1985 PlacementLParen, PlacementArgs, PlacementRParen,
1986 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1987 Initializer);
1988}
1989
1991 Expr *Init, bool IsCPlusPlus20) {
1992 if (!Init)
1993 return true;
1994 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1995 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
1996 if (isa<ImplicitValueInitExpr>(Init))
1997 return true;
1998 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1999 return !CCE->isListInitialization() &&
2000 CCE->getConstructor()->isDefaultConstructor();
2001 else if (Style == CXXNewInitializationStyle::Braces) {
2002 assert(isa<InitListExpr>(Init) &&
2003 "Shouldn't create list CXXConstructExprs for arrays.");
2004 return true;
2005 }
2006 return false;
2007}
2008
2009bool
2011 if (!getLangOpts().AlignedAllocationUnavailable)
2012 return false;
2013 if (FD.isDefined())
2014 return false;
2015 std::optional<unsigned> AlignmentParam;
2016 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2017 AlignmentParam)
2018 return true;
2019 return false;
2020}
2021
2022// Emit a diagnostic if an aligned allocation/deallocation function that is not
2023// implemented in the standard library is selected.
2027 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2028 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2029 getASTContext().getTargetInfo().getPlatformName());
2030 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2031
2033 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
2034 Diag(Loc, diag::err_aligned_allocation_unavailable)
2035 << IsDelete << FD.getType().getAsString() << OSName
2036 << OSVersion.getAsString() << OSVersion.empty();
2037 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2038 }
2039}
2040
2042 SourceLocation PlacementLParen,
2043 MultiExprArg PlacementArgs,
2044 SourceLocation PlacementRParen,
2045 SourceRange TypeIdParens, QualType AllocType,
2046 TypeSourceInfo *AllocTypeInfo,
2047 std::optional<Expr *> ArraySize,
2048 SourceRange DirectInitRange, Expr *Initializer) {
2049 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2050 SourceLocation StartLoc = Range.getBegin();
2051
2052 CXXNewInitializationStyle InitStyle;
2053 if (DirectInitRange.isValid()) {
2054 assert(Initializer && "Have parens but no initializer.");
2056 } else if (isa_and_nonnull<InitListExpr>(Initializer))
2058 else {
2059 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2060 isa<CXXConstructExpr>(Initializer)) &&
2061 "Initializer expression that cannot have been implicitly created.");
2063 }
2064
2065 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2066 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2067 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2068 "paren init for non-call init");
2069 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2070 }
2071
2072 // C++11 [expr.new]p15:
2073 // A new-expression that creates an object of type T initializes that
2074 // object as follows:
2075 InitializationKind Kind = [&] {
2076 switch (InitStyle) {
2077 // - If the new-initializer is omitted, the object is default-
2078 // initialized (8.5); if no initialization is performed,
2079 // the object has indeterminate value
2081 return InitializationKind::CreateDefault(TypeRange.getBegin());
2082 // - Otherwise, the new-initializer is interpreted according to the
2083 // initialization rules of 8.5 for direct-initialization.
2085 return InitializationKind::CreateDirect(TypeRange.getBegin(),
2086 DirectInitRange.getBegin(),
2087 DirectInitRange.getEnd());
2090 Initializer->getBeginLoc(),
2091 Initializer->getEndLoc());
2092 }
2093 llvm_unreachable("Unknown initialization kind");
2094 }();
2095
2096 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2097 auto *Deduced = AllocType->getContainedDeducedType();
2098 if (Deduced && !Deduced->isDeduced() &&
2099 isa<DeducedTemplateSpecializationType>(Deduced)) {
2100 if (ArraySize)
2101 return ExprError(
2102 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2103 diag::err_deduced_class_template_compound_type)
2104 << /*array*/ 2
2105 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2106
2107 InitializedEntity Entity
2108 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2110 AllocTypeInfo, Entity, Kind, Exprs);
2111 if (AllocType.isNull())
2112 return ExprError();
2113 } else if (Deduced && !Deduced->isDeduced()) {
2114 MultiExprArg Inits = Exprs;
2115 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2116 if (Braced) {
2117 auto *ILE = cast<InitListExpr>(Exprs[0]);
2118 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2119 }
2120
2121 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2122 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2123 << AllocType << TypeRange);
2124 if (Inits.size() > 1) {
2125 Expr *FirstBad = Inits[1];
2126 return ExprError(Diag(FirstBad->getBeginLoc(),
2127 diag::err_auto_new_ctor_multiple_expressions)
2128 << AllocType << TypeRange);
2129 }
2130 if (Braced && !getLangOpts().CPlusPlus17)
2131 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2132 << AllocType << TypeRange;
2133 Expr *Deduce = Inits[0];
2134 if (isa<InitListExpr>(Deduce))
2135 return ExprError(
2136 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2137 << Braced << AllocType << TypeRange);
2139 TemplateDeductionInfo Info(Deduce->getExprLoc());
2141 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2144 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2145 << AllocType << Deduce->getType() << TypeRange
2146 << Deduce->getSourceRange());
2147 if (DeducedType.isNull()) {
2149 return ExprError();
2150 }
2151 AllocType = DeducedType;
2152 }
2153
2154 // Per C++0x [expr.new]p5, the type being constructed may be a
2155 // typedef of an array type.
2156 if (!ArraySize) {
2157 if (const ConstantArrayType *Array
2158 = Context.getAsConstantArrayType(AllocType)) {
2159 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2161 TypeRange.getEnd());
2162 AllocType = Array->getElementType();
2163 }
2164 }
2165
2166 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2167 return ExprError();
2168
2169 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2170 return ExprError();
2171
2172 // In ARC, infer 'retaining' for the allocated
2173 if (getLangOpts().ObjCAutoRefCount &&
2174 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2175 AllocType->isObjCLifetimeType()) {
2176 AllocType = Context.getLifetimeQualifiedType(AllocType,
2177 AllocType->getObjCARCImplicitLifetime());
2178 }
2179
2180 QualType ResultType = Context.getPointerType(AllocType);
2181
2182 if (ArraySize && *ArraySize &&
2183 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2184 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2185 if (result.isInvalid()) return ExprError();
2186 ArraySize = result.get();
2187 }
2188 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2189 // integral or enumeration type with a non-negative value."
2190 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2191 // enumeration type, or a class type for which a single non-explicit
2192 // conversion function to integral or unscoped enumeration type exists.
2193 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2194 // std::size_t.
2195 std::optional<uint64_t> KnownArraySize;
2196 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2197 ExprResult ConvertedSize;
2198 if (getLangOpts().CPlusPlus14) {
2199 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2200
2201 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2203
2204 if (!ConvertedSize.isInvalid() &&
2205 (*ArraySize)->getType()->getAs<RecordType>())
2206 // Diagnose the compatibility of this conversion.
2207 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2208 << (*ArraySize)->getType() << 0 << "'size_t'";
2209 } else {
2210 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2211 protected:
2212 Expr *ArraySize;
2213
2214 public:
2215 SizeConvertDiagnoser(Expr *ArraySize)
2216 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2217 ArraySize(ArraySize) {}
2218
2219 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2220 QualType T) override {
2221 return S.Diag(Loc, diag::err_array_size_not_integral)
2222 << S.getLangOpts().CPlusPlus11 << T;
2223 }
2224
2225 SemaDiagnosticBuilder diagnoseIncomplete(
2226 Sema &S, SourceLocation Loc, QualType T) override {
2227 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2228 << T << ArraySize->getSourceRange();
2229 }
2230
2231 SemaDiagnosticBuilder diagnoseExplicitConv(
2232 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2233 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2234 }
2235
2236 SemaDiagnosticBuilder noteExplicitConv(
2237 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2238 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2239 << ConvTy->isEnumeralType() << ConvTy;
2240 }
2241
2242 SemaDiagnosticBuilder diagnoseAmbiguous(
2243 Sema &S, SourceLocation Loc, QualType T) override {
2244 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2245 }
2246
2247 SemaDiagnosticBuilder noteAmbiguous(
2248 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2249 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2250 << ConvTy->isEnumeralType() << ConvTy;
2251 }
2252
2253 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2254 QualType T,
2255 QualType ConvTy) override {
2256 return S.Diag(Loc,
2257 S.getLangOpts().CPlusPlus11
2258 ? diag::warn_cxx98_compat_array_size_conversion
2259 : diag::ext_array_size_conversion)
2260 << T << ConvTy->isEnumeralType() << ConvTy;
2261 }
2262 } SizeDiagnoser(*ArraySize);
2263
2264 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2265 SizeDiagnoser);
2266 }
2267 if (ConvertedSize.isInvalid())
2268 return ExprError();
2269
2270 ArraySize = ConvertedSize.get();
2271 QualType SizeType = (*ArraySize)->getType();
2272
2273 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2274 return ExprError();
2275
2276 // C++98 [expr.new]p7:
2277 // The expression in a direct-new-declarator shall have integral type
2278 // with a non-negative value.
2279 //
2280 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2281 // per CWG1464. Otherwise, if it's not a constant, we must have an
2282 // unparenthesized array type.
2283
2284 // We've already performed any required implicit conversion to integer or
2285 // unscoped enumeration type.
2286 // FIXME: Per CWG1464, we are required to check the value prior to
2287 // converting to size_t. This will never find a negative array size in
2288 // C++14 onwards, because Value is always unsigned here!
2289 if (std::optional<llvm::APSInt> Value =
2290 (*ArraySize)->getIntegerConstantExpr(Context)) {
2291 if (Value->isSigned() && Value->isNegative()) {
2292 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2293 diag::err_typecheck_negative_array_size)
2294 << (*ArraySize)->getSourceRange());
2295 }
2296
2297 if (!AllocType->isDependentType()) {
2298 unsigned ActiveSizeBits =
2300 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2301 return ExprError(
2302 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2303 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2304 }
2305
2306 KnownArraySize = Value->getZExtValue();
2307 } else if (TypeIdParens.isValid()) {
2308 // Can't have dynamic array size when the type-id is in parentheses.
2309 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2310 << (*ArraySize)->getSourceRange()
2311 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2312 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2313
2314 TypeIdParens = SourceRange();
2315 }
2316
2317 // Note that we do *not* convert the argument in any way. It can
2318 // be signed, larger than size_t, whatever.
2319 }
2320
2321 FunctionDecl *OperatorNew = nullptr;
2322 FunctionDecl *OperatorDelete = nullptr;
2323 unsigned Alignment =
2324 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2325 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2326 bool PassAlignment = getLangOpts().AlignedAllocation &&
2327 Alignment > NewAlignment;
2328
2329 if (CheckArgsForPlaceholders(PlacementArgs))
2330 return ExprError();
2331
2333 if (!AllocType->isDependentType() &&
2334 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2336 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2337 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2338 OperatorNew, OperatorDelete))
2339 return ExprError();
2340
2341 // If this is an array allocation, compute whether the usual array
2342 // deallocation function for the type has a size_t parameter.
2343 bool UsualArrayDeleteWantsSize = false;
2344 if (ArraySize && !AllocType->isDependentType())
2345 UsualArrayDeleteWantsSize =
2346 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2347
2348 SmallVector<Expr *, 8> AllPlaceArgs;
2349 if (OperatorNew) {
2350 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2351 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2353
2354 // We've already converted the placement args, just fill in any default
2355 // arguments. Skip the first parameter because we don't have a corresponding
2356 // argument. Skip the second parameter too if we're passing in the
2357 // alignment; we've already filled it in.
2358 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2359 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2360 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2361 CallType))
2362 return ExprError();
2363
2364 if (!AllPlaceArgs.empty())
2365 PlacementArgs = AllPlaceArgs;
2366
2367 // We would like to perform some checking on the given `operator new` call,
2368 // but the PlacementArgs does not contain the implicit arguments,
2369 // namely allocation size and maybe allocation alignment,
2370 // so we need to conjure them.
2371
2372 QualType SizeTy = Context.getSizeType();
2373 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2374
2375 llvm::APInt SingleEltSize(
2376 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2377
2378 // How many bytes do we want to allocate here?
2379 std::optional<llvm::APInt> AllocationSize;
2380 if (!ArraySize && !AllocType->isDependentType()) {
2381 // For non-array operator new, we only want to allocate one element.
2382 AllocationSize = SingleEltSize;
2383 } else if (KnownArraySize && !AllocType->isDependentType()) {
2384 // For array operator new, only deal with static array size case.
2385 bool Overflow;
2386 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2387 .umul_ov(SingleEltSize, Overflow);
2388 (void)Overflow;
2389 assert(
2390 !Overflow &&
2391 "Expected that all the overflows would have been handled already.");
2392 }
2393
2394 IntegerLiteral AllocationSizeLiteral(
2395 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2396 SizeTy, SourceLocation());
2397 // Otherwise, if we failed to constant-fold the allocation size, we'll
2398 // just give up and pass-in something opaque, that isn't a null pointer.
2399 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2400 OK_Ordinary, /*SourceExpr=*/nullptr);
2401
2402 // Let's synthesize the alignment argument in case we will need it.
2403 // Since we *really* want to allocate these on stack, this is slightly ugly
2404 // because there might not be a `std::align_val_t` type.
2406 QualType AlignValT =
2408 IntegerLiteral AlignmentLiteral(
2409 Context,
2410 llvm::APInt(Context.getTypeSize(SizeTy),
2411 Alignment / Context.getCharWidth()),
2412 SizeTy, SourceLocation());
2413 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2414 CK_IntegralCast, &AlignmentLiteral,
2416
2417 // Adjust placement args by prepending conjured size and alignment exprs.
2419 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2420 CallArgs.emplace_back(AllocationSize
2421 ? static_cast<Expr *>(&AllocationSizeLiteral)
2422 : &OpaqueAllocationSize);
2423 if (PassAlignment)
2424 CallArgs.emplace_back(&DesiredAlignment);
2425 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2426
2427 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2428
2429 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2430 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2431
2432 // Warn if the type is over-aligned and is being allocated by (unaligned)
2433 // global operator new.
2434 if (PlacementArgs.empty() && !PassAlignment &&
2435 (OperatorNew->isImplicit() ||
2436 (OperatorNew->getBeginLoc().isValid() &&
2437 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2438 if (Alignment > NewAlignment)
2439 Diag(StartLoc, diag::warn_overaligned_type)
2440 << AllocType
2441 << unsigned(Alignment / Context.getCharWidth())
2442 << unsigned(NewAlignment / Context.getCharWidth());
2443 }
2444 }
2445
2446 // Array 'new' can't have any initializers except empty parentheses.
2447 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2448 // dialect distinction.
2449 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2451 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2452 Exprs.back()->getEndLoc());
2453 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2454 return ExprError();
2455 }
2456
2457 // If we can perform the initialization, and we've not already done so,
2458 // do it now.
2459 if (!AllocType->isDependentType() &&
2461 // The type we initialize is the complete type, including the array bound.
2462 QualType InitType;
2463 if (KnownArraySize)
2464 InitType = Context.getConstantArrayType(
2465 AllocType,
2466 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2467 *KnownArraySize),
2468 *ArraySize, ArraySizeModifier::Normal, 0);
2469 else if (ArraySize)
2470 InitType = Context.getIncompleteArrayType(AllocType,
2472 else
2473 InitType = AllocType;
2474
2475 InitializedEntity Entity
2476 = InitializedEntity::InitializeNew(StartLoc, InitType);
2477 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2478 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2479 if (FullInit.isInvalid())
2480 return ExprError();
2481
2482 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2483 // we don't want the initialized object to be destructed.
2484 // FIXME: We should not create these in the first place.
2485 if (CXXBindTemporaryExpr *Binder =
2486 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2487 FullInit = Binder->getSubExpr();
2488
2489 Initializer = FullInit.get();
2490
2491 // FIXME: If we have a KnownArraySize, check that the array bound of the
2492 // initializer is no greater than that constant value.
2493
2494 if (ArraySize && !*ArraySize) {
2495 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2496 if (CAT) {
2497 // FIXME: Track that the array size was inferred rather than explicitly
2498 // specified.
2499 ArraySize = IntegerLiteral::Create(
2500 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2501 } else {
2502 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2503 << Initializer->getSourceRange();
2504 }
2505 }
2506 }
2507
2508 // Mark the new and delete operators as referenced.
2509 if (OperatorNew) {
2510 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2511 return ExprError();
2512 MarkFunctionReferenced(StartLoc, OperatorNew);
2513 }
2514 if (OperatorDelete) {
2515 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2516 return ExprError();
2517 MarkFunctionReferenced(StartLoc, OperatorDelete);
2518 }
2519
2520 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2521 PassAlignment, UsualArrayDeleteWantsSize,
2522 PlacementArgs, TypeIdParens, ArraySize, InitStyle,
2523 Initializer, ResultType, AllocTypeInfo, Range,
2524 DirectInitRange);
2525}
2526
2528 SourceRange R) {
2529 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2530 // abstract class type or array thereof.
2531 if (AllocType->isFunctionType())
2532 return Diag(Loc, diag::err_bad_new_type)
2533 << AllocType << 0 << R;
2534 else if (AllocType->isReferenceType())
2535 return Diag(Loc, diag::err_bad_new_type)
2536 << AllocType << 1 << R;
2537 else if (!AllocType->isDependentType() &&
2539 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2540 return true;
2541 else if (RequireNonAbstractType(Loc, AllocType,
2542 diag::err_allocation_of_abstract_type))
2543 return true;
2544 else if (AllocType->isVariablyModifiedType())
2545 return Diag(Loc, diag::err_variably_modified_new_type)
2546 << AllocType;
2547 else if (AllocType.getAddressSpace() != LangAS::Default &&
2548 !getLangOpts().OpenCLCPlusPlus)
2549 return Diag(Loc, diag::err_address_space_qualified_new)
2550 << AllocType.getUnqualifiedType()
2552 else if (getLangOpts().ObjCAutoRefCount) {
2553 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2554 QualType BaseAllocType = Context.getBaseElementType(AT);
2555 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2556 BaseAllocType->isObjCLifetimeType())
2557 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2558 << BaseAllocType;
2559 }
2560 }
2561
2562 return false;
2563}
2564
2567 bool &PassAlignment, FunctionDecl *&Operator,
2568 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2569 OverloadCandidateSet Candidates(R.getNameLoc(),
2571 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2572 Alloc != AllocEnd; ++Alloc) {
2573 // Even member operator new/delete are implicitly treated as
2574 // static, so don't use AddMemberCandidate.
2575 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2576
2577 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2578 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2579 /*ExplicitTemplateArgs=*/nullptr, Args,
2580 Candidates,
2581 /*SuppressUserConversions=*/false);
2582 continue;
2583 }
2584
2585 FunctionDecl *Fn = cast<FunctionDecl>(D);
2586 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2587 /*SuppressUserConversions=*/false);
2588 }
2589
2590 // Do the resolution.
2592 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2593 case OR_Success: {
2594 // Got one!
2595 FunctionDecl *FnDecl = Best->Function;
2597 Best->FoundDecl) == Sema::AR_inaccessible)
2598 return true;
2599
2600 Operator = FnDecl;
2601 return false;
2602 }
2603
2605 // C++17 [expr.new]p13:
2606 // If no matching function is found and the allocated object type has
2607 // new-extended alignment, the alignment argument is removed from the
2608 // argument list, and overload resolution is performed again.
2609 if (PassAlignment) {
2610 PassAlignment = false;
2611 AlignArg = Args[1];
2612 Args.erase(Args.begin() + 1);
2613 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2614 Operator, &Candidates, AlignArg,
2615 Diagnose);
2616 }
2617
2618 // MSVC will fall back on trying to find a matching global operator new
2619 // if operator new[] cannot be found. Also, MSVC will leak by not
2620 // generating a call to operator delete or operator delete[], but we
2621 // will not replicate that bug.
2622 // FIXME: Find out how this interacts with the std::align_val_t fallback
2623 // once MSVC implements it.
2624 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2625 S.Context.getLangOpts().MSVCCompat) {
2626 R.clear();
2629 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2630 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2631 Operator, /*Candidates=*/nullptr,
2632 /*AlignArg=*/nullptr, Diagnose);
2633 }
2634
2635 if (Diagnose) {
2636 // If this is an allocation of the form 'new (p) X' for some object
2637 // pointer p (or an expression that will decay to such a pointer),
2638 // diagnose the missing inclusion of <new>.
2639 if (!R.isClassLookup() && Args.size() == 2 &&
2640 (Args[1]->getType()->isObjectPointerType() ||
2641 Args[1]->getType()->isArrayType())) {
2642 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2643 << R.getLookupName() << Range;
2644 // Listing the candidates is unlikely to be useful; skip it.
2645 return true;
2646 }
2647
2648 // Finish checking all candidates before we note any. This checking can
2649 // produce additional diagnostics so can't be interleaved with our
2650 // emission of notes.
2651 //
2652 // For an aligned allocation, separately check the aligned and unaligned
2653 // candidates with their respective argument lists.
2656 llvm::SmallVector<Expr*, 4> AlignedArgs;
2657 if (AlignedCandidates) {
2658 auto IsAligned = [](OverloadCandidate &C) {
2659 return C.Function->getNumParams() > 1 &&
2660 C.Function->getParamDecl(1)->getType()->isAlignValT();
2661 };
2662 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2663
2664 AlignedArgs.reserve(Args.size() + 1);
2665 AlignedArgs.push_back(Args[0]);
2666 AlignedArgs.push_back(AlignArg);
2667 AlignedArgs.append(Args.begin() + 1, Args.end());
2668 AlignedCands = AlignedCandidates->CompleteCandidates(
2669 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2670
2671 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2672 R.getNameLoc(), IsUnaligned);
2673 } else {
2674 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2675 R.getNameLoc());
2676 }
2677
2678 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2679 << R.getLookupName() << Range;
2680 if (AlignedCandidates)
2681 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2682 R.getNameLoc());
2683 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2684 }
2685 return true;
2686
2687 case OR_Ambiguous:
2688 if (Diagnose) {
2689 Candidates.NoteCandidates(
2691 S.PDiag(diag::err_ovl_ambiguous_call)
2692 << R.getLookupName() << Range),
2693 S, OCD_AmbiguousCandidates, Args);
2694 }
2695 return true;
2696
2697 case OR_Deleted: {
2698 if (Diagnose)
2700 Candidates, Best->Function, Args);
2701 return true;
2702 }
2703 }
2704 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2705}
2706
2708 AllocationFunctionScope NewScope,
2709 AllocationFunctionScope DeleteScope,
2710 QualType AllocType, bool IsArray,
2711 bool &PassAlignment, MultiExprArg PlaceArgs,
2712 FunctionDecl *&OperatorNew,
2713 FunctionDecl *&OperatorDelete,
2714 bool Diagnose) {
2715 // --- Choosing an allocation function ---
2716 // C++ 5.3.4p8 - 14 & 18
2717 // 1) If looking in AFS_Global scope for allocation functions, only look in
2718 // the global scope. Else, if AFS_Class, only look in the scope of the
2719 // allocated class. If AFS_Both, look in both.
2720 // 2) If an array size is given, look for operator new[], else look for
2721 // operator new.
2722 // 3) The first argument is always size_t. Append the arguments from the
2723 // placement form.
2724
2725 SmallVector<Expr*, 8> AllocArgs;
2726 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2727
2728 // We don't care about the actual value of these arguments.
2729 // FIXME: Should the Sema create the expression and embed it in the syntax
2730 // tree? Or should the consumer just recalculate the value?
2731 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2732 QualType SizeTy = Context.getSizeType();
2733 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2734 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
2735 SourceLocation());
2736 AllocArgs.push_back(&Size);
2737
2738 QualType AlignValT = Context.VoidTy;
2739 if (PassAlignment) {
2742 }
2743 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2744 if (PassAlignment)
2745 AllocArgs.push_back(&Align);
2746
2747 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2748
2749 // C++ [expr.new]p8:
2750 // If the allocated type is a non-array type, the allocation
2751 // function's name is operator new and the deallocation function's
2752 // name is operator delete. If the allocated type is an array
2753 // type, the allocation function's name is operator new[] and the
2754 // deallocation function's name is operator delete[].
2756 IsArray ? OO_Array_New : OO_New);
2757
2758 QualType AllocElemType = Context.getBaseElementType(AllocType);
2759
2760 // Find the allocation function.
2761 {
2762 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2763
2764 // C++1z [expr.new]p9:
2765 // If the new-expression begins with a unary :: operator, the allocation
2766 // function's name is looked up in the global scope. Otherwise, if the
2767 // allocated type is a class type T or array thereof, the allocation
2768 // function's name is looked up in the scope of T.
2769 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2770 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2771
2772 // We can see ambiguity here if the allocation function is found in
2773 // multiple base classes.
2774 if (R.isAmbiguous())
2775 return true;
2776
2777 // If this lookup fails to find the name, or if the allocated type is not
2778 // a class type, the allocation function's name is looked up in the
2779 // global scope.
2780 if (R.empty()) {
2781 if (NewScope == AFS_Class)
2782 return true;
2783
2785 }
2786
2787 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2788 if (PlaceArgs.empty()) {
2789 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2790 } else {
2791 Diag(StartLoc, diag::err_openclcxx_placement_new);
2792 }
2793 return true;
2794 }
2795
2796 assert(!R.empty() && "implicitly declared allocation functions not found");
2797 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2798
2799 // We do our own custom access checks below.
2801
2802 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2803 OperatorNew, /*Candidates=*/nullptr,
2804 /*AlignArg=*/nullptr, Diagnose))
2805 return true;
2806 }
2807
2808 // We don't need an operator delete if we're running under -fno-exceptions.
2809 if (!getLangOpts().Exceptions) {
2810 OperatorDelete = nullptr;
2811 return false;
2812 }
2813
2814 // Note, the name of OperatorNew might have been changed from array to
2815 // non-array by resolveAllocationOverload.
2817 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2818 ? OO_Array_Delete
2819 : OO_Delete);
2820
2821 // C++ [expr.new]p19:
2822 //
2823 // If the new-expression begins with a unary :: operator, the
2824 // deallocation function's name is looked up in the global
2825 // scope. Otherwise, if the allocated type is a class type T or an
2826 // array thereof, the deallocation function's name is looked up in
2827 // the scope of T. If this lookup fails to find the name, or if
2828 // the allocated type is not a class type or array thereof, the
2829 // deallocation function's name is looked up in the global scope.
2830 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2831 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2832 auto *RD =
2833 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2834 LookupQualifiedName(FoundDelete, RD);
2835 }
2836 if (FoundDelete.isAmbiguous())
2837 return true; // FIXME: clean up expressions?
2838
2839 // Filter out any destroying operator deletes. We can't possibly call such a
2840 // function in this context, because we're handling the case where the object
2841 // was not successfully constructed.
2842 // FIXME: This is not covered by the language rules yet.
2843 {
2844 LookupResult::Filter Filter = FoundDelete.makeFilter();
2845 while (Filter.hasNext()) {
2846 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2847 if (FD && FD->isDestroyingOperatorDelete())
2848 Filter.erase();
2849 }
2850 Filter.done();
2851 }
2852
2853 bool FoundGlobalDelete = FoundDelete.empty();
2854 if (FoundDelete.empty()) {
2855 FoundDelete.clear(LookupOrdinaryName);
2856
2857 if (DeleteScope == AFS_Class)
2858 return true;
2859
2862 }
2863
2864 FoundDelete.suppressDiagnostics();
2865
2867
2868 // Whether we're looking for a placement operator delete is dictated
2869 // by whether we selected a placement operator new, not by whether
2870 // we had explicit placement arguments. This matters for things like
2871 // struct A { void *operator new(size_t, int = 0); ... };
2872 // A *a = new A()
2873 //
2874 // We don't have any definition for what a "placement allocation function"
2875 // is, but we assume it's any allocation function whose
2876 // parameter-declaration-clause is anything other than (size_t).
2877 //
2878 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2879 // This affects whether an exception from the constructor of an overaligned
2880 // type uses the sized or non-sized form of aligned operator delete.
2881 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2882 OperatorNew->isVariadic();
2883
2884 if (isPlacementNew) {
2885 // C++ [expr.new]p20:
2886 // A declaration of a placement deallocation function matches the
2887 // declaration of a placement allocation function if it has the
2888 // same number of parameters and, after parameter transformations
2889 // (8.3.5), all parameter types except the first are
2890 // identical. [...]
2891 //
2892 // To perform this comparison, we compute the function type that
2893 // the deallocation function should have, and use that type both
2894 // for template argument deduction and for comparison purposes.
2895 QualType ExpectedFunctionType;
2896 {
2897 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2898
2899 SmallVector<QualType, 4> ArgTypes;
2900 ArgTypes.push_back(Context.VoidPtrTy);
2901 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2902 ArgTypes.push_back(Proto->getParamType(I));
2903
2905 // FIXME: This is not part of the standard's rule.
2906 EPI.Variadic = Proto->isVariadic();
2907
2908 ExpectedFunctionType
2909 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2910 }
2911
2912 for (LookupResult::iterator D = FoundDelete.begin(),
2913 DEnd = FoundDelete.end();
2914 D != DEnd; ++D) {
2915 FunctionDecl *Fn = nullptr;
2916 if (FunctionTemplateDecl *FnTmpl =
2917 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2918 // Perform template argument deduction to try to match the
2919 // expected function type.
2920 TemplateDeductionInfo Info(StartLoc);
2921 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2923 continue;
2924 } else
2925 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2926
2927 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2928 ExpectedFunctionType,
2929 /*AdjustExcpetionSpec*/true),
2930 ExpectedFunctionType))
2931 Matches.push_back(std::make_pair(D.getPair(), Fn));
2932 }
2933
2934 if (getLangOpts().CUDA)
2935 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2936 Matches);
2937 } else {
2938 // C++1y [expr.new]p22:
2939 // For a non-placement allocation function, the normal deallocation
2940 // function lookup is used
2941 //
2942 // Per [expr.delete]p10, this lookup prefers a member operator delete
2943 // without a size_t argument, but prefers a non-member operator delete
2944 // with a size_t where possible (which it always is in this case).
2946 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2947 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2948 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2949 &BestDeallocFns);
2950 if (Selected)
2951 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2952 else {
2953 // If we failed to select an operator, all remaining functions are viable
2954 // but ambiguous.
2955 for (auto Fn : BestDeallocFns)
2956 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2957 }
2958 }
2959
2960 // C++ [expr.new]p20:
2961 // [...] If the lookup finds a single matching deallocation
2962 // function, that function will be called; otherwise, no
2963 // deallocation function will be called.
2964 if (Matches.size() == 1) {
2965 OperatorDelete = Matches[0].second;
2966
2967 // C++1z [expr.new]p23:
2968 // If the lookup finds a usual deallocation function (3.7.4.2)
2969 // with a parameter of type std::size_t and that function, considered
2970 // as a placement deallocation function, would have been
2971 // selected as a match for the allocation function, the program
2972 // is ill-formed.
2973 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2974 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2975 UsualDeallocFnInfo Info(*this,
2976 DeclAccessPair::make(OperatorDelete, AS_public));
2977 // Core issue, per mail to core reflector, 2016-10-09:
2978 // If this is a member operator delete, and there is a corresponding
2979 // non-sized member operator delete, this isn't /really/ a sized
2980 // deallocation function, it just happens to have a size_t parameter.
2981 bool IsSizedDelete = Info.HasSizeT;
2982 if (IsSizedDelete && !FoundGlobalDelete) {
2983 auto NonSizedDelete =
2984 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2985 /*WantAlign*/Info.HasAlignValT);
2986 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2987 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2988 IsSizedDelete = false;
2989 }
2990
2991 if (IsSizedDelete) {
2992 SourceRange R = PlaceArgs.empty()
2993 ? SourceRange()
2994 : SourceRange(PlaceArgs.front()->getBeginLoc(),
2995 PlaceArgs.back()->getEndLoc());
2996 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2997 if (!OperatorDelete->isImplicit())
2998 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2999 << DeleteName;
3000 }
3001 }
3002
3003 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
3004 Matches[0].first);
3005 } else if (!Matches.empty()) {
3006 // We found multiple suitable operators. Per [expr.new]p20, that means we
3007 // call no 'operator delete' function, but we should at least warn the user.
3008 // FIXME: Suppress this warning if the construction cannot throw.
3009 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
3010 << DeleteName << AllocElemType;
3011
3012 for (auto &Match : Matches)
3013 Diag(Match.second->getLocation(),
3014 diag::note_member_declared_here) << DeleteName;
3015 }
3016
3017 return false;
3018}
3019
3022 return;
3023
3024 // The implicitly declared new and delete operators
3025 // are not supported in OpenCL.
3026 if (getLangOpts().OpenCLCPlusPlus)
3027 return;
3028
3029 // C++ [basic.stc.dynamic.general]p2:
3030 // The library provides default definitions for the global allocation
3031 // and deallocation functions. Some global allocation and deallocation
3032 // functions are replaceable ([new.delete]); these are attached to the
3033 // global module ([module.unit]).
3034 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3035 PushGlobalModuleFragment(SourceLocation());
3036
3037 // C++ [basic.std.dynamic]p2:
3038 // [...] The following allocation and deallocation functions (18.4) are
3039 // implicitly declared in global scope in each translation unit of a
3040 // program
3041 //
3042 // C++03:
3043 // void* operator new(std::size_t) throw(std::bad_alloc);
3044 // void* operator new[](std::size_t) throw(std::bad_alloc);
3045 // void operator delete(void*) throw();
3046 // void operator delete[](void*) throw();
3047 // C++11:
3048 // void* operator new(std::size_t);
3049 // void* operator new[](std::size_t);
3050 // void operator delete(void*) noexcept;
3051 // void operator delete[](void*) noexcept;
3052 // C++1y:
3053 // void* operator new(std::size_t);
3054 // void* operator new[](std::size_t);
3055 // void operator delete(void*) noexcept;
3056 // void operator delete[](void*) noexcept;
3057 // void operator delete(void*, std::size_t) noexcept;
3058 // void operator delete[](void*, std::size_t) noexcept;
3059 //
3060 // These implicit declarations introduce only the function names operator
3061 // new, operator new[], operator delete, operator delete[].
3062 //
3063 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3064 // "std" or "bad_alloc" as necessary to form the exception specification.
3065 // However, we do not make these implicit declarations visible to name
3066 // lookup.
3067 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3068 // The "std::bad_alloc" class has not yet been declared, so build it
3069 // implicitly.
3073 &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3074 getStdBadAlloc()->setImplicit(true);
3075
3076 // The implicitly declared "std::bad_alloc" should live in global module
3077 // fragment.
3078 if (TheGlobalModuleFragment) {
3081 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3082 }
3083 }
3084 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3085 // The "std::align_val_t" enum class has not yet been declared, so build it
3086 // implicitly.
3087 auto *AlignValT = EnumDecl::Create(
3089 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3090
3091 // The implicitly declared "std::align_val_t" should live in global module
3092 // fragment.
3093 if (TheGlobalModuleFragment) {
3094 AlignValT->setModuleOwnershipKind(
3096 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3097 }
3098
3099 AlignValT->setIntegerType(Context.getSizeType());
3100 AlignValT->setPromotionType(Context.getSizeType());
3101 AlignValT->setImplicit(true);
3102
3103 StdAlignValT = AlignValT;
3104 }
3105
3107
3109 QualType SizeT = Context.getSizeType();
3110
3111 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3112 QualType Return, QualType Param) {
3114 Params.push_back(Param);
3115
3116 // Create up to four variants of the function (sized/aligned).
3117 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3118 (Kind == OO_Delete || Kind == OO_Array_Delete);
3119 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3120
3121 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3122 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3123 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3124 if (Sized)
3125 Params.push_back(SizeT);
3126
3127 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3128 if (Aligned)
3129 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3130
3132 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3133
3134 if (Aligned)
3135 Params.pop_back();
3136 }
3137 }
3138 };
3139
3140 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3141 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3142 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3143 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3144
3145 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3146 PopGlobalModuleFragment();
3147}
3148
3149/// DeclareGlobalAllocationFunction - Declares a single implicit global
3150/// allocation function if it doesn't already exist.
3152 QualType Return,
3153 ArrayRef<QualType> Params) {
3155
3156 // Check if this function is already declared.
3157 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3158 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3159 Alloc != AllocEnd; ++Alloc) {
3160 // Only look at non-template functions, as it is the predefined,
3161 // non-templated allocation function we are trying to declare here.
3162 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3163 if (Func->getNumParams() == Params.size()) {
3165 for (auto *P : Func->parameters())
3166 FuncParams.push_back(
3167 Context.getCanonicalType(P->getType().getUnqualifiedType()));
3168 if (llvm::ArrayRef(FuncParams) == Params) {
3169 // Make the function visible to name lookup, even if we found it in
3170 // an unimported module. It either is an implicitly-declared global
3171 // allocation function, or is suppressing that function.
3172 Func->setVisibleDespiteOwningModule();
3173 return;
3174 }
3175 }
3176 }
3177 }
3178
3180 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3181
3182 QualType BadAllocType;
3183 bool HasBadAllocExceptionSpec
3184 = (Name.getCXXOverloadedOperator() == OO_New ||
3185 Name.getCXXOverloadedOperator() == OO_Array_New);
3186 if (HasBadAllocExceptionSpec) {
3187 if (!getLangOpts().CPlusPlus11) {
3188 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3189 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3191 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3192 }
3193 if (getLangOpts().NewInfallible) {
3195 }
3196 } else {
3197 EPI.ExceptionSpec =
3199 }
3200
3201 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3202 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3204 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3205 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3206 true);
3207 Alloc->setImplicit();
3208 // Global allocation functions should always be visible.
3209 Alloc->setVisibleDespiteOwningModule();
3210
3211 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3212 !getLangOpts().CheckNew)
3213 Alloc->addAttr(
3214 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3215
3216 // C++ [basic.stc.dynamic.general]p2:
3217 // The library provides default definitions for the global allocation
3218 // and deallocation functions. Some global allocation and deallocation
3219 // functions are replaceable ([new.delete]); these are attached to the
3220 // global module ([module.unit]).
3221 //
3222 // In the language wording, these functions are attched to the global
3223 // module all the time. But in the implementation, the global module
3224 // is only meaningful when we're in a module unit. So here we attach
3225 // these allocation functions to global module conditionally.
3226 if (TheGlobalModuleFragment) {
3227 Alloc->setModuleOwnershipKind(
3229 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3230 }
3231
3233 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3235 ? VisibilityAttr::Hidden
3237 ? VisibilityAttr::Protected
3238 : VisibilityAttr::Default));
3239
3241 for (QualType T : Params) {
3242 ParamDecls.push_back(ParmVarDecl::Create(
3243 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3244 /*TInfo=*/nullptr, SC_None, nullptr));
3245 ParamDecls.back()->setImplicit();
3246 }
3247 Alloc->setParams(ParamDecls);
3248 if (ExtraAttr)
3249 Alloc->addAttr(ExtraAttr);
3252 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3253 };
3254
3255 if (!LangOpts.CUDA)
3256 CreateAllocationFunctionDecl(nullptr);
3257 else {
3258 // Host and device get their own declaration so each can be
3259 // defined or re-declared independently.
3260 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3261 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3262 }
3263}
3264
3266 bool CanProvideSize,
3267 bool Overaligned,
3268 DeclarationName Name) {
3270
3271 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3273
3274 // FIXME: It's possible for this to result in ambiguity, through a
3275 // user-declared variadic operator delete or the enable_if attribute. We
3276 // should probably not consider those cases to be usual deallocation
3277 // functions. But for now we just make an arbitrary choice in that case.
3278 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3279 Overaligned);
3280 assert(Result.FD && "operator delete missing from global scope?");
3281 return Result.FD;
3282}
3283
3285 CXXRecordDecl *RD) {
3287
3288 FunctionDecl *OperatorDelete = nullptr;
3289 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3290 return nullptr;
3291 if (OperatorDelete)
3292 return OperatorDelete;
3293
3294 // If there's no class-specific operator delete, look up the global
3295 // non-array delete.
3298 Name);
3299}
3300
3302 DeclarationName Name,
3303 FunctionDecl *&Operator, bool Diagnose,
3304 bool WantSize, bool WantAligned) {
3305 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3306 // Try to find operator delete/operator delete[] in class scope.
3308
3309 if (Found.isAmbiguous())
3310 return true;
3311
3312 Found.suppressDiagnostics();
3313
3314 bool Overaligned =
3315 WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3316
3317 // C++17 [expr.delete]p10:
3318 // If the deallocation functions have class scope, the one without a
3319 // parameter of type std::size_t is selected.
3321 resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3322 /*WantAlign*/ Overaligned, &Matches);
3323
3324 // If we could find an overload, use it.
3325 if (Matches.size() == 1) {
3326 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3327
3328 // FIXME: DiagnoseUseOfDecl?
3329 if (Operator->isDeleted()) {
3330 if (Diagnose) {
3331 StringLiteral *Msg = Operator->getDeletedMessage();
3332 Diag(StartLoc, diag::err_deleted_function_use)
3333 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
3334 NoteDeletedFunction(Operator);
3335 }
3336 return true;
3337 }
3338
3339 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3340 Matches[0].Found, Diagnose) == AR_inaccessible)
3341 return true;
3342
3343 return false;
3344 }
3345
3346 // We found multiple suitable operators; complain about the ambiguity.
3347 // FIXME: The standard doesn't say to do this; it appears that the intent
3348 // is that this should never happen.
3349 if (!Matches.empty()) {
3350 if (Diagnose) {
3351 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3352 << Name << RD;
3353 for (auto &Match : Matches)
3354 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3355 }
3356 return true;
3357 }
3358
3359 // We did find operator delete/operator delete[] declarations, but
3360 // none of them were suitable.
3361 if (!Found.empty()) {
3362 if (Diagnose) {
3363 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3364 << Name << RD;
3365
3366 for (NamedDecl *D : Found)
3367 Diag(D->getUnderlyingDecl()->getLocation(),
3368 diag::note_member_declared_here) << Name;
3369 }
3370 return true;
3371 }
3372
3373 Operator = nullptr;
3374 return false;
3375}
3376
3377namespace {
3378/// Checks whether delete-expression, and new-expression used for
3379/// initializing deletee have the same array form.
3380class MismatchingNewDeleteDetector {
3381public:
3382 enum MismatchResult {
3383 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3384 NoMismatch,
3385 /// Indicates that variable is initialized with mismatching form of \a new.
3386 VarInitMismatches,
3387 /// Indicates that member is initialized with mismatching form of \a new.
3388 MemberInitMismatches,
3389 /// Indicates that 1 or more constructors' definitions could not been
3390 /// analyzed, and they will be checked again at the end of translation unit.
3391 AnalyzeLater
3392 };
3393
3394 /// \param EndOfTU True, if this is the final analysis at the end of
3395 /// translation unit. False, if this is the initial analysis at the point
3396 /// delete-expression was encountered.
3397 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3398 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3399 HasUndefinedConstructors(false) {}
3400
3401 /// Checks whether pointee of a delete-expression is initialized with
3402 /// matching form of new-expression.
3403 ///
3404 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3405 /// point where delete-expression is encountered, then a warning will be
3406 /// issued immediately. If return value is \c AnalyzeLater at the point where
3407 /// delete-expression is seen, then member will be analyzed at the end of
3408 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3409 /// couldn't be analyzed. If at least one constructor initializes the member
3410 /// with matching type of new, the return value is \c NoMismatch.
3411 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3412 /// Analyzes a class member.
3413 /// \param Field Class member to analyze.
3414 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3415 /// for deleting the \p Field.
3416 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3418 /// List of mismatching new-expressions used for initialization of the pointee
3420 /// Indicates whether delete-expression was in array form.
3421 bool IsArrayForm;
3422
3423private:
3424 const bool EndOfTU;
3425 /// Indicates that there is at least one constructor without body.
3426 bool HasUndefinedConstructors;
3427 /// Returns \c CXXNewExpr from given initialization expression.
3428 /// \param E Expression used for initializing pointee in delete-expression.
3429 /// E can be a single-element \c InitListExpr consisting of new-expression.
3430 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3431 /// Returns whether member is initialized with mismatching form of
3432 /// \c new either by the member initializer or in-class initialization.
3433 ///
3434 /// If bodies of all constructors are not visible at the end of translation
3435 /// unit or at least one constructor initializes member with the matching
3436 /// form of \c new, mismatch cannot be proven, and this function will return
3437 /// \c NoMismatch.
3438 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3439 /// Returns whether variable is initialized with mismatching form of
3440 /// \c new.
3441 ///
3442 /// If variable is initialized with matching form of \c new or variable is not
3443 /// initialized with a \c new expression, this function will return true.
3444 /// If variable is initialized with mismatching form of \c new, returns false.
3445 /// \param D Variable to analyze.
3446 bool hasMatchingVarInit(const DeclRefExpr *D);
3447 /// Checks whether the constructor initializes pointee with mismatching
3448 /// form of \c new.
3449 ///
3450 /// Returns true, if member is initialized with matching form of \c new in
3451 /// member initializer list. Returns false, if member is initialized with the
3452 /// matching form of \c new in this constructor's initializer or given
3453 /// constructor isn't defined at the point where delete-expression is seen, or
3454 /// member isn't initialized by the constructor.
3455 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3456 /// Checks whether member is initialized with matching form of
3457 /// \c new in member initializer list.
3458 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3459 /// Checks whether member is initialized with mismatching form of \c new by
3460 /// in-class initializer.
3461 MismatchResult analyzeInClassInitializer();
3462};
3463}
3464
3465MismatchingNewDeleteDetector::MismatchResult
3466MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3467 NewExprs.clear();
3468 assert(DE && "Expected delete-expression");
3469 IsArrayForm = DE->isArrayForm();
3470 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3471 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3472 return analyzeMemberExpr(ME);
3473 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3474 if (!hasMatchingVarInit(D))
3475 return VarInitMismatches;
3476 }
3477 return NoMismatch;
3478}
3479
3480const CXXNewExpr *
3481MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3482 assert(E != nullptr && "Expected a valid initializer expression");
3483 E = E->IgnoreParenImpCasts();
3484 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3485 if (ILE->getNumInits() == 1)
3486 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3487 }
3488
3489 return dyn_cast_or_null<const CXXNewExpr>(E);
3490}
3491
3492bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3493 const CXXCtorInitializer *CI) {
3494 const CXXNewExpr *NE = nullptr;
3495 if (Field == CI->getMember() &&
3496 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3497 if (NE->isArray() == IsArrayForm)
3498 return true;
3499 else
3500 NewExprs.push_back(NE);
3501 }
3502 return false;
3503}
3504
3505bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3506 const CXXConstructorDecl *CD) {
3507 if (CD->isImplicit())
3508 return false;
3509 const FunctionDecl *Definition = CD;
3511 HasUndefinedConstructors = true;
3512 return EndOfTU;
3513 }
3514 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3515 if (hasMatchingNewInCtorInit(CI))
3516 return true;
3517 }
3518 return false;
3519}
3520
3521MismatchingNewDeleteDetector::MismatchResult
3522MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3523 assert(Field != nullptr && "This should be called only for members");
3524 const Expr *InitExpr = Field->getInClassInitializer();
3525 if (!InitExpr)
3526 return EndOfTU ? NoMismatch : AnalyzeLater;
3527 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3528 if (NE->isArray() != IsArrayForm) {
3529 NewExprs.push_back(NE);
3530 return MemberInitMismatches;
3531 }
3532 }
3533 return NoMismatch;
3534}
3535
3536MismatchingNewDeleteDetector::MismatchResult
3537MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3538 bool DeleteWasArrayForm) {
3539 assert(Field != nullptr && "Analysis requires a valid class member.");
3540 this->Field = Field;
3541 IsArrayForm = DeleteWasArrayForm;
3542 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3543 for (const auto *CD : RD->ctors()) {
3544 if (hasMatchingNewInCtor(CD))
3545 return NoMismatch;
3546 }
3547 if (HasUndefinedConstructors)
3548 return EndOfTU ? NoMismatch : AnalyzeLater;
3549 if (!NewExprs.empty())
3550 return MemberInitMismatches;
3551 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3552 : NoMismatch;
3553}
3554
3555MismatchingNewDeleteDetector::MismatchResult
3556MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3557 assert(ME != nullptr && "Expected a member expression");
3558 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3559 return analyzeField(F, IsArrayForm);
3560 return NoMismatch;
3561}
3562
3563bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3564 const CXXNewExpr *NE = nullptr;
3565 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3566 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3567 NE->isArray() != IsArrayForm) {
3568 NewExprs.push_back(NE);
3569 }
3570 }
3571 return NewExprs.empty();
3572}
3573
3574static void
3576 const MismatchingNewDeleteDetector &Detector) {
3577 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3578 FixItHint H;
3579 if (!Detector.IsArrayForm)
3580 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3581 else {
3583 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3584 SemaRef.getLangOpts(), true);
3585 if (RSquare.isValid())
3586 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3587 }
3588 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3589 << Detector.IsArrayForm << H;
3590
3591 for (const auto *NE : Detector.NewExprs)
3592 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3593 << Detector.IsArrayForm;
3594}
3595
3596void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3597 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3598 return;
3599 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3600 switch (Detector.analyzeDeleteExpr(DE)) {
3601 case MismatchingNewDeleteDetector::VarInitMismatches:
3602 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3603 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3604 break;
3605 }
3606 case MismatchingNewDeleteDetector::AnalyzeLater: {
3607 DeleteExprs[Detector.Field].push_back(
3608 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3609 break;
3610 }
3611 case MismatchingNewDeleteDetector::NoMismatch:
3612 break;
3613 }
3614}
3615
3616void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3617 bool DeleteWasArrayForm) {
3618 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3619 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3620 case MismatchingNewDeleteDetector::VarInitMismatches:
3621 llvm_unreachable("This analysis should have been done for class members.");
3622 case MismatchingNewDeleteDetector::AnalyzeLater:
3623 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3624 "translation unit.");
3625 case MismatchingNewDeleteDetector::MemberInitMismatches:
3626 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3627 break;
3628 case MismatchingNewDeleteDetector::NoMismatch:
3629 break;
3630 }
3631}
3632
3634Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3635 bool ArrayForm, Expr *ExE) {
3636 // C++ [expr.delete]p1:
3637 // The operand shall have a pointer type, or a class type having a single
3638 // non-explicit conversion function to a pointer type. The result has type
3639 // void.
3640 //
3641 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3642
3643 ExprResult Ex = ExE;
3644 FunctionDecl *OperatorDelete = nullptr;
3645 bool ArrayFormAsWritten = ArrayForm;
3646 bool UsualArrayDeleteWantsSize = false;
3647
3648 if (!Ex.get()->isTypeDependent()) {
3649 // Perform lvalue-to-rvalue cast, if needed.
3650 Ex = DefaultLvalueConversion(Ex.get());
3651 if (Ex.isInvalid())
3652 return ExprError();
3653
3654 QualType Type = Ex.get()->getType();
3655
3656 class DeleteConverter : public ContextualImplicitConverter {
3657 public:
3658 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3659
3660 bool match(QualType ConvType) override {
3661 // FIXME: If we have an operator T* and an operator void*, we must pick
3662 // the operator T*.
3663 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3664 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3665 return true;
3666 return false;
3667 }
3668
3669 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3670 QualType T) override {
3671 return S.Diag(Loc, diag::err_delete_operand) << T;
3672 }
3673
3674 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3675 QualType T) override {
3676 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3677 }
3678
3679 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3680 QualType T,
3681 QualType ConvTy) override {
3682 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3683 }
3684
3685 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3686 QualType ConvTy) override {
3687 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3688 << ConvTy;
3689 }
3690
3691 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3692 QualType T) override {
3693 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3694 }
3695
3696 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3697 QualType ConvTy) override {
3698 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3699 << ConvTy;
3700 }
3701
3702 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3703 QualType T,
3704 QualType ConvTy) override {
3705 llvm_unreachable("conversion functions are permitted");
3706 }
3707 } Converter;
3708
3709 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3710 if (Ex.isInvalid())
3711 return ExprError();
3712 Type = Ex.get()->getType();
3713 if (!Converter.match(Type))
3714 // FIXME: PerformContextualImplicitConversion should return ExprError
3715 // itself in this case.
3716 return ExprError();
3717
3719 QualType PointeeElem = Context.getBaseElementType(Pointee);
3720
3721 if (Pointee.getAddressSpace() != LangAS::Default &&
3722 !getLangOpts().OpenCLCPlusPlus)
3723 return Diag(Ex.get()->getBeginLoc(),
3724 diag::err_address_space_qualified_delete)
3725 << Pointee.getUnqualifiedType()
3727
3728 CXXRecordDecl *PointeeRD = nullptr;
3729 if (Pointee->isVoidType() && !isSFINAEContext()) {
3730 // The C++ standard bans deleting a pointer to a non-object type, which
3731 // effectively bans deletion of "void*". However, most compilers support
3732 // this, so we treat it as a warning unless we're in a SFINAE context.
3733 // But we still prohibit this since C++26.
3734 Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
3735 : diag::ext_delete_void_ptr_operand)
3736 << (LangOpts.CPlusPlus26 ? Pointee : Type)
3737 << Ex.get()->getSourceRange();
3738 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3739 Pointee->isSizelessType()) {
3740 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3741 << Type << Ex.get()->getSourceRange());
3742 } else if (!Pointee->isDependentType()) {
3743 // FIXME: This can result in errors if the definition was imported from a
3744 // module but is hidden.
3745 if (!RequireCompleteType(StartLoc, Pointee,
3746 LangOpts.CPlusPlus26
3747 ? diag::err_delete_incomplete
3748 : diag::warn_delete_incomplete,
3749 Ex.get())) {
3750 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3751 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3752 }
3753 }
3754
3755 if (Pointee->isArrayType() && !ArrayForm) {
3756 Diag(StartLoc, diag::warn_delete_array_type)
3757 << Type << Ex.get()->getSourceRange()
3759 ArrayForm = true;
3760 }
3761
3763 ArrayForm ? OO_Array_Delete : OO_Delete);
3764
3765 if (PointeeRD) {
3766 if (!UseGlobal &&
3767 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3768 OperatorDelete))
3769 return ExprError();
3770
3771 // If we're allocating an array of records, check whether the
3772 // usual operator delete[] has a size_t parameter.
3773 if (ArrayForm) {
3774 // If the user specifically asked to use the global allocator,
3775 // we'll need to do the lookup into the class.
3776 if (UseGlobal)
3777 UsualArrayDeleteWantsSize =
3778 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3779
3780 // Otherwise, the usual operator delete[] should be the
3781 // function we just found.
3782 else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete))
3783 UsualArrayDeleteWantsSize =
3784 UsualDeallocFnInfo(*this,
3785 DeclAccessPair::make(OperatorDelete, AS_public))
3786 .HasSizeT;
3787 }
3788
3789 if (!PointeeRD->hasIrrelevantDestructor())
3790 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3791 MarkFunctionReferenced(StartLoc,
3792 const_cast<CXXDestructorDecl*>(Dtor));
3793 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3794 return ExprError();
3795 }
3796
3797 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3798 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3799 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3800 SourceLocation());
3801 }
3802
3803 if (!OperatorDelete) {
3804 if (getLangOpts().OpenCLCPlusPlus) {
3805 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3806 return ExprError();
3807 }
3808
3809 bool IsComplete = isCompleteType(StartLoc, Pointee);
3810 bool CanProvideSize =
3811 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3812 Pointee.isDestructedType());
3813 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3814
3815 // Look for a global declaration.
3816 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3817 Overaligned, DeleteName);
3818 }
3819
3820 if (OperatorDelete->isInvalidDecl())
3821 return ExprError();
3822
3823 MarkFunctionReferenced(StartLoc, OperatorDelete);
3824
3825 // Check access and ambiguity of destructor if we're going to call it.
3826 // Note that this is required even for a virtual delete.
3827 bool IsVirtualDelete = false;
3828 if (PointeeRD) {
3829 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3830 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3831 PDiag(diag::err_access_dtor) << PointeeElem);
3832 IsVirtualDelete = Dtor->isVirtual();
3833 }
3834 }
3835
3836 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3837
3838 // Convert the operand to the type of the first parameter of operator
3839 // delete. This is only necessary if we selected a destroying operator
3840 // delete that we are going to call (non-virtually); converting to void*
3841 // is trivial and left to AST consumers to handle.
3842 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3843 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3844 Qualifiers Qs = Pointee.getQualifiers();
3845 if (Qs.hasCVRQualifiers()) {
3846 // Qualifiers are irrelevant to this conversion; we're only looking
3847 // for access and ambiguity.
3851 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3852 }
3853 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3854 if (Ex.isInvalid())
3855 return ExprError();
3856 }
3857 }
3858
3860 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3861 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3862 AnalyzeDeleteExprMismatch(Result);
3863 return Result;
3864}
3865
3867 bool IsDelete,
3868 FunctionDecl *&Operator) {
3869
3871 IsDelete ? OO_Delete : OO_New);
3872
3873 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3875 assert(!R.empty() && "implicitly declared allocation functions not found");
3876 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3877
3878 // We do our own custom access checks below.
3880
3881 SmallVector<Expr *, 8> Args(TheCall->arguments());
3882 OverloadCandidateSet Candidates(R.getNameLoc(),
3884 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3885 FnOvl != FnOvlEnd; ++FnOvl) {
3886 // Even member operator new/delete are implicitly treated as
3887 // static, so don't use AddMemberCandidate.
3888 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3889
3890 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3891 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3892 /*ExplicitTemplateArgs=*/nullptr, Args,
3893 Candidates,
3894 /*SuppressUserConversions=*/false);
3895 continue;
3896 }
3897
3898 FunctionDecl *Fn = cast<FunctionDecl>(D);
3899 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3900 /*SuppressUserConversions=*/false);
3901 }
3902
3903 SourceRange Range = TheCall->getSourceRange();
3904
3905 // Do the resolution.
3907 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3908 case OR_Success: {
3909 // Got one!
3910 FunctionDecl *FnDecl = Best->Function;
3911 assert(R.getNamingClass() == nullptr &&
3912 "class members should not be considered");
3913
3915 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3916 << (IsDelete ? 1 : 0) << Range;
3917 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3918 << R.getLookupName() << FnDecl->getSourceRange();
3919 return true;
3920 }
3921
3922 Operator = FnDecl;
3923 return false;
3924 }
3925
3927 Candidates.NoteCandidates(
3929 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3930 << R.getLookupName() << Range),
3931 S, OCD_AllCandidates, Args);
3932 return true;
3933
3934 case OR_Ambiguous:
3935 Candidates.NoteCandidates(
3937 S.PDiag(diag::err_ovl_ambiguous_call)
3938 << R.getLookupName() << Range),
3939 S, OCD_AmbiguousCandidates, Args);
3940 return true;
3941
3942 case OR_Deleted:
3944 Candidates, Best->Function, Args);
3945 return true;
3946 }
3947 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3948}
3949
3950ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3951 bool IsDelete) {
3952 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3953 if (!getLangOpts().CPlusPlus) {
3954 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3955 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3956 << "C++";
3957 return ExprError();
3958 }
3959 // CodeGen assumes it can find the global new and delete to call,
3960 // so ensure that they are declared.
3962
3963 FunctionDecl *OperatorNewOrDelete = nullptr;
3964 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3965 OperatorNewOrDelete))
3966 return ExprError();
3967 assert(OperatorNewOrDelete && "should be found");
3968
3969 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3970 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3971
3972 TheCall->setType(OperatorNewOrDelete->getReturnType());
3973 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3974 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3975 InitializedEntity Entity =
3978 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3979 if (Arg.isInvalid())
3980 return ExprError();
3981 TheCall->setArg(i, Arg.get());
3982 }
3983 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3984 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3985 "Callee expected to be implicit cast to a builtin function pointer");
3986 Callee->setType(OperatorNewOrDelete->getType());
3987
3988 return TheCallResult;
3989}
3990
3992 bool IsDelete, bool CallCanBeVirtual,
3993 bool WarnOnNonAbstractTypes,
3994 SourceLocation DtorLoc) {
3995 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3996 return;
3997
3998 // C++ [expr.delete]p3:
3999 // In the first alternative (delete object), if the static type of the
4000 // object to be deleted is different from its dynamic type, the static
4001 // type shall be a base class of the dynamic type of the object to be
4002 // deleted and the static type shall have a virtual destructor or the
4003 // behavior is undefined.
4004 //
4005 const CXXRecordDecl *PointeeRD = dtor->getParent();
4006 // Note: a final class cannot be derived from, no issue there
4007 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
4008 return;
4009
4010 // If the superclass is in a system header, there's nothing that can be done.
4011 // The `delete` (where we emit the warning) can be in a system header,
4012 // what matters for this warning is where the deleted type is defined.
4013 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4014 return;
4015
4016 QualType ClassType = dtor->getFunctionObjectParameterType();
4017 if (PointeeRD->isAbstract()) {
4018 // If the class is abstract, we warn by default, because we're
4019 // sure the code has undefined behavior.
4020 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4021 << ClassType;
4022 } else if (WarnOnNonAbstractTypes) {
4023 // Otherwise, if this is not an array delete, it's a bit suspect,
4024 // but not necessarily wrong.
4025 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4026 << ClassType;
4027 }
4028 if (!IsDelete) {
4029 std::string TypeStr;
4030 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4031 Diag(DtorLoc, diag::note_delete_non_virtual)
4032 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4033 }
4034}
4035
4037 SourceLocation StmtLoc,
4038 ConditionKind CK) {
4039 ExprResult E =
4040 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4041 if (E.isInvalid())
4042 return ConditionError();
4043 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
4045}
4046
4048 SourceLocation StmtLoc,
4049 ConditionKind CK) {
4050 if (ConditionVar->isInvalidDecl())
4051 return ExprError();
4052
4053 QualType T = ConditionVar->getType();
4054
4055 // C++ [stmt.select]p2:
4056 // The declarator shall not specify a function or an array.
4057 if (T->isFunctionType())
4058 return ExprError(Diag(ConditionVar->getLocation(),
4059 diag::err_invalid_use_of_function_type)
4060 << ConditionVar->getSourceRange());
4061 else if (T->isArrayType())
4062 return ExprError(Diag(ConditionVar->getLocation(),
4063 diag::err_invalid_use_of_array_type)
4064 << ConditionVar->getSourceRange());
4065
4067 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4068 ConditionVar->getLocation());
4069
4070 switch (CK) {
4072 return CheckBooleanCondition(StmtLoc, Condition.get());
4073
4075 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4076
4078 return CheckSwitchCondition(StmtLoc, Condition.get());
4079 }
4080
4081 llvm_unreachable("unexpected condition kind");
4082}
4083
4084ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4085 // C++11 6.4p4:
4086 // The value of a condition that is an initialized declaration in a statement
4087 // other than a switch statement is the value of the declared variable
4088 // implicitly converted to type bool. If that conversion is ill-formed, the
4089 // program is ill-formed.
4090 // The value of a condition that is an expression is the value of the
4091 // expression, implicitly converted to bool.
4092 //
4093 // C++23 8.5.2p2
4094 // If the if statement is of the form if constexpr, the value of the condition
4095 // is contextually converted to bool and the converted expression shall be
4096 // a constant expression.
4097 //
4098
4100 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4101 return E;
4102
4103 // FIXME: Return this value to the caller so they don't need to recompute it.
4104 llvm::APSInt Cond;
4106 E.get(), &Cond,
4107 diag::err_constexpr_if_condition_expression_is_not_constant);
4108 return E;
4109}
4110
4111bool
4113 // Look inside the implicit cast, if it exists.
4114 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4115 From = Cast->getSubExpr();
4116
4117 // A string literal (2.13.4) that is not a wide string literal can
4118 // be converted to an rvalue of type "pointer to char"; a wide
4119 // string literal can be converted to an rvalue of type "pointer
4120 // to wchar_t" (C++ 4.2p2).
4121 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4122 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4123 if (const BuiltinType *ToPointeeType
4124 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4125 // This conversion is considered only when there is an
4126 // explicit appropriate pointer target type (C++ 4.2p2).
4127 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4128 switch (StrLit->getKind()) {
4132 // We don't allow UTF literals to be implicitly converted
4133 break;
4135 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4136 ToPointeeType->getKind() == BuiltinType::Char_S);
4139 QualType(ToPointeeType, 0));
4141 assert(false && "Unevaluated string literal in expression");
4142 break;
4143 }
4144 }
4145 }
4146
4147 return false;
4148}
4149
4151 SourceLocation CastLoc,
4152 QualType Ty,
4153 CastKind Kind,
4154 CXXMethodDecl *Method,
4155 DeclAccessPair FoundDecl,
4156 bool HadMultipleCandidates,
4157 Expr *From) {
4158 switch (Kind) {
4159 default: llvm_unreachable("Unhandled cast kind!");
4160 case CK_ConstructorConversion: {
4161 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4162 SmallVector<Expr*, 8> ConstructorArgs;
4163
4164 if (S.RequireNonAbstractType(CastLoc, Ty,
4165 diag::err_allocation_of_abstract_type))
4166 return ExprError();
4167
4168 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4169 ConstructorArgs))
4170 return ExprError();
4171
4172 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4174 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4175 return ExprError();
4176
4178 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4179 ConstructorArgs, HadMultipleCandidates,
4180 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4182 if (Result.isInvalid())
4183 return ExprError();
4184
4185 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4186 }
4187
4188 case CK_UserDefinedConversion: {
4189 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4190
4191 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4192 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4193 return ExprError();
4194
4195 // Create an implicit call expr that calls it.
4196 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4197 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4198 HadMultipleCandidates);
4199 if (Result.isInvalid())
4200 return ExprError();
4201 // Record usage of conversion in an implicit cast.
4202 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4203 CK_UserDefinedConversion, Result.get(),
4204 nullptr, Result.get()->getValueKind(),
4206
4207 return S.MaybeBindToTemporary(Result.get());
4208 }
4209 }
4210}
4211
4214 const ImplicitConversionSequence &ICS,
4215 AssignmentAction Action,
4217 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4219 !From->getType()->isRecordType())
4220 return From;
4221
4222 switch (ICS.getKind()) {
4224 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4225 Action, CCK);
4226 if (Res.isInvalid())
4227 return ExprError();
4228 From = Res.get();
4229 break;
4230 }
4231
4233
4236 QualType BeforeToType;
4237 assert(FD && "no conversion function for user-defined conversion seq");
4238 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4239 CastKind = CK_UserDefinedConversion;
4240
4241 // If the user-defined conversion is specified by a conversion function,
4242 // the initial standard conversion sequence converts the source type to
4243 // the implicit object parameter of the conversion function.
4244 BeforeToType = Context.getTagDeclType(Conv->getParent());
4245 } else {
4246 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4247 CastKind = CK_ConstructorConversion;
4248 // Do no conversion if dealing with ... for the first conversion.
4250 // If the user-defined conversion is specified by a constructor, the
4251 // initial standard conversion sequence converts the source type to
4252 // the type required by the argument of the constructor
4253 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4254 }
4255 }
4256 // Watch out for ellipsis conversion.
4258 ExprResult Res =
4259 PerformImplicitConversion(From, BeforeToType,
4261 CCK);
4262 if (Res.isInvalid())
4263 return ExprError();
4264 From = Res.get();
4265 }
4266
4268 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4269 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4271
4272 if (CastArg.isInvalid())
4273 return ExprError();
4274
4275 From = CastArg.get();
4276
4277 // C++ [over.match.oper]p7:
4278 // [...] the second standard conversion sequence of a user-defined
4279 // conversion sequence is not applied.
4281 return From;
4282
4283 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4284 AA_Converting, CCK);
4285 }
4286
4288 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4289 PDiag(diag::err_typecheck_ambiguous_condition)
4290 << From->getSourceRange());
4291 return ExprError();
4292
4295 llvm_unreachable("bad conversion");
4296
4299 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4300 bool Diagnosed = DiagnoseAssignmentResult(
4301 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4302 ToType, From->getType(), From, Action);
4303 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4304 return ExprError();
4305 }
4306
4307 // Everything went well.
4308 return From;
4309}
4310
4311// adjustVectorType - Compute the intermediate cast type casting elements of the
4312// from type to the elements of the to type without resizing the vector.
4314 QualType ToType, QualType *ElTy = nullptr) {
4315 auto *ToVec = ToType->castAs<VectorType>();
4316 QualType ElType = ToVec->getElementType();
4317 if (ElTy)
4318 *ElTy = ElType;
4319 if (!FromTy->isVectorType())
4320 return ElType;
4321 auto *FromVec = FromTy->castAs<VectorType>();
4322 return Context.getExtVectorType(ElType, FromVec->getNumElements());
4323}
4324
4327 const StandardConversionSequence& SCS,
4328 AssignmentAction Action,
4330 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4332
4333 // Overall FIXME: we are recomputing too many types here and doing far too
4334 // much extra work. What this means is that we need to keep track of more
4335 // information that is computed when we try the implicit conversion initially,
4336 // so that we don't need to recompute anything here.
4337 QualType FromType = From->getType();
4338
4339 if (SCS.CopyConstructor) {
4340 // FIXME: When can ToType be a reference type?
4341 assert(!ToType->isReferenceType());
4342 if (SCS.Second == ICK_Derived_To_Base) {
4343 SmallVector<Expr*, 8> ConstructorArgs;
4345 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4346 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4347 return ExprError();
4348 return BuildCXXConstructExpr(
4349 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4350 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4351 /*HadMultipleCandidates*/ false,
4352 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4354 }
4355 return BuildCXXConstructExpr(
4356 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4358 /*HadMultipleCandidates*/ false,
4359 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4361 }
4362
4363 // Resolve overloaded function references.
4364 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4367 true, Found);
4368 if (!Fn)
4369 return ExprError();
4370
4371 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4372 return ExprError();
4373
4375 if (Res.isInvalid())
4376 return ExprError();
4377
4378 // We might get back another placeholder expression if we resolved to a
4379 // builtin.
4380 Res = CheckPlaceholderExpr(Res.get());
4381 if (Res.isInvalid())
4382 return ExprError();
4383
4384 From = Res.get();
4385 FromType = From->getType();
4386 }
4387
4388 // If we're converting to an atomic type, first convert to the corresponding
4389 // non-atomic type.
4390 QualType ToAtomicType;
4391 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4392 ToAtomicType = ToType;
4393 ToType = ToAtomic->getValueType();
4394 }
4395
4396 QualType InitialFromType = FromType;
4397 // Perform the first implicit conversion.
4398 switch (SCS.First) {
4399 case ICK_Identity:
4400 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4401 FromType = FromAtomic->getValueType().getUnqualifiedType();
4402 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4403 From, /*BasePath=*/nullptr, VK_PRValue,
4405 }
4406 break;
4407
4408 case ICK_Lvalue_To_Rvalue: {
4409 assert(From->getObjectKind() != OK_ObjCProperty);
4410 ExprResult FromRes = DefaultLvalueConversion(From);
4411 if (FromRes.isInvalid())
4412 return ExprError();
4413
4414 From = FromRes.get();
4415 FromType = From->getType();
4416 break;
4417 }
4418
4420 FromType = Context.getArrayDecayedType(FromType);
4421 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4422 /*BasePath=*/nullptr, CCK)
4423 .get();
4424 break;
4425
4427 FromType = Context.getArrayParameterType(FromType);
4428 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4429 /*BasePath=*/nullptr, CCK)
4430 .get();
4431 break;
4432
4434 FromType = Context.getPointerType(FromType);
4435 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4436 VK_PRValue, /*BasePath=*/nullptr, CCK)
4437 .get();
4438 break;
4439
4440 default:
4441 llvm_unreachable("Improper first standard conversion");
4442 }
4443
4444 // Perform the second implicit conversion
4445 switch (SCS.Second) {
4446 case ICK_Identity:
4447 // C++ [except.spec]p5:
4448 // [For] assignment to and initialization of pointers to functions,
4449 // pointers to member functions, and references to functions: the
4450 // target entity shall allow at least the exceptions allowed by the
4451 // source value in the assignment or initialization.
4452 switch (Action) {
4453 case AA_Assigning:
4454 case AA_Initializing:
4455 // Note, function argument passing and returning are initialization.
4456 case AA_Passing:
4457 case AA_Returning:
4458 case AA_Sending:
4460 if (CheckExceptionSpecCompatibility(From, ToType))
4461 return ExprError();
4462 break;
4463
4464 case AA_Casting:
4465 case AA_Converting:
4466 // Casts and implicit conversions are not initialization, so are not
4467 // checked for exception specification mismatches.
4468 break;
4469 }
4470 // Nothing else to do.
4471 break;
4472
4475 QualType ElTy = ToType;
4476 QualType StepTy = ToType;
4477 if (ToType->isVectorType())
4478 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4479 if (ElTy->isBooleanType()) {
4480 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4482 "only enums with fixed underlying type can promote to bool");
4483 From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,
4484 /*BasePath=*/nullptr, CCK)
4485 .get();
4486 } else {
4487 From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,
4488 /*BasePath=*/nullptr, CCK)
4489 .get();
4490 }
4491 break;
4492 }
4493
4496 QualType StepTy = ToType;
4497 if (ToType->isVectorType())
4498 StepTy = adjustVectorType(Context, FromType, ToType);
4499 From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,
4500 /*BasePath=*/nullptr, CCK)
4501 .get();
4502 break;
4503 }
4504
4507 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4508 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4509 CastKind CK;
4510 if (FromEl->isRealFloatingType()) {
4511 if (ToEl->isRealFloatingType())
4512 CK = CK_FloatingComplexCast;
4513 else
4514 CK = CK_FloatingComplexToIntegralComplex;
4515 } else if (ToEl->isRealFloatingType()) {
4516 CK = CK_IntegralComplexToFloatingComplex;
4517 } else {
4518 CK = CK_IntegralComplexCast;
4519 }
4520 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4521 CCK)
4522 .get();
4523 break;
4524 }
4525
4526 case ICK_Floating_Integral: {
4527 QualType ElTy = ToType;
4528 QualType StepTy = ToType;
4529 if (ToType->isVectorType())
4530 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4531 if (ElTy->isRealFloatingType())
4532 From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,
4533 /*BasePath=*/nullptr, CCK)
4534 .get();
4535 else
4536 From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,
4537 /*BasePath=*/nullptr, CCK)
4538 .get();
4539 break;
4540 }
4541
4543 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4544 "Attempting implicit fixed point conversion without a fixed "
4545 "point operand");
4546 if (FromType->isFloatingType())
4547 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4548 VK_PRValue,
4549 /*BasePath=*/nullptr, CCK).get();
4550 else if (ToType->isFloatingType())
4551 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4552 VK_PRValue,
4553 /*BasePath=*/nullptr, CCK).get();
4554 else if (FromType->isIntegralType(Context))
4555 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4556 VK_PRValue,
4557 /*BasePath=*/nullptr, CCK).get();
4558 else if (ToType->isIntegralType(Context))
4559 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4560 VK_PRValue,
4561 /*BasePath=*/nullptr, CCK).get();
4562 else if (ToType->isBooleanType())
4563 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4564 VK_PRValue,
4565 /*BasePath=*/nullptr, CCK).get();
4566 else
4567 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4568 VK_PRValue,
4569 /*BasePath=*/nullptr, CCK).get();
4570 break;
4571
4573 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4574 /*BasePath=*/nullptr, CCK).get();
4575 break;
4576
4579 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4580 // Diagnose incompatible Objective-C conversions
4581 if (Action == AA_Initializing || Action == AA_Assigning)
4582 Diag(From->getBeginLoc(),
4583 diag::ext_typecheck_convert_incompatible_pointer)
4584 << ToType << From->getType() << Action << From->getSourceRange()
4585 << 0;
4586 else
4587 Diag(From->getBeginLoc(),
4588 diag::ext_typecheck_convert_incompatible_pointer)
4589 << From->getType() << ToType << Action << From->getSourceRange()
4590 << 0;
4591
4592 if (From->getType()->isObjCObjectPointerType() &&
4593 ToType->isObjCObjectPointerType())
4595 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4596 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
4597 From->getType())) {
4598 if (Action == AA_Initializing)
4599 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4600 else
4601 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4602 << (Action == AA_Casting) << From->getType() << ToType
4603 << From->getSourceRange();
4604 }
4605
4606 // Defer address space conversion to the third conversion.
4607 QualType FromPteeType = From->getType()->getPointeeType();
4608 QualType ToPteeType = ToType->getPointeeType();
4609 QualType NewToType = ToType;
4610 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4611 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4612 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4613 NewToType = Context.getAddrSpaceQualType(NewToType,
4614 FromPteeType.getAddressSpace());
4615 if (ToType->isObjCObjectPointerType())
4616 NewToType = Context.getObjCObjectPointerType(NewToType);
4617 else if (ToType->isBlockPointerType())
4618 NewToType = Context.getBlockPointerType(NewToType);
4619 else
4620 NewToType = Context.getPointerType(NewToType);
4621 }
4622
4623 CastKind Kind;
4624 CXXCastPath BasePath;
4625 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4626 return ExprError();
4627
4628 // Make sure we extend blocks if necessary.
4629 // FIXME: doing this here is really ugly.
4630 if (Kind == CK_BlockPointerToObjCPointerCast) {
4631 ExprResult E = From;
4633 From = E.get();
4634 }
4636 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4637 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4638 .get();
4639 break;
4640 }
4641
4642 case ICK_Pointer_Member: {
4643 CastKind Kind;
4644 CXXCastPath BasePath;
4645 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4646 return ExprError();
4647 if (CheckExceptionSpecCompatibility(From, ToType))
4648 return ExprError();
4649
4650 // We may not have been able to figure out what this member pointer resolved
4651 // to up until this exact point. Attempt to lock-in it's inheritance model.
4653 (void)isCompleteType(From->getExprLoc(), From->getType());
4654 (void)isCompleteType(From->getExprLoc(), ToType);
4655 }
4656
4657 From =
4658 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4659 break;
4660 }
4661
4663 // Perform half-to-boolean conversion via float.
4664 if (From->getType()->isHalfType()) {
4665 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4666 FromType = Context.FloatTy;
4667 }
4668 QualType ElTy = FromType;
4669 QualType StepTy = ToType;
4670 if (FromType->isVectorType()) {
4671 if (getLangOpts().HLSL)
4672 StepTy = adjustVectorType(Context, FromType, ToType);
4673 ElTy = FromType->castAs<VectorType>()->getElementType();
4674 }
4675
4676 From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),
4677 VK_PRValue,
4678 /*BasePath=*/nullptr, CCK)
4679 .get();
4680 break;
4681 }
4682
4683 case ICK_Derived_To_Base: {
4684 CXXCastPath BasePath;
4686 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4687 From->getSourceRange(), &BasePath, CStyle))
4688 return ExprError();
4689
4690 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4691 CK_DerivedToBase, From->getValueKind(),
4692 &BasePath, CCK).get();
4693 break;
4694 }
4695
4697 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4698 /*BasePath=*/nullptr, CCK)
4699 .get();
4700 break;
4701
4704 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4705 /*BasePath=*/nullptr, CCK)
4706 .get();
4707 break;
4708
4709 case ICK_Vector_Splat: {
4710 // Vector splat from any arithmetic type to a vector.
4711 Expr *Elem = prepareVectorSplat(ToType, From).get();
4712 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4713 /*BasePath=*/nullptr, CCK)
4714 .get();
4715 break;
4716 }
4717
4718 case ICK_Complex_Real:
4719 // Case 1. x -> _Complex y
4720 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4721 QualType ElType = ToComplex->getElementType();
4722 bool isFloatingComplex = ElType->isRealFloatingType();
4723
4724 // x -> y
4725 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4726 // do nothing
4727 } else if (From->getType()->isRealFloatingType()) {
4728 From = ImpCastExprToType(From, ElType,
4729 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4730 } else {
4731 assert(From->getType()->isIntegerType());
4732 From = ImpCastExprToType(From, ElType,
4733 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4734 }
4735 // y -> _Complex y
4736 From = ImpCastExprToType(From, ToType,
4737 isFloatingComplex ? CK_FloatingRealToComplex
4738 : CK_IntegralRealToComplex).get();
4739
4740 // Case 2. _Complex x -> y
4741 } else {
4742 auto *FromComplex = From->getType()->castAs<ComplexType>();
4743 QualType ElType = FromComplex->getElementType();
4744 bool isFloatingComplex = ElType->isRealFloatingType();
4745
4746 // _Complex x -> x
4747 From = ImpCastExprToType(From, ElType,
4748 isFloatingComplex ? CK_FloatingComplexToReal
4749 : CK_IntegralComplexToReal,
4750 VK_PRValue, /*BasePath=*/nullptr, CCK)
4751 .get();
4752
4753 // x -> y
4754 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4755 // do nothing
4756 } else if (ToType->isRealFloatingType()) {
4757 From = ImpCastExprToType(From, ToType,
4758 isFloatingComplex ? CK_FloatingCast
4759 : CK_IntegralToFloating,
4760 VK_PRValue, /*BasePath=*/nullptr, CCK)
4761 .get();
4762 } else {
4763 assert(ToType->isIntegerType());
4764 From = ImpCastExprToType(From, ToType,
4765 isFloatingComplex ? CK_FloatingToIntegral
4766 : CK_IntegralCast,
4767 VK_PRValue, /*BasePath=*/nullptr, CCK)
4768 .get();
4769 }
4770 }
4771 break;
4772
4774 LangAS AddrSpaceL =
4776 LangAS AddrSpaceR =
4778 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4779 "Invalid cast");
4780 CastKind Kind =
4781 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4782 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4783 VK_PRValue, /*BasePath=*/nullptr, CCK)
4784 .get();
4785 break;
4786 }
4787
4789 ExprResult FromRes = From;
4792 if (FromRes.isInvalid())
4793 return ExprError();
4794 From = FromRes.get();
4795 assert ((ConvTy == Sema::Compatible) &&
4796 "Improper transparent union conversion");
4797 (void)ConvTy;
4798 break;
4799 }
4800
4803 From = ImpCastExprToType(From, ToType,
4804 CK_ZeroToOCLOpaqueType,
4805 From->getValueKind()).get();
4806 break;
4807
4812 case ICK_Qualification:
4819 llvm_unreachable("Improper second standard conversion");
4820 }
4821
4822 if (SCS.Dimension != ICK_Identity) {
4823 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
4824 // vectors or matrices.
4825
4826 // TODO: Support HLSL matrices.
4827 assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&
4828 "Dimension conversion for matrix types is not implemented yet.");
4829 assert(ToType->isVectorType() &&
4830 "Dimension conversion is only supported for vector types.");
4831 switch (SCS.Dimension) {
4832 case ICK_HLSL_Vector_Splat: {
4833 // Vector splat from any arithmetic type to a vector.
4834 Expr *Elem = prepareVectorSplat(ToType, From).get();
4835 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4836 /*BasePath=*/nullptr, CCK)
4837 .get();
4838 break;
4839 }
4841 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a
4842 // vector to a smaller vector, this can only operate on arguments where
4843 // the source and destination types are ExtVectors.
4844 assert(From->getType()->isExtVectorType() && ToType->isExtVectorType() &&
4845 "HLSL vector truncation should only apply to ExtVectors");
4846 auto *FromVec = From->getType()->castAs<VectorType>();
4847 auto *ToVec = ToType->castAs<VectorType>();
4848 QualType ElType = FromVec->getElementType();
4849 QualType TruncTy =
4850 Context.getExtVectorType(ElType, ToVec->getNumElements());
4851 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
4852 From->getValueKind())
4853 .get();
4854 break;
4855 }
4856 case ICK_Identity:
4857 default:
4858 llvm_unreachable("Improper element standard conversion");
4859 }
4860 }
4861
4862 switch (SCS.Third) {
4863 case ICK_Identity:
4864 // Nothing to do.
4865 break;
4866
4868 // If both sides are functions (or pointers/references to them), there could
4869 // be incompatible exception declarations.
4870 if (CheckExceptionSpecCompatibility(From, ToType))
4871 return ExprError();
4872
4873 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4874 /*BasePath=*/nullptr, CCK)
4875 .get();
4876 break;
4877
4878 case ICK_Qualification: {
4879 ExprValueKind VK = From->getValueKind();
4880 CastKind CK = CK_NoOp;
4881
4882 if (ToType->isReferenceType() &&
4883 ToType->getPointeeType().getAddressSpace() !=
4884 From->getType().getAddressSpace())
4885 CK = CK_AddressSpaceConversion;
4886
4887 if (ToType->isPointerType() &&
4888 ToType->getPointeeType().getAddressSpace() !=
4890 CK = CK_AddressSpaceConversion;
4891
4892 if (!isCast(CCK) &&
4893 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4895 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4896 << InitialFromType << ToType;
4897 }
4898
4899 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4900 /*BasePath=*/nullptr, CCK)
4901 .get();
4902
4904 !getLangOpts().WritableStrings) {
4905 Diag(From->getBeginLoc(),
4907 ? diag::ext_deprecated_string_literal_conversion
4908 : diag::warn_deprecated_string_literal_conversion)
4909 << ToType.getNonReferenceType();
4910 }
4911
4912 break;
4913 }
4914
4915 default:
4916 llvm_unreachable("Improper third standard conversion");
4917 }
4918
4919 // If this conversion sequence involved a scalar -> atomic conversion, perform
4920 // that conversion now.
4921 if (!ToAtomicType.isNull()) {
4922 assert(Context.hasSameType(
4923 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4924 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4925 VK_PRValue, nullptr, CCK)
4926 .get();
4927 }
4928
4929 // Materialize a temporary if we're implicitly converting to a reference
4930 // type. This is not required by the C++ rules but is necessary to maintain
4931 // AST invariants.
4932 if (ToType->isReferenceType() && From->isPRValue()) {
4934 if (Res.isInvalid())
4935 return ExprError();
4936 From = Res.get();
4937 }
4938
4939 // If this conversion sequence succeeded and involved implicitly converting a
4940 // _Nullable type to a _Nonnull one, complain.
4941 if (!isCast(CCK))
4942 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4943 From->getBeginLoc());
4944
4945 return From;
4946}
4947
4948/// Checks that type T is not a VLA.
4949///
4950/// @returns @c true if @p T is VLA and a diagnostic was emitted,
4951/// @c false otherwise.
4953 clang::tok::TokenKind TypeTraitID) {
4954 if (!T->getType()->isVariableArrayType())
4955 return false;
4956
4957 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported)
4958 << 1 << TypeTraitID;
4959 return true;
4960}
4961
4962/// Checks that type T is not an atomic type (_Atomic).
4963///
4964/// @returns @c true if @p T is VLA and a diagnostic was emitted,
4965/// @c false otherwise.
4967 clang::tok::TokenKind TypeTraitID) {
4968 if (!T->getType()->isAtomicType())
4969 return false;
4970
4971 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_atomic_unsupported)
4972 << TypeTraitID;
4973 return true;
4974}
4975
4976/// Check the completeness of a type in a unary type trait.
4977///
4978/// If the particular type trait requires a complete type, tries to complete
4979/// it. If completing the type fails, a diagnostic is emitted and false
4980/// returned. If completing the type succeeds or no completion was required,
4981/// returns true.
4984 QualType ArgTy) {
4985 // C++0x [meta.unary.prop]p3:
4986 // For all of the class templates X declared in this Clause, instantiating
4987 // that template with a template argument that is a class template
4988 // specialization may result in the implicit instantiation of the template
4989 // argument if and only if the semantics of X require that the argument
4990 // must be a complete type.
4991 // We apply this rule to all the type trait expressions used to implement
4992 // these class templates. We also try to follow any GCC documented behavior
4993 // in these expressions to ensure portability of standard libraries.
4994 switch (UTT) {
4995 default: llvm_unreachable("not a UTT");
4996 // is_complete_type somewhat obviously cannot require a complete type.
4997 case UTT_IsCompleteType:
4998 // Fall-through
4999
5000 // These traits are modeled on the type predicates in C++0x
5001 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
5002 // requiring a complete type, as whether or not they return true cannot be
5003 // impacted by the completeness of the type.
5004 case UTT_IsVoid:
5005 case UTT_IsIntegral:
5006 case UTT_IsFloatingPoint:
5007 case UTT_IsArray:
5008 case UTT_IsBoundedArray:
5009 case UTT_IsPointer:
5010 case UTT_IsReferenceable:
5011 case UTT_IsLvalueReference:
5012 case UTT_IsRvalueReference:
5013 case UTT_IsMemberFunctionPointer:
5014 case UTT_IsMemberObjectPointer:
5015 case UTT_IsEnum:
5016 case UTT_IsScopedEnum:
5017 case UTT_IsUnion:
5018 case UTT_IsClass:
5019 case UTT_IsFunction:
5020 case UTT_IsReference:
5021 case UTT_IsArithmetic:
5022 case UTT_IsFundamental:
5023 case UTT_IsObject:
5024 case UTT_IsScalar:
5025 case UTT_IsCompound:
5026 case UTT_IsMemberPointer:
5027 // Fall-through
5028
5029 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
5030 // which requires some of its traits to have the complete type. However,
5031 // the completeness of the type cannot impact these traits' semantics, and
5032 // so they don't require it. This matches the comments on these traits in
5033 // Table 49.
5034 case UTT_IsConst:
5035 case UTT_IsVolatile:
5036 case UTT_IsSigned:
5037 case UTT_IsUnboundedArray:
5038 case UTT_IsUnsigned:
5039
5040 // This type trait always returns false, checking the type is moot.
5041 case UTT_IsInterfaceClass:
5042 return true;
5043
5044 // C++14 [meta.unary.prop]:
5045 // If T is a non-union class type, T shall be a complete type.
5046 case UTT_IsEmpty:
5047 case UTT_IsPolymorphic:
5048 case UTT_IsAbstract:
5049 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
5050 if (!RD->isUnion())
5051 return !S.RequireCompleteType(
5052 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5053 return true;
5054
5055 // C++14 [meta.unary.prop]:
5056 // If T is a class type, T shall be a complete type.
5057 case UTT_IsFinal:
5058 case UTT_IsSealed:
5059 if (ArgTy->getAsCXXRecordDecl())
5060 return !S.RequireCompleteType(
5061 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5062 return true;
5063
5064 // LWG3823: T shall be an array type, a complete type, or cv void.
5065 case UTT_IsAggregate:
5066 case UTT_IsImplicitLifetime:
5067 if (ArgTy->isArrayType() || ArgTy->isVoidType())
5068 return true;
5069
5070 return !S.RequireCompleteType(
5071 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5072
5073 // C++1z [meta.unary.prop]:
5074 // remove_all_extents_t<T> shall be a complete type or cv void.
5075 case UTT_IsTrivial:
5076 case UTT_IsTriviallyCopyable:
5077 case UTT_IsStandardLayout:
5078 case UTT_IsPOD:
5079 case UTT_IsLiteral:
5080 case UTT_IsBitwiseCloneable:
5081 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
5082 // impose the same constraints.
5083 case UTT_IsTriviallyRelocatable:
5084 case UTT_IsTriviallyEqualityComparable:
5085 case UTT_CanPassInRegs:
5086 // Per the GCC type traits documentation, T shall be a complete type, cv void,
5087 // or an array of unknown bound. But GCC actually imposes the same constraints
5088 // as above.
5089 case UTT_HasNothrowAssign:
5090 case UTT_HasNothrowMoveAssign:
5091 case UTT_HasNothrowConstructor:
5092 case UTT_HasNothrowCopy:
5093 case UTT_HasTrivialAssign:
5094 case UTT_HasTrivialMoveAssign:
5095 case UTT_HasTrivialDefaultConstructor:
5096 case UTT_HasTrivialMoveConstructor:
5097 case UTT_HasTrivialCopy:
5098 case UTT_HasTrivialDestructor:
5099 case UTT_HasVirtualDestructor:
5100 // has_unique_object_representations<T> when T is an array is defined in terms
5101 // of has_unique_object_representations<remove_all_extents_t<T>>, so the base
5102 // type needs to be complete even if the type is an incomplete array type.
5103 case UTT_HasUniqueObjectRepresentations:
5104 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
5105 [[fallthrough]];
5106
5107 // C++1z [meta.unary.prop]:
5108 // T shall be a complete type, cv void, or an array of unknown bound.
5109 case UTT_IsDestructible:
5110 case UTT_IsNothrowDestructible:
5111 case UTT_IsTriviallyDestructible:
5112 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
5113 return true;
5114
5115 return !S.RequireCompleteType(
5116 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5117 }
5118}
5119
5121 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
5122 bool (CXXRecordDecl::*HasTrivial)() const,
5123 bool (CXXRecordDecl::*HasNonTrivial)() const,
5124 bool (CXXMethodDecl::*IsDesiredOp)() const)
5125{
5126 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5127 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
5128 return true;
5129
5130 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
5131 DeclarationNameInfo NameInfo(Name, KeyLoc);
5133 if (Self.LookupQualifiedName(Res, RD)) {
5134 bool FoundOperator = false;
5135 Res.suppressDiagnostics();
5136 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
5137 Op != OpEnd; ++Op) {
5138 if (isa<FunctionTemplateDecl>(*Op))
5139 continue;
5140
5141 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
5142 if((Operator->*IsDesiredOp)()) {
5143 FoundOperator = true;
5144 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
5145 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5146 if (!CPT || !CPT->isNothrow())
5147 return false;
5148 }
5149 }
5150 return FoundOperator;
5151 }
5152 return false;
5153}
5154
5156 const CXXRecordDecl *Decl,
5157 SourceLocation KeyLoc) {
5158 if (Decl->isUnion())
5159 return false;
5160 if (Decl->isLambda())
5161 return Decl->isCapturelessLambda();
5162
5163 {
5164 EnterExpressionEvaluationContext UnevaluatedContext(
5166 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5168
5169 // const ClassT& obj;
5170 OpaqueValueExpr Operand(
5171 {}, Decl->getTypeForDecl()->getCanonicalTypeUnqualified().withConst(),
5173 UnresolvedSet<16> Functions;
5174 // obj == obj;
5175 S.LookupBinOp(S.TUScope, {}, BinaryOperatorKind::BO_EQ, Functions);
5176
5177 auto Result = S.CreateOverloadedBinOp(KeyLoc, BinaryOperatorKind::BO_EQ,
5178 Functions, &Operand, &Operand);
5179 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5180 return false;
5181
5182 const auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(Result.get());
5183 if (!CallExpr)
5184 return false;
5185 const auto *Callee = CallExpr->getDirectCallee();
5186 auto ParamT = Callee->getParamDecl(0)->getType();
5187 if (!Callee->isDefaulted())
5188 return false;
5189 if (!ParamT->isReferenceType() && !Decl->isTriviallyCopyable())
5190 return false;
5191 if (ParamT.getNonReferenceType()->getUnqualifiedDesugaredType() !=
5192 Decl->getTypeForDecl())
5193 return false;
5194 }
5195
5196 return llvm::all_of(Decl->bases(),
5197 [&](const CXXBaseSpecifier &BS) {
5198 if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
5199 return HasNonDeletedDefaultedEqualityComparison(
5200 S, RD, KeyLoc);
5201 return true;
5202 }) &&
5203 llvm::all_of(Decl->fields(), [&](const FieldDecl *FD) {
5204 auto Type = FD->getType();
5205 if (Type->isArrayType())
5206 Type = Type->getBaseElementTypeUnsafe()
5207 ->getCanonicalTypeUnqualified();
5208
5209 if (Type->isReferenceType() || Type->isEnumeralType())
5210 return false;
5211 if (const auto *RD = Type->getAsCXXRecordDecl())
5212 return HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc);
5213 return true;
5214 });
5215}
5216
5218 QualType CanonicalType = Type.getCanonicalType();
5219 if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
5220 CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
5221 return false;
5222
5223 if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
5224 if (!HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc))
5225 return false;
5226 }
5227
5229 CanonicalType, /*CheckIfTriviallyCopyable=*/false);
5230}
5231
5233 SourceLocation KeyLoc,
5234 TypeSourceInfo *TInfo) {
5235 QualType T = TInfo->getType();
5236 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5237
5238 ASTContext &C = Self.Context;
5239 switch(UTT) {
5240 default: llvm_unreachable("not a UTT");
5241 // Type trait expressions corresponding to the primary type category
5242 // predicates in C++0x [meta.unary.cat].
5243 case UTT_IsVoid:
5244 return T->isVoidType();
5245 case UTT_IsIntegral:
5246 return T->isIntegralType(C);
5247 case UTT_IsFloatingPoint:
5248 return T->isFloatingType();
5249 case UTT_IsArray:
5250 // Zero-sized arrays aren't considered arrays in partial specializations,
5251 // so __is_array shouldn't consider them arrays either.
5252 if (const auto *CAT = C.getAsConstantArrayType(T))
5253 return CAT->getSize() != 0;
5254 return T->isArrayType();
5255 case UTT_IsBoundedArray:
5256 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_bounded_array))
5257 return false;
5258 // Zero-sized arrays aren't considered arrays in partial specializations,
5259 // so __is_bounded_array shouldn't consider them arrays either.
5260 if (const auto *CAT = C.getAsConstantArrayType(T))
5261 return CAT->getSize() != 0;
5262 return T->isArrayType() && !T->isIncompleteArrayType();
5263 case UTT_IsUnboundedArray:
5264 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_unbounded_array))
5265 return false;
5266 return T->isIncompleteArrayType();
5267 case UTT_IsPointer:
5268 return T->isAnyPointerType();
5269 case UTT_IsLvalueReference:
5270 return T->isLValueReferenceType();
5271 case UTT_IsRvalueReference:
5272 return T->isRValueReferenceType();
5273 case UTT_IsMemberFunctionPointer:
5275 case UTT_IsMemberObjectPointer:
5276 return T->isMemberDataPointerType();
5277 case UTT_IsEnum:
5278 return T->isEnumeralType();
5279 case UTT_IsScopedEnum:
5280 return T->isScopedEnumeralType();
5281 case UTT_IsUnion:
5282 return T->isUnionType();
5283 case UTT_IsClass:
5284 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
5285 case UTT_IsFunction:
5286 return T->isFunctionType();
5287
5288 // Type trait expressions which correspond to the convenient composition
5289 // predicates in C++0x [meta.unary.comp].
5290 case UTT_IsReference:
5291 return T->isReferenceType();
5292 case UTT_IsArithmetic:
5293 return T->isArithmeticType() && !T->isEnumeralType();
5294 case UTT_IsFundamental:
5295 return T->isFundamentalType();
5296 case UTT_IsObject:
5297 return T->isObjectType();
5298 case UTT_IsScalar:
5299 // Note: semantic analysis depends on Objective-C lifetime types to be
5300 // considered scalar types. However, such types do not actually behave
5301 // like scalar types at run time (since they may require retain/release
5302 // operations), so we report them as non-scalar.
5303 if (T->isObjCLifetimeType()) {
5304 switch (T.getObjCLifetime()) {
5307 return true;
5308
5312 return false;
5313 }
5314 }
5315
5316 return T->isScalarType();
5317 case UTT_IsCompound:
5318 return T->isCompoundType();
5319 case UTT_IsMemberPointer:
5320 return T->isMemberPointerType();
5321
5322 // Type trait expressions which correspond to the type property predicates
5323 // in C++0x [meta.unary.prop].
5324 case UTT_IsConst:
5325 return T.isConstQualified();
5326 case UTT_IsVolatile:
5327 return T.isVolatileQualified();
5328 case UTT_IsTrivial:
5329 return T.isTrivialType(C);
5330 case UTT_IsTriviallyCopyable:
5331 return T.isTriviallyCopyableType(C);
5332 case UTT_IsStandardLayout:
5333 return T->isStandardLayoutType();
5334 case UTT_IsPOD:
5335 return T.isPODType(C);
5336 case UTT_IsLiteral:
5337 return T->isLiteralType(C);
5338 case UTT_IsEmpty:
5339 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5340 return !RD->isUnion() && RD->isEmpty();
5341 return false;
5342 case UTT_IsPolymorphic:
5343 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5344 return !RD->isUnion() && RD->isPolymorphic();
5345 return false;
5346 case UTT_IsAbstract:
5347 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5348 return !RD->isUnion() && RD->isAbstract();
5349 return false;
5350 case UTT_IsAggregate:
5351 // Report vector extensions and complex types as aggregates because they
5352 // support aggregate initialization. GCC mirrors this behavior for vectors
5353 // but not _Complex.
5354 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5356 // __is_interface_class only returns true when CL is invoked in /CLR mode and
5357 // even then only when it is used with the 'interface struct ...' syntax
5358 // Clang doesn't support /CLR which makes this type trait moot.
5359 case UTT_IsInterfaceClass:
5360 return false;
5361 case UTT_IsFinal:
5362 case UTT_IsSealed:
5363 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5364 return RD->hasAttr<FinalAttr>();
5365 return false;
5366 case UTT_IsSigned:
5367 // Enum types should always return false.
5368 // Floating points should always return true.
5369 return T->isFloatingType() ||
5371 case UTT_IsUnsigned:
5372 // Enum types should always return false.
5373 return T->isUnsignedIntegerType() && !T->isEnumeralType();
5374
5375 // Type trait expressions which query classes regarding their construction,
5376 // destruction, and copying. Rather than being based directly on the
5377 // related type predicates in the standard, they are specified by both
5378 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5379 // specifications.
5380 //
5381 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5382 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5383 //
5384 // Note that these builtins do not behave as documented in g++: if a class
5385 // has both a trivial and a non-trivial special member of a particular kind,
5386 // they return false! For now, we emulate this behavior.
5387 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5388 // does not correctly compute triviality in the presence of multiple special
5389 // members of the same kind. Revisit this once the g++ bug is fixed.
5390 case UTT_HasTrivialDefaultConstructor:
5391 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5392 // If __is_pod (type) is true then the trait is true, else if type is
5393 // a cv class or union type (or array thereof) with a trivial default
5394 // constructor ([class.ctor]) then the trait is true, else it is false.
5395 if (T.isPODType(C))
5396 return true;
5397 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5398 return RD->hasTrivialDefaultConstructor() &&
5400 return false;
5401 case UTT_HasTrivialMoveConstructor:
5402 // This trait is implemented by MSVC 2012 and needed to parse the
5403 // standard library headers. Specifically this is used as the logic
5404 // behind std::is_trivially_move_constructible (20.9.4.3).
5405 if (T.isPODType(C))
5406 return true;
5407 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5409 return false;
5410 case UTT_HasTrivialCopy:
5411 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5412 // If __is_pod (type) is true or type is a reference type then
5413 // the trait is true, else if type is a cv class or union type
5414 // with a trivial copy constructor ([class.copy]) then the trait
5415 // is true, else it is false.
5416 if (T.isPODType(C) || T->isReferenceType())
5417 return true;
5418 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5419 return RD->hasTrivialCopyConstructor() &&
5421 return false;
5422 case UTT_HasTrivialMoveAssign:
5423 // This trait is implemented by MSVC 2012 and needed to parse the
5424 // standard library headers. Specifically it is used as the logic
5425 // behind std::is_trivially_move_assignable (20.9.4.3)
5426 if (T.isPODType(C))
5427 return true;
5428 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5430 return false;
5431 case UTT_HasTrivialAssign:
5432 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5433 // If type is const qualified or is a reference type then the
5434 // trait is false. Otherwise if __is_pod (type) is true then the
5435 // trait is true, else if type is a cv class or union type with
5436 // a trivial copy assignment ([class.copy]) then the trait is
5437 // true, else it is false.
5438 // Note: the const and reference restrictions are interesting,
5439 // given that const and reference members don't prevent a class
5440 // from having a trivial copy assignment operator (but do cause
5441 // errors if the copy assignment operator is actually used, q.v.
5442 // [class.copy]p12).
5443
5444 if (T.isConstQualified())
5445 return false;
5446 if (T.isPODType(C))
5447 return true;
5448 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5449 return RD->hasTrivialCopyAssignment() &&
5451 return false;
5452 case UTT_IsDestructible:
5453 case UTT_IsTriviallyDestructible:
5454 case UTT_IsNothrowDestructible:
5455 // C++14 [meta.unary.prop]:
5456 // For reference types, is_destructible<T>::value is true.
5457 if (T->isReferenceType())
5458 return true;
5459
5460 // Objective-C++ ARC: autorelease types don't require destruction.
5461 if (T->isObjCLifetimeType() &&
5462 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5463 return true;
5464
5465 // C++14 [meta.unary.prop]:
5466 // For incomplete types and function types, is_destructible<T>::value is
5467 // false.
5468 if (T->isIncompleteType() || T->isFunctionType())
5469 return false;
5470
5471 // A type that requires destruction (via a non-trivial destructor or ARC
5472 // lifetime semantics) is not trivially-destructible.
5473 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5474 return false;
5475
5476 // C++14 [meta.unary.prop]:
5477 // For object types and given U equal to remove_all_extents_t<T>, if the
5478 // expression std::declval<U&>().~U() is well-formed when treated as an
5479 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
5480 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5481 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5482 if (!Destructor)
5483 return false;
5484 // C++14 [dcl.fct.def.delete]p2:
5485 // A program that refers to a deleted function implicitly or
5486 // explicitly, other than to declare it, is ill-formed.
5487 if (Destructor->isDeleted())
5488 return false;
5489 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5490 return false;
5491 if (UTT == UTT_IsNothrowDestructible) {
5492 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5493 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5494 if (!CPT || !CPT->isNothrow())
5495 return false;
5496 }
5497 }
5498 return true;
5499
5500 case UTT_HasTrivialDestructor:
5501 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5502 // If __is_pod (type) is true or type is a reference type
5503 // then the trait is true, else if type is a cv class or union
5504 // type (or array thereof) with a trivial destructor
5505 // ([class.dtor]) then the trait is true, else it is
5506 // false.
5507 if (T.isPODType(C) || T->isReferenceType())
5508 return true;
5509
5510 // Objective-C++ ARC: autorelease types don't require destruction.
5511 if (T->isObjCLifetimeType() &&
5512 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5513 return true;
5514
5515 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5516 return RD->hasTrivialDestructor();
5517 return false;
5518 // TODO: Propagate nothrowness for implicitly declared special members.
5519 case UTT_HasNothrowAssign:
5520 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5521 // If type is const qualified or is a reference type then the
5522 // trait is false. Otherwise if __has_trivial_assign (type)
5523 // is true then the trait is true, else if type is a cv class
5524 // or union type with copy assignment operators that are known
5525 // not to throw an exception then the trait is true, else it is
5526 // false.
5527 if (C.getBaseElementType(T).isConstQualified())
5528 return false;
5529 if (T->isReferenceType())
5530 return false;
5531 if (T.isPODType(C) || T->isObjCLifetimeType())
5532 return true;
5533
5534 if (const RecordType *RT = T->getAs<RecordType>())
5535 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5539 return false;
5540 case UTT_HasNothrowMoveAssign:
5541 // This trait is implemented by MSVC 2012 and needed to parse the
5542 // standard library headers. Specifically this is used as the logic
5543 // behind std::is_nothrow_move_assignable (20.9.4.3).
5544 if (T.isPODType(C))
5545 return true;
5546
5547 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5548 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5552 return false;
5553 case UTT_HasNothrowCopy:
5554 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5555 // If __has_trivial_copy (type) is true then the trait is true, else
5556 // if type is a cv class or union type with copy constructors that are
5557 // known not to throw an exception then the trait is true, else it is
5558 // false.
5559 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5560 return true;
5561 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5562 if (RD->hasTrivialCopyConstructor() &&
5564 return true;
5565
5566 bool FoundConstructor = false;
5567 unsigned FoundTQs;
5568 for (const auto *ND : Self.LookupConstructors(RD)) {
5569 // A template constructor is never a copy constructor.
5570 // FIXME: However, it may actually be selected at the actual overload
5571 // resolution point.
5572 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5573 continue;
5574 // UsingDecl itself is not a constructor
5575 if (isa<UsingDecl>(ND))
5576 continue;
5577 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5578 if (Constructor->isCopyConstructor(FoundTQs)) {
5579 FoundConstructor = true;
5580 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5581 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5582 if (!CPT)
5583 return false;
5584 // TODO: check whether evaluating default arguments can throw.
5585 // For now, we'll be conservative and assume that they can throw.
5586 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5587 return false;
5588 }
5589 }
5590
5591 return FoundConstructor;
5592 }
5593 return false;
5594 case UTT_HasNothrowConstructor:
5595 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5596 // If __has_trivial_constructor (type) is true then the trait is
5597 // true, else if type is a cv class or union type (or array
5598 // thereof) with a default constructor that is known not to
5599 // throw an exception then the trait is true, else it is false.
5600 if (T.isPODType(C) || T->isObjCLifetimeType())
5601 return true;
5602 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5603 if (RD->hasTrivialDefaultConstructor() &&
5605 return true;
5606
5607 bool FoundConstructor = false;
5608 for (const auto *ND : Self.LookupConstructors(RD)) {
5609 // FIXME: In C++0x, a constructor template can be a default constructor.
5610 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5611 continue;
5612 // UsingDecl itself is not a constructor
5613 if (isa<UsingDecl>(ND))
5614 continue;
5615 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5616 if (Constructor->isDefaultConstructor()) {
5617 FoundConstructor = true;
5618 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5619 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5620 if (!CPT)
5621 return false;
5622 // FIXME: check whether evaluating default arguments can throw.
5623 // For now, we'll be conservative and assume that they can throw.
5624 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5625 return false;
5626 }
5627 }
5628 return FoundConstructor;
5629 }
5630 return false;
5631 case UTT_HasVirtualDestructor:
5632 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5633 // If type is a class type with a virtual destructor ([class.dtor])
5634 // then the trait is true, else it is false.
5635 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5636 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5637 return Destructor->isVirtual();
5638 return false;
5639
5640 // These type trait expressions are modeled on the specifications for the
5641 // Embarcadero C++0x type trait functions:
5642 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5643 case UTT_IsCompleteType:
5644 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5645 // Returns True if and only if T is a complete type at the point of the
5646 // function call.
5647 return !T->isIncompleteType();
5648 case UTT_HasUniqueObjectRepresentations:
5649 return C.hasUniqueObjectRepresentations(T);
5650 case UTT_IsTriviallyRelocatable:
5651 return T.isTriviallyRelocatableType(C);
5652 case UTT_IsBitwiseCloneable:
5653 return T.isBitwiseCloneableType(C);
5654 case UTT_IsReferenceable:
5655 return T.isReferenceable();
5656 case UTT_CanPassInRegs:
5657 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())
5658 return RD->canPassInRegisters();
5659 Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;
5660 return false;
5661 case UTT_IsTriviallyEqualityComparable:
5662 return isTriviallyEqualityComparableType(Self, T, KeyLoc);
5663 case UTT_IsImplicitLifetime: {
5665 tok::kw___builtin_is_implicit_lifetime);
5667 tok::kw___builtin_is_implicit_lifetime);
5668
5669 // [basic.types.general] p9
5670 // Scalar types, implicit-lifetime class types ([class.prop]),
5671 // array types, and cv-qualified versions of these types
5672 // are collectively called implicit-lifetime types.
5674 if (UnqualT->isScalarType())
5675 return true;
5676 if (UnqualT->isArrayType() || UnqualT->isVectorType())
5677 return true;
5678 const CXXRecordDecl *RD = UnqualT->getAsCXXRecordDecl();
5679 if (!RD)
5680 return false;
5681
5682 // [class.prop] p9
5683 // A class S is an implicit-lifetime class if
5684 // - it is an aggregate whose destructor is not user-provided or
5685 // - it has at least one trivial eligible constructor and a trivial,
5686 // non-deleted destructor.
5687 const CXXDestructorDecl *Dtor = RD->getDestructor();
5688 if (UnqualT->isAggregateType())
5689 if (Dtor && !Dtor->isUserProvided())
5690 return true;
5691 if (RD->hasTrivialDestructor() && (!Dtor || !Dtor->isDeleted()))
5692 if (RD->hasTrivialDefaultConstructor() ||
5694 return true;
5695 return false;
5696 }
5697 }
5698}
5699
5700static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,
5701 const TypeSourceInfo *Rhs, SourceLocation KeyLoc);
5702
5704 Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs,
5705 SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator) {
5706
5707 QualType LhsT = Lhs->getType();
5708 QualType RhsT = Rhs->getType();
5709
5710 // C++0x [meta.rel]p4:
5711 // Given the following function prototype:
5712 //
5713 // template <class T>
5714 // typename add_rvalue_reference<T>::type create();
5715 //
5716 // the predicate condition for a template specialization
5717 // is_convertible<From, To> shall be satisfied if and only if
5718 // the return expression in the following code would be
5719 // well-formed, including any implicit conversions to the return
5720 // type of the function:
5721 //
5722 // To test() {
5723 // return create<From>();
5724 // }
5725 //
5726 // Access checking is performed as if in a context unrelated to To and
5727 // From. Only the validity of the immediate context of the expression
5728 // of the return-statement (including conversions to the return type)
5729 // is considered.
5730 //
5731 // We model the initialization as a copy-initialization of a temporary
5732 // of the appropriate type, which for this expression is identical to the
5733 // return statement (since NRVO doesn't apply).
5734
5735 // Functions aren't allowed to return function or array types.
5736 if (RhsT->isFunctionType() || RhsT->isArrayType())
5737 return ExprError();
5738
5739 // A function definition requires a complete, non-abstract return type.
5740 if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) ||
5741 Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT))
5742 return ExprError();
5743
5744 // Compute the result of add_rvalue_reference.
5745 if (LhsT->isObjectType() || LhsT->isFunctionType())
5746 LhsT = Self.Context.getRValueReferenceType(LhsT);
5747
5748 // Build a fake source and destination for initialization.
5750 Expr *From = new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5751 OpaqueValueExpr(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5753 InitializationKind Kind =
5755
5756 // Perform the initialization in an unevaluated context within a SFINAE
5757 // trap at translation unit scope.
5760 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5761 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5762 InitializationSequence Init(Self, To, Kind, From);
5763 if (Init.Failed())
5764 return ExprError();
5765
5766 ExprResult Result = Init.Perform(Self, To, Kind, From);
5767 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5768 return ExprError();
5769
5770 return Result;
5771}
5772
5774 SourceLocation KWLoc,
5776 SourceLocation RParenLoc,
5777 bool IsDependent) {
5778 if (IsDependent)
5779 return false;
5780
5781 if (Kind <= UTT_Last)
5782 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]);
5783
5784 // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary
5785 // alongside the IsConstructible traits to avoid duplication.
5786 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary &&
5787 Kind != BTT_ReferenceConstructsFromTemporary &&
5788 Kind != BTT_ReferenceConvertsFromTemporary)
5789 return EvaluateBinaryTypeTrait(S, Kind, Args[0],
5790 Args[1], RParenLoc);
5791
5792 switch (Kind) {
5793 case clang::BTT_ReferenceBindsToTemporary:
5794 case clang::BTT_ReferenceConstructsFromTemporary:
5795 case clang::BTT_ReferenceConvertsFromTemporary:
5796 case clang::TT_IsConstructible:
5797 case clang::TT_IsNothrowConstructible:
5798 case clang::TT_IsTriviallyConstructible: {
5799 // C++11 [meta.unary.prop]:
5800 // is_trivially_constructible is defined as:
5801 //
5802 // is_constructible<T, Args...>::value is true and the variable
5803 // definition for is_constructible, as defined below, is known to call
5804 // no operation that is not trivial.
5805 //
5806 // The predicate condition for a template specialization
5807 // is_constructible<T, Args...> shall be satisfied if and only if the
5808 // following variable definition would be well-formed for some invented
5809 // variable t:
5810 //
5811 // T t(create<Args>()...);
5812 assert(!Args.empty());
5813
5814 // Precondition: T and all types in the parameter pack Args shall be
5815 // complete types, (possibly cv-qualified) void, or arrays of
5816 // unknown bound.
5817 for (const auto *TSI : Args) {
5818 QualType ArgTy = TSI->getType();
5819 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5820 continue;
5821
5822 if (S.RequireCompleteType(KWLoc, ArgTy,
5823 diag::err_incomplete_type_used_in_type_trait_expr))
5824 return false;
5825 }
5826
5827 // Make sure the first argument is not incomplete nor a function type.
5828 QualType T = Args[0]->getType();
5829 if (T->isIncompleteType() || T->isFunctionType())
5830 return false;
5831
5832 // Make sure the first argument is not an abstract type.
5834 if (RD && RD->isAbstract())
5835 return false;
5836
5837 llvm::BumpPtrAllocator OpaqueExprAllocator;
5838 SmallVector<Expr *, 2> ArgExprs;
5839 ArgExprs.reserve(Args.size() - 1);
5840 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5841 QualType ArgTy = Args[I]->getType();
5842 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5843 ArgTy = S.Context.getRValueReferenceType(ArgTy);
5844 ArgExprs.push_back(
5845 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5846 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5849 }
5850
5851 // Perform the initialization in an unevaluated context within a SFINAE
5852 // trap at translation unit scope.
5855 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5859 InitializationKind InitKind(
5860 Kind == clang::BTT_ReferenceConvertsFromTemporary
5861 ? InitializationKind::CreateCopy(KWLoc, KWLoc)
5862 : InitializationKind::CreateDirect(KWLoc, KWLoc, RParenLoc));
5863 InitializationSequence Init(S, To, InitKind, ArgExprs);
5864 if (Init.Failed())
5865 return false;
5866
5867 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5868 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5869 return false;
5870
5871 if (Kind == clang::TT_IsConstructible)
5872 return true;
5873
5874 if (Kind == clang::BTT_ReferenceBindsToTemporary ||
5875 Kind == clang::BTT_ReferenceConstructsFromTemporary ||
5876 Kind == clang::BTT_ReferenceConvertsFromTemporary) {
5877 if (!T->isReferenceType())
5878 return false;
5879
5880 if (!Init.isDirectReferenceBinding())
5881 return true;
5882
5883 if (Kind == clang::BTT_ReferenceBindsToTemporary)
5884 return false;
5885
5886 QualType U = Args[1]->getType();
5887 if (U->isReferenceType())
5888 return false;
5889
5891 S.Context.getPointerType(T.getNonReferenceType()));
5893 S.Context.getPointerType(U.getNonReferenceType()));
5894 return !CheckConvertibilityForTypeTraits(S, UPtr, TPtr, RParenLoc,
5895 OpaqueExprAllocator)
5896 .isInvalid();
5897 }
5898
5899 if (Kind == clang::TT_IsNothrowConstructible)
5900 return S.canThrow(Result.get()) == CT_Cannot;
5901
5902 if (Kind == clang::TT_IsTriviallyConstructible) {
5903 // Under Objective-C ARC and Weak, if the destination has non-trivial
5904 // Objective-C lifetime, this is a non-trivial construction.
5905 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5906 return false;
5907
5908 // The initialization succeeded; now make sure there are no non-trivial
5909 // calls.
5910 return !Result.get()->hasNonTrivialCall(S.Context);
5911 }
5912
5913 llvm_unreachable("unhandled type trait");
5914 return false;
5915 }
5916 default: llvm_unreachable("not a TT");
5917 }
5918
5919 return false;
5920}
5921
5922namespace {
5923void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5924 SourceLocation KWLoc) {
5925 TypeTrait Replacement;
5926 switch (Kind) {
5927 case UTT_HasNothrowAssign:
5928 case UTT_HasNothrowMoveAssign:
5929 Replacement = BTT_IsNothrowAssignable;
5930 break;
5931 case UTT_HasNothrowCopy:
5932 case UTT_HasNothrowConstructor:
5933 Replacement = TT_IsNothrowConstructible;
5934 break;
5935 case UTT_HasTrivialAssign:
5936 case UTT_HasTrivialMoveAssign:
5937 Replacement = BTT_IsTriviallyAssignable;
5938 break;
5939 case UTT_HasTrivialCopy:
5940 Replacement = UTT_IsTriviallyCopyable;
5941 break;
5942 case UTT_HasTrivialDefaultConstructor:
5943 case UTT_HasTrivialMoveConstructor:
5944 Replacement = TT_IsTriviallyConstructible;
5945 break;
5946 case UTT_HasTrivialDestructor:
5947 Replacement = UTT_IsTriviallyDestructible;
5948 break;
5949 default:
5950 return;
5951 }
5952 S.Diag(KWLoc, diag::warn_deprecated_builtin)
5953 << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5954}
5955}
5956
5957bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
5958 if (Arity && N != Arity) {
5959 Diag(Loc, diag::err_type_trait_arity)
5960 << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
5961 return false;
5962 }
5963
5964 if (!Arity && N == 0) {
5965 Diag(Loc, diag::err_type_trait_arity)
5966 << 1 << 1 << 1 << (int)N << SourceRange(Loc);
5967 return false;
5968 }
5969 return true;
5970}
5971
5973 Bool,
5974};
5975
5977 return TypeTraitReturnType::Bool;
5978}
5979
5982 SourceLocation RParenLoc) {
5983 if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
5984 return ExprError();
5985
5987 *this, Kind, KWLoc, Args[0]->getType()))
5988 return ExprError();
5989
5990 DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5991
5992 bool Dependent = false;
5993 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5994 if (Args[I]->getType()->isDependentType()) {
5995 Dependent = true;
5996 break;
5997 }
5998 }
5999
6000 switch (GetReturnType(Kind)) {
6001 case TypeTraitReturnType::Bool: {
6002 bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc,
6003 Dependent);
6005 KWLoc, Kind, Args, RParenLoc, Result);
6006 }
6007 }
6008 llvm_unreachable("unhandled type trait return type");
6009}
6010
6013 SourceLocation RParenLoc) {
6015 ConvertedArgs.reserve(Args.size());
6016
6017 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
6018 TypeSourceInfo *TInfo;
6019 QualType T = GetTypeFromParser(Args[I], &TInfo);
6020 if (!TInfo)
6021 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
6022
6023 ConvertedArgs.push_back(TInfo);
6024 }
6025
6026 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
6027}
6028
6030 const TypeSourceInfo *Rhs, SourceLocation KeyLoc) {
6031 QualType LhsT = Lhs->getType();
6032 QualType RhsT = Rhs->getType();
6033
6034 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
6035 "Cannot evaluate traits of dependent types");
6036
6037 switch(BTT) {
6038 case BTT_IsBaseOf: {
6039 // C++0x [meta.rel]p2
6040 // Base is a base class of Derived without regard to cv-qualifiers or
6041 // Base and Derived are not unions and name the same class type without
6042 // regard to cv-qualifiers.
6043
6044 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
6045 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
6046 if (!rhsRecord || !lhsRecord) {
6047 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
6048 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
6049 if (!LHSObjTy || !RHSObjTy)
6050 return false;
6051
6052 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
6053 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
6054 if (!BaseInterface || !DerivedInterface)
6055 return false;
6056
6057 if (Self.RequireCompleteType(
6058 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6059 diag::err_incomplete_type_used_in_type_trait_expr))
6060 return false;
6061
6062 return BaseInterface->isSuperClassOf(DerivedInterface);
6063 }
6064
6065 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
6066 == (lhsRecord == rhsRecord));
6067
6068 // Unions are never base classes, and never have base classes.
6069 // It doesn't matter if they are complete or not. See PR#41843
6070 if (lhsRecord && lhsRecord->getDecl()->isUnion())
6071 return false;
6072 if (rhsRecord && rhsRecord->getDecl()->isUnion())
6073 return false;
6074
6075 if (lhsRecord == rhsRecord)
6076 return true;
6077
6078 // C++0x [meta.rel]p2:
6079 // If Base and Derived are class types and are different types
6080 // (ignoring possible cv-qualifiers) then Derived shall be a
6081 // complete type.
6082 if (Self.RequireCompleteType(
6083 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6084 diag::err_incomplete_type_used_in_type_trait_expr))
6085 return false;
6086
6087 return cast<CXXRecordDecl>(rhsRecord->getDecl())
6088 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
6089 }
6090 case BTT_IsVirtualBaseOf: {
6091 const RecordType *BaseRecord = LhsT->getAs<RecordType>();
6092 const RecordType *DerivedRecord = RhsT->getAs<RecordType>();
6093
6094 if (!BaseRecord || !DerivedRecord) {
6096 tok::kw___builtin_is_virtual_base_of);
6098 tok::kw___builtin_is_virtual_base_of);
6099 return false;
6100 }
6101
6102 if (BaseRecord->isUnionType() || DerivedRecord->isUnionType())
6103 return false;
6104
6105 if (!BaseRecord->isStructureOrClassType() ||
6106 !DerivedRecord->isStructureOrClassType())
6107 return false;
6108
6109 if (Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6110 diag::err_incomplete_type))
6111 return false;
6112
6113 return cast<CXXRecordDecl>(DerivedRecord->getDecl())
6114 ->isVirtuallyDerivedFrom(cast<CXXRecordDecl>(BaseRecord->getDecl()));
6115 }
6116 case BTT_IsSame:
6117 return Self.Context.hasSameType(LhsT, RhsT);
6118 case BTT_TypeCompatible: {
6119 // GCC ignores cv-qualifiers on arrays for this builtin.
6120 Qualifiers LhsQuals, RhsQuals;
6121 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
6122 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
6123 return Self.Context.typesAreCompatible(Lhs, Rhs);
6124 }
6125 case BTT_IsConvertible:
6126 case BTT_IsConvertibleTo:
6127 case BTT_IsNothrowConvertible: {
6128 if (RhsT->isVoidType())
6129 return LhsT->isVoidType();
6130 llvm::BumpPtrAllocator OpaqueExprAllocator;
6132 OpaqueExprAllocator);
6133 if (Result.isInvalid())
6134 return false;
6135
6136 if (BTT != BTT_IsNothrowConvertible)
6137 return true;
6138
6139 return Self.canThrow(Result.get()) == CT_Cannot;
6140 }
6141
6142 case BTT_IsAssignable:
6143 case BTT_IsNothrowAssignable:
6144 case BTT_IsTriviallyAssignable: {
6145 // C++11 [meta.unary.prop]p3:
6146 // is_trivially_assignable is defined as:
6147 // is_assignable<T, U>::value is true and the assignment, as defined by
6148 // is_assignable, is known to call no operation that is not trivial
6149 //
6150 // is_assignable is defined as:
6151 // The expression declval<T>() = declval<U>() is well-formed when
6152 // treated as an unevaluated operand (Clause 5).
6153 //
6154 // For both, T and U shall be complete types, (possibly cv-qualified)
6155 // void, or arrays of unknown bound.
6156 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
6157 Self.RequireCompleteType(
6158 Lhs->getTypeLoc().getBeginLoc(), LhsT,
6159 diag::err_incomplete_type_used_in_type_trait_expr))
6160 return false;
6161 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
6162 Self.RequireCompleteType(
6163 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6164 diag::err_incomplete_type_used_in_type_trait_expr))
6165 return false;
6166
6167 // cv void is never assignable.
6168 if (LhsT->isVoidType() || RhsT->isVoidType())
6169 return false;
6170
6171 // Build expressions that emulate the effect of declval<T>() and
6172 // declval<U>().
6173 if (LhsT->isObjectType() || LhsT->isFunctionType())
6174 LhsT = Self.Context.getRValueReferenceType(LhsT);
6175 if (RhsT->isObjectType() || RhsT->isFunctionType())
6176 RhsT = Self.Context.getRValueReferenceType(RhsT);
6177 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
6179 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
6181
6182 // Attempt the assignment in an unevaluated context within a SFINAE
6183 // trap at translation unit scope.
6186 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
6187 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
6188 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
6189 &Rhs);
6190 if (Result.isInvalid())
6191 return false;
6192
6193 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
6194 Self.CheckUnusedVolatileAssignment(Result.get());
6195
6196 if (SFINAE.hasErrorOccurred())
6197 return false;
6198
6199 if (BTT == BTT_IsAssignable)
6200 return true;
6201
6202 if (BTT == BTT_IsNothrowAssignable)
6203 return Self.canThrow(Result.get()) == CT_Cannot;
6204
6205 if (BTT == BTT_IsTriviallyAssignable) {
6206 // Under Objective-C ARC and Weak, if the destination has non-trivial
6207 // Objective-C lifetime, this is a non-trivial assignment.
6209 return false;
6210
6211 return !Result.get()->hasNonTrivialCall(Self.Context);
6212 }
6213
6214 llvm_unreachable("unhandled type trait");
6215 return false;
6216 }
6217 case BTT_IsLayoutCompatible: {
6218 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType())
6219 Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,
6220 diag::err_incomplete_type);
6221 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType())
6222 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6223 diag::err_incomplete_type);
6224
6225 DiagnoseVLAInCXXTypeTrait(Self, Lhs, tok::kw___is_layout_compatible);
6226 DiagnoseVLAInCXXTypeTrait(Self, Rhs, tok::kw___is_layout_compatible);
6227
6228 return Self.IsLayoutCompatible(LhsT, RhsT);
6229 }
6230 case BTT_IsPointerInterconvertibleBaseOf: {
6231 if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() &&
6232 !Self.getASTContext().hasSameUnqualifiedType(LhsT, RhsT)) {
6233 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6234 diag::err_incomplete_type);
6235 }
6236
6238 tok::kw___is_pointer_interconvertible_base_of);
6240 tok::kw___is_pointer_interconvertible_base_of);
6241
6242 return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs);
6243 }
6244 case BTT_IsDeducible: {
6245 const auto *TSTToBeDeduced = cast<DeducedTemplateSpecializationType>(LhsT);
6246 sema::TemplateDeductionInfo Info(KeyLoc);
6247 return Self.DeduceTemplateArgumentsFromType(
6248 TSTToBeDeduced->getTemplateName().getAsTemplateDecl(), RhsT,
6250 }
6251 default:
6252 llvm_unreachable("not a BTT");
6253 }
6254 llvm_unreachable("Unknown type trait or not implemented");
6255}
6256
6258 SourceLocation KWLoc,
6259 ParsedType Ty,
6260 Expr* DimExpr,
6261 SourceLocation RParen) {
6262 TypeSourceInfo *TSInfo;
6263 QualType T = GetTypeFromParser(Ty, &TSInfo);
6264 if (!TSInfo)
6266
6267 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
6268}
6269
6271 QualType T, Expr *DimExpr,
6272 SourceLocation KeyLoc) {
6273 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
6274
6275 switch(ATT) {
6276 case ATT_ArrayRank:
6277 if (T->isArrayType()) {
6278 unsigned Dim = 0;
6279 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6280 ++Dim;
6281 T = AT->getElementType();
6282 }
6283 return Dim;
6284 }
6285 return 0;
6286
6287 case ATT_ArrayExtent: {
6288 llvm::APSInt Value;
6289 uint64_t Dim;
6290 if (Self.VerifyIntegerConstantExpression(
6291 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
6292 .isInvalid())
6293 return 0;
6294 if (Value.isSigned() && Value.isNegative()) {
6295 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
6296 << DimExpr->getSourceRange();
6297 return 0;
6298 }
6299 Dim = Value.getLimitedValue();
6300
6301 if (T->isArrayType()) {
6302 unsigned D = 0;
6303 bool Matched = false;
6304 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6305 if (Dim == D) {
6306 Matched = true;
6307 break;
6308 }
6309 ++D;
6310 T = AT->getElementType();
6311 }
6312
6313 if (Matched && T->isArrayType()) {
6314 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
6315 return CAT->getLimitedSize();
6316 }
6317 }
6318 return 0;
6319 }
6320 }
6321 llvm_unreachable("Unknown type trait or not implemented");
6322}
6323
6325 SourceLocation KWLoc,
6326 TypeSourceInfo *TSInfo,
6327 Expr* DimExpr,
6328 SourceLocation RParen) {
6329 QualType T = TSInfo->getType();
6330
6331 // FIXME: This should likely be tracked as an APInt to remove any host
6332 // assumptions about the width of size_t on the target.
6333 uint64_t Value = 0;
6334 if (!T->isDependentType())
6335 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
6336
6337 // While the specification for these traits from the Embarcadero C++
6338 // compiler's documentation says the return type is 'unsigned int', Clang
6339 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
6340 // compiler, there is no difference. On several other platforms this is an
6341 // important distinction.
6342 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
6343 RParen, Context.getSizeType());
6344}
6345
6347 SourceLocation KWLoc,
6348 Expr *Queried,
6349 SourceLocation RParen) {
6350 // If error parsing the expression, ignore.
6351 if (!Queried)
6352 return ExprError();
6353
6354 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
6355
6356 return Result;
6357}
6358
6360 switch (ET) {
6361 case ET_IsLValueExpr: return E->isLValue();
6362 case ET_IsRValueExpr:
6363 return E->isPRValue();
6364 }
6365 llvm_unreachable("Expression trait not covered by switch");
6366}
6367
6369 SourceLocation KWLoc,
6370 Expr *Queried,
6371 SourceLocation RParen) {
6372 if (Queried->isTypeDependent()) {
6373 // Delay type-checking for type-dependent expressions.
6374 } else if (Queried->hasPlaceholderType()) {
6375 ExprResult PE = CheckPlaceholderExpr(Queried);
6376 if (PE.isInvalid()) return ExprError();
6377 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
6378 }
6379
6380 bool Value = EvaluateExpressionTrait(ET, Queried);
6381
6382 return new (Context)
6383 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
6384}
6385
6387 ExprValueKind &VK,
6389 bool isIndirect) {
6390 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
6391 "placeholders should have been weeded out by now");
6392
6393 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
6394 // temporary materialization conversion otherwise.
6395 if (isIndirect)
6396 LHS = DefaultLvalueConversion(LHS.get());
6397 else if (LHS.get()->isPRValue())
6399 if (LHS.isInvalid())
6400 return QualType();
6401
6402 // The RHS always undergoes lvalue conversions.
6403 RHS = DefaultLvalueConversion(RHS.get());
6404 if (RHS.isInvalid()) return QualType();
6405
6406 const char *OpSpelling = isIndirect ? "->*" : ".*";
6407 // C++ 5.5p2
6408 // The binary operator .* [p3: ->*] binds its second operand, which shall
6409 // be of type "pointer to member of T" (where T is a completely-defined
6410 // class type) [...]
6411 QualType RHSType = RHS.get()->getType();
6412 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
6413 if (!MemPtr) {
6414 Diag(Loc, diag::err_bad_memptr_rhs)
6415 << OpSpelling << RHSType << RHS.get()->getSourceRange();
6416 return QualType();
6417 }
6418
6419 QualType Class(MemPtr->getClass(), 0);
6420
6421 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
6422 // member pointer points must be completely-defined. However, there is no
6423 // reason for this semantic distinction, and the rule is not enforced by
6424 // other compilers. Therefore, we do not check this property, as it is
6425 // likely to be considered a defect.
6426
6427 // C++ 5.5p2
6428 // [...] to its first operand, which shall be of class T or of a class of
6429 // which T is an unambiguous and accessible base class. [p3: a pointer to
6430 // such a class]
6431 QualType LHSType = LHS.get()->getType();
6432 if (isIndirect) {
6433 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
6434 LHSType = Ptr->getPointeeType();
6435 else {
6436 Diag(Loc, diag::err_bad_memptr_lhs)
6437 << OpSpelling << 1 << LHSType
6439 return QualType();
6440 }
6441 }
6442
6443 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
6444 // If we want to check the hierarchy, we need a complete type.
6445 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
6446 OpSpelling, (int)isIndirect)) {
6447 return QualType();
6448 }
6449
6450 if (!IsDerivedFrom(Loc, LHSType, Class)) {
6451 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6452 << (int)isIndirect << LHS.get()->getType();
6453 return QualType();
6454 }
6455
6456 CXXCastPath BasePath;
6458 LHSType, Class, Loc,
6459 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6460 &BasePath))
6461 return QualType();
6462
6463 // Cast LHS to type of use.
6464 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6465 if (isIndirect)
6466 UseType = Context.getPointerType(UseType);
6467 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6468 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6469 &BasePath);
6470 }
6471
6472 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6473 // Diagnose use of pointer-to-member type which when used as
6474 // the functional cast in a pointer-to-member expression.
6475 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6476 return QualType();
6477 }
6478
6479 // C++ 5.5p2
6480 // The result is an object or a function of the type specified by the
6481 // second operand.
6482 // The cv qualifiers are the union of those in the pointer and the left side,
6483 // in accordance with 5.5p5 and 5.2.5.
6484 QualType Result = MemPtr->getPointeeType();
6486
6487 // C++0x [expr.mptr.oper]p6:
6488 // In a .* expression whose object expression is an rvalue, the program is
6489 // ill-formed if the second operand is a pointer to member function with
6490 // ref-qualifier &. In a ->* expression or in a .* expression whose object
6491 // expression is an lvalue, the program is ill-formed if the second operand
6492 // is a pointer to member function with ref-qualifier &&.
6493 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6494 switch (Proto->getRefQualifier()) {
6495 case RQ_None:
6496 // Do nothing
6497 break;
6498
6499 case RQ_LValue:
6500 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6501 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6502 // is (exactly) 'const'.
6503 if (Proto->isConst() && !Proto->isVolatile())
6505 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6506 : diag::ext_pointer_to_const_ref_member_on_rvalue);
6507 else
6508 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6509 << RHSType << 1 << LHS.get()->getSourceRange();
6510 }
6511 break;
6512
6513 case RQ_RValue:
6514 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6515 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6516 << RHSType << 0 << LHS.get()->getSourceRange();
6517 break;
6518 }
6519 }
6520
6521 // C++ [expr.mptr.oper]p6:
6522 // The result of a .* expression whose second operand is a pointer
6523 // to a data member is of the same value category as its
6524 // first operand. The result of a .* expression whose second
6525 // operand is a pointer to a member function is a prvalue. The
6526 // result of an ->* expression is an lvalue if its second operand
6527 // is a pointer to data member and a prvalue otherwise.
6528 if (Result->isFunctionType()) {
6529 VK = VK_PRValue;
6530 return Context.BoundMemberTy;
6531 } else if (isIndirect) {
6532 VK = VK_LValue;
6533 } else {
6534 VK = LHS.get()->getValueKind();
6535 }
6536
6537 return Result;
6538}
6539
6540/// Try to convert a type to another according to C++11 5.16p3.
6541///
6542/// This is part of the parameter validation for the ? operator. If either
6543/// value operand is a class type, the two operands are attempted to be
6544/// converted to each other. This function does the conversion in one direction.
6545/// It returns true if the program is ill-formed and has already been diagnosed
6546/// as such.
6547static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6548 SourceLocation QuestionLoc,
6549 bool &HaveConversion,
6550 QualType &ToType) {
6551 HaveConversion = false;
6552 ToType = To->getType();
6553
6554 InitializationKind Kind =
6556 // C++11 5.16p3
6557 // The process for determining whether an operand expression E1 of type T1
6558 // can be converted to match an operand expression E2 of type T2 is defined
6559 // as follows:
6560 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6561 // implicitly converted to type "lvalue reference to T2", subject to the
6562 // constraint that in the conversion the reference must bind directly to
6563 // an lvalue.
6564 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6565 // implicitly converted to the type "rvalue reference to R2", subject to
6566 // the constraint that the reference must bind directly.
6567 if (To->isGLValue()) {
6568 QualType T = Self.Context.getReferenceQualifiedType(To);
6570
6571 InitializationSequence InitSeq(Self, Entity, Kind, From);
6572 if (InitSeq.isDirectReferenceBinding()) {
6573 ToType = T;
6574 HaveConversion = true;
6575 return false;
6576 }
6577
6578 if (InitSeq.isAmbiguous())
6579 return InitSeq.Diagnose(Self, Entity, Kind, From);
6580 }
6581
6582 // -- If E2 is an rvalue, or if the conversion above cannot be done:
6583 // -- if E1 and E2 have class type, and the underlying class types are
6584 // the same or one is a base class of the other:
6585 QualType FTy = From->getType();
6586 QualType TTy = To->getType();
6587 const RecordType *FRec = FTy->getAs<RecordType>();
6588 const RecordType *TRec = TTy->getAs<RecordType>();
6589 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6590 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6591 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6592 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6593 // E1 can be converted to match E2 if the class of T2 is the
6594 // same type as, or a base class of, the class of T1, and
6595 // [cv2 > cv1].
6596 if (FRec == TRec || FDerivedFromT) {
6597 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6599 InitializationSequence InitSeq(Self, Entity, Kind, From);
6600 if (InitSeq) {
6601 HaveConversion = true;
6602 return false;
6603 }
6604
6605 if (InitSeq.isAmbiguous())
6606 return InitSeq.Diagnose(Self, Entity, Kind, From);
6607 }
6608 }
6609
6610 return false;
6611 }
6612
6613 // -- Otherwise: E1 can be converted to match E2 if E1 can be
6614 // implicitly converted to the type that expression E2 would have
6615 // if E2 were converted to an rvalue (or the type it has, if E2 is
6616 // an rvalue).
6617 //
6618 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6619 // to the array-to-pointer or function-to-pointer conversions.
6620 TTy = TTy.getNonLValueExprType(Self.Context);
6621
6623 InitializationSequence InitSeq(Self, Entity, Kind, From);
6624 HaveConversion = !InitSeq.Failed();
6625 ToType = TTy;
6626 if (InitSeq.isAmbiguous())
6627 return InitSeq.Diagnose(Self, Entity, Kind, From);
6628
6629 return false;
6630}
6631
6632/// Try to find a common type for two according to C++0x 5.16p5.
6633///
6634/// This is part of the parameter validation for the ? operator. If either
6635/// value operand is a class type, overload resolution is used to find a
6636/// conversion to a common type.
6638 SourceLocation QuestionLoc) {
6639 Expr *Args[2] = { LHS.get(), RHS.get() };
6640 OverloadCandidateSet CandidateSet(QuestionLoc,
6642 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6643 CandidateSet);
6644
6646 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6647 case OR_Success: {
6648 // We found a match. Perform the conversions on the arguments and move on.
6649 ExprResult LHSRes = Self.PerformImplicitConversion(
6650 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6652 if (LHSRes.isInvalid())
6653 break;
6654 LHS = LHSRes;
6655
6656 ExprResult RHSRes = Self.PerformImplicitConversion(
6657 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6659 if (RHSRes.isInvalid())
6660 break;
6661 RHS = RHSRes;
6662 if (Best->Function)
6663 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6664 return false;
6665 }
6666
6668
6669 // Emit a better diagnostic if one of the expressions is a null pointer
6670 // constant and the other is a pointer type. In this case, the user most
6671 // likely forgot to take the address of the other expression.
6672 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6673 return true;
6674
6675 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6676 << LHS.get()->getType() << RHS.get()->getType()
6677 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6678 return true;
6679
6680 case OR_Ambiguous:
6681 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6682 << LHS.get()->getType() << RHS.get()->getType()
6683 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6684 // FIXME: Print the possible common types by printing the return types of
6685 // the viable candidates.
6686 break;
6687
6688 case OR_Deleted:
6689 llvm_unreachable("Conditional operator has only built-in overloads");
6690 }
6691 return true;
6692}
6693
6694/// Perform an "extended" implicit conversion as returned by
6695/// TryClassUnification.
6698 InitializationKind Kind =
6700 Expr *Arg = E.get();
6701 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6702 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6703 if (Result.isInvalid())
6704 return true;
6705
6706 E = Result;
6707 return false;
6708}
6709
6710// Check the condition operand of ?: to see if it is valid for the GCC
6711// extension.
6713 QualType CondTy) {
6714 if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6715 return false;
6716 const QualType EltTy =
6717 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6718 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6719 return EltTy->isIntegralType(Ctx);
6720}
6721
6723 QualType CondTy) {
6724 if (!CondTy->isSveVLSBuiltinType())
6725 return false;
6726 const QualType EltTy =
6727 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6728 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6729 return EltTy->isIntegralType(Ctx);
6730}
6731
6733 ExprResult &RHS,
6734 SourceLocation QuestionLoc) {
6737
6738 QualType CondType = Cond.get()->getType();
6739 const auto *CondVT = CondType->castAs<VectorType>();
6740 QualType CondElementTy = CondVT->getElementType();
6741 unsigned CondElementCount = CondVT->getNumElements();
6742 QualType LHSType = LHS.get()->getType();
6743 const auto *LHSVT = LHSType->getAs<VectorType>();
6744 QualType RHSType = RHS.get()->getType();
6745 const auto *RHSVT = RHSType->getAs<VectorType>();
6746
6747 QualType ResultType;
6748
6749
6750 if (LHSVT && RHSVT) {
6751 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6752 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6753 << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6754 return {};
6755 }
6756
6757 // If both are vector types, they must be the same type.
6758 if (!Context.hasSameType(LHSType, RHSType)) {
6759 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6760 << LHSType << RHSType;
6761 return {};
6762 }
6763 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6764 } else if (LHSVT || RHSVT) {
6765 ResultType = CheckVectorOperands(
6766 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6767 /*AllowBoolConversions*/ false,
6768 /*AllowBoolOperation*/ true,
6769 /*ReportInvalid*/ true);
6770 if (ResultType.isNull())
6771 return {};
6772 } else {
6773 // Both are scalar.
6774 LHSType = LHSType.getUnqualifiedType();
6775 RHSType = RHSType.getUnqualifiedType();
6776 QualType ResultElementTy =
6777 Context.hasSameType(LHSType, RHSType)
6778 ? Context.getCommonSugaredType(LHSType, RHSType)
6779 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6781
6782 if (ResultElementTy->isEnumeralType()) {
6783 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6784 << ResultElementTy;
6785 return {};
6786 }
6787 if (CondType->isExtVectorType())
6788 ResultType =
6789 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6790 else
6791 ResultType = Context.getVectorType(
6792 ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);
6793
6794 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6795 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6796 }
6797
6798 assert(!ResultType.isNull() && ResultType->isVectorType() &&
6799 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6800 "Result should have been a vector type");
6801 auto *ResultVectorTy = ResultType->castAs<VectorType>();
6802 QualType ResultElementTy = ResultVectorTy->getElementType();
6803 unsigned ResultElementCount = ResultVectorTy->getNumElements();
6804
6805 if (ResultElementCount != CondElementCount) {
6806 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6807 << ResultType;
6808 return {};
6809 }
6810
6811 if (Context.getTypeSize(ResultElementTy) !=
6812 Context.getTypeSize(CondElementTy)) {
6813 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6814 << ResultType;
6815 return {};
6816 }
6817
6818 return ResultType;
6819}
6820
6822 ExprResult &LHS,
6823 ExprResult &RHS,
6824 SourceLocation QuestionLoc) {
6827
6828 QualType CondType = Cond.get()->getType();
6829 const auto *CondBT = CondType->castAs<BuiltinType>();
6830 QualType CondElementTy = CondBT->getSveEltType(Context);
6831 llvm::ElementCount CondElementCount =
6833
6834 QualType LHSType = LHS.get()->getType();
6835 const auto *LHSBT =
6836 LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6837 QualType RHSType = RHS.get()->getType();
6838 const auto *RHSBT =
6839 RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6840
6841 QualType ResultType;
6842
6843 if (LHSBT && RHSBT) {
6844 // If both are sizeless vector types, they must be the same type.
6845 if (!Context.hasSameType(LHSType, RHSType)) {
6846 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6847 << LHSType << RHSType;
6848 return QualType();
6849 }
6850 ResultType = LHSType;
6851 } else if (LHSBT || RHSBT) {
6852 ResultType = CheckSizelessVectorOperands(
6853 LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6854 if (ResultType.isNull())
6855 return QualType();
6856 } else {
6857 // Both are scalar so splat
6858 QualType ResultElementTy;
6859 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6860 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6861
6862 if (Context.hasSameType(LHSType, RHSType))
6863 ResultElementTy = LHSType;
6864 else
6865 ResultElementTy =
6866 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6867
6868 if (ResultElementTy->isEnumeralType()) {
6869 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6870 << ResultElementTy;
6871 return QualType();
6872 }
6873
6874 ResultType = Context.getScalableVectorType(
6875 ResultElementTy, CondElementCount.getKnownMinValue());
6876
6877 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6878 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6879 }
6880
6881 assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&
6882 "Result should have been a vector type");
6883 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6884 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6885 llvm::ElementCount ResultElementCount =
6886 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6887
6888 if (ResultElementCount != CondElementCount) {
6889 Diag(QuestionLoc, diag::err_conditional_vector_size)
6890 << CondType << ResultType;
6891 return QualType();
6892 }
6893
6894 if (Context.getTypeSize(ResultElementTy) !=
6895 Context.getTypeSize(CondElementTy)) {
6896 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6897 << CondType << ResultType;
6898 return QualType();
6899 }
6900
6901 return ResultType;
6902}
6903
6905 ExprResult &RHS, ExprValueKind &VK,
6906 ExprObjectKind &OK,
6907 SourceLocation QuestionLoc) {
6908 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6909 // pointers.
6910
6911 // Assume r-value.
6912 VK = VK_PRValue;
6913 OK = OK_Ordinary;
6914 bool IsVectorConditional =
6916
6917 bool IsSizelessVectorConditional =
6919 Cond.get()->getType());
6920
6921 // C++11 [expr.cond]p1
6922 // The first expression is contextually converted to bool.
6923 if (!Cond.get()->isTypeDependent()) {
6924 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6926 : CheckCXXBooleanCondition(Cond.get());
6927 if (CondRes.isInvalid())
6928 return QualType();
6929 Cond = CondRes;
6930 } else {
6931 // To implement C++, the first expression typically doesn't alter the result
6932 // type of the conditional, however the GCC compatible vector extension
6933 // changes the result type to be that of the conditional. Since we cannot
6934 // know if this is a vector extension here, delay the conversion of the
6935 // LHS/RHS below until later.
6936 return Context.DependentTy;
6937 }
6938
6939
6940 // Either of the arguments dependent?
6941 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6942 return Context.DependentTy;
6943
6944 // C++11 [expr.cond]p2
6945 // If either the second or the third operand has type (cv) void, ...
6946 QualType LTy = LHS.get()->getType();
6947 QualType RTy = RHS.get()->getType();
6948 bool LVoid = LTy->isVoidType();
6949 bool RVoid = RTy->isVoidType();
6950 if (LVoid || RVoid) {
6951 // ... one of the following shall hold:
6952 // -- The second or the third operand (but not both) is a (possibly
6953 // parenthesized) throw-expression; the result is of the type
6954 // and value category of the other.
6955 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6956 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6957
6958 // Void expressions aren't legal in the vector-conditional expressions.
6959 if (IsVectorConditional) {
6960 SourceRange DiagLoc =
6961 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6962 bool IsThrow = LVoid ? LThrow : RThrow;
6963 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6964 << DiagLoc << IsThrow;
6965 return QualType();
6966 }
6967
6968 if (LThrow != RThrow) {
6969 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6970 VK = NonThrow->getValueKind();
6971 // DR (no number yet): the result is a bit-field if the
6972 // non-throw-expression operand is a bit-field.
6973 OK = NonThrow->getObjectKind();
6974 return NonThrow->getType();
6975 }
6976
6977 // -- Both the second and third operands have type void; the result is of
6978 // type void and is a prvalue.
6979 if (LVoid && RVoid)
6980 return Context.getCommonSugaredType(LTy, RTy);
6981
6982 // Neither holds, error.
6983 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6984 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6985 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6986 return QualType();
6987 }
6988
6989 // Neither is void.
6990 if (IsVectorConditional)
6991 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6992
6993 if (IsSizelessVectorConditional)
6994 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6995
6996 // WebAssembly tables are not allowed as conditional LHS or RHS.
6997 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
6998 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
6999 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7000 return QualType();
7001 }
7002
7003 // C++11 [expr.cond]p3
7004 // Otherwise, if the second and third operand have different types, and
7005 // either has (cv) class type [...] an attempt is made to convert each of
7006 // those operands to the type of the other.
7007 if (!Context.hasSameType(LTy, RTy) &&
7008 (LTy->isRecordType() || RTy->isRecordType())) {
7009 // These return true if a single direction is already ambiguous.
7010 QualType L2RType, R2LType;
7011 bool HaveL2R, HaveR2L;
7012 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
7013 return QualType();
7014 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
7015 return QualType();
7016
7017 // If both can be converted, [...] the program is ill-formed.
7018 if (HaveL2R && HaveR2L) {
7019 Diag(QuestionLoc, diag::err_conditional_ambiguous)
7020 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7021 return QualType();
7022 }
7023
7024 // If exactly one conversion is possible, that conversion is applied to
7025 // the chosen operand and the converted operands are used in place of the
7026 // original operands for the remainder of this section.
7027 if (HaveL2R) {
7028 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
7029 return QualType();
7030 LTy = LHS.get()->getType();
7031 } else if (HaveR2L) {
7032 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
7033 return QualType();
7034 RTy = RHS.get()->getType();
7035 }
7036 }
7037
7038 // C++11 [expr.cond]p3
7039 // if both are glvalues of the same value category and the same type except
7040 // for cv-qualification, an attempt is made to convert each of those
7041 // operands to the type of the other.
7042 // FIXME:
7043 // Resolving a defect in P0012R1: we extend this to cover all cases where
7044 // one of the operands is reference-compatible with the other, in order
7045 // to support conditionals between functions differing in noexcept. This
7046 // will similarly cover difference in array bounds after P0388R4.
7047 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
7048 // that instead?
7049 ExprValueKind LVK = LHS.get()->getValueKind();
7050 ExprValueKind RVK = RHS.get()->getValueKind();
7051 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
7052 // DerivedToBase was already handled by the class-specific case above.
7053 // FIXME: Should we allow ObjC conversions here?
7054 const ReferenceConversions AllowedConversions =
7055 ReferenceConversions::Qualification |
7056 ReferenceConversions::NestedQualification |
7057 ReferenceConversions::Function;
7058
7059 ReferenceConversions RefConv;
7060 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
7062 !(RefConv & ~AllowedConversions) &&
7063 // [...] subject to the constraint that the reference must bind
7064 // directly [...]
7065 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
7066 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
7067 RTy = RHS.get()->getType();
7068 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
7070 !(RefConv & ~AllowedConversions) &&
7071 !LHS.get()->refersToBitField() &&
7072 !LHS.get()->refersToVectorElement()) {
7073 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
7074 LTy = LHS.get()->getType();
7075 }
7076 }
7077
7078 // C++11 [expr.cond]p4
7079 // If the second and third operands are glvalues of the same value
7080 // category and have the same type, the result is of that type and
7081 // value category and it is a bit-field if the second or the third
7082 // operand is a bit-field, or if both are bit-fields.
7083 // We only extend this to bitfields, not to the crazy other kinds of
7084 // l-values.
7085 bool Same = Context.hasSameType(LTy, RTy);
7086 if (Same && LVK == RVK && LVK != VK_PRValue &&
7089 VK = LHS.get()->getValueKind();
7090 if (LHS.get()->getObjectKind() == OK_BitField ||
7091 RHS.get()->getObjectKind() == OK_BitField)
7092 OK = OK_BitField;
7093 return Context.getCommonSugaredType(LTy, RTy);
7094 }
7095
7096 // C++11 [expr.cond]p5
7097 // Otherwise, the result is a prvalue. If the second and third operands
7098 // do not have the same type, and either has (cv) class type, ...
7099 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
7100 // ... overload resolution is used to determine the conversions (if any)
7101 // to be applied to the operands. If the overload resolution fails, the
7102 // program is ill-formed.
7103 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
7104 return QualType();
7105 }
7106
7107 // C++11 [expr.cond]p6
7108 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
7109 // conversions are performed on the second and third operands.
7112 if (LHS.isInvalid() || RHS.isInvalid())
7113 return QualType();
7114 LTy = LHS.get()->getType();
7115 RTy = RHS.get()->getType();
7116
7117 // After those conversions, one of the following shall hold:
7118 // -- The second and third operands have the same type; the result
7119 // is of that type. If the operands have class type, the result
7120 // is a prvalue temporary of the result type, which is
7121 // copy-initialized from either the second operand or the third
7122 // operand depending on the value of the first operand.
7123 if (Context.hasSameType(LTy, RTy)) {
7124 if (LTy->isRecordType()) {
7125 // The operands have class type. Make a temporary copy.
7128 if (LHSCopy.isInvalid())
7129 return QualType();
7130
7133 if (RHSCopy.isInvalid())
7134 return QualType();
7135
7136 LHS = LHSCopy;
7137 RHS = RHSCopy;
7138 }
7139 return Context.getCommonSugaredType(LTy, RTy);
7140 }
7141
7142 // Extension: conditional operator involving vector types.
7143 if (LTy->isVectorType() || RTy->isVectorType())
7144 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
7145 /*AllowBothBool*/ true,
7146 /*AllowBoolConversions*/ false,
7147 /*AllowBoolOperation*/ false,
7148 /*ReportInvalid*/ true);
7149
7150 // -- The second and third operands have arithmetic or enumeration type;
7151 // the usual arithmetic conversions are performed to bring them to a
7152 // common type, and the result is of that type.
7153 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
7154 QualType ResTy =
7155 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7156 if (LHS.isInvalid() || RHS.isInvalid())
7157 return QualType();
7158 if (ResTy.isNull()) {
7159 Diag(QuestionLoc,
7160 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
7161 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7162 return QualType();
7163 }
7164
7165 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7166 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7167
7168 return ResTy;
7169 }
7170
7171 // -- The second and third operands have pointer type, or one has pointer
7172 // type and the other is a null pointer constant, or both are null
7173 // pointer constants, at least one of which is non-integral; pointer
7174 // conversions and qualification conversions are performed to bring them
7175 // to their composite pointer type. The result is of the composite
7176 // pointer type.
7177 // -- The second and third operands have pointer to member type, or one has
7178 // pointer to member type and the other is a null pointer constant;
7179 // pointer to member conversions and qualification conversions are
7180 // performed to bring them to a common type, whose cv-qualification
7181 // shall match the cv-qualification of either the second or the third
7182 // operand. The result is of the common type.
7183 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
7184 if (!Composite.isNull())
7185 return Composite;
7186
7187 // Similarly, attempt to find composite type of two objective-c pointers.
7188 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
7189 if (LHS.isInvalid() || RHS.isInvalid())
7190 return QualType();
7191 if (!Composite.isNull())
7192 return Composite;
7193
7194 // Check if we are using a null with a non-pointer type.
7195 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7196 return QualType();
7197
7198 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7199 << LHS.get()->getType() << RHS.get()->getType()
7200 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7201 return QualType();
7202}
7203
7205 Expr *&E1, Expr *&E2,
7206 bool ConvertArgs) {
7207 assert(getLangOpts().CPlusPlus && "This function assumes C++");
7208
7209 // C++1z [expr]p14:
7210 // The composite pointer type of two operands p1 and p2 having types T1
7211 // and T2
7212 QualType T1 = E1->getType(), T2 = E2->getType();
7213
7214 // where at least one is a pointer or pointer to member type or
7215 // std::nullptr_t is:
7216 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
7217 T1->isNullPtrType();
7218 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
7219 T2->isNullPtrType();
7220 if (!T1IsPointerLike && !T2IsPointerLike)
7221 return QualType();
7222
7223 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
7224 // This can't actually happen, following the standard, but we also use this
7225 // to implement the end of [expr.conv], which hits this case.
7226 //
7227 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
7228 if (T1IsPointerLike &&
7230 if (ConvertArgs)
7231 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
7232 ? CK_NullToMemberPointer
7233 : CK_NullToPointer).get();
7234 return T1;
7235 }
7236 if (T2IsPointerLike &&
7238 if (ConvertArgs)
7239 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
7240 ? CK_NullToMemberPointer
7241 : CK_NullToPointer).get();
7242 return T2;
7243 }
7244
7245 // Now both have to be pointers or member pointers.
7246 if (!T1IsPointerLike || !T2IsPointerLike)
7247 return QualType();
7248 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
7249 "nullptr_t should be a null pointer constant");
7250
7251 struct Step {
7252 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
7253 // Qualifiers to apply under the step kind.
7254 Qualifiers Quals;
7255 /// The class for a pointer-to-member; a constant array type with a bound
7256 /// (if any) for an array.
7257 const Type *ClassOrBound;
7258
7259 Step(Kind K, const Type *ClassOrBound = nullptr)
7260 : K(K), ClassOrBound(ClassOrBound) {}
7261 QualType rebuild(ASTContext &Ctx, QualType T) const {
7262 T = Ctx.getQualifiedType(T, Quals);
7263 switch (K) {
7264 case Pointer:
7265 return Ctx.getPointerType(T);
7266 case MemberPointer:
7267 return Ctx.getMemberPointerType(T, ClassOrBound);
7268 case ObjCPointer:
7269 return Ctx.getObjCObjectPointerType(T);
7270 case Array:
7271 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
7272 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
7273 ArraySizeModifier::Normal, 0);
7274 else
7275 return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);
7276 }
7277 llvm_unreachable("unknown step kind");
7278 }
7279 };
7280
7282
7283 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7284 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7285 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
7286 // respectively;
7287 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
7288 // to member of C2 of type cv2 U2" for some non-function type U, where
7289 // C1 is reference-related to C2 or C2 is reference-related to C1, the
7290 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
7291 // respectively;
7292 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
7293 // T2;
7294 //
7295 // Dismantle T1 and T2 to simultaneously determine whether they are similar
7296 // and to prepare to form the cv-combined type if so.
7297 QualType Composite1 = T1;
7298 QualType Composite2 = T2;
7299 unsigned NeedConstBefore = 0;
7300 while (true) {
7301 assert(!Composite1.isNull() && !Composite2.isNull());
7302
7303 Qualifiers Q1, Q2;
7304 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
7305 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
7306
7307 // Top-level qualifiers are ignored. Merge at all lower levels.
7308 if (!Steps.empty()) {
7309 // Find the qualifier union: (approximately) the unique minimal set of
7310 // qualifiers that is compatible with both types.
7312 Q2.getCVRUQualifiers());
7313
7314 // Under one level of pointer or pointer-to-member, we can change to an
7315 // unambiguous compatible address space.
7316 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
7317 Quals.setAddressSpace(Q1.getAddressSpace());
7318 } else if (Steps.size() == 1) {
7319 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
7320 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
7321 if (MaybeQ1 == MaybeQ2) {
7322 // Exception for ptr size address spaces. Should be able to choose
7323 // either address space during comparison.
7326 MaybeQ1 = true;
7327 else
7328 return QualType(); // No unique best address space.
7329 }
7330 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
7331 : Q2.getAddressSpace());
7332 } else {
7333 return QualType();
7334 }
7335
7336 // FIXME: In C, we merge __strong and none to __strong at the top level.
7337 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
7338 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
7339 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7340 assert(Steps.size() == 1);
7341 else
7342 return QualType();
7343
7344 // Mismatched lifetime qualifiers never compatibly include each other.
7345 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
7346 Quals.setObjCLifetime(Q1.getObjCLifetime());
7347 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7348 assert(Steps.size() == 1);
7349 else
7350 return QualType();
7351
7352 Steps.back().Quals = Quals;
7353 if (Q1 != Quals || Q2 != Quals)
7354 NeedConstBefore = Steps.size() - 1;
7355 }
7356
7357 // FIXME: Can we unify the following with UnwrapSimilarTypes?
7358
7359 const ArrayType *Arr1, *Arr2;
7360 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
7361 (Arr2 = Context.getAsArrayType(Composite2))) {
7362 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
7363 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
7364 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
7365 Composite1 = Arr1->getElementType();
7366 Composite2 = Arr2->getElementType();
7367 Steps.emplace_back(Step::Array, CAT1);
7368 continue;
7369 }
7370 bool IAT1 = isa<IncompleteArrayType>(Arr1);
7371 bool IAT2 = isa<IncompleteArrayType>(Arr2);
7372 if ((IAT1 && IAT2) ||
7373 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
7374 ((bool)CAT1 != (bool)CAT2) &&
7375 (Steps.empty() || Steps.back().K != Step::Array))) {
7376 // In C++20 onwards, we can unify an array of N T with an array of
7377 // a different or unknown bound. But we can't form an array whose
7378 // element type is an array of unknown bound by doing so.
7379 Composite1 = Arr1->getElementType();
7380 Composite2 = Arr2->getElementType();
7381 Steps.emplace_back(Step::Array);
7382 if (CAT1 || CAT2)
7383 NeedConstBefore = Steps.size();
7384 continue;
7385 }
7386 }
7387
7388 const PointerType *Ptr1, *Ptr2;
7389 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
7390 (Ptr2 = Composite2->getAs<PointerType>())) {
7391 Composite1 = Ptr1->getPointeeType();
7392 Composite2 = Ptr2->getPointeeType();
7393 Steps.emplace_back(Step::Pointer);
7394 continue;
7395 }
7396
7397 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
7398 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
7399 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
7400 Composite1 = ObjPtr1->getPointeeType();
7401 Composite2 = ObjPtr2->getPointeeType();
7402 Steps.emplace_back(Step::ObjCPointer);
7403 continue;
7404 }
7405
7406 const MemberPointerType *MemPtr1, *MemPtr2;
7407 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
7408 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
7409 Composite1 = MemPtr1->getPointeeType();
7410 Composite2 = MemPtr2->getPointeeType();
7411
7412 // At the top level, we can perform a base-to-derived pointer-to-member
7413 // conversion:
7414 //
7415 // - [...] where C1 is reference-related to C2 or C2 is
7416 // reference-related to C1
7417 //
7418 // (Note that the only kinds of reference-relatedness in scope here are
7419 // "same type or derived from".) At any other level, the class must
7420 // exactly match.
7421 const Type *Class = nullptr;
7422 QualType Cls1(MemPtr1->getClass(), 0);
7423 QualType Cls2(MemPtr2->getClass(), 0);
7424 if (Context.hasSameType(Cls1, Cls2))
7425 Class = MemPtr1->getClass();
7426 else if (Steps.empty())
7427 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7428 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7429 if (!Class)
7430 return QualType();
7431
7432 Steps.emplace_back(Step::MemberPointer, Class);
7433 continue;
7434 }
7435
7436 // Special case: at the top level, we can decompose an Objective-C pointer
7437 // and a 'cv void *'. Unify the qualifiers.
7438 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7439 Composite2->isObjCObjectPointerType()) ||
7440 (Composite1->isObjCObjectPointerType() &&
7441 Composite2->isVoidPointerType()))) {
7442 Composite1 = Composite1->getPointeeType();
7443 Composite2 = Composite2->getPointeeType();
7444 Steps.emplace_back(Step::Pointer);
7445 continue;
7446 }
7447
7448 // FIXME: block pointer types?
7449
7450 // Cannot unwrap any more types.
7451 break;
7452 }
7453
7454 // - if T1 or T2 is "pointer to noexcept function" and the other type is
7455 // "pointer to function", where the function types are otherwise the same,
7456 // "pointer to function";
7457 // - if T1 or T2 is "pointer to member of C1 of type function", the other
7458 // type is "pointer to member of C2 of type noexcept function", and C1
7459 // is reference-related to C2 or C2 is reference-related to C1, where
7460 // the function types are otherwise the same, "pointer to member of C2 of
7461 // type function" or "pointer to member of C1 of type function",
7462 // respectively;
7463 //
7464 // We also support 'noreturn' here, so as a Clang extension we generalize the
7465 // above to:
7466 //
7467 // - [Clang] If T1 and T2 are both of type "pointer to function" or
7468 // "pointer to member function" and the pointee types can be unified
7469 // by a function pointer conversion, that conversion is applied
7470 // before checking the following rules.
7471 //
7472 // We've already unwrapped down to the function types, and we want to merge
7473 // rather than just convert, so do this ourselves rather than calling
7474 // IsFunctionConversion.
7475 //
7476 // FIXME: In order to match the standard wording as closely as possible, we
7477 // currently only do this under a single level of pointers. Ideally, we would
7478 // allow this in general, and set NeedConstBefore to the relevant depth on
7479 // the side(s) where we changed anything. If we permit that, we should also
7480 // consider this conversion when determining type similarity and model it as
7481 // a qualification conversion.
7482 if (Steps.size() == 1) {
7483 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7484 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7485 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7486 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7487
7488 // The result is noreturn if both operands are.
7489 bool Noreturn =
7490 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7491 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7492 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7493
7494 // The result is nothrow if both operands are.
7495 SmallVector<QualType, 8> ExceptionTypeStorage;
7497 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7499
7500 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7501 FPT1->getParamTypes(), EPI1);
7502 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7503 FPT2->getParamTypes(), EPI2);
7504 }
7505 }
7506 }
7507
7508 // There are some more conversions we can perform under exactly one pointer.
7509 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7510 !Context.hasSameType(Composite1, Composite2)) {
7511 // - if T1 or T2 is "pointer to cv1 void" and the other type is
7512 // "pointer to cv2 T", where T is an object type or void,
7513 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7514 if (Composite1->isVoidType() && Composite2->isObjectType())
7515 Composite2 = Composite1;
7516 else if (Composite2->isVoidType() && Composite1->isObjectType())
7517 Composite1 = Composite2;
7518 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7519 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7520 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7521 // T1, respectively;
7522 //
7523 // The "similar type" handling covers all of this except for the "T1 is a
7524 // base class of T2" case in the definition of reference-related.
7525 else if (IsDerivedFrom(Loc, Composite1, Composite2))
7526 Composite1 = Composite2;
7527 else if (IsDerivedFrom(Loc, Composite2, Composite1))
7528 Composite2 = Composite1;
7529 }
7530
7531 // At this point, either the inner types are the same or we have failed to
7532 // find a composite pointer type.
7533 if (!Context.hasSameType(Composite1, Composite2))
7534 return QualType();
7535
7536 // Per C++ [conv.qual]p3, add 'const' to every level before the last
7537 // differing qualifier.
7538 for (unsigned I = 0; I != NeedConstBefore; ++I)
7539 Steps[I].Quals.addConst();
7540
7541 // Rebuild the composite type.
7542 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7543 for (auto &S : llvm::reverse(Steps))
7544 Composite = S.rebuild(Context, Composite);
7545
7546 if (ConvertArgs) {
7547 // Convert the expressions to the composite pointer type.
7548 InitializedEntity Entity =
7550 InitializationKind Kind =
7552
7553 InitializationSequence E1ToC(*this, Entity, Kind, E1);
7554 if (!E1ToC)
7555 return QualType();
7556
7557 InitializationSequence E2ToC(*this, Entity, Kind, E2);
7558 if (!E2ToC)
7559 return QualType();
7560
7561 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7562 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7563 if (E1Result.isInvalid())
7564 return QualType();
7565 E1 = E1Result.get();
7566
7567 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7568 if (E2Result.isInvalid())
7569 return QualType();
7570 E2 = E2Result.get();
7571 }
7572
7573 return Composite;
7574}
7575
7577 if (!E)
7578 return ExprError();
7579
7580 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7581
7582 // If the result is a glvalue, we shouldn't bind it.
7583 if (E->isGLValue())
7584 return E;
7585
7586 // In ARC, calls that return a retainable type can return retained,
7587 // in which case we have to insert a consuming cast.
7588 if (getLangOpts().ObjCAutoRefCount &&
7590
7591 bool ReturnsRetained;
7592
7593 // For actual calls, we compute this by examining the type of the
7594 // called value.
7595 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7596 Expr *Callee = Call->getCallee()->IgnoreParens();
7597 QualType T = Callee->getType();
7598
7599 if (T == Context.BoundMemberTy) {
7600 // Handle pointer-to-members.
7601 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7602 T = BinOp->getRHS()->getType();
7603 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7604 T = Mem->getMemberDecl()->getType();
7605 }
7606
7607 if (const PointerType *Ptr = T->getAs<PointerType>())
7608 T = Ptr->getPointeeType();
7609 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7610 T = Ptr->getPointeeType();
7611 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7612 T = MemPtr->getPointeeType();
7613
7614 auto *FTy = T->castAs<FunctionType>();
7615 ReturnsRetained = FTy->getExtInfo().getProducesResult();
7616
7617 // ActOnStmtExpr arranges things so that StmtExprs of retainable
7618 // type always produce a +1 object.
7619 } else if (isa<StmtExpr>(E)) {
7620 ReturnsRetained = true;
7621
7622 // We hit this case with the lambda conversion-to-block optimization;
7623 // we don't want any extra casts here.
7624 } else if (isa<CastExpr>(E) &&
7625 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7626 return E;
7627
7628 // For message sends and property references, we try to find an
7629 // actual method. FIXME: we should infer retention by selector in
7630 // cases where we don't have an actual method.
7631 } else {
7632 ObjCMethodDecl *D = nullptr;
7633 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7634 D = Send->getMethodDecl();
7635 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7636 D = BoxedExpr->getBoxingMethod();
7637 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7638 // Don't do reclaims if we're using the zero-element array
7639 // constant.
7640 if (ArrayLit->getNumElements() == 0 &&
7642 return E;
7643
7644 D = ArrayLit->getArrayWithObjectsMethod();
7645 } else if (ObjCDictionaryLiteral *DictLit
7646 = dyn_cast<ObjCDictionaryLiteral>(E)) {
7647 // Don't do reclaims if we're using the zero-element dictionary
7648 // constant.
7649 if (DictLit->getNumElements() == 0 &&
7651 return E;
7652
7653 D = DictLit->getDictWithObjectsMethod();
7654 }
7655
7656 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7657
7658 // Don't do reclaims on performSelector calls; despite their
7659 // return type, the invoked method doesn't necessarily actually
7660 // return an object.
7661 if (!ReturnsRetained &&
7662 D && D->getMethodFamily() == OMF_performSelector)
7663 return E;
7664 }
7665
7666 // Don't reclaim an object of Class type.
7667 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7668 return E;
7669
7671
7672 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7673 : CK_ARCReclaimReturnedObject);
7674 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7676 }
7677
7680
7681 if (!getLangOpts().CPlusPlus)
7682 return E;
7683
7684 // Search for the base element type (cf. ASTContext::getBaseElementType) with
7685 // a fast path for the common case that the type is directly a RecordType.
7687 const RecordType *RT = nullptr;
7688 while (!RT) {
7689 switch (T->getTypeClass()) {
7690 case Type::Record:
7691 RT = cast<RecordType>(T);
7692 break;
7693 case Type::ConstantArray:
7694 case Type::IncompleteArray:
7695 case Type::VariableArray:
7696 case Type::DependentSizedArray:
7697 T = cast<ArrayType>(T)->getElementType().getTypePtr();
7698 break;
7699 default:
7700 return E;
7701 }
7702 }
7703
7704 // That should be enough to guarantee that this type is complete, if we're
7705 // not processing a decltype expression.
7706 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7707 if (RD->isInvalidDecl() || RD->isDependentContext())
7708 return E;
7709
7710 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7712 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7713
7714 if (Destructor) {
7717 PDiag(diag::err_access_dtor_temp)
7718 << E->getType());
7720 return ExprError();
7721
7722 // If destructor is trivial, we can avoid the extra copy.
7723 if (Destructor->isTrivial())
7724 return E;
7725
7726 // We need a cleanup, but we don't need to remember the temporary.
7728 }
7729
7732
7733 if (IsDecltype)
7734 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7735
7736 return Bind;
7737}
7738
7741 if (SubExpr.isInvalid())
7742 return ExprError();
7743
7744 return MaybeCreateExprWithCleanups(SubExpr.get());
7745}
7746
7748 assert(SubExpr && "subexpression can't be null!");
7749
7751
7752 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7753 assert(ExprCleanupObjects.size() >= FirstCleanup);
7754 assert(Cleanup.exprNeedsCleanups() ||
7755 ExprCleanupObjects.size() == FirstCleanup);
7757 return SubExpr;
7758
7759 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7760 ExprCleanupObjects.size() - FirstCleanup);
7761
7763 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7765
7766 return E;
7767}
7768
7770 assert(SubStmt && "sub-statement can't be null!");
7771
7773
7775 return SubStmt;
7776
7777 // FIXME: In order to attach the temporaries, wrap the statement into
7778 // a StmtExpr; currently this is only used for asm statements.
7779 // This is hacky, either create a new CXXStmtWithTemporaries statement or
7780 // a new AsmStmtWithTemporaries.
7781 CompoundStmt *CompStmt =
7784 Expr *E = new (Context)
7786 /*FIXME TemplateDepth=*/0);
7788}
7789
7791 assert(ExprEvalContexts.back().ExprContext ==
7793 "not in a decltype expression");
7794
7796 if (Result.isInvalid())
7797 return ExprError();
7798 E = Result.get();
7799
7800 // C++11 [expr.call]p11:
7801 // If a function call is a prvalue of object type,
7802 // -- if the function call is either
7803 // -- the operand of a decltype-specifier, or
7804 // -- the right operand of a comma operator that is the operand of a
7805 // decltype-specifier,
7806 // a temporary object is not introduced for the prvalue.
7807
7808 // Recursively rebuild ParenExprs and comma expressions to strip out the
7809 // outermost CXXBindTemporaryExpr, if any.
7810 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7811 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7812 if (SubExpr.isInvalid())
7813 return ExprError();
7814 if (SubExpr.get() == PE->getSubExpr())
7815 return E;
7816 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7817 }
7818 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7819 if (BO->getOpcode() == BO_Comma) {
7820 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7821 if (RHS.isInvalid())
7822 return ExprError();
7823 if (RHS.get() == BO->getRHS())
7824 return E;
7825 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7826 BO->getType(), BO->getValueKind(),
7827 BO->getObjectKind(), BO->getOperatorLoc(),
7828 BO->getFPFeatures());
7829 }
7830 }
7831
7832 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7833 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7834 : nullptr;
7835 if (TopCall)
7836 E = TopCall;
7837 else
7838 TopBind = nullptr;
7839
7840 // Disable the special decltype handling now.
7841 ExprEvalContexts.back().ExprContext =
7843
7845 if (Result.isInvalid())
7846 return ExprError();
7847 E = Result.get();
7848
7849 // In MS mode, don't perform any extra checking of call return types within a
7850 // decltype expression.
7851 if (getLangOpts().MSVCCompat)
7852 return E;
7853
7854 // Perform the semantic checks we delayed until this point.
7855 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7856 I != N; ++I) {
7857 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7858 if (Call == TopCall)
7859 continue;
7860
7861 if (CheckCallReturnType(Call->getCallReturnType(Context),
7862 Call->getBeginLoc(), Call, Call->getDirectCallee()))
7863 return ExprError();
7864 }
7865
7866 // Now all relevant types are complete, check the destructors are accessible
7867 // and non-deleted, and annotate them on the temporaries.
7868 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7869 I != N; ++I) {
7871 ExprEvalContexts.back().DelayedDecltypeBinds[I];
7872 if (Bind == TopBind)
7873 continue;
7874
7875 CXXTemporary *Temp = Bind->getTemporary();
7876
7877 CXXRecordDecl *RD =
7878 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7881
7882 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7883 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7884 PDiag(diag::err_access_dtor_temp)
7885 << Bind->getType());
7886 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7887 return ExprError();
7888
7889 // We need a cleanup, but we don't need to remember the temporary.
7891 }
7892
7893 // Possibly strip off the top CXXBindTemporaryExpr.
7894 return E;
7895}
7896
7897/// Note a set of 'operator->' functions that were used for a member access.
7899 ArrayRef<FunctionDecl *> OperatorArrows) {
7900 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7901 // FIXME: Make this configurable?
7902 unsigned Limit = 9;
7903 if (OperatorArrows.size() > Limit) {
7904 // Produce Limit-1 normal notes and one 'skipping' note.
7905 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7906 SkipCount = OperatorArrows.size() - (Limit - 1);
7907 }
7908
7909 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7910 if (I == SkipStart) {
7911 S.Diag(OperatorArrows[I]->getLocation(),
7912 diag::note_operator_arrows_suppressed)
7913 << SkipCount;
7914 I += SkipCount;
7915 } else {
7916 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7917 << OperatorArrows[I]->getCallResultType();
7918 ++I;
7919 }
7920 }
7921}
7922
7924 SourceLocation OpLoc,
7925 tok::TokenKind OpKind,
7926 ParsedType &ObjectType,
7927 bool &MayBePseudoDestructor) {
7928 // Since this might be a postfix expression, get rid of ParenListExprs.
7930 if (Result.isInvalid()) return ExprError();
7931 Base = Result.get();
7932
7934 if (Result.isInvalid()) return ExprError();
7935 Base = Result.get();
7936
7937 QualType BaseType = Base->getType();
7938 MayBePseudoDestructor = false;
7939 if (BaseType->isDependentType()) {
7940 // If we have a pointer to a dependent type and are using the -> operator,
7941 // the object type is the type that the pointer points to. We might still
7942 // have enough information about that type to do something useful.
7943 if (OpKind == tok::arrow)
7944 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7945 BaseType = Ptr->getPointeeType();
7946
7947 ObjectType = ParsedType::make(BaseType);
7948 MayBePseudoDestructor = true;
7949 return Base;
7950 }
7951
7952 // C++ [over.match.oper]p8:
7953 // [...] When operator->returns, the operator-> is applied to the value
7954 // returned, with the original second operand.
7955 if (OpKind == tok::arrow) {
7956 QualType StartingType = BaseType;
7957 bool NoArrowOperatorFound = false;
7958 bool FirstIteration = true;
7959 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7960 // The set of types we've considered so far.
7962 SmallVector<FunctionDecl*, 8> OperatorArrows;
7963 CTypes.insert(Context.getCanonicalType(BaseType));
7964
7965 while (BaseType->isRecordType()) {
7966 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7967 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7968 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7969 noteOperatorArrows(*this, OperatorArrows);
7970 Diag(OpLoc, diag::note_operator_arrow_depth)
7971 << getLangOpts().ArrowDepth;
7972 return ExprError();
7973 }
7974
7976 S, Base, OpLoc,
7977 // When in a template specialization and on the first loop iteration,
7978 // potentially give the default diagnostic (with the fixit in a
7979 // separate note) instead of having the error reported back to here
7980 // and giving a diagnostic with a fixit attached to the error itself.
7981 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7982 ? nullptr
7983 : &NoArrowOperatorFound);
7984 if (Result.isInvalid()) {
7985 if (NoArrowOperatorFound) {
7986 if (FirstIteration) {
7987 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7988 << BaseType << 1 << Base->getSourceRange()
7989 << FixItHint::CreateReplacement(OpLoc, ".");
7990 OpKind = tok::period;
7991 break;
7992 }
7993 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7994 << BaseType << Base->getSourceRange();
7995 CallExpr *CE = dyn_cast<CallExpr>(Base);
7996 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7997 Diag(CD->getBeginLoc(),
7998 diag::note_member_reference_arrow_from_operator_arrow);
7999 }
8000 }
8001 return ExprError();
8002 }
8003 Base = Result.get();
8004 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
8005 OperatorArrows.push_back(OpCall->getDirectCallee());
8006 BaseType = Base->getType();
8007 CanQualType CBaseType = Context.getCanonicalType(BaseType);
8008 if (!CTypes.insert(CBaseType).second) {
8009 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
8010 noteOperatorArrows(*this, OperatorArrows);
8011 return ExprError();
8012 }
8013 FirstIteration = false;
8014 }
8015
8016 if (OpKind == tok::arrow) {
8017 if (BaseType->isPointerType())
8018 BaseType = BaseType->getPointeeType();
8019 else if (auto *AT = Context.getAsArrayType(BaseType))
8020 BaseType = AT->getElementType();
8021 }
8022 }
8023
8024 // Objective-C properties allow "." access on Objective-C pointer types,
8025 // so adjust the base type to the object type itself.
8026 if (BaseType->isObjCObjectPointerType())
8027 BaseType = BaseType->getPointeeType();
8028
8029 // C++ [basic.lookup.classref]p2:
8030 // [...] If the type of the object expression is of pointer to scalar
8031 // type, the unqualified-id is looked up in the context of the complete
8032 // postfix-expression.
8033 //
8034 // This also indicates that we could be parsing a pseudo-destructor-name.
8035 // Note that Objective-C class and object types can be pseudo-destructor
8036 // expressions or normal member (ivar or property) access expressions, and
8037 // it's legal for the type to be incomplete if this is a pseudo-destructor
8038 // call. We'll do more incomplete-type checks later in the lookup process,
8039 // so just skip this check for ObjC types.
8040 if (!BaseType->isRecordType()) {
8041 ObjectType = ParsedType::make(BaseType);
8042 MayBePseudoDestructor = true;
8043 return Base;
8044 }
8045
8046 // The object type must be complete (or dependent), or
8047 // C++11 [expr.prim.general]p3:
8048 // Unlike the object expression in other contexts, *this is not required to
8049 // be of complete type for purposes of class member access (5.2.5) outside
8050 // the member function body.
8051 if (!BaseType->isDependentType() &&
8053 RequireCompleteType(OpLoc, BaseType,
8054 diag::err_incomplete_member_access)) {
8055 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
8056 }
8057
8058 // C++ [basic.lookup.classref]p2:
8059 // If the id-expression in a class member access (5.2.5) is an
8060 // unqualified-id, and the type of the object expression is of a class
8061 // type C (or of pointer to a class type C), the unqualified-id is looked
8062 // up in the scope of class C. [...]
8063 ObjectType = ParsedType::make(BaseType);
8064 return Base;
8065}
8066
8067static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
8068 tok::TokenKind &OpKind, SourceLocation OpLoc) {
8069 if (Base->hasPlaceholderType()) {
8071 if (result.isInvalid()) return true;
8072 Base = result.get();
8073 }
8074 ObjectType = Base->getType();
8075
8076 // C++ [expr.pseudo]p2:
8077 // The left-hand side of the dot operator shall be of scalar type. The
8078 // left-hand side of the arrow operator shall be of pointer to scalar type.
8079 // This scalar type is the object type.
8080 // Note that this is rather different from the normal handling for the
8081 // arrow operator.
8082 if (OpKind == tok::arrow) {
8083 // The operator requires a prvalue, so perform lvalue conversions.
8084 // Only do this if we might plausibly end with a pointer, as otherwise
8085 // this was likely to be intended to be a '.'.
8086 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
8087 ObjectType->isFunctionType()) {
8089 if (BaseResult.isInvalid())
8090 return true;
8091 Base = BaseResult.get();
8092 ObjectType = Base->getType();
8093 }
8094
8095 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
8096 ObjectType = Ptr->getPointeeType();
8097 } else if (!Base->isTypeDependent()) {
8098 // The user wrote "p->" when they probably meant "p."; fix it.
8099 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8100 << ObjectType << true
8101 << FixItHint::CreateReplacement(OpLoc, ".");
8102 if (S.isSFINAEContext())
8103 return true;
8104
8105 OpKind = tok::period;
8106 }
8107 }
8108
8109 return false;
8110}
8111
8112/// Check if it's ok to try and recover dot pseudo destructor calls on
8113/// pointer objects.
8114static bool
8116 QualType DestructedType) {
8117 // If this is a record type, check if its destructor is callable.
8118 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
8119 if (RD->hasDefinition())
8121 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
8122 return false;
8123 }
8124
8125 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
8126 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
8127 DestructedType->isVectorType();
8128}
8129
8131 SourceLocation OpLoc,
8132 tok::TokenKind OpKind,
8133 const CXXScopeSpec &SS,
8134 TypeSourceInfo *ScopeTypeInfo,
8135 SourceLocation CCLoc,
8136 SourceLocation TildeLoc,
8137 PseudoDestructorTypeStorage Destructed) {
8138 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
8139
8140 QualType ObjectType;
8141 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8142 return ExprError();
8143
8144 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
8145 !ObjectType->isVectorType()) {
8146 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
8147 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
8148 else {
8149 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
8150 << ObjectType << Base->getSourceRange();
8151 return ExprError();
8152 }
8153 }
8154
8155 // C++ [expr.pseudo]p2:
8156 // [...] The cv-unqualified versions of the object type and of the type
8157 // designated by the pseudo-destructor-name shall be the same type.
8158 if (DestructedTypeInfo) {
8159 QualType DestructedType = DestructedTypeInfo->getType();
8160 SourceLocation DestructedTypeStart =
8161 DestructedTypeInfo->getTypeLoc().getBeginLoc();
8162 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
8163 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
8164 // Detect dot pseudo destructor calls on pointer objects, e.g.:
8165 // Foo *foo;
8166 // foo.~Foo();
8167 if (OpKind == tok::period && ObjectType->isPointerType() &&
8168 Context.hasSameUnqualifiedType(DestructedType,
8169 ObjectType->getPointeeType())) {
8170 auto Diagnostic =
8171 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8172 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
8173
8174 // Issue a fixit only when the destructor is valid.
8176 *this, DestructedType))
8178
8179 // Recover by setting the object type to the destructed type and the
8180 // operator to '->'.
8181 ObjectType = DestructedType;
8182 OpKind = tok::arrow;
8183 } else {
8184 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
8185 << ObjectType << DestructedType << Base->getSourceRange()
8186 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8187
8188 // Recover by setting the destructed type to the object type.
8189 DestructedType = ObjectType;
8190 DestructedTypeInfo =
8191 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
8192 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8193 }
8194 } else if (DestructedType.getObjCLifetime() !=
8195 ObjectType.getObjCLifetime()) {
8196
8197 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
8198 // Okay: just pretend that the user provided the correctly-qualified
8199 // type.
8200 } else {
8201 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
8202 << ObjectType << DestructedType << Base->getSourceRange()
8203 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8204 }
8205
8206 // Recover by setting the destructed type to the object type.
8207 DestructedType = ObjectType;
8208 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
8209 DestructedTypeStart);
8210 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8211 }
8212 }
8213 }
8214
8215 // C++ [expr.pseudo]p2:
8216 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
8217 // form
8218 //
8219 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
8220 //
8221 // shall designate the same scalar type.
8222 if (ScopeTypeInfo) {
8223 QualType ScopeType = ScopeTypeInfo->getType();
8224 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
8225 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
8226
8227 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
8228 diag::err_pseudo_dtor_type_mismatch)
8229 << ObjectType << ScopeType << Base->getSourceRange()
8230 << ScopeTypeInfo->getTypeLoc().getSourceRange();
8231
8232 ScopeType = QualType();
8233 ScopeTypeInfo = nullptr;
8234 }
8235 }
8236
8237 Expr *Result
8239 OpKind == tok::arrow, OpLoc,
8241 ScopeTypeInfo,
8242 CCLoc,
8243 TildeLoc,
8244 Destructed);
8245
8246 return Result;
8247}
8248
8250 SourceLocation OpLoc,
8251 tok::TokenKind OpKind,
8252 CXXScopeSpec &SS,
8253 UnqualifiedId &FirstTypeName,
8254 SourceLocation CCLoc,
8255 SourceLocation TildeLoc,
8256 UnqualifiedId &SecondTypeName) {
8257 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8258 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8259 "Invalid first type name in pseudo-destructor");
8260 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8261 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8262 "Invalid second type name in pseudo-destructor");
8263
8264 QualType ObjectType;
8265 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8266 return ExprError();
8267
8268 // Compute the object type that we should use for name lookup purposes. Only
8269 // record types and dependent types matter.
8270 ParsedType ObjectTypePtrForLookup;
8271 if (!SS.isSet()) {
8272 if (ObjectType->isRecordType())
8273 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
8274 else if (ObjectType->isDependentType())
8275 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
8276 }
8277
8278 // Convert the name of the type being destructed (following the ~) into a
8279 // type (with source-location information).
8280 QualType DestructedType;
8281 TypeSourceInfo *DestructedTypeInfo = nullptr;
8282 PseudoDestructorTypeStorage Destructed;
8283 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8284 ParsedType T = getTypeName(*SecondTypeName.Identifier,
8285 SecondTypeName.StartLocation,
8286 S, &SS, true, false, ObjectTypePtrForLookup,
8287 /*IsCtorOrDtorName*/true);
8288 if (!T &&
8289 ((SS.isSet() && !computeDeclContext(SS, false)) ||
8290 (!SS.isSet() && ObjectType->isDependentType()))) {
8291 // The name of the type being destroyed is a dependent name, and we
8292 // couldn't find anything useful in scope. Just store the identifier and
8293 // it's location, and we'll perform (qualified) name lookup again at
8294 // template instantiation time.
8295 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
8296 SecondTypeName.StartLocation);
8297 } else if (!T) {
8298 Diag(SecondTypeName.StartLocation,
8299 diag::err_pseudo_dtor_destructor_non_type)
8300 << SecondTypeName.Identifier << ObjectType;
8301 if (isSFINAEContext())
8302 return ExprError();
8303
8304 // Recover by assuming we had the right type all along.
8305 DestructedType = ObjectType;
8306 } else
8307 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
8308 } else {
8309 // Resolve the template-id to a type.
8310 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
8311 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8312 TemplateId->NumArgs);
8314 SS,
8315 TemplateId->TemplateKWLoc,
8316 TemplateId->Template,
8317 TemplateId->Name,
8318 TemplateId->TemplateNameLoc,
8319 TemplateId->LAngleLoc,
8320 TemplateArgsPtr,
8321 TemplateId->RAngleLoc,
8322 /*IsCtorOrDtorName*/true);
8323 if (T.isInvalid() || !T.get()) {
8324 // Recover by assuming we had the right type all along.
8325 DestructedType = ObjectType;
8326 } else
8327 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
8328 }
8329
8330 // If we've performed some kind of recovery, (re-)build the type source
8331 // information.
8332 if (!DestructedType.isNull()) {
8333 if (!DestructedTypeInfo)
8334 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
8335 SecondTypeName.StartLocation);
8336 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8337 }
8338
8339 // Convert the name of the scope type (the type prior to '::') into a type.
8340 TypeSourceInfo *ScopeTypeInfo = nullptr;
8341 QualType ScopeType;
8342 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8343 FirstTypeName.Identifier) {
8344 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8345 ParsedType T = getTypeName(*FirstTypeName.Identifier,
8346 FirstTypeName.StartLocation,
8347 S, &SS, true, false, ObjectTypePtrForLookup,
8348 /*IsCtorOrDtorName*/true);
8349 if (!T) {
8350 Diag(FirstTypeName.StartLocation,
8351 diag::err_pseudo_dtor_destructor_non_type)
8352 << FirstTypeName.Identifier << ObjectType;
8353
8354 if (isSFINAEContext())
8355 return ExprError();
8356
8357 // Just drop this type. It's unnecessary anyway.
8358 ScopeType = QualType();
8359 } else
8360 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
8361 } else {
8362 // Resolve the template-id to a type.
8363 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
8364 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8365 TemplateId->NumArgs);
8367 SS,
8368 TemplateId->TemplateKWLoc,
8369 TemplateId->Template,
8370 TemplateId->Name,
8371 TemplateId->TemplateNameLoc,
8372 TemplateId->LAngleLoc,
8373 TemplateArgsPtr,
8374 TemplateId->RAngleLoc,
8375 /*IsCtorOrDtorName*/true);
8376 if (T.isInvalid() || !T.get()) {
8377 // Recover by dropping this type.
8378 ScopeType = QualType();
8379 } else
8380 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
8381 }
8382 }
8383
8384 if (!ScopeType.isNull() && !ScopeTypeInfo)
8385 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
8386 FirstTypeName.StartLocation);
8387
8388
8389 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
8390 ScopeTypeInfo, CCLoc, TildeLoc,
8391 Destructed);
8392}
8393
8395 SourceLocation OpLoc,
8396 tok::TokenKind OpKind,
8397 SourceLocation TildeLoc,
8398 const DeclSpec& DS) {
8399 QualType ObjectType;
8400 QualType T;
8401 TypeLocBuilder TLB;
8402 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8403 return ExprError();
8404
8405 switch (DS.getTypeSpecType()) {
8407 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
8408 return true;
8409 }
8411 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
8412 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
8413 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
8414 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
8415 break;
8416 }
8419 DS.getBeginLoc(), DS.getEllipsisLoc());
8421 cast<PackIndexingType>(T.getTypePtr())->getPattern(),
8422 DS.getBeginLoc());
8424 PITL.setEllipsisLoc(DS.getEllipsisLoc());
8425 break;
8426 }
8427 default:
8428 llvm_unreachable("Unsupported type in pseudo destructor");
8429 }
8430 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
8431 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
8432
8433 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
8434 nullptr, SourceLocation(), TildeLoc,
8435 Destructed);
8436}
8437
8439 SourceLocation RParen) {
8440 // If the operand is an unresolved lookup expression, the expression is ill-
8441 // formed per [over.over]p1, because overloaded function names cannot be used
8442 // without arguments except in explicit contexts.
8443 ExprResult R = CheckPlaceholderExpr(Operand);
8444 if (R.isInvalid())
8445 return R;
8446
8448 if (R.isInvalid())
8449 return ExprError();
8450
8451 Operand = R.get();
8452
8453 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8454 Operand->HasSideEffects(Context, false)) {
8455 // The expression operand for noexcept is in an unevaluated expression
8456 // context, so side effects could result in unintended consequences.
8457 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8458 }
8459
8460 CanThrowResult CanThrow = canThrow(Operand);
8461 return new (Context)
8462 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8463}
8464
8466 Expr *Operand, SourceLocation RParen) {
8467 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8468}
8469
8471 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8472 DeclRefExpr *LHS = nullptr;
8473 bool IsCompoundAssign = false;
8474 bool isIncrementDecrementUnaryOp = false;
8475 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8476 if (BO->getLHS()->getType()->isDependentType() ||
8477 BO->getRHS()->getType()->isDependentType()) {
8478 if (BO->getOpcode() != BO_Assign)
8479 return;
8480 } else if (!BO->isAssignmentOp())
8481 return;
8482 else
8483 IsCompoundAssign = BO->isCompoundAssignmentOp();
8484 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8485 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8486 if (COCE->getOperator() != OO_Equal)
8487 return;
8488 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8489 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8490 if (!UO->isIncrementDecrementOp())
8491 return;
8492 isIncrementDecrementUnaryOp = true;
8493 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8494 }
8495 if (!LHS)
8496 return;
8497 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8498 if (!VD)
8499 return;
8500 // Don't decrement RefsMinusAssignments if volatile variable with compound
8501 // assignment (+=, ...) or increment/decrement unary operator to avoid
8502 // potential unused-but-set-variable warning.
8503 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8505 return;
8506 auto iter = RefsMinusAssignments.find(VD);
8507 if (iter == RefsMinusAssignments.end())
8508 return;
8509 iter->getSecond()--;
8510}
8511
8512/// Perform the conversions required for an expression used in a
8513/// context that ignores the result.
8516
8517 if (E->hasPlaceholderType()) {
8519 if (result.isInvalid()) return E;
8520 E = result.get();
8521 }
8522
8523 if (getLangOpts().CPlusPlus) {
8524 // The C++11 standard defines the notion of a discarded-value expression;
8525 // normally, we don't need to do anything to handle it, but if it is a
8526 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8527 // conversion.
8530 if (Res.isInvalid())
8531 return E;
8532 E = Res.get();
8533 } else {
8534 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8535 // it occurs as a discarded-value expression.
8537 }
8538
8539 // C++1z:
8540 // If the expression is a prvalue after this optional conversion, the
8541 // temporary materialization conversion is applied.
8542 //
8543 // We do not materialize temporaries by default in order to avoid creating
8544 // unnecessary temporary objects. If we skip this step, IR generation is
8545 // able to synthesize the storage for itself in the aggregate case, and
8546 // adding the extra node to the AST is just clutter.
8548 E->isPRValue() && !E->getType()->isVoidType()) {
8550 if (Res.isInvalid())
8551 return E;
8552 E = Res.get();
8553 }
8554 return E;
8555 }
8556
8557 // C99 6.3.2.1:
8558 // [Except in specific positions,] an lvalue that does not have
8559 // array type is converted to the value stored in the
8560 // designated object (and is no longer an lvalue).
8561 if (E->isPRValue()) {
8562 // In C, function designators (i.e. expressions of function type)
8563 // are r-values, but we still want to do function-to-pointer decay
8564 // on them. This is both technically correct and convenient for
8565 // some clients.
8568
8569 return E;
8570 }
8571
8572 // GCC seems to also exclude expressions of incomplete enum type.
8573 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8574 if (!T->getDecl()->isComplete()) {
8575 // FIXME: stupid workaround for a codegen bug!
8576 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8577 return E;
8578 }
8579 }
8580
8582 if (Res.isInvalid())
8583 return E;
8584 E = Res.get();
8585
8586 if (!E->getType()->isVoidType())
8588 diag::err_incomplete_type);
8589 return E;
8590}
8591
8593 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8594 // it occurs as an unevaluated operand.
8596
8597 return E;
8598}
8599
8600// If we can unambiguously determine whether Var can never be used
8601// in a constant expression, return true.
8602// - if the variable and its initializer are non-dependent, then
8603// we can unambiguously check if the variable is a constant expression.
8604// - if the initializer is not value dependent - we can determine whether
8605// it can be used to initialize a constant expression. If Init can not
8606// be used to initialize a constant expression we conclude that Var can
8607// never be a constant expression.
8608// - FXIME: if the initializer is dependent, we can still do some analysis and
8609// identify certain cases unambiguously as non-const by using a Visitor:
8610// - such as those that involve odr-use of a ParmVarDecl, involve a new
8611// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8614 if (isa<ParmVarDecl>(Var)) return true;
8615 const VarDecl *DefVD = nullptr;
8616
8617 // If there is no initializer - this can not be a constant expression.
8618 const Expr *Init = Var->getAnyInitializer(DefVD);
8619 if (!Init)
8620 return true;
8621 assert(DefVD);
8622 if (DefVD->isWeak())
8623 return false;
8624
8625 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8626 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8627 // of value-dependent expressions, and use it here to determine whether the
8628 // initializer is a potential constant expression.
8629 return false;
8630 }
8631
8633}
8634
8635/// Check if the current lambda has any potential captures
8636/// that must be captured by any of its enclosing lambdas that are ready to
8637/// capture. If there is a lambda that can capture a nested
8638/// potential-capture, go ahead and do so. Also, check to see if any
8639/// variables are uncaptureable or do not involve an odr-use so do not
8640/// need to be captured.
8641
8643 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8644
8645 assert(!S.isUnevaluatedContext());
8646 assert(S.CurContext->isDependentContext());
8647#ifndef NDEBUG
8648 DeclContext *DC = S.CurContext;
8649 while (isa_and_nonnull<CapturedDecl>(DC))
8650 DC = DC->getParent();
8651 assert(
8652 CurrentLSI->CallOperator == DC &&
8653 "The current call operator must be synchronized with Sema's CurContext");
8654#endif // NDEBUG
8655
8656 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8657
8658 // All the potentially captureable variables in the current nested
8659 // lambda (within a generic outer lambda), must be captured by an
8660 // outer lambda that is enclosed within a non-dependent context.
8661 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8662 // If the variable is clearly identified as non-odr-used and the full
8663 // expression is not instantiation dependent, only then do we not
8664 // need to check enclosing lambda's for speculative captures.
8665 // For e.g.:
8666 // Even though 'x' is not odr-used, it should be captured.
8667 // int test() {
8668 // const int x = 10;
8669 // auto L = [=](auto a) {
8670 // (void) +x + a;
8671 // };
8672 // }
8673 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8674 !IsFullExprInstantiationDependent)
8675 return;
8676
8677 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8678 if (!UnderlyingVar)
8679 return;
8680
8681 // If we have a capture-capable lambda for the variable, go ahead and
8682 // capture the variable in that lambda (and all its enclosing lambdas).
8683 if (const std::optional<unsigned> Index =
8685 S.FunctionScopes, Var, S))
8686 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8687 const bool IsVarNeverAConstantExpression =
8689 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8690 // This full expression is not instantiation dependent or the variable
8691 // can not be used in a constant expression - which means
8692 // this variable must be odr-used here, so diagnose a
8693 // capture violation early, if the variable is un-captureable.
8694 // This is purely for diagnosing errors early. Otherwise, this
8695 // error would get diagnosed when the lambda becomes capture ready.
8696 QualType CaptureType, DeclRefType;
8697 SourceLocation ExprLoc = VarExpr->getExprLoc();
8698 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8699 /*EllipsisLoc*/ SourceLocation(),
8700 /*BuildAndDiagnose*/false, CaptureType,
8701 DeclRefType, nullptr)) {
8702 // We will never be able to capture this variable, and we need
8703 // to be able to in any and all instantiations, so diagnose it.
8704 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8705 /*EllipsisLoc*/ SourceLocation(),
8706 /*BuildAndDiagnose*/true, CaptureType,
8707 DeclRefType, nullptr);
8708 }
8709 }
8710 });
8711
8712 // Check if 'this' needs to be captured.
8713 if (CurrentLSI->hasPotentialThisCapture()) {
8714 // If we have a capture-capable lambda for 'this', go ahead and capture
8715 // 'this' in that lambda (and all its enclosing lambdas).
8716 if (const std::optional<unsigned> Index =
8718 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8719 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8721 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8722 &FunctionScopeIndexOfCapturableLambda);
8723 }
8724 }
8725
8726 // Reset all the potential captures at the end of each full-expression.
8727 CurrentLSI->clearPotentialCaptures();
8728}
8729
8732 const TypoCorrection &TC) {
8733 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8734 Consumer.getLookupResult().getLookupKind());
8735 const CXXScopeSpec *SS = Consumer.getSS();
8736 CXXScopeSpec NewSS;
8737
8738 // Use an approprate CXXScopeSpec for building the expr.
8739 if (auto *NNS = TC.getCorrectionSpecifier())
8741 else if (SS && !TC.WillReplaceSpecifier())
8742 NewSS = *SS;
8743
8744 if (auto *ND = TC.getFoundDecl()) {
8745 R.setLookupName(ND->getDeclName());
8746 R.addDecl(ND);
8747 if (ND->isCXXClassMember()) {
8748 // Figure out the correct naming class to add to the LookupResult.
8749 CXXRecordDecl *Record = nullptr;
8750 if (auto *NNS = TC.getCorrectionSpecifier())
8751 Record = NNS->getAsType()->getAsCXXRecordDecl();
8752 if (!Record)
8753 Record =
8754 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8755 if (Record)
8757
8758 // Detect and handle the case where the decl might be an implicit
8759 // member.
8761 NewSS, R, Consumer.isAddressOfOperand()))
8763 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8764 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8765 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8766 return SemaRef.ObjC().LookupInObjCMethod(R, Consumer.getScope(),
8767 Ivar->getIdentifier());
8768 }
8769 }
8770
8771 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8772 /*AcceptInvalidDecl*/ true);
8773}
8774
8775namespace {
8776class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8778
8779public:
8780 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8781 : TypoExprs(TypoExprs) {}
8782 bool VisitTypoExpr(TypoExpr *TE) {
8783 TypoExprs.insert(TE);
8784 return true;
8785 }
8786};
8787
8788class TransformTypos : public TreeTransform<TransformTypos> {
8789 typedef TreeTransform<TransformTypos> BaseTransform;
8790
8791 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8792 // process of being initialized.
8793 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8794 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8795 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8796 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8797
8798 /// Emit diagnostics for all of the TypoExprs encountered.
8799 ///
8800 /// If the TypoExprs were successfully corrected, then the diagnostics should
8801 /// suggest the corrections. Otherwise the diagnostics will not suggest
8802 /// anything (having been passed an empty TypoCorrection).
8803 ///
8804 /// If we've failed to correct due to ambiguous corrections, we need to
8805 /// be sure to pass empty corrections and replacements. Otherwise it's
8806 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8807 /// and we don't want to report those diagnostics.
8808 void EmitAllDiagnostics(bool IsAmbiguous) {
8809 for (TypoExpr *TE : TypoExprs) {
8810 auto &State = SemaRef.getTypoExprState(TE);
8811 if (State.DiagHandler) {
8812 TypoCorrection TC = IsAmbiguous
8813 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8814 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8815
8816 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8817 // TypoCorrection, replacing the existing decls. This ensures the right
8818 // NamedDecl is used in diagnostics e.g. in the case where overload
8819 // resolution was used to select one from several possible decls that
8820 // had been stored in the TypoCorrection.
8821 if (auto *ND = getDeclFromExpr(
8822 Replacement.isInvalid() ? nullptr : Replacement.get()))
8823 TC.setCorrectionDecl(ND);
8824
8825 State.DiagHandler(TC);
8826 }
8827 SemaRef.clearDelayedTypo(TE);
8828 }
8829 }
8830
8831 /// Try to advance the typo correction state of the first unfinished TypoExpr.
8832 /// We allow advancement of the correction stream by removing it from the
8833 /// TransformCache which allows `TransformTypoExpr` to advance during the
8834 /// next transformation attempt.
8835 ///
8836 /// Any substitution attempts for the previous TypoExprs (which must have been
8837 /// finished) will need to be retried since it's possible that they will now
8838 /// be invalid given the latest advancement.
8839 ///
8840 /// We need to be sure that we're making progress - it's possible that the
8841 /// tree is so malformed that the transform never makes it to the
8842 /// `TransformTypoExpr`.
8843 ///
8844 /// Returns true if there are any untried correction combinations.
8845 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8846 for (auto *TE : TypoExprs) {
8847 auto &State = SemaRef.getTypoExprState(TE);
8848 TransformCache.erase(TE);
8849 if (!State.Consumer->hasMadeAnyCorrectionProgress())
8850 return false;
8851 if (!State.Consumer->finished())
8852 return true;
8853 State.Consumer->resetCorrectionStream();
8854 }
8855 return false;
8856 }
8857
8859 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8860 E = OverloadResolution[OE];
8861
8862 if (!E)
8863 return nullptr;
8864 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8865 return DRE->getFoundDecl();
8866 if (auto *ME = dyn_cast<MemberExpr>(E))
8867 return ME->getFoundDecl();
8868 // FIXME: Add any other expr types that could be seen by the delayed typo
8869 // correction TreeTransform for which the corresponding TypoCorrection could
8870 // contain multiple decls.
8871 return nullptr;
8872 }
8873
8874 ExprResult TryTransform(Expr *E) {
8875 Sema::SFINAETrap Trap(SemaRef);
8876 ExprResult Res = TransformExpr(E);
8877 if (Trap.hasErrorOccurred() || Res.isInvalid())
8878 return ExprError();
8879
8880 return ExprFilter(Res.get());
8881 }
8882
8883 // Since correcting typos may intoduce new TypoExprs, this function
8884 // checks for new TypoExprs and recurses if it finds any. Note that it will
8885 // only succeed if it is able to correct all typos in the given expression.
8886 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8887 if (Res.isInvalid()) {
8888 return Res;
8889 }
8890 // Check to see if any new TypoExprs were created. If so, we need to recurse
8891 // to check their validity.
8892 Expr *FixedExpr = Res.get();
8893
8894 auto SavedTypoExprs = std::move(TypoExprs);
8895 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8896 TypoExprs.clear();
8897 AmbiguousTypoExprs.clear();
8898
8899 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8900 if (!TypoExprs.empty()) {
8901 // Recurse to handle newly created TypoExprs. If we're not able to
8902 // handle them, discard these TypoExprs.
8903 ExprResult RecurResult =
8904 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8905 if (RecurResult.isInvalid()) {
8906 Res = ExprError();
8907 // Recursive corrections didn't work, wipe them away and don't add
8908 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8909 // since we don't want to clear them twice. Note: it's possible the
8910 // TypoExprs were created recursively and thus won't be in our
8911 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8912 auto &SemaTypoExprs = SemaRef.TypoExprs;
8913 for (auto *TE : TypoExprs) {
8914 TransformCache.erase(TE);
8915 SemaRef.clearDelayedTypo(TE);
8916
8917 auto SI = find(SemaTypoExprs, TE);
8918 if (SI != SemaTypoExprs.end()) {
8919 SemaTypoExprs.erase(SI);
8920 }
8921 }
8922 } else {
8923 // TypoExpr is valid: add newly created TypoExprs since we were
8924 // able to correct them.
8925 Res = RecurResult;
8926 SavedTypoExprs.set_union(TypoExprs);
8927 }
8928 }
8929
8930 TypoExprs = std::move(SavedTypoExprs);
8931 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8932
8933 return Res;
8934 }
8935
8936 // Try to transform the given expression, looping through the correction
8937 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8938 //
8939 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8940 // true and this method immediately will return an `ExprError`.
8941 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8942 ExprResult Res;
8943 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8944 SemaRef.TypoExprs.clear();
8945
8946 while (true) {
8947 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8948
8949 // Recursion encountered an ambiguous correction. This means that our
8950 // correction itself is ambiguous, so stop now.
8951 if (IsAmbiguous)
8952 break;
8953
8954 // If the transform is still valid after checking for any new typos,
8955 // it's good to go.
8956 if (!Res.isInvalid())
8957 break;
8958
8959 // The transform was invalid, see if we have any TypoExprs with untried
8960 // correction candidates.
8961 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8962 break;
8963 }
8964
8965 // If we found a valid result, double check to make sure it's not ambiguous.
8966 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8967 auto SavedTransformCache =
8968 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8969
8970 // Ensure none of the TypoExprs have multiple typo correction candidates
8971 // with the same edit length that pass all the checks and filters.
8972 while (!AmbiguousTypoExprs.empty()) {
8973 auto TE = AmbiguousTypoExprs.back();
8974
8975 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8976 // and invalidating our TypoExprState, so always fetch it instead of storing.
8977 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8978
8979 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8980 TypoCorrection Next;
8981 do {
8982 // Fetch the next correction by erasing the typo from the cache and calling
8983 // `TryTransform` which will iterate through corrections in
8984 // `TransformTypoExpr`.
8985 TransformCache.erase(TE);
8986 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8987
8988 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8989 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8990 SavedTransformCache.erase(TE);
8991 Res = ExprError();
8992 IsAmbiguous = true;
8993 break;
8994 }
8995 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8996 Next.getEditDistance(false) == TC.getEditDistance(false));
8997
8998 if (IsAmbiguous)
8999 break;
9000
9001 AmbiguousTypoExprs.remove(TE);
9002 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
9003 TransformCache[TE] = SavedTransformCache[TE];
9004 }
9005 TransformCache = std::move(SavedTransformCache);
9006 }
9007
9008 // Wipe away any newly created TypoExprs that we don't know about. Since we
9009 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
9010 // possible if a `TypoExpr` is created during a transformation but then
9011 // fails before we can discover it.
9012 auto &SemaTypoExprs = SemaRef.TypoExprs;
9013 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
9014 auto TE = *Iterator;
9015 auto FI = find(TypoExprs, TE);
9016 if (FI != TypoExprs.end()) {
9017 Iterator++;
9018 continue;
9019 }
9020 SemaRef.clearDelayedTypo(TE);
9021 Iterator = SemaTypoExprs.erase(Iterator);
9022 }
9023 SemaRef.TypoExprs = std::move(SavedTypoExprs);
9024
9025 return Res;
9026 }
9027
9028public:
9029 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
9030 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
9031
9032 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
9033 MultiExprArg Args,
9034 SourceLocation RParenLoc,
9035 Expr *ExecConfig = nullptr) {
9036 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
9037 RParenLoc, ExecConfig);
9038 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
9039 if (Result.isUsable()) {
9040 Expr *ResultCall = Result.get();
9041 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
9042 ResultCall = BE->getSubExpr();
9043 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
9044 OverloadResolution[OE] = CE->getCallee();
9045 }
9046 }
9047 return Result;
9048 }
9049
9050 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
9051
9052 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
9053
9054 ExprResult Transform(Expr *E) {
9055 bool IsAmbiguous = false;
9056 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
9057
9058 if (!Res.isUsable())
9059 FindTypoExprs(TypoExprs).TraverseStmt(E);
9060
9061 EmitAllDiagnostics(IsAmbiguous);
9062
9063 return Res;
9064 }
9065
9066 ExprResult TransformTypoExpr(TypoExpr *E) {
9067 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
9068 // cached transformation result if there is one and the TypoExpr isn't the
9069 // first one that was encountered.
9070 auto &CacheEntry = TransformCache[E];
9071 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
9072 return CacheEntry;
9073 }
9074
9075 auto &State = SemaRef.getTypoExprState(E);
9076 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
9077
9078 // For the first TypoExpr and an uncached TypoExpr, find the next likely
9079 // typo correction and return it.
9080 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
9081 if (InitDecl && TC.getFoundDecl() == InitDecl)
9082 continue;
9083 // FIXME: If we would typo-correct to an invalid declaration, it's
9084 // probably best to just suppress all errors from this typo correction.
9085 ExprResult NE = State.RecoveryHandler ?
9086 State.RecoveryHandler(SemaRef, E, TC) :
9087 attemptRecovery(SemaRef, *State.Consumer, TC);
9088 if (!NE.isInvalid()) {
9089 // Check whether there may be a second viable correction with the same
9090 // edit distance; if so, remember this TypoExpr may have an ambiguous
9091 // correction so it can be more thoroughly vetted later.
9092 TypoCorrection Next;
9093 if ((Next = State.Consumer->peekNextCorrection()) &&
9094 Next.getEditDistance(false) == TC.getEditDistance(false)) {
9095 AmbiguousTypoExprs.insert(E);
9096 } else {
9097 AmbiguousTypoExprs.remove(E);
9098 }
9099 assert(!NE.isUnset() &&
9100 "Typo was transformed into a valid-but-null ExprResult");
9101 return CacheEntry = NE;
9102 }
9103 }
9104 return CacheEntry = ExprError();
9105 }
9106};
9107}
9108
9111 bool RecoverUncorrectedTypos,
9112 llvm::function_ref<ExprResult(Expr *)> Filter) {
9113 // If the current evaluation context indicates there are uncorrected typos
9114 // and the current expression isn't guaranteed to not have typos, try to
9115 // resolve any TypoExpr nodes that might be in the expression.
9116 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
9117 (E->isTypeDependent() || E->isValueDependent() ||
9119 auto TyposResolved = DelayedTypos.size();
9120 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
9121 TyposResolved -= DelayedTypos.size();
9122 if (Result.isInvalid() || Result.get() != E) {
9123 ExprEvalContexts.back().NumTypos -= TyposResolved;
9124 if (Result.isInvalid() && RecoverUncorrectedTypos) {
9125 struct TyposReplace : TreeTransform<TyposReplace> {
9126 TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
9127 ExprResult TransformTypoExpr(clang::TypoExpr *E) {
9128 return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
9129 E->getEndLoc(), {});
9130 }
9131 } TT(*this);
9132 return TT.TransformExpr(E);
9133 }
9134 return Result;
9135 }
9136 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
9137 }
9138 return E;
9139}
9140
9142 bool DiscardedValue, bool IsConstexpr,
9143 bool IsTemplateArgument) {
9144 ExprResult FullExpr = FE;
9145
9146 if (!FullExpr.get())
9147 return ExprError();
9148
9149 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
9150 return ExprError();
9151
9152 if (DiscardedValue) {
9153 // Top-level expressions default to 'id' when we're in a debugger.
9154 if (getLangOpts().DebuggerCastResultToId &&
9155 FullExpr.get()->getType() == Context.UnknownAnyTy) {
9157 if (FullExpr.isInvalid())
9158 return ExprError();
9159 }
9160
9162 if (FullExpr.isInvalid())
9163 return ExprError();
9164
9166 if (FullExpr.isInvalid())
9167 return ExprError();
9168
9169 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
9170 }
9171
9172 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
9173 /*RecoverUncorrectedTypos=*/true);
9174 if (FullExpr.isInvalid())
9175 return ExprError();
9176
9177 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
9178
9179 // At the end of this full expression (which could be a deeply nested
9180 // lambda), if there is a potential capture within the nested lambda,
9181 // have the outer capture-able lambda try and capture it.
9182 // Consider the following code:
9183 // void f(int, int);
9184 // void f(const int&, double);
9185 // void foo() {
9186 // const int x = 10, y = 20;
9187 // auto L = [=](auto a) {
9188 // auto M = [=](auto b) {
9189 // f(x, b); <-- requires x to be captured by L and M
9190 // f(y, a); <-- requires y to be captured by L, but not all Ms
9191 // };
9192 // };
9193 // }
9194
9195 // FIXME: Also consider what happens for something like this that involves
9196 // the gnu-extension statement-expressions or even lambda-init-captures:
9197 // void f() {
9198 // const int n = 0;
9199 // auto L = [&](auto a) {
9200 // +n + ({ 0; a; });
9201 // };
9202 // }
9203 //
9204 // Here, we see +n, and then the full-expression 0; ends, so we don't
9205 // capture n (and instead remove it from our list of potential captures),
9206 // and then the full-expression +n + ({ 0; }); ends, but it's too late
9207 // for us to see that we need to capture n after all.
9208
9209 LambdaScopeInfo *const CurrentLSI =
9210 getCurLambda(/*IgnoreCapturedRegions=*/true);
9211 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
9212 // even if CurContext is not a lambda call operator. Refer to that Bug Report
9213 // for an example of the code that might cause this asynchrony.
9214 // By ensuring we are in the context of a lambda's call operator
9215 // we can fix the bug (we only need to check whether we need to capture
9216 // if we are within a lambda's body); but per the comments in that
9217 // PR, a proper fix would entail :
9218 // "Alternative suggestion:
9219 // - Add to Sema an integer holding the smallest (outermost) scope
9220 // index that we are *lexically* within, and save/restore/set to
9221 // FunctionScopes.size() in InstantiatingTemplate's
9222 // constructor/destructor.
9223 // - Teach the handful of places that iterate over FunctionScopes to
9224 // stop at the outermost enclosing lexical scope."
9225 DeclContext *DC = CurContext;
9226 while (isa_and_nonnull<CapturedDecl>(DC))
9227 DC = DC->getParent();
9228 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
9229 if (IsInLambdaDeclContext && CurrentLSI &&
9230 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
9232 *this);
9234}
9235
9237 if (!FullStmt) return StmtError();
9238
9239 return MaybeCreateStmtWithCleanups(FullStmt);
9240}
9241
9244 CXXScopeSpec &SS,
9245 const DeclarationNameInfo &TargetNameInfo) {
9246 DeclarationName TargetName = TargetNameInfo.getName();
9247 if (!TargetName)
9248 return IER_DoesNotExist;
9249
9250 // If the name itself is dependent, then the result is dependent.
9251 if (TargetName.isDependentName())
9252 return IER_Dependent;
9253
9254 // Do the redeclaration lookup in the current scope.
9255 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
9256 RedeclarationKind::NotForRedeclaration);
9257 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
9259
9260 switch (R.getResultKind()) {
9265 return IER_Exists;
9266
9268 return IER_DoesNotExist;
9269
9271 return IER_Dependent;
9272 }
9273
9274 llvm_unreachable("Invalid LookupResult Kind!");
9275}
9276
9279 bool IsIfExists, CXXScopeSpec &SS,
9280 UnqualifiedId &Name) {
9281 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9282
9283 // Check for an unexpanded parameter pack.
9284 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
9285 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
9286 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
9287 return IER_Error;
9288
9289 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
9290}
9291
9293 return BuildExprRequirement(E, /*IsSimple=*/true,
9294 /*NoexceptLoc=*/SourceLocation(),
9295 /*ReturnTypeRequirement=*/{});
9296}
9297
9299 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
9300 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
9301 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
9302 "Exactly one of TypeName and TemplateId must be specified.");
9303 TypeSourceInfo *TSI = nullptr;
9304 if (TypeName) {
9305 QualType T =
9307 SS.getWithLocInContext(Context), *TypeName, NameLoc,
9308 &TSI, /*DeducedTSTContext=*/false);
9309 if (T.isNull())
9310 return nullptr;
9311 } else {
9312 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
9313 TemplateId->NumArgs);
9314 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
9315 TemplateId->TemplateKWLoc,
9316 TemplateId->Template, TemplateId->Name,
9317 TemplateId->TemplateNameLoc,
9318 TemplateId->LAngleLoc, ArgsPtr,
9319 TemplateId->RAngleLoc);
9320 if (T.isInvalid())
9321 return nullptr;
9322 if (GetTypeFromParser(T.get(), &TSI).isNull())
9323 return nullptr;
9324 }
9325 return BuildTypeRequirement(TSI);
9326}
9327
9330 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
9331 /*ReturnTypeRequirement=*/{});
9332}
9333
9336 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9337 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
9338 // C++2a [expr.prim.req.compound] p1.3.3
9339 // [..] the expression is deduced against an invented function template
9340 // F [...] F is a void function template with a single type template
9341 // parameter T declared with the constrained-parameter. Form a new
9342 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
9343 // around the constrained-parameter. F has a single parameter whose
9344 // type-specifier is cv T followed by the abstract-declarator. [...]
9345 //
9346 // The cv part is done in the calling function - we get the concept with
9347 // arguments and the abstract declarator with the correct CV qualification and
9348 // have to synthesize T and the single parameter of F.
9349 auto &II = Context.Idents.get("expr-type");
9352 SourceLocation(), Depth,
9353 /*Index=*/0, &II,
9354 /*Typename=*/true,
9355 /*ParameterPack=*/false,
9356 /*HasTypeConstraint=*/true);
9357
9358 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
9359 /*EllipsisLoc=*/SourceLocation(),
9360 /*AllowUnexpandedPack=*/true))
9361 // Just produce a requirement with no type requirements.
9362 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
9363
9366 ArrayRef<NamedDecl *>(TParam),
9368 /*RequiresClause=*/nullptr);
9369 return BuildExprRequirement(
9370 E, /*IsSimple=*/false, NoexceptLoc,
9372}
9373
9376 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9379 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9381 ReturnTypeRequirement.isDependent())
9383 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9385 else if (ReturnTypeRequirement.isSubstitutionFailure())
9387 else if (ReturnTypeRequirement.isTypeConstraint()) {
9388 // C++2a [expr.prim.req]p1.3.3
9389 // The immediately-declared constraint ([temp]) of decltype((E)) shall
9390 // be satisfied.
9392 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9393 QualType MatchedType =
9396 Args.push_back(TemplateArgument(MatchedType));
9397
9398 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9399
9400 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false);
9401 MLTAL.addOuterRetainedLevels(TPL->getDepth());
9402 const TypeConstraint *TC = Param->getTypeConstraint();
9403 assert(TC && "Type Constraint cannot be null here");
9404 auto *IDC = TC->getImmediatelyDeclaredConstraint();
9405 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
9406 ExprResult Constraint = SubstExpr(IDC, MLTAL);
9407 if (Constraint.isInvalid()) {
9409 concepts::createSubstDiagAt(*this, IDC->getExprLoc(),
9410 [&](llvm::raw_ostream &OS) {
9411 IDC->printPretty(OS, /*Helper=*/nullptr,
9412 getPrintingPolicy());
9413 }),
9414 IsSimple, NoexceptLoc, ReturnTypeRequirement);
9415 }
9416 SubstitutedConstraintExpr =
9417 cast<ConceptSpecializationExpr>(Constraint.get());
9418 if (!SubstitutedConstraintExpr->isSatisfied())
9420 }
9421 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9422 ReturnTypeRequirement, Status,
9423 SubstitutedConstraintExpr);
9424}
9425
9428 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9429 bool IsSimple, SourceLocation NoexceptLoc,
9431 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9432 IsSimple, NoexceptLoc,
9433 ReturnTypeRequirement);
9434}
9435
9439}
9440
9444 return new (Context) concepts::TypeRequirement(SubstDiag);
9445}
9446
9448 return BuildNestedRequirement(Constraint);
9449}
9450
9453 ConstraintSatisfaction Satisfaction;
9454 if (!Constraint->isInstantiationDependent() &&
9455 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9456 Constraint->getSourceRange(), Satisfaction))
9457 return nullptr;
9458 return new (Context) concepts::NestedRequirement(Context, Constraint,
9459 Satisfaction);
9460}
9461
9463Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9464 const ASTConstraintSatisfaction &Satisfaction) {
9466 InvalidConstraintEntity,
9468}
9469
9472 ArrayRef<ParmVarDecl *> LocalParameters,
9473 Scope *BodyScope) {
9474 assert(BodyScope);
9475
9477 RequiresKWLoc);
9478
9479 PushDeclContext(BodyScope, Body);
9480
9481 for (ParmVarDecl *Param : LocalParameters) {
9482 if (Param->hasDefaultArg())
9483 // C++2a [expr.prim.req] p4
9484 // [...] A local parameter of a requires-expression shall not have a
9485 // default argument. [...]
9486 Diag(Param->getDefaultArgRange().getBegin(),
9487 diag::err_requires_expr_local_parameter_default_argument);
9488 // Ignore default argument and move on
9489
9490 Param->setDeclContext(Body);
9491 // If this has an identifier, add it to the scope stack.
9492 if (Param->getIdentifier()) {
9493 CheckShadow(BodyScope, Param);
9494 PushOnScopeChains(Param, BodyScope);
9495 }
9496 }
9497 return Body;
9498}
9499
9501 assert(CurContext && "DeclContext imbalance!");
9503 assert(CurContext && "Popped translation unit!");
9504}
9505
9507 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
9508 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
9509 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
9510 SourceLocation ClosingBraceLoc) {
9511 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
9512 LocalParameters, RParenLoc, Requirements,
9513 ClosingBraceLoc);
9515 return ExprError();
9516 return RE;
9517}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
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:2679
static CanQualType GetReturnType(QualType RetTy)
Returns the "extra-canonicalized" return type, which discards qualifiers on the return type.
Definition: CGCall.cpp:110
const Decl * D
enum clang::sema::@1655::IndirectLocalPathEntry::EntryKind Kind
Expr * E
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition: Darwin.cpp:3318
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
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 void collectPublicBases(CXXRecordDecl *RD, llvm::DenseMap< CXXRecordDecl *, unsigned > &SubobjectsSeen, llvm::SmallPtrSetImpl< CXXRecordDecl * > &VBases, llvm::SetVector< CXXRecordDecl * > &PublicSubobjectsSeen, bool ParentIsPublic)
static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs, SourceLocation KeyLoc)
static bool HasNonDeletedDefaultedEqualityComparison(Sema &S, const CXXRecordDecl *Decl, SourceLocation KeyLoc)
static bool DiagnoseVLAInCXXTypeTrait(Sema &S, const TypeSourceInfo *T, clang::tok::TokenKind TypeTraitID)
Checks that type T is not a VLA.
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 ExprResult attemptRecovery(Sema &SemaRef, const TypoCorrectionConsumer &Consumer, const TypoCorrection &TC)
static void DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, const MismatchingNewDeleteDetector &Detector)
static void getUnambiguousPublicSubobjects(CXXRecordDecl *RD, llvm::SmallVectorImpl< CXXRecordDecl * > &Objects)
static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style, Expr *Init, bool IsCPlusPlus20)
static QualType adjustVectorType(ASTContext &Context, QualType FromTy, QualType ToType, QualType *ElTy=nullptr)
static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S)
Check if the current lambda has any potential captures that must be captured by any of its enclosing ...
static void getUuidAttrOfType(Sema &SemaRef, QualType QT, llvm::SmallSetVector< const UuidAttr *, 1 > &UuidAttrs)
Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to a single GUID.
static bool resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl< Expr * > &Args, bool &PassAlignment, FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose)
static QualType adjustCVQualifiersForCXXThisWithinLambda(ArrayRef< FunctionScopeInfo * > FunctionScopes, QualType ThisTy, DeclContext *CurSemaContext, ASTContext &ASTCtx)
static bool DiagnoseAtomicInCXXTypeTrait(Sema &S, const TypeSourceInfo *T, clang::tok::TokenKind TypeTraitID)
Checks that type T is not an atomic type (_Atomic).
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 HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, Sema &Self, SourceLocation KeyLoc, ASTContext &C, bool(CXXRecordDecl::*HasTrivial)() const, bool(CXXRecordDecl::*HasNonTrivial)() const, bool(CXXMethodDecl::*IsDesiredOp)() const)
static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E)
static UsualDeallocFnInfo resolveDeallocationOverload(Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 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)
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 doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, QualType allocType)
Determine whether a given type is a class for which 'delete[]' would call a member 'operator delete[]...
static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, SourceLocation KeyLoc, TypeSourceInfo *TInfo)
static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, QualType T, Expr *DimExpr, SourceLocation KeyLoc)
static bool isValidVectorForConditionalCondition(ASTContext &Ctx, QualType CondTy)
static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, SourceLocation Loc, QualType ArgTy)
Check the completeness of a type in a unary type trait.
static void noteOperatorArrows(Sema &S, ArrayRef< FunctionDecl * > OperatorArrows)
Note a set of 'operator->' functions that were used for a member access.
static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx, QualType CondTy)
static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI)
static ExprResult CheckConvertibilityForTypeTraits(Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs, SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator)
TypeTraitReturnType
static bool EvaluateBooleanTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc, bool IsDependent)
static bool isTriviallyEqualityComparableType(Sema &S, QualType Type, SourceLocation KeyLoc)
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD)
Determine whether the given function is a non-placement deallocation function.
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14505
This file provides some common utility functions for processing Lambdas.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
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.
Defines enumerations for the type traits support.
C Language Family Type Representation.
__device__ int
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
MSGuidDecl * getMSGuidDecl(MSGuidDeclParts Parts) const
Return a declaration for the global GUID object representing the given GUID value.
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
unsigned getIntWidth(QualType T) const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:664
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
CanQualType FloatTy
Definition: ASTContext.h:1131
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getMSGuidType() const
Retrieve the implicitly-predeclared 'struct _GUID' type.
Definition: ASTContext.h:2194
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
CanQualType DependentTy
Definition: ASTContext.h:1147
CanQualType NullPtrTy
Definition: ASTContext.h:1146
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1637
IdentifierTable & Idents
Definition: ASTContext.h:660
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:797
bool hasUniqueObjectRepresentations(QualType Ty, bool CheckIfTriviallyCopyable=true) const
Return true if the specified type has unique object representations according to (C++17 [meta....
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1120
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1147
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CharUnits getExnObjectAlignment() const
Return the alignment (in bytes) of the thrown exception object.
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1147
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2117
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
FunctionProtoType::ExceptionSpecInfo mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1, FunctionProtoType::ExceptionSpecInfo ESI2, SmallVectorImpl< QualType > &ExceptionTypeStorage, bool AcceptDependent)
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1119
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1148
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
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 getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
void addCopyConstructorForExceptionObject(CXXRecordDecl *RD, CXXConstructorDecl *CD)
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
Definition: ASTContext.h:2205
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2233
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1847
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2053
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.
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2425
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2398
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2853
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
QualType getElementType() const
Definition: Type.h:3578
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7580
Attr - This represents one attribute.
Definition: Attr.h:42
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6375
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
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:4859
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6365
Pointer to a block type.
Definition: Type.h:3397
This class is used for builtin types like 'int'.
Definition: Type.h:3023
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1491
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition: ExprCXX.cpp:1098
const Expr * getSubExpr() const
Definition: ExprCXX.h:1513
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2304
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2444
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2506
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2498
bool isArrayForm() const
Definition: ExprCXX.h:2524
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2548
Expr * getArgument()
Definition: ExprCXX.h:2539
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
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:902
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
bool isVirtual() const
Definition: DeclCXX.h:2119
bool isUsualDeallocationFunction(SmallVectorImpl< const FunctionDecl * > &PreventedBy) const
Determine whether this is a usual deallocation function (C++ [basic.stc.dynamic.deallocation]p2),...
Definition: DeclCXX.cpp:2416
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2526
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2214
bool isConst() const
Definition: DeclCXX.h:2116
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2504
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2241
static CXXNewExpr * Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, 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:292
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4126
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition: ExprCXX.h:2617
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool hasTrivialMoveAssignment() const
Determine whether this class has a trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1346
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1339
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1245
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1371
base_class_range bases()
Definition: DeclCXX.h:620
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1306
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1283
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1219
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:132
bool hasTrivialCopyAssignment() const
Determine whether this class has a trivial copy assignment operator (C++ [class.copy]p11,...
Definition: DeclCXX.h:1333
capture_const_range captures() const
Definition: DeclCXX.h:1102
ctor_range ctors() const
Definition: DeclCXX.h:682
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:1407
bool hasNonTrivialMoveConstructor() const
Determine whether this class has a non-trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1318
bool hasDefinition() const
Definition: DeclCXX.h:572
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1191
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:2014
bool hasNonTrivialMoveAssignment() const
Determine whether this class has a non-trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1353
bool hasNonTrivialDefaultConstructor() const
Determine whether this class has a non-trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1252
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1293
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1633
An expression "T()" which creates an rvalue of a non-class type T.
Definition: ExprCXX.h:2182
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:236
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceLocation getLastQualifierNameLoc() const
Retrieve the location of the name in the last qualifier in this nested name specifier.
Definition: DeclSpec.cpp:145
SourceLocation getEndLoc() const
Definition: DeclSpec.h:85
SourceRange getRange() const
Definition: DeclSpec.h:80
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Represents a C++ temporary.
Definition: ExprCXX.h:1457
void setDestructor(const CXXDestructorDecl *Dtor)
Definition: ExprCXX.h:1470
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1093
Represents the this expression in C++.
Definition: ExprCXX.h:1152
static CXXThisExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType Ty, bool IsImplicit)
Definition: ExprCXX.cpp:1569
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1206
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
static CXXUnresolvedConstructExpr * Create(const ASTContext &Context, QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool IsListInit)
Definition: ExprCXX.cpp:1472
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3021
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3034
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3000
Expr * getCallee()
Definition: Expr.h:2980
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3008
arg_range arguments()
Definition: Expr.h:3069
Decl * getCalleeDecl()
Definition: Expr.h:2994
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.
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
bool cleanupsHaveSideEffects() const
Definition: CleanupInfo.h:26
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
Complex values, per C99 6.2.5p11.
Definition: Type.h:3134
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1611
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:383
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Definition: ExprConcepts.h:124
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3604
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:178
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:218
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2106
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1766
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
ValueDecl * getDecl()
Definition: Expr.h:1333
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
Expr * getPackIndexingExpr() const
Definition: DeclSpec.h:560
TST getTypeSpecType() const
Definition: DeclSpec.h:537
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:575
static const TST TST_typename_pack_indexing
Definition: DeclSpec.h:313
ParsedType getRepAsType() const
Definition: DeclSpec.h:547
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:623
Expr * getRepAsExpr() const
Definition: DeclSpec.h:555
static const TST TST_decltype
Definition: DeclSpec.h:311
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:582
static const TST TST_decltype_auto
Definition: DeclSpec.h:312
static const TST TST_error
Definition: DeclSpec.h:328
SourceRange getTypeofParensRange() const
Definition: DeclSpec.h:592
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:442
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
Kind
Lists the kind of concrete classes of Decl.
Definition: DeclBase.h:89
bool isInvalidDecl() const
Definition: DeclBase.h:595
SourceLocation getLocation() const
Definition: DeclBase.h:446
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:823
void setImplicit(bool I=true)
Definition: DeclBase.h:601
DeclContext * getDeclContext()
Definition: DeclBase.h:455
bool hasAttr() const
Definition: DeclBase.h:584
@ ReachableWhenImported
This declaration has an owning module, and is visible to lookups that occurs within that module.
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:871
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:434
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 ...
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:2087
void setDecltypeLoc(SourceLocation Loc)
Definition: TypeLoc.h:2084
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6341
bool isDeduced() const
Definition: Type.h:6363
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1571
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition: Diagnostic.h:562
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3844
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4851
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4058
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
EnumDecl * getDecl() const
Definition: Type.h:5998
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1447
bool isLValue() const
Definition: Expr.h:380
bool isRValue() const
Definition: Expr.h:384
This represents one expression.
Definition: Expr.h:110
bool isReadIfDiscardedInCPlusPlus11() const
Determine whether an lvalue-to-rvalue conversion should implicitly be applied to this expression if i...
Definition: Expr.cpp:2534
bool isGLValue() const
Definition: Expr.h:280
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition: Expr.cpp:4156
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3290
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
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:3567
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
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:3941
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition: Expr.h:405
QualType getType() const
Definition: Expr.h:142
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:448
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
An expression trait intrinsic.
Definition: ExprCXX.h:2924
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
Represents a member of a struct/union/class.
Definition: Decl.h:3030
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1044
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4040
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2246
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2630
QualType getReturnType() const
Definition: Decl.h:2717
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
bool isReplaceableGlobalAllocationFunction(std::optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3352
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, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2121
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4381
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3965
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition: Decl.h:2335
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
size_t param_size() const
Definition: Decl.h:2662
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:3191
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
unsigned getNumParams() const
Definition: Type.h:5255
QualType getParamType(unsigned i) const
Definition: Type.h:5257
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5379
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5374
Declaration of a template function.
Definition: DeclTemplate.h:957
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4493
bool getNoReturn() const
Definition: Type.h:4467
bool getProducesResult() const
Definition: Type.h:4468
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
ExtInfo getExtInfo() const
Definition: Type.h:4642
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....
StringRef getName() const
Return the actual identifier string.
bool tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name)
Try to add the given declaration to the top level scope, if it (or a redeclaration of it) hasn't alre...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:567
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:618
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:622
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:5039
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.
Definition: SemaInit.cpp:7522
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3810
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:8610
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....
Definition: SemaInit.cpp:3799
Describes an entity that is being initialized.
static InitializedEntity InitializeException(SourceLocation ThrowLoc, QualType Type)
Create the initialization entity for an exception object.
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type)
Create the initialization entity for an object allocated via new.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:511
bool hasGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:757
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
Definition: LangOptions.h:670
bool hasHiddenGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:772
bool hasProtectedGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:767
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:1358
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:675
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:721
bool hasNext() const
Definition: Lookup.h:706
NamedDecl * next()
Definition: Lookup.h:710
Represents the results of name lookup.
Definition: Lookup.h:46
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:749
bool isAmbiguous() const
Definition: Lookup.h:324
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
bool isClassLookup() const
Returns whether these results arose from performing a lookup into a class.
Definition: Lookup.h:432
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition: Lookup.h:457
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
A global _GUID constant.
Definition: DeclCXX.h:4293
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3270
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3274
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3508
QualType getPointeeType() const
Definition: Type.h:3524
const Type * getClass() const
Definition: Type.h:3538
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
void addOuterRetainedLevels(unsigned Num)
Definition: Template.h:260
This represents a decl that may have a name.
Definition: Decl.h:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition: ExprObjC.h:191
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:127
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition: ExprObjC.h:309
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
bool isSuperClassOf(const ObjCInterfaceDecl *I) const
isSuperClassOf - Return true if this class is the specified class or is a super class of the specifie...
Definition: DeclObjC.h:1809
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition: Type.h:7399
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7411
Represents a class type in Objective C.
Definition: Type.h:7145
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7378
bool hasEmptyCollections() const
Are the empty collection symbols available?
Definition: ObjCRuntime.h:436
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
PtrTy get() const
Definition: Ownership.h:80
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:1019
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
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:2112
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
Represents a parameter to a function.
Definition: Decl.h:1722
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:2903
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
QualType getPointeeType() const
Definition: Type.h:3197
SourceManager & getSourceManager() const
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
Stores the type being destroyed by a pseudo-destructor expression.
Definition: ExprCXX.h:2566
TypeSourceInfo * getTypeSourceInfo() const
Definition: ExprCXX.h:2582
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7834
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3476
@ DK_nontrivial_c_struct
Definition: Type.h:1535
QualType withConst() const
Definition: Type.h:1166
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1163
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7932
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7750
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7876
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7790
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
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: Type.h:7951
QualType getCanonicalType() const
Definition: Type.h:7802
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2840
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7796
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1448
The collection of all-type qualifiers we support.
Definition: Type.h:319
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:482
GC getObjCGCAttr() const
Definition: Type.h:506
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:341
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:337
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
bool hasCVRQualifiers() const
Definition: Type.h:474
bool hasUnaligned() const
Definition: Type.h:498
unsigned getAddressSpaceAttributePrintValue() const
Get the address space attribute value to be printed by diagnostics.
Definition: Type.h:565
void setAddressSpace(LangAS space)
Definition: Type.h:578
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:695
unsigned getCVRUQualifiers() const
Definition: Type.h:476
void setObjCGCAttr(GC type)
Definition: Type.h:507
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition: Type.h:428
LangAS getAddressSpace() const
Definition: Type.h:558
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:535
Represents a struct/union/class.
Definition: Decl.h:4145
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition: Decl.h:4274
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
RecordDecl * getDecl() const
Definition: Type.h:5975
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
Represents the body of a requires-expression.
Definition: DeclCXX.h:2033
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:2212
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
@ 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:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
Sema & SemaRef
Definition: SemaBase.h:40
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:819
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:320
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:227
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
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.
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition: SemaPPC.cpp:259
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:3023
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:10056
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12099
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12129
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name)
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
QualType CheckSizelessVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6329
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:763
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
Definition: SemaType.cpp:2018
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:7873
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9015
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition: Sema.h:9030
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9018
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:9060
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:412
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
VariadicCallType
Definition: Sema.h:2346
@ VariadicDoesNotApply
Definition: Sema.h:2351
@ VariadicFunction
Definition: Sema.h:2347
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
bool CheckCXXThisType(SourceLocation Loc, QualType Type)
Check whether the type of 'this' is valid in the current context.
TypeResult ActOnTemplateIdType(Scope *S, 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)
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition: Sema.h:8485
@ IER_DoesNotExist
The symbol does not exist.
Definition: Sema.h:8490
@ IER_Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
Definition: Sema.h:8494
@ IER_Error
An error occurred.
Definition: Sema.h:8497
@ IER_Exists
The symbol exists.
Definition: Sema.h:8487
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1551
ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
ActOnExpressionTrait - Parsed one of the unary type trait support pseudo-functions.
SemaCUDA & CUDA()
Definition: Sema.h:1124
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...
Definition: SemaExpr.cpp:20133
ConditionKind
Definition: Sema.h:7371
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
@ Switch
An integral condition for a 'switch' statement.
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:900
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10148
@ AR_inaccessible
Definition: Sema.h:1314
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
Definition: SemaCast.cpp:3367
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)
Definition: SemaExpr.cpp:18205
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:16940
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
Definition: SemaExpr.cpp:10064
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1710
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 * 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:1567
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:
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1058
ASTContext & Context
Definition: Sema.h:962
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:626
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc)
ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a C++ typeid expression with a type operand.
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
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...
Definition: SemaExpr.cpp:7821
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1164
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....
@ AllowFold
Definition: Sema.h:7265
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1496
ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19414
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
ASTContext & getASTContext() const
Definition: Sema.h:560
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.
Definition: SemaExpr.cpp:18696
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15085
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9505
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
bool CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N)
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:702
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.
Definition: SemaExpr.cpp:6132
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)
ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen)
ActOnArrayTypeTrait - Parsed one of the binary type trait support pseudo-functions.
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:868
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2198
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition: Sema.h:7987
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...
Definition: SemaStmt.cpp:3238
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 CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
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:225
FPOptions & getCurFPFeatures()
Definition: Sema.h:555
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
@ UPPC_IfExists
Microsoft __if_exists.
Definition: Sema.h:13948
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition: Sema.h:13951
const LangOptions & getLangOpts() const
Definition: Sema.h:553
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...
Definition: SemaExpr.cpp:7220
SemaOpenACC & OpenACC()
Definition: Sema.h:1169
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:961
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization)
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14375
const LangOptions & LangOpts
Definition: Sema.h:960
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2409
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.
Definition: SemaInit.cpp:7485
SemaHLSL & HLSL()
Definition: Sema.h:1129
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,...
Definition: SemaExpr.cpp:17263
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:73
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.
Definition: SemaExpr.cpp:19813
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:6487
ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc)
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.
ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen)
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:785
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.
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)
Definition: SemaExpr.cpp:10323
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6484
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
Definition: SemaInit.cpp:9726
void MarkThisReferenced(CXXThisExpr *This)
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3175
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7804
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9613
static bool isCast(CheckedConversionKind CCK)
Definition: Sema.h:2115
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7597
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1097
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true, bool WantSize=false, bool WantAligned=false)
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5776
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...
Definition: SemaExpr.cpp:7843
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType)
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7796
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1547
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7599
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7601
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7680
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).
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:7426
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:7998
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4093
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20717
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17162
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:13497
SourceManager & getSourceManager() const
Definition: Sema.h:558
@ TryCapture_Implicit
Definition: Sema.h:6614
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition: Sema.h:8069
AssignmentAction
Definition: Sema.h:6495
@ AA_Returning
Definition: Sema.h:6498
@ AA_Passing_CFAudited
Definition: Sema.h:6503
@ AA_Initializing
Definition: Sema.h:6500
@ AA_Converting
Definition: Sema.h:6499
@ AA_Assigning
Definition: Sema.h:6496
@ AA_Passing
Definition: Sema.h:6497
@ AA_Casting
Definition: Sema.h:6502
@ AA_Sending
Definition: Sema.h:6501
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.
Definition: SemaStmt.cpp:3373
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
CanThrowResult canThrow(const Stmt *E)
bool isThisOutsideMemberFunctionBody(QualType BaseType)
Determine whether the given type is the type of *this that is used outside of the body of a member fu...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
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)
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?: under C++ semantics.
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
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.
Definition: SemaDecl.cpp:8198
ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo &Name)
Handle the result of the special case name lookup for inheriting constructor declarations.
Definition: SemaExprCXX.cpp:58
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:14945
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:7994
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:10027
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
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:288
ASTConsumer & Consumer
Definition: Sema.h:963
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:6491
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16406
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
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...
Definition: SemaType.cpp:9492
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5653
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20007
SemaPPC & PPC()
Definition: Sema.h:1184
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8907
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:923
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.
Definition: SemaExpr.cpp:20647
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:8005
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17681
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7946
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1307
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
DiagnosticsEngine & Diags
Definition: Sema.h:964
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:516
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9656
ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef< ParsedType > Args, SourceLocation RParenLoc)
Parsed one of the type trait support pseudo-functions.
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:1771
concepts::NestedRequirement * BuildNestedRequirement(Expr *E)
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
Definition: SemaType.cpp:9506
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen)
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...
Definition: SemaExpr.cpp:16607
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,...
Definition: SemaExpr.cpp:17862
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5893
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1967
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20914
ParsedType getConstructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:92
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:7991
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9083
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
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)
Definition: SemaType.cpp:2731
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:7358
IdentifierResolver IdResolver
Definition: Sema.h:3016
const TypoExprState & getTypoExprState(TypoExpr *TE) const
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:7314
ExprResult ActOnCXXThis(SourceLocation Loc)
ExprResult ActOnDecltypeExpression(Expr *E)
Process the expression contained within a decltype.
AllocationFunctionScope
The scope in which to find allocation functions.
Definition: Sema.h:8188
@ AFS_Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition: Sema.h:8196
@ AFS_Class
Only look for allocation functions in the scope of the allocated class.
Definition: Sema.h:8193
@ AFS_Global
Only look for allocation functions in the global scope.
Definition: Sema.h:8190
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5314
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8293
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.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:292
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:379
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:297
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:318
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:378
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:328
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:312
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition: Overload.h:308
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4417
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
StringRef getString() const
Definition: Expr.h:1855
bool isUnion() const
Definition: Decl.h:3767
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
bool isItaniumFamily() const
Does this ABI generally fall into the Itanium family of ABIs?
Definition: TargetCXXABI.h:122
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with '::operator new(size_t)' is g...
Definition: TargetInfo.h:742
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:509
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
A template argument list.
Definition: DeclTemplate.h:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
Represents a template argument.
Definition: TemplateBase.h:61
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, unsigned D, unsigned P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, std::optional< unsigned > NumExpanded=std::nullopt)
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
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:242
Represents a declaration of a type.
Definition: Decl.h:3367
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:153
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7721
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7732
static TypeTraitExpr * Create(const ASTContext &C, QualType T, SourceLocation Loc, TypeTrait Kind, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc, bool Value)
Create a new type trait expression.
Definition: ExprCXX.cpp:1877
The base class of the type hierarchy.
Definition: Type.h:1829
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:2477
bool isStructureType() const
Definition: Type.cpp:629
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isBlockPointerType() const
Definition: Type.h:8017
bool isVoidType() const
Definition: Type.h:8319
bool isBooleanType() const
Definition: Type.h:8447
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2892
bool isIncompleteArrayType() const
Definition: Type.h:8083
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8295
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2146
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
bool isRValueReferenceType() const
Definition: Type.h:8029
bool isFundamentalType() const
Tests whether the type is categorized as a fundamental type.
Definition: Type.h:7966
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isArrayType() const
Definition: Type.h:8075
bool isArithmeticType() const
Definition: Type.cpp:2281
bool isPointerType() const
Definition: Type.h:8003
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8359
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
bool isEnumeralType() const
Definition: Type.h:8107
bool isScalarType() const
Definition: Type.h:8418
bool isInterfaceType() const
Definition: Type.cpp:651
bool isVariableArrayType() const
Definition: Type.h:8087
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2510
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isExtVectorType() const
Definition: Type.h:8119
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2548
bool isMemberDataPointerType() const
Definition: Type.h:8068
bool isLValueReferenceType() const
Definition: Type.h:8025
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2338
bool isAnyComplexType() const
Definition: Type.h:8111
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8372
bool isHalfType() const
Definition: Type.h:8323
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2011
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2467
bool isCompoundType() const
Tests whether the type is categorized as a compound type.
Definition: Type.h:7977
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8490
bool isMemberPointerType() const
Definition: Type.h:8057
bool isAtomicType() const
Definition: Type.h:8158
bool isMatrixType() const
Definition: Type.h:8133
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2973
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2713
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4970
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2439
bool isPointerOrReferenceType() const
Definition: Type.h:8007
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4913
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:7999
bool isObjCObjectPointerType() const
Definition: Type.h:8145
bool isStructureOrClassType() const
Definition: Type.cpp:657
bool isMemberFunctionPointerType() const
Definition: Type.h:8061
bool isVectorType() const
Definition: Type.h:8115
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isFloatingType() const
Definition: Type.cpp:2249
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2196
bool isAnyPointerType() const
Definition: Type.h:8011
bool isClassType() const
Definition: Type.cpp:623
TypeClass getTypeClass() const
Definition: Type.h:2334
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:4919
bool isNullPtrType() const
Definition: Type.h:8352
bool isRecordType() const
Definition: Type.h:8103
bool isObjCRetainableType() const
Definition: Type.cpp:4950
bool isUnionType() const
Definition: Type.cpp:671
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1890
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition: Type.cpp:688
Simple class containing the result of Sema::CorrectTypo.
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:6777
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1086
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition: DeclSpec.h:1056
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1110
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1080
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
QualType getType() const
Definition: Decl.h:678
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5364
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3339
Represents a variable declaration or definition.
Definition: Decl.h:879
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2172
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:2493
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1306
Represents a GCC generic vector type.
Definition: Type.h:4021
unsigned getNumElements() const
Definition: Type.h:4036
TemplateParameterList * getTypeConstraintTemplateParameterList() const
Definition: ExprConcepts.h:347
A requires-expression requirement which queries the validity and properties of an expression ('simple...
Definition: ExprConcepts.h:280
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:429
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:168
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:225
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:752
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1093
SourceLocation PotentialThisCaptureLocation
Definition: ScopeInfo.h:950
bool hasPotentialThisCapture() const
Definition: ScopeInfo.h:999
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:878
bool lambdaCaptureShouldBeConst() const
Definition: ScopeInfo.cpp:252
bool hasPotentialCaptures() const
Definition: ScopeInfo.h:1065
bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const
Definition: ScopeInfo.h:1048
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
void visitPotentialCaptures(llvm::function_ref< void(ValueDecl *, Expr *)> Callback) const
Definition: ScopeInfo.cpp:236
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:886
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
Requirement::SubstitutionDiagnostic * createSubstDiagAt(Sema &S, SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using Sema's a...
bool NE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1090
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
llvm::cl::opt< std::string > Filter
The JSON file list parser is used to communicate input to InstallAPI.
@ Bind
'bind' clause, allowed on routine constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
bool isLambdaCallWithImplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:43
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
ArrayTypeTrait
Names for the array type traits.
Definition: TypeTraits.h:42
@ CPlusPlus23
Definition: LangStandard.h:61
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus17
Definition: LangStandard.h:59
unsigned getTypeTraitArity(TypeTrait T) LLVM_READONLY
Return the arity of the type trait T.
Definition: TypeTraits.cpp:107
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
CanThrowResult
Possible results from evaluation of a noexcept expression.
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:180
bool isReservedInAllContexts(ReservedIdentifierStatus Status)
Determine whether an identifier is reserved in all contexts.
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1778
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1781
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1784
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition: Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition: Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:154
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
@ IK_TemplateId
A template-id, e.g., f<int>.
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
@ IK_Identifier
An identifier.
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
@ SC_None
Definition: Specifiers.h:250
@ OMF_performSelector
StmtResult StmtError()
Definition: Ownership.h:265
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition: Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition: Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition: Overload.h:205
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition: Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition: Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition: Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition: Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition: Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition: Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition: Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition: Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition: Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition: Overload.h:208
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition: Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition: Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition: Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition: Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition: Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition: Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition: Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition: Overload.h:124
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition: Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition: Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition: Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition: Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS)
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
@ Class
The "class" keyword.
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:229
const FunctionProtoType * T
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:345
@ Success
Template argument deduction was successful.
@ AlreadyDiagnosed
Some error which was already diagnosed.
@ Generic
not a target-specific vector type
@ None
No keyword precedes the qualified type name.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
ReservedIdentifierStatus
@ Other
Other implicit parameter.
TypeTrait
Names for traits that operate specifically on types.
Definition: TypeTraits.h:21
@ BTT_Last
Definition: TypeTraits.h:30
@ UTT_Last
Definition: TypeTraits.h:24
CXXNewInitializationStyle
Definition: ExprCXX.h:2226
@ Parens
New-expression has a C++98 paren-delimited initializer.
@ None
New-expression has no initializer as written.
@ Braces
New-expression has a C++11 list-initializer.
@ EST_DynamicNone
throw()
@ EST_BasicNoexcept
noexcept
@ EST_Dynamic
throw(T1, T2)
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:414
@ CStyleCast
A C-style cast.
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
@ FunctionalCast
A functional-style cast.
@ AS_public
Definition: Specifiers.h:124
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:89
static ASTConstraintSatisfaction * Rebuild(const ASTContext &C, const ASTConstraintSatisfaction &Satisfaction)
Definition: ASTConcept.cpp:70
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:1312
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1321
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1251
ArrayTypeInfo Arr
Definition: DeclSpec.h:1641
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1259
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5061
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5064
Extra information about a function prototype.
Definition: Type.h:5087
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5094
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5088
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4268
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:872
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:10156
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:434
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:456
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:447
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:451
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:442
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:461