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:
1650 // If the type is cv void and the initializer is (), the expression is a
1651 // prvalue of the specified type that performs no initialization.
1652 if (!Ty->isVoidType() &&
1653 RequireCompleteType(TyBeginLoc, ElemTy,
1654 diag::err_invalid_incomplete_type_use, FullRange))
1655 return ExprError();
1656
1657 // Otherwise, the expression is a prvalue of the specified type whose
1658 // result object is direct-initialized (11.6) with the initializer.
1659 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1660 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1661
1662 if (Result.isInvalid())
1663 return Result;
1664
1665 Expr *Inner = Result.get();
1666 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1667 Inner = BTE->getSubExpr();
1668 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1669 CE && CE->isImmediateInvocation())
1670 Inner = CE->getSubExpr();
1671 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1672 !isa<CXXScalarValueInitExpr>(Inner)) {
1673 // If we created a CXXTemporaryObjectExpr, that node also represents the
1674 // functional cast. Otherwise, create an explicit cast to represent
1675 // the syntactic form of a functional-style cast that was used here.
1676 //
1677 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1678 // would give a more consistent AST representation than using a
1679 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1680 // is sometimes handled by initialization and sometimes not.
1681 QualType ResultType = Result.get()->getType();
1682 SourceRange Locs = ListInitialization
1683 ? SourceRange()
1684 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1686 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1687 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1688 Locs.getBegin(), Locs.getEnd());
1689 }
1690
1691 return Result;
1692}
1693
1695 // [CUDA] Ignore this function, if we can't call it.
1696 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1697 if (getLangOpts().CUDA) {
1698 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1699 // If it's not callable at all, it's not the right function.
1700 if (CallPreference < SemaCUDA::CFP_WrongSide)
1701 return false;
1702 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1703 // Maybe. We have to check if there are better alternatives.
1705 Method->getDeclContext()->lookup(Method->getDeclName());
1706 for (const auto *D : R) {
1707 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1708 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1709 return false;
1710 }
1711 }
1712 // We've found no better variants.
1713 }
1714 }
1715
1717 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1718
1719 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1720 return Result;
1721
1722 // In case of CUDA, return true if none of the 1-argument deallocator
1723 // functions are actually callable.
1724 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1725 assert(FD->getNumParams() == 1 &&
1726 "Only single-operand functions should be in PreventedBy");
1727 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1728 });
1729}
1730
1731/// Determine whether the given function is a non-placement
1732/// deallocation function.
1734 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1735 return S.isUsualDeallocationFunction(Method);
1736
1737 if (FD->getOverloadedOperator() != OO_Delete &&
1738 FD->getOverloadedOperator() != OO_Array_Delete)
1739 return false;
1740
1741 unsigned UsualParams = 1;
1742
1743 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1745 FD->getParamDecl(UsualParams)->getType(),
1746 S.Context.getSizeType()))
1747 ++UsualParams;
1748
1749 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1751 FD->getParamDecl(UsualParams)->getType(),
1753 ++UsualParams;
1754
1755 return UsualParams == FD->getNumParams();
1756}
1757
1758namespace {
1759 struct UsualDeallocFnInfo {
1760 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1761 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1762 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1763 Destroying(false), HasSizeT(false), HasAlignValT(false),
1764 CUDAPref(SemaCUDA::CFP_Native) {
1765 // A function template declaration is never a usual deallocation function.
1766 if (!FD)
1767 return;
1768 unsigned NumBaseParams = 1;
1769 if (FD->isDestroyingOperatorDelete()) {
1770 Destroying = true;
1771 ++NumBaseParams;
1772 }
1773
1774 if (NumBaseParams < FD->getNumParams() &&
1776 FD->getParamDecl(NumBaseParams)->getType(),
1777 S.Context.getSizeType())) {
1778 ++NumBaseParams;
1779 HasSizeT = true;
1780 }
1781
1782 if (NumBaseParams < FD->getNumParams() &&
1783 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1784 ++NumBaseParams;
1785 HasAlignValT = true;
1786 }
1787
1788 // In CUDA, determine how much we'd like / dislike to call this.
1789 if (S.getLangOpts().CUDA)
1790 CUDAPref = S.CUDA().IdentifyPreference(
1791 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1792 }
1793
1794 explicit operator bool() const { return FD; }
1795
1796 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1797 bool WantAlign) const {
1798 // C++ P0722:
1799 // A destroying operator delete is preferred over a non-destroying
1800 // operator delete.
1801 if (Destroying != Other.Destroying)
1802 return Destroying;
1803
1804 // C++17 [expr.delete]p10:
1805 // If the type has new-extended alignment, a function with a parameter
1806 // of type std::align_val_t is preferred; otherwise a function without
1807 // such a parameter is preferred
1808 if (HasAlignValT != Other.HasAlignValT)
1809 return HasAlignValT == WantAlign;
1810
1811 if (HasSizeT != Other.HasSizeT)
1812 return HasSizeT == WantSize;
1813
1814 // Use CUDA call preference as a tiebreaker.
1815 return CUDAPref > Other.CUDAPref;
1816 }
1817
1819 FunctionDecl *FD;
1820 bool Destroying, HasSizeT, HasAlignValT;
1822 };
1823}
1824
1825/// Determine whether a type has new-extended alignment. This may be called when
1826/// the type is incomplete (for a delete-expression with an incomplete pointee
1827/// type), in which case it will conservatively return false if the alignment is
1828/// not known.
1829static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1830 return S.getLangOpts().AlignedAllocation &&
1831 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1833}
1834
1835/// Select the correct "usual" deallocation function to use from a selection of
1836/// deallocation functions (either global or class-scope).
1837static UsualDeallocFnInfo resolveDeallocationOverload(
1838 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1839 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1840 UsualDeallocFnInfo Best;
1841
1842 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1843 UsualDeallocFnInfo Info(S, I.getPair());
1844 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1845 Info.CUDAPref == SemaCUDA::CFP_Never)
1846 continue;
1847
1848 if (!Best) {
1849 Best = Info;
1850 if (BestFns)
1851 BestFns->push_back(Info);
1852 continue;
1853 }
1854
1855 if (Best.isBetterThan(Info, WantSize, WantAlign))
1856 continue;
1857
1858 // If more than one preferred function is found, all non-preferred
1859 // functions are eliminated from further consideration.
1860 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1861 BestFns->clear();
1862
1863 Best = Info;
1864 if (BestFns)
1865 BestFns->push_back(Info);
1866 }
1867
1868 return Best;
1869}
1870
1871/// Determine whether a given type is a class for which 'delete[]' would call
1872/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1873/// we need to store the array size (even if the type is
1874/// trivially-destructible).
1876 QualType allocType) {
1877 const RecordType *record =
1878 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1879 if (!record) return false;
1880
1881 // Try to find an operator delete[] in class scope.
1882
1883 DeclarationName deleteName =
1884 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1885 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1886 S.LookupQualifiedName(ops, record->getDecl());
1887
1888 // We're just doing this for information.
1889 ops.suppressDiagnostics();
1890
1891 // Very likely: there's no operator delete[].
1892 if (ops.empty()) return false;
1893
1894 // If it's ambiguous, it should be illegal to call operator delete[]
1895 // on this thing, so it doesn't matter if we allocate extra space or not.
1896 if (ops.isAmbiguous()) return false;
1897
1898 // C++17 [expr.delete]p10:
1899 // If the deallocation functions have class scope, the one without a
1900 // parameter of type std::size_t is selected.
1901 auto Best = resolveDeallocationOverload(
1902 S, ops, /*WantSize*/false,
1903 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1904 return Best && Best.HasSizeT;
1905}
1906
1908Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1909 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1910 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1912 std::optional<Expr *> ArraySize;
1913 // If the specified type is an array, unwrap it and save the expression.
1914 if (D.getNumTypeObjects() > 0 &&
1915 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1916 DeclaratorChunk &Chunk = D.getTypeObject(0);
1917 if (D.getDeclSpec().hasAutoTypeSpec())
1918 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1919 << D.getSourceRange());
1920 if (Chunk.Arr.hasStatic)
1921 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1922 << D.getSourceRange());
1923 if (!Chunk.Arr.NumElts && !Initializer)
1924 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1925 << D.getSourceRange());
1926
1927 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1928 D.DropFirstTypeObject();
1929 }
1930
1931 // Every dimension shall be of constant size.
1932 if (ArraySize) {
1933 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1934 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1935 break;
1936
1937 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1938 if (Expr *NumElts = (Expr *)Array.NumElts) {
1939 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1940 // FIXME: GCC permits constant folding here. We should either do so consistently
1941 // or not do so at all, rather than changing behavior in C++14 onwards.
1942 if (getLangOpts().CPlusPlus14) {
1943 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1944 // shall be a converted constant expression (5.19) of type std::size_t
1945 // and shall evaluate to a strictly positive value.
1946 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1947 Array.NumElts
1950 .get();
1951 } else {
1952 Array.NumElts =
1954 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1955 .get();
1956 }
1957 if (!Array.NumElts)
1958 return ExprError();
1959 }
1960 }
1961 }
1962 }
1963
1965 QualType AllocType = TInfo->getType();
1966 if (D.isInvalidType())
1967 return ExprError();
1968
1969 SourceRange DirectInitRange;
1970 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1971 DirectInitRange = List->getSourceRange();
1972
1973 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1974 PlacementLParen, PlacementArgs, PlacementRParen,
1975 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1976 Initializer);
1977}
1978
1980 Expr *Init, bool IsCPlusPlus20) {
1981 if (!Init)
1982 return true;
1983 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1984 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
1985 if (isa<ImplicitValueInitExpr>(Init))
1986 return true;
1987 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1988 return !CCE->isListInitialization() &&
1989 CCE->getConstructor()->isDefaultConstructor();
1990 else if (Style == CXXNewInitializationStyle::Braces) {
1991 assert(isa<InitListExpr>(Init) &&
1992 "Shouldn't create list CXXConstructExprs for arrays.");
1993 return true;
1994 }
1995 return false;
1996}
1997
1998bool
2000 if (!getLangOpts().AlignedAllocationUnavailable)
2001 return false;
2002 if (FD.isDefined())
2003 return false;
2004 std::optional<unsigned> AlignmentParam;
2005 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2006 AlignmentParam)
2007 return true;
2008 return false;
2009}
2010
2011// Emit a diagnostic if an aligned allocation/deallocation function that is not
2012// implemented in the standard library is selected.
2016 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2017 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2018 getASTContext().getTargetInfo().getPlatformName());
2019 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2020
2022 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
2023 Diag(Loc, diag::err_aligned_allocation_unavailable)
2024 << IsDelete << FD.getType().getAsString() << OSName
2025 << OSVersion.getAsString() << OSVersion.empty();
2026 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2027 }
2028}
2029
2031 SourceLocation PlacementLParen,
2032 MultiExprArg PlacementArgs,
2033 SourceLocation PlacementRParen,
2034 SourceRange TypeIdParens, QualType AllocType,
2035 TypeSourceInfo *AllocTypeInfo,
2036 std::optional<Expr *> ArraySize,
2037 SourceRange DirectInitRange, Expr *Initializer) {
2038 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2039 SourceLocation StartLoc = Range.getBegin();
2040
2041 CXXNewInitializationStyle InitStyle;
2042 if (DirectInitRange.isValid()) {
2043 assert(Initializer && "Have parens but no initializer.");
2045 } else if (isa_and_nonnull<InitListExpr>(Initializer))
2047 else {
2048 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2049 isa<CXXConstructExpr>(Initializer)) &&
2050 "Initializer expression that cannot have been implicitly created.");
2052 }
2053
2054 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2055 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2056 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2057 "paren init for non-call init");
2058 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2059 }
2060
2061 // C++11 [expr.new]p15:
2062 // A new-expression that creates an object of type T initializes that
2063 // object as follows:
2064 InitializationKind Kind = [&] {
2065 switch (InitStyle) {
2066 // - If the new-initializer is omitted, the object is default-
2067 // initialized (8.5); if no initialization is performed,
2068 // the object has indeterminate value
2070 return InitializationKind::CreateDefault(TypeRange.getBegin());
2071 // - Otherwise, the new-initializer is interpreted according to the
2072 // initialization rules of 8.5 for direct-initialization.
2074 return InitializationKind::CreateDirect(TypeRange.getBegin(),
2075 DirectInitRange.getBegin(),
2076 DirectInitRange.getEnd());
2079 Initializer->getBeginLoc(),
2080 Initializer->getEndLoc());
2081 }
2082 llvm_unreachable("Unknown initialization kind");
2083 }();
2084
2085 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2086 auto *Deduced = AllocType->getContainedDeducedType();
2087 if (Deduced && !Deduced->isDeduced() &&
2088 isa<DeducedTemplateSpecializationType>(Deduced)) {
2089 if (ArraySize)
2090 return ExprError(
2091 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2092 diag::err_deduced_class_template_compound_type)
2093 << /*array*/ 2
2094 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2095
2096 InitializedEntity Entity
2097 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2099 AllocTypeInfo, Entity, Kind, Exprs);
2100 if (AllocType.isNull())
2101 return ExprError();
2102 } else if (Deduced && !Deduced->isDeduced()) {
2103 MultiExprArg Inits = Exprs;
2104 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2105 if (Braced) {
2106 auto *ILE = cast<InitListExpr>(Exprs[0]);
2107 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2108 }
2109
2110 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2111 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2112 << AllocType << TypeRange);
2113 if (Inits.size() > 1) {
2114 Expr *FirstBad = Inits[1];
2115 return ExprError(Diag(FirstBad->getBeginLoc(),
2116 diag::err_auto_new_ctor_multiple_expressions)
2117 << AllocType << TypeRange);
2118 }
2119 if (Braced && !getLangOpts().CPlusPlus17)
2120 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2121 << AllocType << TypeRange;
2122 Expr *Deduce = Inits[0];
2123 if (isa<InitListExpr>(Deduce))
2124 return ExprError(
2125 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2126 << Braced << AllocType << TypeRange);
2128 TemplateDeductionInfo Info(Deduce->getExprLoc());
2130 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2133 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2134 << AllocType << Deduce->getType() << TypeRange
2135 << Deduce->getSourceRange());
2136 if (DeducedType.isNull()) {
2138 return ExprError();
2139 }
2140 AllocType = DeducedType;
2141 }
2142
2143 // Per C++0x [expr.new]p5, the type being constructed may be a
2144 // typedef of an array type.
2145 if (!ArraySize) {
2146 if (const ConstantArrayType *Array
2147 = Context.getAsConstantArrayType(AllocType)) {
2148 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2150 TypeRange.getEnd());
2151 AllocType = Array->getElementType();
2152 }
2153 }
2154
2155 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2156 return ExprError();
2157
2158 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2159 return ExprError();
2160
2161 // In ARC, infer 'retaining' for the allocated
2162 if (getLangOpts().ObjCAutoRefCount &&
2163 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2164 AllocType->isObjCLifetimeType()) {
2165 AllocType = Context.getLifetimeQualifiedType(AllocType,
2166 AllocType->getObjCARCImplicitLifetime());
2167 }
2168
2169 QualType ResultType = Context.getPointerType(AllocType);
2170
2171 if (ArraySize && *ArraySize &&
2172 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2173 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2174 if (result.isInvalid()) return ExprError();
2175 ArraySize = result.get();
2176 }
2177 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2178 // integral or enumeration type with a non-negative value."
2179 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2180 // enumeration type, or a class type for which a single non-explicit
2181 // conversion function to integral or unscoped enumeration type exists.
2182 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2183 // std::size_t.
2184 std::optional<uint64_t> KnownArraySize;
2185 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2186 ExprResult ConvertedSize;
2187 if (getLangOpts().CPlusPlus14) {
2188 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2189
2190 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2192
2193 if (!ConvertedSize.isInvalid() &&
2194 (*ArraySize)->getType()->getAs<RecordType>())
2195 // Diagnose the compatibility of this conversion.
2196 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2197 << (*ArraySize)->getType() << 0 << "'size_t'";
2198 } else {
2199 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2200 protected:
2201 Expr *ArraySize;
2202
2203 public:
2204 SizeConvertDiagnoser(Expr *ArraySize)
2205 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2206 ArraySize(ArraySize) {}
2207
2208 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2209 QualType T) override {
2210 return S.Diag(Loc, diag::err_array_size_not_integral)
2211 << S.getLangOpts().CPlusPlus11 << T;
2212 }
2213
2214 SemaDiagnosticBuilder diagnoseIncomplete(
2215 Sema &S, SourceLocation Loc, QualType T) override {
2216 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2217 << T << ArraySize->getSourceRange();
2218 }
2219
2220 SemaDiagnosticBuilder diagnoseExplicitConv(
2221 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2222 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2223 }
2224
2225 SemaDiagnosticBuilder noteExplicitConv(
2226 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2227 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2228 << ConvTy->isEnumeralType() << ConvTy;
2229 }
2230
2231 SemaDiagnosticBuilder diagnoseAmbiguous(
2232 Sema &S, SourceLocation Loc, QualType T) override {
2233 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2234 }
2235
2236 SemaDiagnosticBuilder noteAmbiguous(
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 diagnoseConversion(Sema &S, SourceLocation Loc,
2243 QualType T,
2244 QualType ConvTy) override {
2245 return S.Diag(Loc,
2246 S.getLangOpts().CPlusPlus11
2247 ? diag::warn_cxx98_compat_array_size_conversion
2248 : diag::ext_array_size_conversion)
2249 << T << ConvTy->isEnumeralType() << ConvTy;
2250 }
2251 } SizeDiagnoser(*ArraySize);
2252
2253 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2254 SizeDiagnoser);
2255 }
2256 if (ConvertedSize.isInvalid())
2257 return ExprError();
2258
2259 ArraySize = ConvertedSize.get();
2260 QualType SizeType = (*ArraySize)->getType();
2261
2262 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2263 return ExprError();
2264
2265 // C++98 [expr.new]p7:
2266 // The expression in a direct-new-declarator shall have integral type
2267 // with a non-negative value.
2268 //
2269 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2270 // per CWG1464. Otherwise, if it's not a constant, we must have an
2271 // unparenthesized array type.
2272
2273 // We've already performed any required implicit conversion to integer or
2274 // unscoped enumeration type.
2275 // FIXME: Per CWG1464, we are required to check the value prior to
2276 // converting to size_t. This will never find a negative array size in
2277 // C++14 onwards, because Value is always unsigned here!
2278 if (std::optional<llvm::APSInt> Value =
2279 (*ArraySize)->getIntegerConstantExpr(Context)) {
2280 if (Value->isSigned() && Value->isNegative()) {
2281 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2282 diag::err_typecheck_negative_array_size)
2283 << (*ArraySize)->getSourceRange());
2284 }
2285
2286 if (!AllocType->isDependentType()) {
2287 unsigned ActiveSizeBits =
2289 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2290 return ExprError(
2291 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2292 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2293 }
2294
2295 KnownArraySize = Value->getZExtValue();
2296 } else if (TypeIdParens.isValid()) {
2297 // Can't have dynamic array size when the type-id is in parentheses.
2298 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2299 << (*ArraySize)->getSourceRange()
2300 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2301 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2302
2303 TypeIdParens = SourceRange();
2304 }
2305
2306 // Note that we do *not* convert the argument in any way. It can
2307 // be signed, larger than size_t, whatever.
2308 }
2309
2310 FunctionDecl *OperatorNew = nullptr;
2311 FunctionDecl *OperatorDelete = nullptr;
2312 unsigned Alignment =
2313 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2314 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2315 bool PassAlignment = getLangOpts().AlignedAllocation &&
2316 Alignment > NewAlignment;
2317
2318 if (CheckArgsForPlaceholders(PlacementArgs))
2319 return ExprError();
2320
2322 if (!AllocType->isDependentType() &&
2323 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2325 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2326 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2327 OperatorNew, OperatorDelete))
2328 return ExprError();
2329
2330 // If this is an array allocation, compute whether the usual array
2331 // deallocation function for the type has a size_t parameter.
2332 bool UsualArrayDeleteWantsSize = false;
2333 if (ArraySize && !AllocType->isDependentType())
2334 UsualArrayDeleteWantsSize =
2335 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2336
2337 SmallVector<Expr *, 8> AllPlaceArgs;
2338 if (OperatorNew) {
2339 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2340 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2342
2343 // We've already converted the placement args, just fill in any default
2344 // arguments. Skip the first parameter because we don't have a corresponding
2345 // argument. Skip the second parameter too if we're passing in the
2346 // alignment; we've already filled it in.
2347 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2348 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2349 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2350 CallType))
2351 return ExprError();
2352
2353 if (!AllPlaceArgs.empty())
2354 PlacementArgs = AllPlaceArgs;
2355
2356 // We would like to perform some checking on the given `operator new` call,
2357 // but the PlacementArgs does not contain the implicit arguments,
2358 // namely allocation size and maybe allocation alignment,
2359 // so we need to conjure them.
2360
2361 QualType SizeTy = Context.getSizeType();
2362 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2363
2364 llvm::APInt SingleEltSize(
2365 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2366
2367 // How many bytes do we want to allocate here?
2368 std::optional<llvm::APInt> AllocationSize;
2369 if (!ArraySize && !AllocType->isDependentType()) {
2370 // For non-array operator new, we only want to allocate one element.
2371 AllocationSize = SingleEltSize;
2372 } else if (KnownArraySize && !AllocType->isDependentType()) {
2373 // For array operator new, only deal with static array size case.
2374 bool Overflow;
2375 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2376 .umul_ov(SingleEltSize, Overflow);
2377 (void)Overflow;
2378 assert(
2379 !Overflow &&
2380 "Expected that all the overflows would have been handled already.");
2381 }
2382
2383 IntegerLiteral AllocationSizeLiteral(
2384 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2385 SizeTy, SourceLocation());
2386 // Otherwise, if we failed to constant-fold the allocation size, we'll
2387 // just give up and pass-in something opaque, that isn't a null pointer.
2388 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2389 OK_Ordinary, /*SourceExpr=*/nullptr);
2390
2391 // Let's synthesize the alignment argument in case we will need it.
2392 // Since we *really* want to allocate these on stack, this is slightly ugly
2393 // because there might not be a `std::align_val_t` type.
2395 QualType AlignValT =
2397 IntegerLiteral AlignmentLiteral(
2398 Context,
2399 llvm::APInt(Context.getTypeSize(SizeTy),
2400 Alignment / Context.getCharWidth()),
2401 SizeTy, SourceLocation());
2402 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2403 CK_IntegralCast, &AlignmentLiteral,
2405
2406 // Adjust placement args by prepending conjured size and alignment exprs.
2408 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2409 CallArgs.emplace_back(AllocationSize
2410 ? static_cast<Expr *>(&AllocationSizeLiteral)
2411 : &OpaqueAllocationSize);
2412 if (PassAlignment)
2413 CallArgs.emplace_back(&DesiredAlignment);
2414 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2415
2416 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2417
2418 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2419 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2420
2421 // Warn if the type is over-aligned and is being allocated by (unaligned)
2422 // global operator new.
2423 if (PlacementArgs.empty() && !PassAlignment &&
2424 (OperatorNew->isImplicit() ||
2425 (OperatorNew->getBeginLoc().isValid() &&
2426 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2427 if (Alignment > NewAlignment)
2428 Diag(StartLoc, diag::warn_overaligned_type)
2429 << AllocType
2430 << unsigned(Alignment / Context.getCharWidth())
2431 << unsigned(NewAlignment / Context.getCharWidth());
2432 }
2433 }
2434
2435 // Array 'new' can't have any initializers except empty parentheses.
2436 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2437 // dialect distinction.
2438 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2440 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2441 Exprs.back()->getEndLoc());
2442 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2443 return ExprError();
2444 }
2445
2446 // If we can perform the initialization, and we've not already done so,
2447 // do it now.
2448 if (!AllocType->isDependentType() &&
2450 // The type we initialize is the complete type, including the array bound.
2451 QualType InitType;
2452 if (KnownArraySize)
2453 InitType = Context.getConstantArrayType(
2454 AllocType,
2455 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2456 *KnownArraySize),
2457 *ArraySize, ArraySizeModifier::Normal, 0);
2458 else if (ArraySize)
2459 InitType = Context.getIncompleteArrayType(AllocType,
2461 else
2462 InitType = AllocType;
2463
2464 InitializedEntity Entity
2465 = InitializedEntity::InitializeNew(StartLoc, InitType);
2466 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2467 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2468 if (FullInit.isInvalid())
2469 return ExprError();
2470
2471 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2472 // we don't want the initialized object to be destructed.
2473 // FIXME: We should not create these in the first place.
2474 if (CXXBindTemporaryExpr *Binder =
2475 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2476 FullInit = Binder->getSubExpr();
2477
2478 Initializer = FullInit.get();
2479
2480 // FIXME: If we have a KnownArraySize, check that the array bound of the
2481 // initializer is no greater than that constant value.
2482
2483 if (ArraySize && !*ArraySize) {
2484 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2485 if (CAT) {
2486 // FIXME: Track that the array size was inferred rather than explicitly
2487 // specified.
2488 ArraySize = IntegerLiteral::Create(
2489 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2490 } else {
2491 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2492 << Initializer->getSourceRange();
2493 }
2494 }
2495 }
2496
2497 // Mark the new and delete operators as referenced.
2498 if (OperatorNew) {
2499 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2500 return ExprError();
2501 MarkFunctionReferenced(StartLoc, OperatorNew);
2502 }
2503 if (OperatorDelete) {
2504 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2505 return ExprError();
2506 MarkFunctionReferenced(StartLoc, OperatorDelete);
2507 }
2508
2509 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2510 PassAlignment, UsualArrayDeleteWantsSize,
2511 PlacementArgs, TypeIdParens, ArraySize, InitStyle,
2512 Initializer, ResultType, AllocTypeInfo, Range,
2513 DirectInitRange);
2514}
2515
2517 SourceRange R) {
2518 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2519 // abstract class type or array thereof.
2520 if (AllocType->isFunctionType())
2521 return Diag(Loc, diag::err_bad_new_type)
2522 << AllocType << 0 << R;
2523 else if (AllocType->isReferenceType())
2524 return Diag(Loc, diag::err_bad_new_type)
2525 << AllocType << 1 << R;
2526 else if (!AllocType->isDependentType() &&
2528 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2529 return true;
2530 else if (RequireNonAbstractType(Loc, AllocType,
2531 diag::err_allocation_of_abstract_type))
2532 return true;
2533 else if (AllocType->isVariablyModifiedType())
2534 return Diag(Loc, diag::err_variably_modified_new_type)
2535 << AllocType;
2536 else if (AllocType.getAddressSpace() != LangAS::Default &&
2537 !getLangOpts().OpenCLCPlusPlus)
2538 return Diag(Loc, diag::err_address_space_qualified_new)
2539 << AllocType.getUnqualifiedType()
2541 else if (getLangOpts().ObjCAutoRefCount) {
2542 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2543 QualType BaseAllocType = Context.getBaseElementType(AT);
2544 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2545 BaseAllocType->isObjCLifetimeType())
2546 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2547 << BaseAllocType;
2548 }
2549 }
2550
2551 return false;
2552}
2553
2556 bool &PassAlignment, FunctionDecl *&Operator,
2557 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2558 OverloadCandidateSet Candidates(R.getNameLoc(),
2560 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2561 Alloc != AllocEnd; ++Alloc) {
2562 // Even member operator new/delete are implicitly treated as
2563 // static, so don't use AddMemberCandidate.
2564 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2565
2566 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2567 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2568 /*ExplicitTemplateArgs=*/nullptr, Args,
2569 Candidates,
2570 /*SuppressUserConversions=*/false);
2571 continue;
2572 }
2573
2574 FunctionDecl *Fn = cast<FunctionDecl>(D);
2575 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2576 /*SuppressUserConversions=*/false);
2577 }
2578
2579 // Do the resolution.
2581 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2582 case OR_Success: {
2583 // Got one!
2584 FunctionDecl *FnDecl = Best->Function;
2586 Best->FoundDecl) == Sema::AR_inaccessible)
2587 return true;
2588
2589 Operator = FnDecl;
2590 return false;
2591 }
2592
2594 // C++17 [expr.new]p13:
2595 // If no matching function is found and the allocated object type has
2596 // new-extended alignment, the alignment argument is removed from the
2597 // argument list, and overload resolution is performed again.
2598 if (PassAlignment) {
2599 PassAlignment = false;
2600 AlignArg = Args[1];
2601 Args.erase(Args.begin() + 1);
2602 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2603 Operator, &Candidates, AlignArg,
2604 Diagnose);
2605 }
2606
2607 // MSVC will fall back on trying to find a matching global operator new
2608 // if operator new[] cannot be found. Also, MSVC will leak by not
2609 // generating a call to operator delete or operator delete[], but we
2610 // will not replicate that bug.
2611 // FIXME: Find out how this interacts with the std::align_val_t fallback
2612 // once MSVC implements it.
2613 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2614 S.Context.getLangOpts().MSVCCompat) {
2615 R.clear();
2618 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2619 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2620 Operator, /*Candidates=*/nullptr,
2621 /*AlignArg=*/nullptr, Diagnose);
2622 }
2623
2624 if (Diagnose) {
2625 // If this is an allocation of the form 'new (p) X' for some object
2626 // pointer p (or an expression that will decay to such a pointer),
2627 // diagnose the missing inclusion of <new>.
2628 if (!R.isClassLookup() && Args.size() == 2 &&
2629 (Args[1]->getType()->isObjectPointerType() ||
2630 Args[1]->getType()->isArrayType())) {
2631 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2632 << R.getLookupName() << Range;
2633 // Listing the candidates is unlikely to be useful; skip it.
2634 return true;
2635 }
2636
2637 // Finish checking all candidates before we note any. This checking can
2638 // produce additional diagnostics so can't be interleaved with our
2639 // emission of notes.
2640 //
2641 // For an aligned allocation, separately check the aligned and unaligned
2642 // candidates with their respective argument lists.
2645 llvm::SmallVector<Expr*, 4> AlignedArgs;
2646 if (AlignedCandidates) {
2647 auto IsAligned = [](OverloadCandidate &C) {
2648 return C.Function->getNumParams() > 1 &&
2649 C.Function->getParamDecl(1)->getType()->isAlignValT();
2650 };
2651 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2652
2653 AlignedArgs.reserve(Args.size() + 1);
2654 AlignedArgs.push_back(Args[0]);
2655 AlignedArgs.push_back(AlignArg);
2656 AlignedArgs.append(Args.begin() + 1, Args.end());
2657 AlignedCands = AlignedCandidates->CompleteCandidates(
2658 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2659
2660 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2661 R.getNameLoc(), IsUnaligned);
2662 } else {
2663 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2664 R.getNameLoc());
2665 }
2666
2667 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2668 << R.getLookupName() << Range;
2669 if (AlignedCandidates)
2670 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2671 R.getNameLoc());
2672 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2673 }
2674 return true;
2675
2676 case OR_Ambiguous:
2677 if (Diagnose) {
2678 Candidates.NoteCandidates(
2680 S.PDiag(diag::err_ovl_ambiguous_call)
2681 << R.getLookupName() << Range),
2682 S, OCD_AmbiguousCandidates, Args);
2683 }
2684 return true;
2685
2686 case OR_Deleted: {
2687 if (Diagnose)
2689 Candidates, Best->Function, Args);
2690 return true;
2691 }
2692 }
2693 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2694}
2695
2697 AllocationFunctionScope NewScope,
2698 AllocationFunctionScope DeleteScope,
2699 QualType AllocType, bool IsArray,
2700 bool &PassAlignment, MultiExprArg PlaceArgs,
2701 FunctionDecl *&OperatorNew,
2702 FunctionDecl *&OperatorDelete,
2703 bool Diagnose) {
2704 // --- Choosing an allocation function ---
2705 // C++ 5.3.4p8 - 14 & 18
2706 // 1) If looking in AFS_Global scope for allocation functions, only look in
2707 // the global scope. Else, if AFS_Class, only look in the scope of the
2708 // allocated class. If AFS_Both, look in both.
2709 // 2) If an array size is given, look for operator new[], else look for
2710 // operator new.
2711 // 3) The first argument is always size_t. Append the arguments from the
2712 // placement form.
2713
2714 SmallVector<Expr*, 8> AllocArgs;
2715 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2716
2717 // We don't care about the actual value of these arguments.
2718 // FIXME: Should the Sema create the expression and embed it in the syntax
2719 // tree? Or should the consumer just recalculate the value?
2720 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2721 QualType SizeTy = Context.getSizeType();
2722 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2723 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
2724 SourceLocation());
2725 AllocArgs.push_back(&Size);
2726
2727 QualType AlignValT = Context.VoidTy;
2728 if (PassAlignment) {
2731 }
2732 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2733 if (PassAlignment)
2734 AllocArgs.push_back(&Align);
2735
2736 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2737
2738 // C++ [expr.new]p8:
2739 // If the allocated type is a non-array type, the allocation
2740 // function's name is operator new and the deallocation function's
2741 // name is operator delete. If the allocated type is an array
2742 // type, the allocation function's name is operator new[] and the
2743 // deallocation function's name is operator delete[].
2745 IsArray ? OO_Array_New : OO_New);
2746
2747 QualType AllocElemType = Context.getBaseElementType(AllocType);
2748
2749 // Find the allocation function.
2750 {
2751 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2752
2753 // C++1z [expr.new]p9:
2754 // If the new-expression begins with a unary :: operator, the allocation
2755 // function's name is looked up in the global scope. Otherwise, if the
2756 // allocated type is a class type T or array thereof, the allocation
2757 // function's name is looked up in the scope of T.
2758 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2759 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2760
2761 // We can see ambiguity here if the allocation function is found in
2762 // multiple base classes.
2763 if (R.isAmbiguous())
2764 return true;
2765
2766 // If this lookup fails to find the name, or if the allocated type is not
2767 // a class type, the allocation function's name is looked up in the
2768 // global scope.
2769 if (R.empty()) {
2770 if (NewScope == AFS_Class)
2771 return true;
2772
2774 }
2775
2776 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2777 if (PlaceArgs.empty()) {
2778 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2779 } else {
2780 Diag(StartLoc, diag::err_openclcxx_placement_new);
2781 }
2782 return true;
2783 }
2784
2785 assert(!R.empty() && "implicitly declared allocation functions not found");
2786 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2787
2788 // We do our own custom access checks below.
2790
2791 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2792 OperatorNew, /*Candidates=*/nullptr,
2793 /*AlignArg=*/nullptr, Diagnose))
2794 return true;
2795 }
2796
2797 // We don't need an operator delete if we're running under -fno-exceptions.
2798 if (!getLangOpts().Exceptions) {
2799 OperatorDelete = nullptr;
2800 return false;
2801 }
2802
2803 // Note, the name of OperatorNew might have been changed from array to
2804 // non-array by resolveAllocationOverload.
2806 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2807 ? OO_Array_Delete
2808 : OO_Delete);
2809
2810 // C++ [expr.new]p19:
2811 //
2812 // If the new-expression begins with a unary :: operator, the
2813 // deallocation function's name is looked up in the global
2814 // scope. Otherwise, if the allocated type is a class type T or an
2815 // array thereof, the deallocation function's name is looked up in
2816 // the scope of T. If this lookup fails to find the name, or if
2817 // the allocated type is not a class type or array thereof, the
2818 // deallocation function's name is looked up in the global scope.
2819 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2820 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2821 auto *RD =
2822 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2823 LookupQualifiedName(FoundDelete, RD);
2824 }
2825 if (FoundDelete.isAmbiguous())
2826 return true; // FIXME: clean up expressions?
2827
2828 // Filter out any destroying operator deletes. We can't possibly call such a
2829 // function in this context, because we're handling the case where the object
2830 // was not successfully constructed.
2831 // FIXME: This is not covered by the language rules yet.
2832 {
2833 LookupResult::Filter Filter = FoundDelete.makeFilter();
2834 while (Filter.hasNext()) {
2835 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2836 if (FD && FD->isDestroyingOperatorDelete())
2837 Filter.erase();
2838 }
2839 Filter.done();
2840 }
2841
2842 bool FoundGlobalDelete = FoundDelete.empty();
2843 if (FoundDelete.empty()) {
2844 FoundDelete.clear(LookupOrdinaryName);
2845
2846 if (DeleteScope == AFS_Class)
2847 return true;
2848
2851 }
2852
2853 FoundDelete.suppressDiagnostics();
2854
2856
2857 // Whether we're looking for a placement operator delete is dictated
2858 // by whether we selected a placement operator new, not by whether
2859 // we had explicit placement arguments. This matters for things like
2860 // struct A { void *operator new(size_t, int = 0); ... };
2861 // A *a = new A()
2862 //
2863 // We don't have any definition for what a "placement allocation function"
2864 // is, but we assume it's any allocation function whose
2865 // parameter-declaration-clause is anything other than (size_t).
2866 //
2867 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2868 // This affects whether an exception from the constructor of an overaligned
2869 // type uses the sized or non-sized form of aligned operator delete.
2870 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2871 OperatorNew->isVariadic();
2872
2873 if (isPlacementNew) {
2874 // C++ [expr.new]p20:
2875 // A declaration of a placement deallocation function matches the
2876 // declaration of a placement allocation function if it has the
2877 // same number of parameters and, after parameter transformations
2878 // (8.3.5), all parameter types except the first are
2879 // identical. [...]
2880 //
2881 // To perform this comparison, we compute the function type that
2882 // the deallocation function should have, and use that type both
2883 // for template argument deduction and for comparison purposes.
2884 QualType ExpectedFunctionType;
2885 {
2886 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2887
2888 SmallVector<QualType, 4> ArgTypes;
2889 ArgTypes.push_back(Context.VoidPtrTy);
2890 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2891 ArgTypes.push_back(Proto->getParamType(I));
2892
2894 // FIXME: This is not part of the standard's rule.
2895 EPI.Variadic = Proto->isVariadic();
2896
2897 ExpectedFunctionType
2898 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2899 }
2900
2901 for (LookupResult::iterator D = FoundDelete.begin(),
2902 DEnd = FoundDelete.end();
2903 D != DEnd; ++D) {
2904 FunctionDecl *Fn = nullptr;
2905 if (FunctionTemplateDecl *FnTmpl =
2906 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2907 // Perform template argument deduction to try to match the
2908 // expected function type.
2909 TemplateDeductionInfo Info(StartLoc);
2910 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2912 continue;
2913 } else
2914 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2915
2916 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2917 ExpectedFunctionType,
2918 /*AdjustExcpetionSpec*/true),
2919 ExpectedFunctionType))
2920 Matches.push_back(std::make_pair(D.getPair(), Fn));
2921 }
2922
2923 if (getLangOpts().CUDA)
2924 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2925 Matches);
2926 } else {
2927 // C++1y [expr.new]p22:
2928 // For a non-placement allocation function, the normal deallocation
2929 // function lookup is used
2930 //
2931 // Per [expr.delete]p10, this lookup prefers a member operator delete
2932 // without a size_t argument, but prefers a non-member operator delete
2933 // with a size_t where possible (which it always is in this case).
2935 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2936 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2937 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2938 &BestDeallocFns);
2939 if (Selected)
2940 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2941 else {
2942 // If we failed to select an operator, all remaining functions are viable
2943 // but ambiguous.
2944 for (auto Fn : BestDeallocFns)
2945 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2946 }
2947 }
2948
2949 // C++ [expr.new]p20:
2950 // [...] If the lookup finds a single matching deallocation
2951 // function, that function will be called; otherwise, no
2952 // deallocation function will be called.
2953 if (Matches.size() == 1) {
2954 OperatorDelete = Matches[0].second;
2955
2956 // C++1z [expr.new]p23:
2957 // If the lookup finds a usual deallocation function (3.7.4.2)
2958 // with a parameter of type std::size_t and that function, considered
2959 // as a placement deallocation function, would have been
2960 // selected as a match for the allocation function, the program
2961 // is ill-formed.
2962 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2963 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2964 UsualDeallocFnInfo Info(*this,
2965 DeclAccessPair::make(OperatorDelete, AS_public));
2966 // Core issue, per mail to core reflector, 2016-10-09:
2967 // If this is a member operator delete, and there is a corresponding
2968 // non-sized member operator delete, this isn't /really/ a sized
2969 // deallocation function, it just happens to have a size_t parameter.
2970 bool IsSizedDelete = Info.HasSizeT;
2971 if (IsSizedDelete && !FoundGlobalDelete) {
2972 auto NonSizedDelete =
2973 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2974 /*WantAlign*/Info.HasAlignValT);
2975 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2976 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2977 IsSizedDelete = false;
2978 }
2979
2980 if (IsSizedDelete) {
2981 SourceRange R = PlaceArgs.empty()
2982 ? SourceRange()
2983 : SourceRange(PlaceArgs.front()->getBeginLoc(),
2984 PlaceArgs.back()->getEndLoc());
2985 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2986 if (!OperatorDelete->isImplicit())
2987 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2988 << DeleteName;
2989 }
2990 }
2991
2992 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2993 Matches[0].first);
2994 } else if (!Matches.empty()) {
2995 // We found multiple suitable operators. Per [expr.new]p20, that means we
2996 // call no 'operator delete' function, but we should at least warn the user.
2997 // FIXME: Suppress this warning if the construction cannot throw.
2998 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2999 << DeleteName << AllocElemType;
3000
3001 for (auto &Match : Matches)
3002 Diag(Match.second->getLocation(),
3003 diag::note_member_declared_here) << DeleteName;
3004 }
3005
3006 return false;
3007}
3008
3011 return;
3012
3013 // The implicitly declared new and delete operators
3014 // are not supported in OpenCL.
3015 if (getLangOpts().OpenCLCPlusPlus)
3016 return;
3017
3018 // C++ [basic.stc.dynamic.general]p2:
3019 // The library provides default definitions for the global allocation
3020 // and deallocation functions. Some global allocation and deallocation
3021 // functions are replaceable ([new.delete]); these are attached to the
3022 // global module ([module.unit]).
3023 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3024 PushGlobalModuleFragment(SourceLocation());
3025
3026 // C++ [basic.std.dynamic]p2:
3027 // [...] The following allocation and deallocation functions (18.4) are
3028 // implicitly declared in global scope in each translation unit of a
3029 // program
3030 //
3031 // C++03:
3032 // void* operator new(std::size_t) throw(std::bad_alloc);
3033 // void* operator new[](std::size_t) throw(std::bad_alloc);
3034 // void operator delete(void*) throw();
3035 // void operator delete[](void*) throw();
3036 // C++11:
3037 // void* operator new(std::size_t);
3038 // void* operator new[](std::size_t);
3039 // void operator delete(void*) noexcept;
3040 // void operator delete[](void*) noexcept;
3041 // C++1y:
3042 // void* operator new(std::size_t);
3043 // void* operator new[](std::size_t);
3044 // void operator delete(void*) noexcept;
3045 // void operator delete[](void*) noexcept;
3046 // void operator delete(void*, std::size_t) noexcept;
3047 // void operator delete[](void*, std::size_t) noexcept;
3048 //
3049 // These implicit declarations introduce only the function names operator
3050 // new, operator new[], operator delete, operator delete[].
3051 //
3052 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3053 // "std" or "bad_alloc" as necessary to form the exception specification.
3054 // However, we do not make these implicit declarations visible to name
3055 // lookup.
3056 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3057 // The "std::bad_alloc" class has not yet been declared, so build it
3058 // implicitly.
3062 &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3063 getStdBadAlloc()->setImplicit(true);
3064
3065 // The implicitly declared "std::bad_alloc" should live in global module
3066 // fragment.
3067 if (TheGlobalModuleFragment) {
3070 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3071 }
3072 }
3073 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3074 // The "std::align_val_t" enum class has not yet been declared, so build it
3075 // implicitly.
3076 auto *AlignValT = EnumDecl::Create(
3078 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3079
3080 // The implicitly declared "std::align_val_t" should live in global module
3081 // fragment.
3082 if (TheGlobalModuleFragment) {
3083 AlignValT->setModuleOwnershipKind(
3085 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3086 }
3087
3088 AlignValT->setIntegerType(Context.getSizeType());
3089 AlignValT->setPromotionType(Context.getSizeType());
3090 AlignValT->setImplicit(true);
3091
3092 StdAlignValT = AlignValT;
3093 }
3094
3096
3098 QualType SizeT = Context.getSizeType();
3099
3100 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3101 QualType Return, QualType Param) {
3103 Params.push_back(Param);
3104
3105 // Create up to four variants of the function (sized/aligned).
3106 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3107 (Kind == OO_Delete || Kind == OO_Array_Delete);
3108 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3109
3110 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3111 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3112 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3113 if (Sized)
3114 Params.push_back(SizeT);
3115
3116 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3117 if (Aligned)
3118 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3119
3121 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3122
3123 if (Aligned)
3124 Params.pop_back();
3125 }
3126 }
3127 };
3128
3129 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3130 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3131 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3132 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3133
3134 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3135 PopGlobalModuleFragment();
3136}
3137
3138/// DeclareGlobalAllocationFunction - Declares a single implicit global
3139/// allocation function if it doesn't already exist.
3141 QualType Return,
3142 ArrayRef<QualType> Params) {
3144
3145 // Check if this function is already declared.
3146 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3147 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3148 Alloc != AllocEnd; ++Alloc) {
3149 // Only look at non-template functions, as it is the predefined,
3150 // non-templated allocation function we are trying to declare here.
3151 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3152 if (Func->getNumParams() == Params.size()) {
3154 for (auto *P : Func->parameters())
3155 FuncParams.push_back(
3156 Context.getCanonicalType(P->getType().getUnqualifiedType()));
3157 if (llvm::ArrayRef(FuncParams) == Params) {
3158 // Make the function visible to name lookup, even if we found it in
3159 // an unimported module. It either is an implicitly-declared global
3160 // allocation function, or is suppressing that function.
3161 Func->setVisibleDespiteOwningModule();
3162 return;
3163 }
3164 }
3165 }
3166 }
3167
3169 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3170
3171 QualType BadAllocType;
3172 bool HasBadAllocExceptionSpec
3173 = (Name.getCXXOverloadedOperator() == OO_New ||
3174 Name.getCXXOverloadedOperator() == OO_Array_New);
3175 if (HasBadAllocExceptionSpec) {
3176 if (!getLangOpts().CPlusPlus11) {
3177 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3178 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3180 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3181 }
3182 if (getLangOpts().NewInfallible) {
3184 }
3185 } else {
3186 EPI.ExceptionSpec =
3188 }
3189
3190 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3191 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3193 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3194 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3195 true);
3196 Alloc->setImplicit();
3197 // Global allocation functions should always be visible.
3198 Alloc->setVisibleDespiteOwningModule();
3199
3200 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3201 !getLangOpts().CheckNew)
3202 Alloc->addAttr(
3203 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3204
3205 // C++ [basic.stc.dynamic.general]p2:
3206 // The library provides default definitions for the global allocation
3207 // and deallocation functions. Some global allocation and deallocation
3208 // functions are replaceable ([new.delete]); these are attached to the
3209 // global module ([module.unit]).
3210 //
3211 // In the language wording, these functions are attched to the global
3212 // module all the time. But in the implementation, the global module
3213 // is only meaningful when we're in a module unit. So here we attach
3214 // these allocation functions to global module conditionally.
3215 if (TheGlobalModuleFragment) {
3216 Alloc->setModuleOwnershipKind(
3218 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3219 }
3220
3222 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3224 ? VisibilityAttr::Hidden
3226 ? VisibilityAttr::Protected
3227 : VisibilityAttr::Default));
3228
3230 for (QualType T : Params) {
3231 ParamDecls.push_back(ParmVarDecl::Create(
3232 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3233 /*TInfo=*/nullptr, SC_None, nullptr));
3234 ParamDecls.back()->setImplicit();
3235 }
3236 Alloc->setParams(ParamDecls);
3237 if (ExtraAttr)
3238 Alloc->addAttr(ExtraAttr);
3241 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3242 };
3243
3244 if (!LangOpts.CUDA)
3245 CreateAllocationFunctionDecl(nullptr);
3246 else {
3247 // Host and device get their own declaration so each can be
3248 // defined or re-declared independently.
3249 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3250 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3251 }
3252}
3253
3255 bool CanProvideSize,
3256 bool Overaligned,
3257 DeclarationName Name) {
3259
3260 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3262
3263 // FIXME: It's possible for this to result in ambiguity, through a
3264 // user-declared variadic operator delete or the enable_if attribute. We
3265 // should probably not consider those cases to be usual deallocation
3266 // functions. But for now we just make an arbitrary choice in that case.
3267 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3268 Overaligned);
3269 assert(Result.FD && "operator delete missing from global scope?");
3270 return Result.FD;
3271}
3272
3274 CXXRecordDecl *RD) {
3276
3277 FunctionDecl *OperatorDelete = nullptr;
3278 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3279 return nullptr;
3280 if (OperatorDelete)
3281 return OperatorDelete;
3282
3283 // If there's no class-specific operator delete, look up the global
3284 // non-array delete.
3287 Name);
3288}
3289
3291 DeclarationName Name,
3292 FunctionDecl *&Operator, bool Diagnose,
3293 bool WantSize, bool WantAligned) {
3294 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3295 // Try to find operator delete/operator delete[] in class scope.
3297
3298 if (Found.isAmbiguous())
3299 return true;
3300
3301 Found.suppressDiagnostics();
3302
3303 bool Overaligned =
3304 WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3305
3306 // C++17 [expr.delete]p10:
3307 // If the deallocation functions have class scope, the one without a
3308 // parameter of type std::size_t is selected.
3310 resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3311 /*WantAlign*/ Overaligned, &Matches);
3312
3313 // If we could find an overload, use it.
3314 if (Matches.size() == 1) {
3315 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3316
3317 // FIXME: DiagnoseUseOfDecl?
3318 if (Operator->isDeleted()) {
3319 if (Diagnose) {
3320 StringLiteral *Msg = Operator->getDeletedMessage();
3321 Diag(StartLoc, diag::err_deleted_function_use)
3322 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
3323 NoteDeletedFunction(Operator);
3324 }
3325 return true;
3326 }
3327
3328 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3329 Matches[0].Found, Diagnose) == AR_inaccessible)
3330 return true;
3331
3332 return false;
3333 }
3334
3335 // We found multiple suitable operators; complain about the ambiguity.
3336 // FIXME: The standard doesn't say to do this; it appears that the intent
3337 // is that this should never happen.
3338 if (!Matches.empty()) {
3339 if (Diagnose) {
3340 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3341 << Name << RD;
3342 for (auto &Match : Matches)
3343 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3344 }
3345 return true;
3346 }
3347
3348 // We did find operator delete/operator delete[] declarations, but
3349 // none of them were suitable.
3350 if (!Found.empty()) {
3351 if (Diagnose) {
3352 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3353 << Name << RD;
3354
3355 for (NamedDecl *D : Found)
3356 Diag(D->getUnderlyingDecl()->getLocation(),
3357 diag::note_member_declared_here) << Name;
3358 }
3359 return true;
3360 }
3361
3362 Operator = nullptr;
3363 return false;
3364}
3365
3366namespace {
3367/// Checks whether delete-expression, and new-expression used for
3368/// initializing deletee have the same array form.
3369class MismatchingNewDeleteDetector {
3370public:
3371 enum MismatchResult {
3372 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3373 NoMismatch,
3374 /// Indicates that variable is initialized with mismatching form of \a new.
3375 VarInitMismatches,
3376 /// Indicates that member is initialized with mismatching form of \a new.
3377 MemberInitMismatches,
3378 /// Indicates that 1 or more constructors' definitions could not been
3379 /// analyzed, and they will be checked again at the end of translation unit.
3380 AnalyzeLater
3381 };
3382
3383 /// \param EndOfTU True, if this is the final analysis at the end of
3384 /// translation unit. False, if this is the initial analysis at the point
3385 /// delete-expression was encountered.
3386 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3387 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3388 HasUndefinedConstructors(false) {}
3389
3390 /// Checks whether pointee of a delete-expression is initialized with
3391 /// matching form of new-expression.
3392 ///
3393 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3394 /// point where delete-expression is encountered, then a warning will be
3395 /// issued immediately. If return value is \c AnalyzeLater at the point where
3396 /// delete-expression is seen, then member will be analyzed at the end of
3397 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3398 /// couldn't be analyzed. If at least one constructor initializes the member
3399 /// with matching type of new, the return value is \c NoMismatch.
3400 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3401 /// Analyzes a class member.
3402 /// \param Field Class member to analyze.
3403 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3404 /// for deleting the \p Field.
3405 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3407 /// List of mismatching new-expressions used for initialization of the pointee
3409 /// Indicates whether delete-expression was in array form.
3410 bool IsArrayForm;
3411
3412private:
3413 const bool EndOfTU;
3414 /// Indicates that there is at least one constructor without body.
3415 bool HasUndefinedConstructors;
3416 /// Returns \c CXXNewExpr from given initialization expression.
3417 /// \param E Expression used for initializing pointee in delete-expression.
3418 /// E can be a single-element \c InitListExpr consisting of new-expression.
3419 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3420 /// Returns whether member is initialized with mismatching form of
3421 /// \c new either by the member initializer or in-class initialization.
3422 ///
3423 /// If bodies of all constructors are not visible at the end of translation
3424 /// unit or at least one constructor initializes member with the matching
3425 /// form of \c new, mismatch cannot be proven, and this function will return
3426 /// \c NoMismatch.
3427 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3428 /// Returns whether variable is initialized with mismatching form of
3429 /// \c new.
3430 ///
3431 /// If variable is initialized with matching form of \c new or variable is not
3432 /// initialized with a \c new expression, this function will return true.
3433 /// If variable is initialized with mismatching form of \c new, returns false.
3434 /// \param D Variable to analyze.
3435 bool hasMatchingVarInit(const DeclRefExpr *D);
3436 /// Checks whether the constructor initializes pointee with mismatching
3437 /// form of \c new.
3438 ///
3439 /// Returns true, if member is initialized with matching form of \c new in
3440 /// member initializer list. Returns false, if member is initialized with the
3441 /// matching form of \c new in this constructor's initializer or given
3442 /// constructor isn't defined at the point where delete-expression is seen, or
3443 /// member isn't initialized by the constructor.
3444 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3445 /// Checks whether member is initialized with matching form of
3446 /// \c new in member initializer list.
3447 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3448 /// Checks whether member is initialized with mismatching form of \c new by
3449 /// in-class initializer.
3450 MismatchResult analyzeInClassInitializer();
3451};
3452}
3453
3454MismatchingNewDeleteDetector::MismatchResult
3455MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3456 NewExprs.clear();
3457 assert(DE && "Expected delete-expression");
3458 IsArrayForm = DE->isArrayForm();
3459 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3460 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3461 return analyzeMemberExpr(ME);
3462 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3463 if (!hasMatchingVarInit(D))
3464 return VarInitMismatches;
3465 }
3466 return NoMismatch;
3467}
3468
3469const CXXNewExpr *
3470MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3471 assert(E != nullptr && "Expected a valid initializer expression");
3472 E = E->IgnoreParenImpCasts();
3473 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3474 if (ILE->getNumInits() == 1)
3475 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3476 }
3477
3478 return dyn_cast_or_null<const CXXNewExpr>(E);
3479}
3480
3481bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3482 const CXXCtorInitializer *CI) {
3483 const CXXNewExpr *NE = nullptr;
3484 if (Field == CI->getMember() &&
3485 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3486 if (NE->isArray() == IsArrayForm)
3487 return true;
3488 else
3489 NewExprs.push_back(NE);
3490 }
3491 return false;
3492}
3493
3494bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3495 const CXXConstructorDecl *CD) {
3496 if (CD->isImplicit())
3497 return false;
3498 const FunctionDecl *Definition = CD;
3500 HasUndefinedConstructors = true;
3501 return EndOfTU;
3502 }
3503 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3504 if (hasMatchingNewInCtorInit(CI))
3505 return true;
3506 }
3507 return false;
3508}
3509
3510MismatchingNewDeleteDetector::MismatchResult
3511MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3512 assert(Field != nullptr && "This should be called only for members");
3513 const Expr *InitExpr = Field->getInClassInitializer();
3514 if (!InitExpr)
3515 return EndOfTU ? NoMismatch : AnalyzeLater;
3516 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3517 if (NE->isArray() != IsArrayForm) {
3518 NewExprs.push_back(NE);
3519 return MemberInitMismatches;
3520 }
3521 }
3522 return NoMismatch;
3523}
3524
3525MismatchingNewDeleteDetector::MismatchResult
3526MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3527 bool DeleteWasArrayForm) {
3528 assert(Field != nullptr && "Analysis requires a valid class member.");
3529 this->Field = Field;
3530 IsArrayForm = DeleteWasArrayForm;
3531 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3532 for (const auto *CD : RD->ctors()) {
3533 if (hasMatchingNewInCtor(CD))
3534 return NoMismatch;
3535 }
3536 if (HasUndefinedConstructors)
3537 return EndOfTU ? NoMismatch : AnalyzeLater;
3538 if (!NewExprs.empty())
3539 return MemberInitMismatches;
3540 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3541 : NoMismatch;
3542}
3543
3544MismatchingNewDeleteDetector::MismatchResult
3545MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3546 assert(ME != nullptr && "Expected a member expression");
3547 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3548 return analyzeField(F, IsArrayForm);
3549 return NoMismatch;
3550}
3551
3552bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3553 const CXXNewExpr *NE = nullptr;
3554 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3555 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3556 NE->isArray() != IsArrayForm) {
3557 NewExprs.push_back(NE);
3558 }
3559 }
3560 return NewExprs.empty();
3561}
3562
3563static void
3565 const MismatchingNewDeleteDetector &Detector) {
3566 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3567 FixItHint H;
3568 if (!Detector.IsArrayForm)
3569 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3570 else {
3572 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3573 SemaRef.getLangOpts(), true);
3574 if (RSquare.isValid())
3575 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3576 }
3577 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3578 << Detector.IsArrayForm << H;
3579
3580 for (const auto *NE : Detector.NewExprs)
3581 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3582 << Detector.IsArrayForm;
3583}
3584
3585void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3586 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3587 return;
3588 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3589 switch (Detector.analyzeDeleteExpr(DE)) {
3590 case MismatchingNewDeleteDetector::VarInitMismatches:
3591 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3592 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3593 break;
3594 }
3595 case MismatchingNewDeleteDetector::AnalyzeLater: {
3596 DeleteExprs[Detector.Field].push_back(
3597 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3598 break;
3599 }
3600 case MismatchingNewDeleteDetector::NoMismatch:
3601 break;
3602 }
3603}
3604
3605void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3606 bool DeleteWasArrayForm) {
3607 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3608 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3609 case MismatchingNewDeleteDetector::VarInitMismatches:
3610 llvm_unreachable("This analysis should have been done for class members.");
3611 case MismatchingNewDeleteDetector::AnalyzeLater:
3612 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3613 "translation unit.");
3614 case MismatchingNewDeleteDetector::MemberInitMismatches:
3615 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3616 break;
3617 case MismatchingNewDeleteDetector::NoMismatch:
3618 break;
3619 }
3620}
3621
3623Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3624 bool ArrayForm, Expr *ExE) {
3625 // C++ [expr.delete]p1:
3626 // The operand shall have a pointer type, or a class type having a single
3627 // non-explicit conversion function to a pointer type. The result has type
3628 // void.
3629 //
3630 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3631
3632 ExprResult Ex = ExE;
3633 FunctionDecl *OperatorDelete = nullptr;
3634 bool ArrayFormAsWritten = ArrayForm;
3635 bool UsualArrayDeleteWantsSize = false;
3636
3637 if (!Ex.get()->isTypeDependent()) {
3638 // Perform lvalue-to-rvalue cast, if needed.
3639 Ex = DefaultLvalueConversion(Ex.get());
3640 if (Ex.isInvalid())
3641 return ExprError();
3642
3643 QualType Type = Ex.get()->getType();
3644
3645 class DeleteConverter : public ContextualImplicitConverter {
3646 public:
3647 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3648
3649 bool match(QualType ConvType) override {
3650 // FIXME: If we have an operator T* and an operator void*, we must pick
3651 // the operator T*.
3652 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3653 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3654 return true;
3655 return false;
3656 }
3657
3658 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3659 QualType T) override {
3660 return S.Diag(Loc, diag::err_delete_operand) << T;
3661 }
3662
3663 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3664 QualType T) override {
3665 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3666 }
3667
3668 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3669 QualType T,
3670 QualType ConvTy) override {
3671 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3672 }
3673
3674 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3675 QualType ConvTy) override {
3676 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3677 << ConvTy;
3678 }
3679
3680 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3681 QualType T) override {
3682 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3683 }
3684
3685 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3686 QualType ConvTy) override {
3687 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3688 << ConvTy;
3689 }
3690
3691 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3692 QualType T,
3693 QualType ConvTy) override {
3694 llvm_unreachable("conversion functions are permitted");
3695 }
3696 } Converter;
3697
3698 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3699 if (Ex.isInvalid())
3700 return ExprError();
3701 Type = Ex.get()->getType();
3702 if (!Converter.match(Type))
3703 // FIXME: PerformContextualImplicitConversion should return ExprError
3704 // itself in this case.
3705 return ExprError();
3706
3708 QualType PointeeElem = Context.getBaseElementType(Pointee);
3709
3710 if (Pointee.getAddressSpace() != LangAS::Default &&
3711 !getLangOpts().OpenCLCPlusPlus)
3712 return Diag(Ex.get()->getBeginLoc(),
3713 diag::err_address_space_qualified_delete)
3714 << Pointee.getUnqualifiedType()
3716
3717 CXXRecordDecl *PointeeRD = nullptr;
3718 if (Pointee->isVoidType() && !isSFINAEContext()) {
3719 // The C++ standard bans deleting a pointer to a non-object type, which
3720 // effectively bans deletion of "void*". However, most compilers support
3721 // this, so we treat it as a warning unless we're in a SFINAE context.
3722 // But we still prohibit this since C++26.
3723 Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
3724 : diag::ext_delete_void_ptr_operand)
3725 << (LangOpts.CPlusPlus26 ? Pointee : Type)
3726 << Ex.get()->getSourceRange();
3727 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3728 Pointee->isSizelessType()) {
3729 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3730 << Type << Ex.get()->getSourceRange());
3731 } else if (!Pointee->isDependentType()) {
3732 // FIXME: This can result in errors if the definition was imported from a
3733 // module but is hidden.
3734 if (!RequireCompleteType(StartLoc, Pointee,
3735 LangOpts.CPlusPlus26
3736 ? diag::err_delete_incomplete
3737 : diag::warn_delete_incomplete,
3738 Ex.get())) {
3739 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3740 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3741 }
3742 }
3743
3744 if (Pointee->isArrayType() && !ArrayForm) {
3745 Diag(StartLoc, diag::warn_delete_array_type)
3746 << Type << Ex.get()->getSourceRange()
3748 ArrayForm = true;
3749 }
3750
3752 ArrayForm ? OO_Array_Delete : OO_Delete);
3753
3754 if (PointeeRD) {
3755 if (!UseGlobal &&
3756 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3757 OperatorDelete))
3758 return ExprError();
3759
3760 // If we're allocating an array of records, check whether the
3761 // usual operator delete[] has a size_t parameter.
3762 if (ArrayForm) {
3763 // If the user specifically asked to use the global allocator,
3764 // we'll need to do the lookup into the class.
3765 if (UseGlobal)
3766 UsualArrayDeleteWantsSize =
3767 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3768
3769 // Otherwise, the usual operator delete[] should be the
3770 // function we just found.
3771 else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete))
3772 UsualArrayDeleteWantsSize =
3773 UsualDeallocFnInfo(*this,
3774 DeclAccessPair::make(OperatorDelete, AS_public))
3775 .HasSizeT;
3776 }
3777
3778 if (!PointeeRD->hasIrrelevantDestructor())
3779 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3780 MarkFunctionReferenced(StartLoc,
3781 const_cast<CXXDestructorDecl*>(Dtor));
3782 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3783 return ExprError();
3784 }
3785
3786 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3787 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3788 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3789 SourceLocation());
3790 }
3791
3792 if (!OperatorDelete) {
3793 if (getLangOpts().OpenCLCPlusPlus) {
3794 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3795 return ExprError();
3796 }
3797
3798 bool IsComplete = isCompleteType(StartLoc, Pointee);
3799 bool CanProvideSize =
3800 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3801 Pointee.isDestructedType());
3802 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3803
3804 // Look for a global declaration.
3805 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3806 Overaligned, DeleteName);
3807 }
3808
3809 if (OperatorDelete->isInvalidDecl())
3810 return ExprError();
3811
3812 MarkFunctionReferenced(StartLoc, OperatorDelete);
3813
3814 // Check access and ambiguity of destructor if we're going to call it.
3815 // Note that this is required even for a virtual delete.
3816 bool IsVirtualDelete = false;
3817 if (PointeeRD) {
3818 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3819 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3820 PDiag(diag::err_access_dtor) << PointeeElem);
3821 IsVirtualDelete = Dtor->isVirtual();
3822 }
3823 }
3824
3825 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3826
3827 // Convert the operand to the type of the first parameter of operator
3828 // delete. This is only necessary if we selected a destroying operator
3829 // delete that we are going to call (non-virtually); converting to void*
3830 // is trivial and left to AST consumers to handle.
3831 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3832 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3833 Qualifiers Qs = Pointee.getQualifiers();
3834 if (Qs.hasCVRQualifiers()) {
3835 // Qualifiers are irrelevant to this conversion; we're only looking
3836 // for access and ambiguity.
3840 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3841 }
3842 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3843 if (Ex.isInvalid())
3844 return ExprError();
3845 }
3846 }
3847
3849 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3850 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3851 AnalyzeDeleteExprMismatch(Result);
3852 return Result;
3853}
3854
3856 bool IsDelete,
3857 FunctionDecl *&Operator) {
3858
3860 IsDelete ? OO_Delete : OO_New);
3861
3862 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3864 assert(!R.empty() && "implicitly declared allocation functions not found");
3865 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3866
3867 // We do our own custom access checks below.
3869
3870 SmallVector<Expr *, 8> Args(TheCall->arguments());
3871 OverloadCandidateSet Candidates(R.getNameLoc(),
3873 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3874 FnOvl != FnOvlEnd; ++FnOvl) {
3875 // Even member operator new/delete are implicitly treated as
3876 // static, so don't use AddMemberCandidate.
3877 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3878
3879 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3880 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3881 /*ExplicitTemplateArgs=*/nullptr, Args,
3882 Candidates,
3883 /*SuppressUserConversions=*/false);
3884 continue;
3885 }
3886
3887 FunctionDecl *Fn = cast<FunctionDecl>(D);
3888 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3889 /*SuppressUserConversions=*/false);
3890 }
3891
3892 SourceRange Range = TheCall->getSourceRange();
3893
3894 // Do the resolution.
3896 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3897 case OR_Success: {
3898 // Got one!
3899 FunctionDecl *FnDecl = Best->Function;
3900 assert(R.getNamingClass() == nullptr &&
3901 "class members should not be considered");
3902
3904 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3905 << (IsDelete ? 1 : 0) << Range;
3906 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3907 << R.getLookupName() << FnDecl->getSourceRange();
3908 return true;
3909 }
3910
3911 Operator = FnDecl;
3912 return false;
3913 }
3914
3916 Candidates.NoteCandidates(
3918 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3919 << R.getLookupName() << Range),
3920 S, OCD_AllCandidates, Args);
3921 return true;
3922
3923 case OR_Ambiguous:
3924 Candidates.NoteCandidates(
3926 S.PDiag(diag::err_ovl_ambiguous_call)
3927 << R.getLookupName() << Range),
3928 S, OCD_AmbiguousCandidates, Args);
3929 return true;
3930
3931 case OR_Deleted:
3933 Candidates, Best->Function, Args);
3934 return true;
3935 }
3936 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3937}
3938
3939ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3940 bool IsDelete) {
3941 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3942 if (!getLangOpts().CPlusPlus) {
3943 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3944 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3945 << "C++";
3946 return ExprError();
3947 }
3948 // CodeGen assumes it can find the global new and delete to call,
3949 // so ensure that they are declared.
3951
3952 FunctionDecl *OperatorNewOrDelete = nullptr;
3953 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3954 OperatorNewOrDelete))
3955 return ExprError();
3956 assert(OperatorNewOrDelete && "should be found");
3957
3958 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3959 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3960
3961 TheCall->setType(OperatorNewOrDelete->getReturnType());
3962 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3963 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3964 InitializedEntity Entity =
3967 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3968 if (Arg.isInvalid())
3969 return ExprError();
3970 TheCall->setArg(i, Arg.get());
3971 }
3972 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3973 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3974 "Callee expected to be implicit cast to a builtin function pointer");
3975 Callee->setType(OperatorNewOrDelete->getType());
3976
3977 return TheCallResult;
3978}
3979
3981 bool IsDelete, bool CallCanBeVirtual,
3982 bool WarnOnNonAbstractTypes,
3983 SourceLocation DtorLoc) {
3984 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3985 return;
3986
3987 // C++ [expr.delete]p3:
3988 // In the first alternative (delete object), if the static type of the
3989 // object to be deleted is different from its dynamic type, the static
3990 // type shall be a base class of the dynamic type of the object to be
3991 // deleted and the static type shall have a virtual destructor or the
3992 // behavior is undefined.
3993 //
3994 const CXXRecordDecl *PointeeRD = dtor->getParent();
3995 // Note: a final class cannot be derived from, no issue there
3996 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3997 return;
3998
3999 // If the superclass is in a system header, there's nothing that can be done.
4000 // The `delete` (where we emit the warning) can be in a system header,
4001 // what matters for this warning is where the deleted type is defined.
4002 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4003 return;
4004
4005 QualType ClassType = dtor->getFunctionObjectParameterType();
4006 if (PointeeRD->isAbstract()) {
4007 // If the class is abstract, we warn by default, because we're
4008 // sure the code has undefined behavior.
4009 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4010 << ClassType;
4011 } else if (WarnOnNonAbstractTypes) {
4012 // Otherwise, if this is not an array delete, it's a bit suspect,
4013 // but not necessarily wrong.
4014 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4015 << ClassType;
4016 }
4017 if (!IsDelete) {
4018 std::string TypeStr;
4019 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4020 Diag(DtorLoc, diag::note_delete_non_virtual)
4021 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4022 }
4023}
4024
4026 SourceLocation StmtLoc,
4027 ConditionKind CK) {
4028 ExprResult E =
4029 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4030 if (E.isInvalid())
4031 return ConditionError();
4032 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
4034}
4035
4037 SourceLocation StmtLoc,
4038 ConditionKind CK) {
4039 if (ConditionVar->isInvalidDecl())
4040 return ExprError();
4041
4042 QualType T = ConditionVar->getType();
4043
4044 // C++ [stmt.select]p2:
4045 // The declarator shall not specify a function or an array.
4046 if (T->isFunctionType())
4047 return ExprError(Diag(ConditionVar->getLocation(),
4048 diag::err_invalid_use_of_function_type)
4049 << ConditionVar->getSourceRange());
4050 else if (T->isArrayType())
4051 return ExprError(Diag(ConditionVar->getLocation(),
4052 diag::err_invalid_use_of_array_type)
4053 << ConditionVar->getSourceRange());
4054
4056 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4057 ConditionVar->getLocation());
4058
4059 switch (CK) {
4061 return CheckBooleanCondition(StmtLoc, Condition.get());
4062
4064 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4065
4067 return CheckSwitchCondition(StmtLoc, Condition.get());
4068 }
4069
4070 llvm_unreachable("unexpected condition kind");
4071}
4072
4073ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4074 // C++11 6.4p4:
4075 // The value of a condition that is an initialized declaration in a statement
4076 // other than a switch statement is the value of the declared variable
4077 // implicitly converted to type bool. If that conversion is ill-formed, the
4078 // program is ill-formed.
4079 // The value of a condition that is an expression is the value of the
4080 // expression, implicitly converted to bool.
4081 //
4082 // C++23 8.5.2p2
4083 // If the if statement is of the form if constexpr, the value of the condition
4084 // is contextually converted to bool and the converted expression shall be
4085 // a constant expression.
4086 //
4087
4089 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4090 return E;
4091
4092 // FIXME: Return this value to the caller so they don't need to recompute it.
4093 llvm::APSInt Cond;
4095 E.get(), &Cond,
4096 diag::err_constexpr_if_condition_expression_is_not_constant);
4097 return E;
4098}
4099
4100bool
4102 // Look inside the implicit cast, if it exists.
4103 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4104 From = Cast->getSubExpr();
4105
4106 // A string literal (2.13.4) that is not a wide string literal can
4107 // be converted to an rvalue of type "pointer to char"; a wide
4108 // string literal can be converted to an rvalue of type "pointer
4109 // to wchar_t" (C++ 4.2p2).
4110 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4111 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4112 if (const BuiltinType *ToPointeeType
4113 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4114 // This conversion is considered only when there is an
4115 // explicit appropriate pointer target type (C++ 4.2p2).
4116 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4117 switch (StrLit->getKind()) {
4121 // We don't allow UTF literals to be implicitly converted
4122 break;
4124 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4125 ToPointeeType->getKind() == BuiltinType::Char_S);
4128 QualType(ToPointeeType, 0));
4130 assert(false && "Unevaluated string literal in expression");
4131 break;
4132 }
4133 }
4134 }
4135
4136 return false;
4137}
4138
4140 SourceLocation CastLoc,
4141 QualType Ty,
4142 CastKind Kind,
4143 CXXMethodDecl *Method,
4144 DeclAccessPair FoundDecl,
4145 bool HadMultipleCandidates,
4146 Expr *From) {
4147 switch (Kind) {
4148 default: llvm_unreachable("Unhandled cast kind!");
4149 case CK_ConstructorConversion: {
4150 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4151 SmallVector<Expr*, 8> ConstructorArgs;
4152
4153 if (S.RequireNonAbstractType(CastLoc, Ty,
4154 diag::err_allocation_of_abstract_type))
4155 return ExprError();
4156
4157 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4158 ConstructorArgs))
4159 return ExprError();
4160
4161 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4163 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4164 return ExprError();
4165
4167 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4168 ConstructorArgs, HadMultipleCandidates,
4169 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4171 if (Result.isInvalid())
4172 return ExprError();
4173
4174 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4175 }
4176
4177 case CK_UserDefinedConversion: {
4178 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4179
4180 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4181 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4182 return ExprError();
4183
4184 // Create an implicit call expr that calls it.
4185 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4186 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4187 HadMultipleCandidates);
4188 if (Result.isInvalid())
4189 return ExprError();
4190 // Record usage of conversion in an implicit cast.
4191 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4192 CK_UserDefinedConversion, Result.get(),
4193 nullptr, Result.get()->getValueKind(),
4195
4196 return S.MaybeBindToTemporary(Result.get());
4197 }
4198 }
4199}
4200
4203 const ImplicitConversionSequence &ICS,
4204 AssignmentAction Action,
4206 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4208 !From->getType()->isRecordType())
4209 return From;
4210
4211 switch (ICS.getKind()) {
4213 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4214 Action, CCK);
4215 if (Res.isInvalid())
4216 return ExprError();
4217 From = Res.get();
4218 break;
4219 }
4220
4222
4225 QualType BeforeToType;
4226 assert(FD && "no conversion function for user-defined conversion seq");
4227 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4228 CastKind = CK_UserDefinedConversion;
4229
4230 // If the user-defined conversion is specified by a conversion function,
4231 // the initial standard conversion sequence converts the source type to
4232 // the implicit object parameter of the conversion function.
4233 BeforeToType = Context.getTagDeclType(Conv->getParent());
4234 } else {
4235 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4236 CastKind = CK_ConstructorConversion;
4237 // Do no conversion if dealing with ... for the first conversion.
4239 // If the user-defined conversion is specified by a constructor, the
4240 // initial standard conversion sequence converts the source type to
4241 // the type required by the argument of the constructor
4242 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4243 }
4244 }
4245 // Watch out for ellipsis conversion.
4247 ExprResult Res =
4248 PerformImplicitConversion(From, BeforeToType,
4250 CCK);
4251 if (Res.isInvalid())
4252 return ExprError();
4253 From = Res.get();
4254 }
4255
4257 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4258 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4260
4261 if (CastArg.isInvalid())
4262 return ExprError();
4263
4264 From = CastArg.get();
4265
4266 // C++ [over.match.oper]p7:
4267 // [...] the second standard conversion sequence of a user-defined
4268 // conversion sequence is not applied.
4270 return From;
4271
4272 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4273 AA_Converting, CCK);
4274 }
4275
4277 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4278 PDiag(diag::err_typecheck_ambiguous_condition)
4279 << From->getSourceRange());
4280 return ExprError();
4281
4284 llvm_unreachable("bad conversion");
4285
4288 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4289 bool Diagnosed = DiagnoseAssignmentResult(
4290 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4291 ToType, From->getType(), From, Action);
4292 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4293 return ExprError();
4294 }
4295
4296 // Everything went well.
4297 return From;
4298}
4299
4300// adjustVectorType - Compute the intermediate cast type casting elements of the
4301// from type to the elements of the to type without resizing the vector.
4303 QualType ToType, QualType *ElTy = nullptr) {
4304 auto *ToVec = ToType->castAs<VectorType>();
4305 QualType ElType = ToVec->getElementType();
4306 if (ElTy)
4307 *ElTy = ElType;
4308 if (!FromTy->isVectorType())
4309 return ElType;
4310 auto *FromVec = FromTy->castAs<VectorType>();
4311 return Context.getExtVectorType(ElType, FromVec->getNumElements());
4312}
4313
4316 const StandardConversionSequence& SCS,
4317 AssignmentAction Action,
4319 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4321
4322 // Overall FIXME: we are recomputing too many types here and doing far too
4323 // much extra work. What this means is that we need to keep track of more
4324 // information that is computed when we try the implicit conversion initially,
4325 // so that we don't need to recompute anything here.
4326 QualType FromType = From->getType();
4327
4328 if (SCS.CopyConstructor) {
4329 // FIXME: When can ToType be a reference type?
4330 assert(!ToType->isReferenceType());
4331 if (SCS.Second == ICK_Derived_To_Base) {
4332 SmallVector<Expr*, 8> ConstructorArgs;
4334 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4335 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4336 return ExprError();
4337 return BuildCXXConstructExpr(
4338 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4339 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4340 /*HadMultipleCandidates*/ false,
4341 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4343 }
4344 return BuildCXXConstructExpr(
4345 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4347 /*HadMultipleCandidates*/ false,
4348 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4350 }
4351
4352 // Resolve overloaded function references.
4353 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4356 true, Found);
4357 if (!Fn)
4358 return ExprError();
4359
4360 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4361 return ExprError();
4362
4364 if (Res.isInvalid())
4365 return ExprError();
4366
4367 // We might get back another placeholder expression if we resolved to a
4368 // builtin.
4369 Res = CheckPlaceholderExpr(Res.get());
4370 if (Res.isInvalid())
4371 return ExprError();
4372
4373 From = Res.get();
4374 FromType = From->getType();
4375 }
4376
4377 // If we're converting to an atomic type, first convert to the corresponding
4378 // non-atomic type.
4379 QualType ToAtomicType;
4380 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4381 ToAtomicType = ToType;
4382 ToType = ToAtomic->getValueType();
4383 }
4384
4385 QualType InitialFromType = FromType;
4386 // Perform the first implicit conversion.
4387 switch (SCS.First) {
4388 case ICK_Identity:
4389 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4390 FromType = FromAtomic->getValueType().getUnqualifiedType();
4391 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4392 From, /*BasePath=*/nullptr, VK_PRValue,
4394 }
4395 break;
4396
4397 case ICK_Lvalue_To_Rvalue: {
4398 assert(From->getObjectKind() != OK_ObjCProperty);
4399 ExprResult FromRes = DefaultLvalueConversion(From);
4400 if (FromRes.isInvalid())
4401 return ExprError();
4402
4403 From = FromRes.get();
4404 FromType = From->getType();
4405 break;
4406 }
4407
4409 FromType = Context.getArrayDecayedType(FromType);
4410 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4411 /*BasePath=*/nullptr, CCK)
4412 .get();
4413 break;
4414
4416 FromType = Context.getArrayParameterType(FromType);
4417 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4418 /*BasePath=*/nullptr, CCK)
4419 .get();
4420 break;
4421
4423 FromType = Context.getPointerType(FromType);
4424 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4425 VK_PRValue, /*BasePath=*/nullptr, CCK)
4426 .get();
4427 break;
4428
4429 default:
4430 llvm_unreachable("Improper first standard conversion");
4431 }
4432
4433 // Perform the second implicit conversion
4434 switch (SCS.Second) {
4435 case ICK_Identity:
4436 // C++ [except.spec]p5:
4437 // [For] assignment to and initialization of pointers to functions,
4438 // pointers to member functions, and references to functions: the
4439 // target entity shall allow at least the exceptions allowed by the
4440 // source value in the assignment or initialization.
4441 switch (Action) {
4442 case AA_Assigning:
4443 case AA_Initializing:
4444 // Note, function argument passing and returning are initialization.
4445 case AA_Passing:
4446 case AA_Returning:
4447 case AA_Sending:
4449 if (CheckExceptionSpecCompatibility(From, ToType))
4450 return ExprError();
4451 break;
4452
4453 case AA_Casting:
4454 case AA_Converting:
4455 // Casts and implicit conversions are not initialization, so are not
4456 // checked for exception specification mismatches.
4457 break;
4458 }
4459 // Nothing else to do.
4460 break;
4461
4464 QualType ElTy = ToType;
4465 QualType StepTy = ToType;
4466 if (ToType->isVectorType())
4467 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4468 if (ElTy->isBooleanType()) {
4469 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4471 "only enums with fixed underlying type can promote to bool");
4472 From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,
4473 /*BasePath=*/nullptr, CCK)
4474 .get();
4475 } else {
4476 From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,
4477 /*BasePath=*/nullptr, CCK)
4478 .get();
4479 }
4480 break;
4481 }
4482
4485 QualType StepTy = ToType;
4486 if (ToType->isVectorType())
4487 StepTy = adjustVectorType(Context, FromType, ToType);
4488 From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,
4489 /*BasePath=*/nullptr, CCK)
4490 .get();
4491 break;
4492 }
4493
4496 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4497 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4498 CastKind CK;
4499 if (FromEl->isRealFloatingType()) {
4500 if (ToEl->isRealFloatingType())
4501 CK = CK_FloatingComplexCast;
4502 else
4503 CK = CK_FloatingComplexToIntegralComplex;
4504 } else if (ToEl->isRealFloatingType()) {
4505 CK = CK_IntegralComplexToFloatingComplex;
4506 } else {
4507 CK = CK_IntegralComplexCast;
4508 }
4509 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4510 CCK)
4511 .get();
4512 break;
4513 }
4514
4515 case ICK_Floating_Integral: {
4516 QualType ElTy = ToType;
4517 QualType StepTy = ToType;
4518 if (ToType->isVectorType())
4519 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4520 if (ElTy->isRealFloatingType())
4521 From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,
4522 /*BasePath=*/nullptr, CCK)
4523 .get();
4524 else
4525 From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,
4526 /*BasePath=*/nullptr, CCK)
4527 .get();
4528 break;
4529 }
4530
4532 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4533 "Attempting implicit fixed point conversion without a fixed "
4534 "point operand");
4535 if (FromType->isFloatingType())
4536 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4537 VK_PRValue,
4538 /*BasePath=*/nullptr, CCK).get();
4539 else if (ToType->isFloatingType())
4540 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4541 VK_PRValue,
4542 /*BasePath=*/nullptr, CCK).get();
4543 else if (FromType->isIntegralType(Context))
4544 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4545 VK_PRValue,
4546 /*BasePath=*/nullptr, CCK).get();
4547 else if (ToType->isIntegralType(Context))
4548 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4549 VK_PRValue,
4550 /*BasePath=*/nullptr, CCK).get();
4551 else if (ToType->isBooleanType())
4552 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4553 VK_PRValue,
4554 /*BasePath=*/nullptr, CCK).get();
4555 else
4556 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4557 VK_PRValue,
4558 /*BasePath=*/nullptr, CCK).get();
4559 break;
4560
4562 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4563 /*BasePath=*/nullptr, CCK).get();
4564 break;
4565
4568 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4569 // Diagnose incompatible Objective-C conversions
4570 if (Action == AA_Initializing || Action == AA_Assigning)
4571 Diag(From->getBeginLoc(),
4572 diag::ext_typecheck_convert_incompatible_pointer)
4573 << ToType << From->getType() << Action << From->getSourceRange()
4574 << 0;
4575 else
4576 Diag(From->getBeginLoc(),
4577 diag::ext_typecheck_convert_incompatible_pointer)
4578 << From->getType() << ToType << Action << From->getSourceRange()
4579 << 0;
4580
4581 if (From->getType()->isObjCObjectPointerType() &&
4582 ToType->isObjCObjectPointerType())
4584 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4585 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
4586 From->getType())) {
4587 if (Action == AA_Initializing)
4588 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4589 else
4590 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4591 << (Action == AA_Casting) << From->getType() << ToType
4592 << From->getSourceRange();
4593 }
4594
4595 // Defer address space conversion to the third conversion.
4596 QualType FromPteeType = From->getType()->getPointeeType();
4597 QualType ToPteeType = ToType->getPointeeType();
4598 QualType NewToType = ToType;
4599 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4600 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4601 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4602 NewToType = Context.getAddrSpaceQualType(NewToType,
4603 FromPteeType.getAddressSpace());
4604 if (ToType->isObjCObjectPointerType())
4605 NewToType = Context.getObjCObjectPointerType(NewToType);
4606 else if (ToType->isBlockPointerType())
4607 NewToType = Context.getBlockPointerType(NewToType);
4608 else
4609 NewToType = Context.getPointerType(NewToType);
4610 }
4611
4612 CastKind Kind;
4613 CXXCastPath BasePath;
4614 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4615 return ExprError();
4616
4617 // Make sure we extend blocks if necessary.
4618 // FIXME: doing this here is really ugly.
4619 if (Kind == CK_BlockPointerToObjCPointerCast) {
4620 ExprResult E = From;
4622 From = E.get();
4623 }
4625 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4626 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4627 .get();
4628 break;
4629 }
4630
4631 case ICK_Pointer_Member: {
4632 CastKind Kind;
4633 CXXCastPath BasePath;
4634 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4635 return ExprError();
4636 if (CheckExceptionSpecCompatibility(From, ToType))
4637 return ExprError();
4638
4639 // We may not have been able to figure out what this member pointer resolved
4640 // to up until this exact point. Attempt to lock-in it's inheritance model.
4642 (void)isCompleteType(From->getExprLoc(), From->getType());
4643 (void)isCompleteType(From->getExprLoc(), ToType);
4644 }
4645
4646 From =
4647 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4648 break;
4649 }
4650
4652 // Perform half-to-boolean conversion via float.
4653 if (From->getType()->isHalfType()) {
4654 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4655 FromType = Context.FloatTy;
4656 }
4657 QualType ElTy = FromType;
4658 QualType StepTy = ToType;
4659 if (FromType->isVectorType()) {
4660 if (getLangOpts().HLSL)
4661 StepTy = adjustVectorType(Context, FromType, ToType);
4662 ElTy = FromType->castAs<VectorType>()->getElementType();
4663 }
4664
4665 From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),
4666 VK_PRValue,
4667 /*BasePath=*/nullptr, CCK)
4668 .get();
4669 break;
4670 }
4671
4672 case ICK_Derived_To_Base: {
4673 CXXCastPath BasePath;
4675 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4676 From->getSourceRange(), &BasePath, CStyle))
4677 return ExprError();
4678
4679 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4680 CK_DerivedToBase, From->getValueKind(),
4681 &BasePath, CCK).get();
4682 break;
4683 }
4684
4686 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4687 /*BasePath=*/nullptr, CCK)
4688 .get();
4689 break;
4690
4693 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4694 /*BasePath=*/nullptr, CCK)
4695 .get();
4696 break;
4697
4698 case ICK_Vector_Splat: {
4699 // Vector splat from any arithmetic type to a vector.
4700 Expr *Elem = prepareVectorSplat(ToType, From).get();
4701 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4702 /*BasePath=*/nullptr, CCK)
4703 .get();
4704 break;
4705 }
4706
4707 case ICK_Complex_Real:
4708 // Case 1. x -> _Complex y
4709 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4710 QualType ElType = ToComplex->getElementType();
4711 bool isFloatingComplex = ElType->isRealFloatingType();
4712
4713 // x -> y
4714 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4715 // do nothing
4716 } else if (From->getType()->isRealFloatingType()) {
4717 From = ImpCastExprToType(From, ElType,
4718 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4719 } else {
4720 assert(From->getType()->isIntegerType());
4721 From = ImpCastExprToType(From, ElType,
4722 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4723 }
4724 // y -> _Complex y
4725 From = ImpCastExprToType(From, ToType,
4726 isFloatingComplex ? CK_FloatingRealToComplex
4727 : CK_IntegralRealToComplex).get();
4728
4729 // Case 2. _Complex x -> y
4730 } else {
4731 auto *FromComplex = From->getType()->castAs<ComplexType>();
4732 QualType ElType = FromComplex->getElementType();
4733 bool isFloatingComplex = ElType->isRealFloatingType();
4734
4735 // _Complex x -> x
4736 From = ImpCastExprToType(From, ElType,
4737 isFloatingComplex ? CK_FloatingComplexToReal
4738 : CK_IntegralComplexToReal,
4739 VK_PRValue, /*BasePath=*/nullptr, CCK)
4740 .get();
4741
4742 // x -> y
4743 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4744 // do nothing
4745 } else if (ToType->isRealFloatingType()) {
4746 From = ImpCastExprToType(From, ToType,
4747 isFloatingComplex ? CK_FloatingCast
4748 : CK_IntegralToFloating,
4749 VK_PRValue, /*BasePath=*/nullptr, CCK)
4750 .get();
4751 } else {
4752 assert(ToType->isIntegerType());
4753 From = ImpCastExprToType(From, ToType,
4754 isFloatingComplex ? CK_FloatingToIntegral
4755 : CK_IntegralCast,
4756 VK_PRValue, /*BasePath=*/nullptr, CCK)
4757 .get();
4758 }
4759 }
4760 break;
4761
4763 LangAS AddrSpaceL =
4765 LangAS AddrSpaceR =
4767 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4768 "Invalid cast");
4769 CastKind Kind =
4770 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4771 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4772 VK_PRValue, /*BasePath=*/nullptr, CCK)
4773 .get();
4774 break;
4775 }
4776
4778 ExprResult FromRes = From;
4781 if (FromRes.isInvalid())
4782 return ExprError();
4783 From = FromRes.get();
4784 assert ((ConvTy == Sema::Compatible) &&
4785 "Improper transparent union conversion");
4786 (void)ConvTy;
4787 break;
4788 }
4789
4792 From = ImpCastExprToType(From, ToType,
4793 CK_ZeroToOCLOpaqueType,
4794 From->getValueKind()).get();
4795 break;
4796
4801 case ICK_Qualification:
4808 llvm_unreachable("Improper second standard conversion");
4809 }
4810
4811 if (SCS.Dimension != ICK_Identity) {
4812 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
4813 // vectors or matrices.
4814
4815 // TODO: Support HLSL matrices.
4816 assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&
4817 "Dimension conversion for matrix types is not implemented yet.");
4818 assert(ToType->isVectorType() &&
4819 "Dimension conversion is only supported for vector types.");
4820 switch (SCS.Dimension) {
4821 case ICK_HLSL_Vector_Splat: {
4822 // Vector splat from any arithmetic type to a vector.
4823 Expr *Elem = prepareVectorSplat(ToType, From).get();
4824 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4825 /*BasePath=*/nullptr, CCK)
4826 .get();
4827 break;
4828 }
4830 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a
4831 // vector to a smaller vector, this can only operate on arguments where
4832 // the source and destination types are ExtVectors.
4833 assert(From->getType()->isExtVectorType() && ToType->isExtVectorType() &&
4834 "HLSL vector truncation should only apply to ExtVectors");
4835 auto *FromVec = From->getType()->castAs<VectorType>();
4836 auto *ToVec = ToType->castAs<VectorType>();
4837 QualType ElType = FromVec->getElementType();
4838 QualType TruncTy =
4839 Context.getExtVectorType(ElType, ToVec->getNumElements());
4840 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
4841 From->getValueKind())
4842 .get();
4843 break;
4844 }
4845 case ICK_Identity:
4846 default:
4847 llvm_unreachable("Improper element standard conversion");
4848 }
4849 }
4850
4851 switch (SCS.Third) {
4852 case ICK_Identity:
4853 // Nothing to do.
4854 break;
4855
4857 // If both sides are functions (or pointers/references to them), there could
4858 // be incompatible exception declarations.
4859 if (CheckExceptionSpecCompatibility(From, ToType))
4860 return ExprError();
4861
4862 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4863 /*BasePath=*/nullptr, CCK)
4864 .get();
4865 break;
4866
4867 case ICK_Qualification: {
4868 ExprValueKind VK = From->getValueKind();
4869 CastKind CK = CK_NoOp;
4870
4871 if (ToType->isReferenceType() &&
4872 ToType->getPointeeType().getAddressSpace() !=
4873 From->getType().getAddressSpace())
4874 CK = CK_AddressSpaceConversion;
4875
4876 if (ToType->isPointerType() &&
4877 ToType->getPointeeType().getAddressSpace() !=
4879 CK = CK_AddressSpaceConversion;
4880
4881 if (!isCast(CCK) &&
4882 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4884 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4885 << InitialFromType << ToType;
4886 }
4887
4888 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4889 /*BasePath=*/nullptr, CCK)
4890 .get();
4891
4893 !getLangOpts().WritableStrings) {
4894 Diag(From->getBeginLoc(),
4896 ? diag::ext_deprecated_string_literal_conversion
4897 : diag::warn_deprecated_string_literal_conversion)
4898 << ToType.getNonReferenceType();
4899 }
4900
4901 break;
4902 }
4903
4904 default:
4905 llvm_unreachable("Improper third standard conversion");
4906 }
4907
4908 // If this conversion sequence involved a scalar -> atomic conversion, perform
4909 // that conversion now.
4910 if (!ToAtomicType.isNull()) {
4911 assert(Context.hasSameType(
4912 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4913 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4914 VK_PRValue, nullptr, CCK)
4915 .get();
4916 }
4917
4918 // Materialize a temporary if we're implicitly converting to a reference
4919 // type. This is not required by the C++ rules but is necessary to maintain
4920 // AST invariants.
4921 if (ToType->isReferenceType() && From->isPRValue()) {
4923 if (Res.isInvalid())
4924 return ExprError();
4925 From = Res.get();
4926 }
4927
4928 // If this conversion sequence succeeded and involved implicitly converting a
4929 // _Nullable type to a _Nonnull one, complain.
4930 if (!isCast(CCK))
4931 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4932 From->getBeginLoc());
4933
4934 return From;
4935}
4936
4937/// Checks that type T is not a VLA.
4938///
4939/// @returns @c true if @p T is VLA and a diagnostic was emitted,
4940/// @c false otherwise.
4942 clang::tok::TokenKind TypeTraitID) {
4943 if (!T->getType()->isVariableArrayType())
4944 return false;
4945
4946 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported)
4947 << 1 << TypeTraitID;
4948 return true;
4949}
4950
4951/// Checks that type T is not an atomic type (_Atomic).
4952///
4953/// @returns @c true if @p T is VLA and a diagnostic was emitted,
4954/// @c false otherwise.
4956 clang::tok::TokenKind TypeTraitID) {
4957 if (!T->getType()->isAtomicType())
4958 return false;
4959
4960 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_atomic_unsupported)
4961 << TypeTraitID;
4962 return true;
4963}
4964
4965/// Check the completeness of a type in a unary type trait.
4966///
4967/// If the particular type trait requires a complete type, tries to complete
4968/// it. If completing the type fails, a diagnostic is emitted and false
4969/// returned. If completing the type succeeds or no completion was required,
4970/// returns true.
4973 QualType ArgTy) {
4974 // C++0x [meta.unary.prop]p3:
4975 // For all of the class templates X declared in this Clause, instantiating
4976 // that template with a template argument that is a class template
4977 // specialization may result in the implicit instantiation of the template
4978 // argument if and only if the semantics of X require that the argument
4979 // must be a complete type.
4980 // We apply this rule to all the type trait expressions used to implement
4981 // these class templates. We also try to follow any GCC documented behavior
4982 // in these expressions to ensure portability of standard libraries.
4983 switch (UTT) {
4984 default: llvm_unreachable("not a UTT");
4985 // is_complete_type somewhat obviously cannot require a complete type.
4986 case UTT_IsCompleteType:
4987 // Fall-through
4988
4989 // These traits are modeled on the type predicates in C++0x
4990 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4991 // requiring a complete type, as whether or not they return true cannot be
4992 // impacted by the completeness of the type.
4993 case UTT_IsVoid:
4994 case UTT_IsIntegral:
4995 case UTT_IsFloatingPoint:
4996 case UTT_IsArray:
4997 case UTT_IsBoundedArray:
4998 case UTT_IsPointer:
4999 case UTT_IsReferenceable:
5000 case UTT_IsLvalueReference:
5001 case UTT_IsRvalueReference:
5002 case UTT_IsMemberFunctionPointer:
5003 case UTT_IsMemberObjectPointer:
5004 case UTT_IsEnum:
5005 case UTT_IsScopedEnum:
5006 case UTT_IsUnion:
5007 case UTT_IsClass:
5008 case UTT_IsFunction:
5009 case UTT_IsReference:
5010 case UTT_IsArithmetic:
5011 case UTT_IsFundamental:
5012 case UTT_IsObject:
5013 case UTT_IsScalar:
5014 case UTT_IsCompound:
5015 case UTT_IsMemberPointer:
5016 // Fall-through
5017
5018 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
5019 // which requires some of its traits to have the complete type. However,
5020 // the completeness of the type cannot impact these traits' semantics, and
5021 // so they don't require it. This matches the comments on these traits in
5022 // Table 49.
5023 case UTT_IsConst:
5024 case UTT_IsVolatile:
5025 case UTT_IsSigned:
5026 case UTT_IsUnboundedArray:
5027 case UTT_IsUnsigned:
5028
5029 // This type trait always returns false, checking the type is moot.
5030 case UTT_IsInterfaceClass:
5031 return true;
5032
5033 // C++14 [meta.unary.prop]:
5034 // If T is a non-union class type, T shall be a complete type.
5035 case UTT_IsEmpty:
5036 case UTT_IsPolymorphic:
5037 case UTT_IsAbstract:
5038 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
5039 if (!RD->isUnion())
5040 return !S.RequireCompleteType(
5041 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5042 return true;
5043
5044 // C++14 [meta.unary.prop]:
5045 // If T is a class type, T shall be a complete type.
5046 case UTT_IsFinal:
5047 case UTT_IsSealed:
5048 if (ArgTy->getAsCXXRecordDecl())
5049 return !S.RequireCompleteType(
5050 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5051 return true;
5052
5053 // LWG3823: T shall be an array type, a complete type, or cv void.
5054 case UTT_IsAggregate:
5055 case UTT_IsImplicitLifetime:
5056 if (ArgTy->isArrayType() || ArgTy->isVoidType())
5057 return true;
5058
5059 return !S.RequireCompleteType(
5060 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5061
5062 // C++1z [meta.unary.prop]:
5063 // remove_all_extents_t<T> shall be a complete type or cv void.
5064 case UTT_IsTrivial:
5065 case UTT_IsTriviallyCopyable:
5066 case UTT_IsStandardLayout:
5067 case UTT_IsPOD:
5068 case UTT_IsLiteral:
5069 case UTT_IsBitwiseCloneable:
5070 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
5071 // impose the same constraints.
5072 case UTT_IsTriviallyRelocatable:
5073 case UTT_IsTriviallyEqualityComparable:
5074 case UTT_CanPassInRegs:
5075 // Per the GCC type traits documentation, T shall be a complete type, cv void,
5076 // or an array of unknown bound. But GCC actually imposes the same constraints
5077 // as above.
5078 case UTT_HasNothrowAssign:
5079 case UTT_HasNothrowMoveAssign:
5080 case UTT_HasNothrowConstructor:
5081 case UTT_HasNothrowCopy:
5082 case UTT_HasTrivialAssign:
5083 case UTT_HasTrivialMoveAssign:
5084 case UTT_HasTrivialDefaultConstructor:
5085 case UTT_HasTrivialMoveConstructor:
5086 case UTT_HasTrivialCopy:
5087 case UTT_HasTrivialDestructor:
5088 case UTT_HasVirtualDestructor:
5089 // has_unique_object_representations<T> when T is an array is defined in terms
5090 // of has_unique_object_representations<remove_all_extents_t<T>>, so the base
5091 // type needs to be complete even if the type is an incomplete array type.
5092 case UTT_HasUniqueObjectRepresentations:
5093 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
5094 [[fallthrough]];
5095
5096 // C++1z [meta.unary.prop]:
5097 // T shall be a complete type, cv void, or an array of unknown bound.
5098 case UTT_IsDestructible:
5099 case UTT_IsNothrowDestructible:
5100 case UTT_IsTriviallyDestructible:
5101 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
5102 return true;
5103
5104 return !S.RequireCompleteType(
5105 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5106 }
5107}
5108
5110 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
5111 bool (CXXRecordDecl::*HasTrivial)() const,
5112 bool (CXXRecordDecl::*HasNonTrivial)() const,
5113 bool (CXXMethodDecl::*IsDesiredOp)() const)
5114{
5115 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5116 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
5117 return true;
5118
5119 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
5120 DeclarationNameInfo NameInfo(Name, KeyLoc);
5122 if (Self.LookupQualifiedName(Res, RD)) {
5123 bool FoundOperator = false;
5124 Res.suppressDiagnostics();
5125 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
5126 Op != OpEnd; ++Op) {
5127 if (isa<FunctionTemplateDecl>(*Op))
5128 continue;
5129
5130 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
5131 if((Operator->*IsDesiredOp)()) {
5132 FoundOperator = true;
5133 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
5134 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5135 if (!CPT || !CPT->isNothrow())
5136 return false;
5137 }
5138 }
5139 return FoundOperator;
5140 }
5141 return false;
5142}
5143
5145 const CXXRecordDecl *Decl,
5146 SourceLocation KeyLoc) {
5147 if (Decl->isUnion())
5148 return false;
5149 if (Decl->isLambda())
5150 return Decl->isCapturelessLambda();
5151
5152 {
5153 EnterExpressionEvaluationContext UnevaluatedContext(
5155 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5157
5158 // const ClassT& obj;
5159 OpaqueValueExpr Operand(
5160 {}, Decl->getTypeForDecl()->getCanonicalTypeUnqualified().withConst(),
5162 UnresolvedSet<16> Functions;
5163 // obj == obj;
5164 S.LookupBinOp(S.TUScope, {}, BinaryOperatorKind::BO_EQ, Functions);
5165
5166 auto Result = S.CreateOverloadedBinOp(KeyLoc, BinaryOperatorKind::BO_EQ,
5167 Functions, &Operand, &Operand);
5168 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5169 return false;
5170
5171 const auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(Result.get());
5172 if (!CallExpr)
5173 return false;
5174 const auto *Callee = CallExpr->getDirectCallee();
5175 auto ParamT = Callee->getParamDecl(0)->getType();
5176 if (!Callee->isDefaulted())
5177 return false;
5178 if (!ParamT->isReferenceType() && !Decl->isTriviallyCopyable())
5179 return false;
5180 if (ParamT.getNonReferenceType()->getUnqualifiedDesugaredType() !=
5181 Decl->getTypeForDecl())
5182 return false;
5183 }
5184
5185 return llvm::all_of(Decl->bases(),
5186 [&](const CXXBaseSpecifier &BS) {
5187 if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
5188 return HasNonDeletedDefaultedEqualityComparison(
5189 S, RD, KeyLoc);
5190 return true;
5191 }) &&
5192 llvm::all_of(Decl->fields(), [&](const FieldDecl *FD) {
5193 auto Type = FD->getType();
5194 if (Type->isArrayType())
5195 Type = Type->getBaseElementTypeUnsafe()
5196 ->getCanonicalTypeUnqualified();
5197
5198 if (Type->isReferenceType() || Type->isEnumeralType())
5199 return false;
5200 if (const auto *RD = Type->getAsCXXRecordDecl())
5201 return HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc);
5202 return true;
5203 });
5204}
5205
5207 QualType CanonicalType = Type.getCanonicalType();
5208 if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
5209 CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
5210 return false;
5211
5212 if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
5213 if (!HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc))
5214 return false;
5215 }
5216
5218 CanonicalType, /*CheckIfTriviallyCopyable=*/false);
5219}
5220
5222 SourceLocation KeyLoc,
5223 TypeSourceInfo *TInfo) {
5224 QualType T = TInfo->getType();
5225 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5226
5227 ASTContext &C = Self.Context;
5228 switch(UTT) {
5229 default: llvm_unreachable("not a UTT");
5230 // Type trait expressions corresponding to the primary type category
5231 // predicates in C++0x [meta.unary.cat].
5232 case UTT_IsVoid:
5233 return T->isVoidType();
5234 case UTT_IsIntegral:
5235 return T->isIntegralType(C);
5236 case UTT_IsFloatingPoint:
5237 return T->isFloatingType();
5238 case UTT_IsArray:
5239 // Zero-sized arrays aren't considered arrays in partial specializations,
5240 // so __is_array shouldn't consider them arrays either.
5241 if (const auto *CAT = C.getAsConstantArrayType(T))
5242 return CAT->getSize() != 0;
5243 return T->isArrayType();
5244 case UTT_IsBoundedArray:
5245 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_bounded_array))
5246 return false;
5247 // Zero-sized arrays aren't considered arrays in partial specializations,
5248 // so __is_bounded_array shouldn't consider them arrays either.
5249 if (const auto *CAT = C.getAsConstantArrayType(T))
5250 return CAT->getSize() != 0;
5251 return T->isArrayType() && !T->isIncompleteArrayType();
5252 case UTT_IsUnboundedArray:
5253 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_unbounded_array))
5254 return false;
5255 return T->isIncompleteArrayType();
5256 case UTT_IsPointer:
5257 return T->isAnyPointerType();
5258 case UTT_IsLvalueReference:
5259 return T->isLValueReferenceType();
5260 case UTT_IsRvalueReference:
5261 return T->isRValueReferenceType();
5262 case UTT_IsMemberFunctionPointer:
5264 case UTT_IsMemberObjectPointer:
5265 return T->isMemberDataPointerType();
5266 case UTT_IsEnum:
5267 return T->isEnumeralType();
5268 case UTT_IsScopedEnum:
5269 return T->isScopedEnumeralType();
5270 case UTT_IsUnion:
5271 return T->isUnionType();
5272 case UTT_IsClass:
5273 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
5274 case UTT_IsFunction:
5275 return T->isFunctionType();
5276
5277 // Type trait expressions which correspond to the convenient composition
5278 // predicates in C++0x [meta.unary.comp].
5279 case UTT_IsReference:
5280 return T->isReferenceType();
5281 case UTT_IsArithmetic:
5282 return T->isArithmeticType() && !T->isEnumeralType();
5283 case UTT_IsFundamental:
5284 return T->isFundamentalType();
5285 case UTT_IsObject:
5286 return T->isObjectType();
5287 case UTT_IsScalar:
5288 // Note: semantic analysis depends on Objective-C lifetime types to be
5289 // considered scalar types. However, such types do not actually behave
5290 // like scalar types at run time (since they may require retain/release
5291 // operations), so we report them as non-scalar.
5292 if (T->isObjCLifetimeType()) {
5293 switch (T.getObjCLifetime()) {
5296 return true;
5297
5301 return false;
5302 }
5303 }
5304
5305 return T->isScalarType();
5306 case UTT_IsCompound:
5307 return T->isCompoundType();
5308 case UTT_IsMemberPointer:
5309 return T->isMemberPointerType();
5310
5311 // Type trait expressions which correspond to the type property predicates
5312 // in C++0x [meta.unary.prop].
5313 case UTT_IsConst:
5314 return T.isConstQualified();
5315 case UTT_IsVolatile:
5316 return T.isVolatileQualified();
5317 case UTT_IsTrivial:
5318 return T.isTrivialType(C);
5319 case UTT_IsTriviallyCopyable:
5320 return T.isTriviallyCopyableType(C);
5321 case UTT_IsStandardLayout:
5322 return T->isStandardLayoutType();
5323 case UTT_IsPOD:
5324 return T.isPODType(C);
5325 case UTT_IsLiteral:
5326 return T->isLiteralType(C);
5327 case UTT_IsEmpty:
5328 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5329 return !RD->isUnion() && RD->isEmpty();
5330 return false;
5331 case UTT_IsPolymorphic:
5332 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5333 return !RD->isUnion() && RD->isPolymorphic();
5334 return false;
5335 case UTT_IsAbstract:
5336 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5337 return !RD->isUnion() && RD->isAbstract();
5338 return false;
5339 case UTT_IsAggregate:
5340 // Report vector extensions and complex types as aggregates because they
5341 // support aggregate initialization. GCC mirrors this behavior for vectors
5342 // but not _Complex.
5343 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5345 // __is_interface_class only returns true when CL is invoked in /CLR mode and
5346 // even then only when it is used with the 'interface struct ...' syntax
5347 // Clang doesn't support /CLR which makes this type trait moot.
5348 case UTT_IsInterfaceClass:
5349 return false;
5350 case UTT_IsFinal:
5351 case UTT_IsSealed:
5352 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5353 return RD->hasAttr<FinalAttr>();
5354 return false;
5355 case UTT_IsSigned:
5356 // Enum types should always return false.
5357 // Floating points should always return true.
5358 return T->isFloatingType() ||
5360 case UTT_IsUnsigned:
5361 // Enum types should always return false.
5362 return T->isUnsignedIntegerType() && !T->isEnumeralType();
5363
5364 // Type trait expressions which query classes regarding their construction,
5365 // destruction, and copying. Rather than being based directly on the
5366 // related type predicates in the standard, they are specified by both
5367 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5368 // specifications.
5369 //
5370 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5371 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5372 //
5373 // Note that these builtins do not behave as documented in g++: if a class
5374 // has both a trivial and a non-trivial special member of a particular kind,
5375 // they return false! For now, we emulate this behavior.
5376 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5377 // does not correctly compute triviality in the presence of multiple special
5378 // members of the same kind. Revisit this once the g++ bug is fixed.
5379 case UTT_HasTrivialDefaultConstructor:
5380 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5381 // If __is_pod (type) is true then the trait is true, else if type is
5382 // a cv class or union type (or array thereof) with a trivial default
5383 // constructor ([class.ctor]) then the trait is true, else it is false.
5384 if (T.isPODType(C))
5385 return true;
5386 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5387 return RD->hasTrivialDefaultConstructor() &&
5389 return false;
5390 case UTT_HasTrivialMoveConstructor:
5391 // This trait is implemented by MSVC 2012 and needed to parse the
5392 // standard library headers. Specifically this is used as the logic
5393 // behind std::is_trivially_move_constructible (20.9.4.3).
5394 if (T.isPODType(C))
5395 return true;
5396 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5398 return false;
5399 case UTT_HasTrivialCopy:
5400 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5401 // If __is_pod (type) is true or type is a reference type then
5402 // the trait is true, else if type is a cv class or union type
5403 // with a trivial copy constructor ([class.copy]) then the trait
5404 // is true, else it is false.
5405 if (T.isPODType(C) || T->isReferenceType())
5406 return true;
5407 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5408 return RD->hasTrivialCopyConstructor() &&
5410 return false;
5411 case UTT_HasTrivialMoveAssign:
5412 // This trait is implemented by MSVC 2012 and needed to parse the
5413 // standard library headers. Specifically it is used as the logic
5414 // behind std::is_trivially_move_assignable (20.9.4.3)
5415 if (T.isPODType(C))
5416 return true;
5417 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5419 return false;
5420 case UTT_HasTrivialAssign:
5421 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5422 // If type is const qualified or is a reference type then the
5423 // trait is false. Otherwise if __is_pod (type) is true then the
5424 // trait is true, else if type is a cv class or union type with
5425 // a trivial copy assignment ([class.copy]) then the trait is
5426 // true, else it is false.
5427 // Note: the const and reference restrictions are interesting,
5428 // given that const and reference members don't prevent a class
5429 // from having a trivial copy assignment operator (but do cause
5430 // errors if the copy assignment operator is actually used, q.v.
5431 // [class.copy]p12).
5432
5433 if (T.isConstQualified())
5434 return false;
5435 if (T.isPODType(C))
5436 return true;
5437 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5438 return RD->hasTrivialCopyAssignment() &&
5440 return false;
5441 case UTT_IsDestructible:
5442 case UTT_IsTriviallyDestructible:
5443 case UTT_IsNothrowDestructible:
5444 // C++14 [meta.unary.prop]:
5445 // For reference types, is_destructible<T>::value is true.
5446 if (T->isReferenceType())
5447 return true;
5448
5449 // Objective-C++ ARC: autorelease types don't require destruction.
5450 if (T->isObjCLifetimeType() &&
5451 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5452 return true;
5453
5454 // C++14 [meta.unary.prop]:
5455 // For incomplete types and function types, is_destructible<T>::value is
5456 // false.
5457 if (T->isIncompleteType() || T->isFunctionType())
5458 return false;
5459
5460 // A type that requires destruction (via a non-trivial destructor or ARC
5461 // lifetime semantics) is not trivially-destructible.
5462 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5463 return false;
5464
5465 // C++14 [meta.unary.prop]:
5466 // For object types and given U equal to remove_all_extents_t<T>, if the
5467 // expression std::declval<U&>().~U() is well-formed when treated as an
5468 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
5469 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5470 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5471 if (!Destructor)
5472 return false;
5473 // C++14 [dcl.fct.def.delete]p2:
5474 // A program that refers to a deleted function implicitly or
5475 // explicitly, other than to declare it, is ill-formed.
5476 if (Destructor->isDeleted())
5477 return false;
5478 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5479 return false;
5480 if (UTT == UTT_IsNothrowDestructible) {
5481 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5482 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5483 if (!CPT || !CPT->isNothrow())
5484 return false;
5485 }
5486 }
5487 return true;
5488
5489 case UTT_HasTrivialDestructor:
5490 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5491 // If __is_pod (type) is true or type is a reference type
5492 // then the trait is true, else if type is a cv class or union
5493 // type (or array thereof) with a trivial destructor
5494 // ([class.dtor]) then the trait is true, else it is
5495 // false.
5496 if (T.isPODType(C) || T->isReferenceType())
5497 return true;
5498
5499 // Objective-C++ ARC: autorelease types don't require destruction.
5500 if (T->isObjCLifetimeType() &&
5501 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5502 return true;
5503
5504 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5505 return RD->hasTrivialDestructor();
5506 return false;
5507 // TODO: Propagate nothrowness for implicitly declared special members.
5508 case UTT_HasNothrowAssign:
5509 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5510 // If type is const qualified or is a reference type then the
5511 // trait is false. Otherwise if __has_trivial_assign (type)
5512 // is true then the trait is true, else if type is a cv class
5513 // or union type with copy assignment operators that are known
5514 // not to throw an exception then the trait is true, else it is
5515 // false.
5516 if (C.getBaseElementType(T).isConstQualified())
5517 return false;
5518 if (T->isReferenceType())
5519 return false;
5520 if (T.isPODType(C) || T->isObjCLifetimeType())
5521 return true;
5522
5523 if (const RecordType *RT = T->getAs<RecordType>())
5524 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5528 return false;
5529 case UTT_HasNothrowMoveAssign:
5530 // This trait is implemented by MSVC 2012 and needed to parse the
5531 // standard library headers. Specifically this is used as the logic
5532 // behind std::is_nothrow_move_assignable (20.9.4.3).
5533 if (T.isPODType(C))
5534 return true;
5535
5536 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5537 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5541 return false;
5542 case UTT_HasNothrowCopy:
5543 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5544 // If __has_trivial_copy (type) is true then the trait is true, else
5545 // if type is a cv class or union type with copy constructors that are
5546 // known not to throw an exception then the trait is true, else it is
5547 // false.
5548 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5549 return true;
5550 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5551 if (RD->hasTrivialCopyConstructor() &&
5553 return true;
5554
5555 bool FoundConstructor = false;
5556 unsigned FoundTQs;
5557 for (const auto *ND : Self.LookupConstructors(RD)) {
5558 // A template constructor is never a copy constructor.
5559 // FIXME: However, it may actually be selected at the actual overload
5560 // resolution point.
5561 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5562 continue;
5563 // UsingDecl itself is not a constructor
5564 if (isa<UsingDecl>(ND))
5565 continue;
5566 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5567 if (Constructor->isCopyConstructor(FoundTQs)) {
5568 FoundConstructor = true;
5569 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5570 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5571 if (!CPT)
5572 return false;
5573 // TODO: check whether evaluating default arguments can throw.
5574 // For now, we'll be conservative and assume that they can throw.
5575 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5576 return false;
5577 }
5578 }
5579
5580 return FoundConstructor;
5581 }
5582 return false;
5583 case UTT_HasNothrowConstructor:
5584 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5585 // If __has_trivial_constructor (type) is true then the trait is
5586 // true, else if type is a cv class or union type (or array
5587 // thereof) with a default constructor that is known not to
5588 // throw an exception then the trait is true, else it is false.
5589 if (T.isPODType(C) || T->isObjCLifetimeType())
5590 return true;
5591 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5592 if (RD->hasTrivialDefaultConstructor() &&
5594 return true;
5595
5596 bool FoundConstructor = false;
5597 for (const auto *ND : Self.LookupConstructors(RD)) {
5598 // FIXME: In C++0x, a constructor template can be a default constructor.
5599 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5600 continue;
5601 // UsingDecl itself is not a constructor
5602 if (isa<UsingDecl>(ND))
5603 continue;
5604 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5605 if (Constructor->isDefaultConstructor()) {
5606 FoundConstructor = true;
5607 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5608 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5609 if (!CPT)
5610 return false;
5611 // FIXME: check whether evaluating default arguments can throw.
5612 // For now, we'll be conservative and assume that they can throw.
5613 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5614 return false;
5615 }
5616 }
5617 return FoundConstructor;
5618 }
5619 return false;
5620 case UTT_HasVirtualDestructor:
5621 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5622 // If type is a class type with a virtual destructor ([class.dtor])
5623 // then the trait is true, else it is false.
5624 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5625 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5626 return Destructor->isVirtual();
5627 return false;
5628
5629 // These type trait expressions are modeled on the specifications for the
5630 // Embarcadero C++0x type trait functions:
5631 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5632 case UTT_IsCompleteType:
5633 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5634 // Returns True if and only if T is a complete type at the point of the
5635 // function call.
5636 return !T->isIncompleteType();
5637 case UTT_HasUniqueObjectRepresentations:
5638 return C.hasUniqueObjectRepresentations(T);
5639 case UTT_IsTriviallyRelocatable:
5640 return T.isTriviallyRelocatableType(C);
5641 case UTT_IsBitwiseCloneable:
5642 return T.isBitwiseCloneableType(C);
5643 case UTT_IsReferenceable:
5644 return T.isReferenceable();
5645 case UTT_CanPassInRegs:
5646 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())
5647 return RD->canPassInRegisters();
5648 Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;
5649 return false;
5650 case UTT_IsTriviallyEqualityComparable:
5651 return isTriviallyEqualityComparableType(Self, T, KeyLoc);
5652 case UTT_IsImplicitLifetime: {
5654 tok::kw___builtin_is_implicit_lifetime);
5656 tok::kw___builtin_is_implicit_lifetime);
5657
5658 // [basic.types.general] p9
5659 // Scalar types, implicit-lifetime class types ([class.prop]),
5660 // array types, and cv-qualified versions of these types
5661 // are collectively called implicit-lifetime types.
5663 if (UnqualT->isScalarType())
5664 return true;
5665 if (UnqualT->isArrayType() || UnqualT->isVectorType())
5666 return true;
5667 const CXXRecordDecl *RD = UnqualT->getAsCXXRecordDecl();
5668 if (!RD)
5669 return false;
5670
5671 // [class.prop] p9
5672 // A class S is an implicit-lifetime class if
5673 // - it is an aggregate whose destructor is not user-provided or
5674 // - it has at least one trivial eligible constructor and a trivial,
5675 // non-deleted destructor.
5676 const CXXDestructorDecl *Dtor = RD->getDestructor();
5677 if (UnqualT->isAggregateType())
5678 if (Dtor && !Dtor->isUserProvided())
5679 return true;
5680 if (RD->hasTrivialDestructor() && (!Dtor || !Dtor->isDeleted()))
5681 if (RD->hasTrivialDefaultConstructor() ||
5683 return true;
5684 return false;
5685 }
5686 }
5687}
5688
5689static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,
5690 const TypeSourceInfo *Rhs, SourceLocation KeyLoc);
5691
5693 Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs,
5694 SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator) {
5695
5696 QualType LhsT = Lhs->getType();
5697 QualType RhsT = Rhs->getType();
5698
5699 // C++0x [meta.rel]p4:
5700 // Given the following function prototype:
5701 //
5702 // template <class T>
5703 // typename add_rvalue_reference<T>::type create();
5704 //
5705 // the predicate condition for a template specialization
5706 // is_convertible<From, To> shall be satisfied if and only if
5707 // the return expression in the following code would be
5708 // well-formed, including any implicit conversions to the return
5709 // type of the function:
5710 //
5711 // To test() {
5712 // return create<From>();
5713 // }
5714 //
5715 // Access checking is performed as if in a context unrelated to To and
5716 // From. Only the validity of the immediate context of the expression
5717 // of the return-statement (including conversions to the return type)
5718 // is considered.
5719 //
5720 // We model the initialization as a copy-initialization of a temporary
5721 // of the appropriate type, which for this expression is identical to the
5722 // return statement (since NRVO doesn't apply).
5723
5724 // Functions aren't allowed to return function or array types.
5725 if (RhsT->isFunctionType() || RhsT->isArrayType())
5726 return ExprError();
5727
5728 // A function definition requires a complete, non-abstract return type.
5729 if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) ||
5730 Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT))
5731 return ExprError();
5732
5733 // Compute the result of add_rvalue_reference.
5734 if (LhsT->isObjectType() || LhsT->isFunctionType())
5735 LhsT = Self.Context.getRValueReferenceType(LhsT);
5736
5737 // Build a fake source and destination for initialization.
5739 Expr *From = new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5740 OpaqueValueExpr(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5742 InitializationKind Kind =
5744
5745 // Perform the initialization in an unevaluated context within a SFINAE
5746 // trap at translation unit scope.
5749 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5750 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5751 InitializationSequence Init(Self, To, Kind, From);
5752 if (Init.Failed())
5753 return ExprError();
5754
5755 ExprResult Result = Init.Perform(Self, To, Kind, From);
5756 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5757 return ExprError();
5758
5759 return Result;
5760}
5761
5763 SourceLocation KWLoc,
5765 SourceLocation RParenLoc,
5766 bool IsDependent) {
5767 if (IsDependent)
5768 return false;
5769
5770 if (Kind <= UTT_Last)
5771 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]);
5772
5773 // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary
5774 // alongside the IsConstructible traits to avoid duplication.
5775 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary &&
5776 Kind != BTT_ReferenceConstructsFromTemporary &&
5777 Kind != BTT_ReferenceConvertsFromTemporary)
5778 return EvaluateBinaryTypeTrait(S, Kind, Args[0],
5779 Args[1], RParenLoc);
5780
5781 switch (Kind) {
5782 case clang::BTT_ReferenceBindsToTemporary:
5783 case clang::BTT_ReferenceConstructsFromTemporary:
5784 case clang::BTT_ReferenceConvertsFromTemporary:
5785 case clang::TT_IsConstructible:
5786 case clang::TT_IsNothrowConstructible:
5787 case clang::TT_IsTriviallyConstructible: {
5788 // C++11 [meta.unary.prop]:
5789 // is_trivially_constructible is defined as:
5790 //
5791 // is_constructible<T, Args...>::value is true and the variable
5792 // definition for is_constructible, as defined below, is known to call
5793 // no operation that is not trivial.
5794 //
5795 // The predicate condition for a template specialization
5796 // is_constructible<T, Args...> shall be satisfied if and only if the
5797 // following variable definition would be well-formed for some invented
5798 // variable t:
5799 //
5800 // T t(create<Args>()...);
5801 assert(!Args.empty());
5802
5803 // Precondition: T and all types in the parameter pack Args shall be
5804 // complete types, (possibly cv-qualified) void, or arrays of
5805 // unknown bound.
5806 for (const auto *TSI : Args) {
5807 QualType ArgTy = TSI->getType();
5808 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5809 continue;
5810
5811 if (S.RequireCompleteType(KWLoc, ArgTy,
5812 diag::err_incomplete_type_used_in_type_trait_expr))
5813 return false;
5814 }
5815
5816 // Make sure the first argument is not incomplete nor a function type.
5817 QualType T = Args[0]->getType();
5818 if (T->isIncompleteType() || T->isFunctionType())
5819 return false;
5820
5821 // Make sure the first argument is not an abstract type.
5823 if (RD && RD->isAbstract())
5824 return false;
5825
5826 llvm::BumpPtrAllocator OpaqueExprAllocator;
5827 SmallVector<Expr *, 2> ArgExprs;
5828 ArgExprs.reserve(Args.size() - 1);
5829 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5830 QualType ArgTy = Args[I]->getType();
5831 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5832 ArgTy = S.Context.getRValueReferenceType(ArgTy);
5833 ArgExprs.push_back(
5834 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5835 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5838 }
5839
5840 // Perform the initialization in an unevaluated context within a SFINAE
5841 // trap at translation unit scope.
5844 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5848 InitializationKind InitKind(
5849 Kind == clang::BTT_ReferenceConvertsFromTemporary
5850 ? InitializationKind::CreateCopy(KWLoc, KWLoc)
5851 : InitializationKind::CreateDirect(KWLoc, KWLoc, RParenLoc));
5852 InitializationSequence Init(S, To, InitKind, ArgExprs);
5853 if (Init.Failed())
5854 return false;
5855
5856 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5857 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5858 return false;
5859
5860 if (Kind == clang::TT_IsConstructible)
5861 return true;
5862
5863 if (Kind == clang::BTT_ReferenceBindsToTemporary ||
5864 Kind == clang::BTT_ReferenceConstructsFromTemporary ||
5865 Kind == clang::BTT_ReferenceConvertsFromTemporary) {
5866 if (!T->isReferenceType())
5867 return false;
5868
5869 if (!Init.isDirectReferenceBinding())
5870 return true;
5871
5872 if (Kind == clang::BTT_ReferenceBindsToTemporary)
5873 return false;
5874
5875 QualType U = Args[1]->getType();
5876 if (U->isReferenceType())
5877 return false;
5878
5880 S.Context.getPointerType(T.getNonReferenceType()));
5882 S.Context.getPointerType(U.getNonReferenceType()));
5883 return !CheckConvertibilityForTypeTraits(S, UPtr, TPtr, RParenLoc,
5884 OpaqueExprAllocator)
5885 .isInvalid();
5886 }
5887
5888 if (Kind == clang::TT_IsNothrowConstructible)
5889 return S.canThrow(Result.get()) == CT_Cannot;
5890
5891 if (Kind == clang::TT_IsTriviallyConstructible) {
5892 // Under Objective-C ARC and Weak, if the destination has non-trivial
5893 // Objective-C lifetime, this is a non-trivial construction.
5894 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5895 return false;
5896
5897 // The initialization succeeded; now make sure there are no non-trivial
5898 // calls.
5899 return !Result.get()->hasNonTrivialCall(S.Context);
5900 }
5901
5902 llvm_unreachable("unhandled type trait");
5903 return false;
5904 }
5905 default: llvm_unreachable("not a TT");
5906 }
5907
5908 return false;
5909}
5910
5911namespace {
5912void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5913 SourceLocation KWLoc) {
5914 TypeTrait Replacement;
5915 switch (Kind) {
5916 case UTT_HasNothrowAssign:
5917 case UTT_HasNothrowMoveAssign:
5918 Replacement = BTT_IsNothrowAssignable;
5919 break;
5920 case UTT_HasNothrowCopy:
5921 case UTT_HasNothrowConstructor:
5922 Replacement = TT_IsNothrowConstructible;
5923 break;
5924 case UTT_HasTrivialAssign:
5925 case UTT_HasTrivialMoveAssign:
5926 Replacement = BTT_IsTriviallyAssignable;
5927 break;
5928 case UTT_HasTrivialCopy:
5929 Replacement = UTT_IsTriviallyCopyable;
5930 break;
5931 case UTT_HasTrivialDefaultConstructor:
5932 case UTT_HasTrivialMoveConstructor:
5933 Replacement = TT_IsTriviallyConstructible;
5934 break;
5935 case UTT_HasTrivialDestructor:
5936 Replacement = UTT_IsTriviallyDestructible;
5937 break;
5938 default:
5939 return;
5940 }
5941 S.Diag(KWLoc, diag::warn_deprecated_builtin)
5942 << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5943}
5944}
5945
5946bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
5947 if (Arity && N != Arity) {
5948 Diag(Loc, diag::err_type_trait_arity)
5949 << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
5950 return false;
5951 }
5952
5953 if (!Arity && N == 0) {
5954 Diag(Loc, diag::err_type_trait_arity)
5955 << 1 << 1 << 1 << (int)N << SourceRange(Loc);
5956 return false;
5957 }
5958 return true;
5959}
5960
5962 Bool,
5963};
5964
5966 return TypeTraitReturnType::Bool;
5967}
5968
5971 SourceLocation RParenLoc) {
5972 if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
5973 return ExprError();
5974
5976 *this, Kind, KWLoc, Args[0]->getType()))
5977 return ExprError();
5978
5979 DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5980
5981 bool Dependent = false;
5982 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5983 if (Args[I]->getType()->isDependentType()) {
5984 Dependent = true;
5985 break;
5986 }
5987 }
5988
5989 switch (GetReturnType(Kind)) {
5990 case TypeTraitReturnType::Bool: {
5991 bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc,
5992 Dependent);
5994 KWLoc, Kind, Args, RParenLoc, Result);
5995 }
5996 }
5997 llvm_unreachable("unhandled type trait return type");
5998}
5999
6002 SourceLocation RParenLoc) {
6004 ConvertedArgs.reserve(Args.size());
6005
6006 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
6007 TypeSourceInfo *TInfo;
6008 QualType T = GetTypeFromParser(Args[I], &TInfo);
6009 if (!TInfo)
6010 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
6011
6012 ConvertedArgs.push_back(TInfo);
6013 }
6014
6015 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
6016}
6017
6019 const TypeSourceInfo *Rhs, SourceLocation KeyLoc) {
6020 QualType LhsT = Lhs->getType();
6021 QualType RhsT = Rhs->getType();
6022
6023 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
6024 "Cannot evaluate traits of dependent types");
6025
6026 switch(BTT) {
6027 case BTT_IsBaseOf: {
6028 // C++0x [meta.rel]p2
6029 // Base is a base class of Derived without regard to cv-qualifiers or
6030 // Base and Derived are not unions and name the same class type without
6031 // regard to cv-qualifiers.
6032
6033 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
6034 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
6035 if (!rhsRecord || !lhsRecord) {
6036 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
6037 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
6038 if (!LHSObjTy || !RHSObjTy)
6039 return false;
6040
6041 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
6042 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
6043 if (!BaseInterface || !DerivedInterface)
6044 return false;
6045
6046 if (Self.RequireCompleteType(
6047 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6048 diag::err_incomplete_type_used_in_type_trait_expr))
6049 return false;
6050
6051 return BaseInterface->isSuperClassOf(DerivedInterface);
6052 }
6053
6054 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
6055 == (lhsRecord == rhsRecord));
6056
6057 // Unions are never base classes, and never have base classes.
6058 // It doesn't matter if they are complete or not. See PR#41843
6059 if (lhsRecord && lhsRecord->getDecl()->isUnion())
6060 return false;
6061 if (rhsRecord && rhsRecord->getDecl()->isUnion())
6062 return false;
6063
6064 if (lhsRecord == rhsRecord)
6065 return true;
6066
6067 // C++0x [meta.rel]p2:
6068 // If Base and Derived are class types and are different types
6069 // (ignoring possible cv-qualifiers) then Derived shall be a
6070 // complete type.
6071 if (Self.RequireCompleteType(
6072 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6073 diag::err_incomplete_type_used_in_type_trait_expr))
6074 return false;
6075
6076 return cast<CXXRecordDecl>(rhsRecord->getDecl())
6077 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
6078 }
6079 case BTT_IsVirtualBaseOf: {
6080 const RecordType *BaseRecord = LhsT->getAs<RecordType>();
6081 const RecordType *DerivedRecord = RhsT->getAs<RecordType>();
6082
6083 if (!BaseRecord || !DerivedRecord) {
6085 tok::kw___builtin_is_virtual_base_of);
6087 tok::kw___builtin_is_virtual_base_of);
6088 return false;
6089 }
6090
6091 if (BaseRecord->isUnionType() || DerivedRecord->isUnionType())
6092 return false;
6093
6094 if (!BaseRecord->isStructureOrClassType() ||
6095 !DerivedRecord->isStructureOrClassType())
6096 return false;
6097
6098 if (Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6099 diag::err_incomplete_type))
6100 return false;
6101
6102 return cast<CXXRecordDecl>(DerivedRecord->getDecl())
6103 ->isVirtuallyDerivedFrom(cast<CXXRecordDecl>(BaseRecord->getDecl()));
6104 }
6105 case BTT_IsSame:
6106 return Self.Context.hasSameType(LhsT, RhsT);
6107 case BTT_TypeCompatible: {
6108 // GCC ignores cv-qualifiers on arrays for this builtin.
6109 Qualifiers LhsQuals, RhsQuals;
6110 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
6111 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
6112 return Self.Context.typesAreCompatible(Lhs, Rhs);
6113 }
6114 case BTT_IsConvertible:
6115 case BTT_IsConvertibleTo:
6116 case BTT_IsNothrowConvertible: {
6117 if (RhsT->isVoidType())
6118 return LhsT->isVoidType();
6119 llvm::BumpPtrAllocator OpaqueExprAllocator;
6121 OpaqueExprAllocator);
6122 if (Result.isInvalid())
6123 return false;
6124
6125 if (BTT != BTT_IsNothrowConvertible)
6126 return true;
6127
6128 return Self.canThrow(Result.get()) == CT_Cannot;
6129 }
6130
6131 case BTT_IsAssignable:
6132 case BTT_IsNothrowAssignable:
6133 case BTT_IsTriviallyAssignable: {
6134 // C++11 [meta.unary.prop]p3:
6135 // is_trivially_assignable is defined as:
6136 // is_assignable<T, U>::value is true and the assignment, as defined by
6137 // is_assignable, is known to call no operation that is not trivial
6138 //
6139 // is_assignable is defined as:
6140 // The expression declval<T>() = declval<U>() is well-formed when
6141 // treated as an unevaluated operand (Clause 5).
6142 //
6143 // For both, T and U shall be complete types, (possibly cv-qualified)
6144 // void, or arrays of unknown bound.
6145 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
6146 Self.RequireCompleteType(
6147 Lhs->getTypeLoc().getBeginLoc(), LhsT,
6148 diag::err_incomplete_type_used_in_type_trait_expr))
6149 return false;
6150 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
6151 Self.RequireCompleteType(
6152 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6153 diag::err_incomplete_type_used_in_type_trait_expr))
6154 return false;
6155
6156 // cv void is never assignable.
6157 if (LhsT->isVoidType() || RhsT->isVoidType())
6158 return false;
6159
6160 // Build expressions that emulate the effect of declval<T>() and
6161 // declval<U>().
6162 if (LhsT->isObjectType() || LhsT->isFunctionType())
6163 LhsT = Self.Context.getRValueReferenceType(LhsT);
6164 if (RhsT->isObjectType() || RhsT->isFunctionType())
6165 RhsT = Self.Context.getRValueReferenceType(RhsT);
6166 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
6168 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
6170
6171 // Attempt the assignment in an unevaluated context within a SFINAE
6172 // trap at translation unit scope.
6175 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
6176 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
6177 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
6178 &Rhs);
6179 if (Result.isInvalid())
6180 return false;
6181
6182 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
6183 Self.CheckUnusedVolatileAssignment(Result.get());
6184
6185 if (SFINAE.hasErrorOccurred())
6186 return false;
6187
6188 if (BTT == BTT_IsAssignable)
6189 return true;
6190
6191 if (BTT == BTT_IsNothrowAssignable)
6192 return Self.canThrow(Result.get()) == CT_Cannot;
6193
6194 if (BTT == BTT_IsTriviallyAssignable) {
6195 // Under Objective-C ARC and Weak, if the destination has non-trivial
6196 // Objective-C lifetime, this is a non-trivial assignment.
6198 return false;
6199
6200 return !Result.get()->hasNonTrivialCall(Self.Context);
6201 }
6202
6203 llvm_unreachable("unhandled type trait");
6204 return false;
6205 }
6206 case BTT_IsLayoutCompatible: {
6207 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType())
6208 Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,
6209 diag::err_incomplete_type);
6210 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType())
6211 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6212 diag::err_incomplete_type);
6213
6214 DiagnoseVLAInCXXTypeTrait(Self, Lhs, tok::kw___is_layout_compatible);
6215 DiagnoseVLAInCXXTypeTrait(Self, Rhs, tok::kw___is_layout_compatible);
6216
6217 return Self.IsLayoutCompatible(LhsT, RhsT);
6218 }
6219 case BTT_IsPointerInterconvertibleBaseOf: {
6220 if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() &&
6221 !Self.getASTContext().hasSameUnqualifiedType(LhsT, RhsT)) {
6222 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6223 diag::err_incomplete_type);
6224 }
6225
6227 tok::kw___is_pointer_interconvertible_base_of);
6229 tok::kw___is_pointer_interconvertible_base_of);
6230
6231 return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs);
6232 }
6233 case BTT_IsDeducible: {
6234 const auto *TSTToBeDeduced = cast<DeducedTemplateSpecializationType>(LhsT);
6235 sema::TemplateDeductionInfo Info(KeyLoc);
6236 return Self.DeduceTemplateArgumentsFromType(
6237 TSTToBeDeduced->getTemplateName().getAsTemplateDecl(), RhsT,
6239 }
6240 default:
6241 llvm_unreachable("not a BTT");
6242 }
6243 llvm_unreachable("Unknown type trait or not implemented");
6244}
6245
6247 SourceLocation KWLoc,
6248 ParsedType Ty,
6249 Expr* DimExpr,
6250 SourceLocation RParen) {
6251 TypeSourceInfo *TSInfo;
6252 QualType T = GetTypeFromParser(Ty, &TSInfo);
6253 if (!TSInfo)
6255
6256 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
6257}
6258
6260 QualType T, Expr *DimExpr,
6261 SourceLocation KeyLoc) {
6262 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
6263
6264 switch(ATT) {
6265 case ATT_ArrayRank:
6266 if (T->isArrayType()) {
6267 unsigned Dim = 0;
6268 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6269 ++Dim;
6270 T = AT->getElementType();
6271 }
6272 return Dim;
6273 }
6274 return 0;
6275
6276 case ATT_ArrayExtent: {
6277 llvm::APSInt Value;
6278 uint64_t Dim;
6279 if (Self.VerifyIntegerConstantExpression(
6280 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
6281 .isInvalid())
6282 return 0;
6283 if (Value.isSigned() && Value.isNegative()) {
6284 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
6285 << DimExpr->getSourceRange();
6286 return 0;
6287 }
6288 Dim = Value.getLimitedValue();
6289
6290 if (T->isArrayType()) {
6291 unsigned D = 0;
6292 bool Matched = false;
6293 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6294 if (Dim == D) {
6295 Matched = true;
6296 break;
6297 }
6298 ++D;
6299 T = AT->getElementType();
6300 }
6301
6302 if (Matched && T->isArrayType()) {
6303 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
6304 return CAT->getLimitedSize();
6305 }
6306 }
6307 return 0;
6308 }
6309 }
6310 llvm_unreachable("Unknown type trait or not implemented");
6311}
6312
6314 SourceLocation KWLoc,
6315 TypeSourceInfo *TSInfo,
6316 Expr* DimExpr,
6317 SourceLocation RParen) {
6318 QualType T = TSInfo->getType();
6319
6320 // FIXME: This should likely be tracked as an APInt to remove any host
6321 // assumptions about the width of size_t on the target.
6322 uint64_t Value = 0;
6323 if (!T->isDependentType())
6324 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
6325
6326 // While the specification for these traits from the Embarcadero C++
6327 // compiler's documentation says the return type is 'unsigned int', Clang
6328 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
6329 // compiler, there is no difference. On several other platforms this is an
6330 // important distinction.
6331 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
6332 RParen, Context.getSizeType());
6333}
6334
6336 SourceLocation KWLoc,
6337 Expr *Queried,
6338 SourceLocation RParen) {
6339 // If error parsing the expression, ignore.
6340 if (!Queried)
6341 return ExprError();
6342
6343 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
6344
6345 return Result;
6346}
6347
6349 switch (ET) {
6350 case ET_IsLValueExpr: return E->isLValue();
6351 case ET_IsRValueExpr:
6352 return E->isPRValue();
6353 }
6354 llvm_unreachable("Expression trait not covered by switch");
6355}
6356
6358 SourceLocation KWLoc,
6359 Expr *Queried,
6360 SourceLocation RParen) {
6361 if (Queried->isTypeDependent()) {
6362 // Delay type-checking for type-dependent expressions.
6363 } else if (Queried->hasPlaceholderType()) {
6364 ExprResult PE = CheckPlaceholderExpr(Queried);
6365 if (PE.isInvalid()) return ExprError();
6366 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
6367 }
6368
6369 bool Value = EvaluateExpressionTrait(ET, Queried);
6370
6371 return new (Context)
6372 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
6373}
6374
6376 ExprValueKind &VK,
6378 bool isIndirect) {
6379 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
6380 "placeholders should have been weeded out by now");
6381
6382 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
6383 // temporary materialization conversion otherwise.
6384 if (isIndirect)
6385 LHS = DefaultLvalueConversion(LHS.get());
6386 else if (LHS.get()->isPRValue())
6388 if (LHS.isInvalid())
6389 return QualType();
6390
6391 // The RHS always undergoes lvalue conversions.
6392 RHS = DefaultLvalueConversion(RHS.get());
6393 if (RHS.isInvalid()) return QualType();
6394
6395 const char *OpSpelling = isIndirect ? "->*" : ".*";
6396 // C++ 5.5p2
6397 // The binary operator .* [p3: ->*] binds its second operand, which shall
6398 // be of type "pointer to member of T" (where T is a completely-defined
6399 // class type) [...]
6400 QualType RHSType = RHS.get()->getType();
6401 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
6402 if (!MemPtr) {
6403 Diag(Loc, diag::err_bad_memptr_rhs)
6404 << OpSpelling << RHSType << RHS.get()->getSourceRange();
6405 return QualType();
6406 }
6407
6408 QualType Class(MemPtr->getClass(), 0);
6409
6410 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
6411 // member pointer points must be completely-defined. However, there is no
6412 // reason for this semantic distinction, and the rule is not enforced by
6413 // other compilers. Therefore, we do not check this property, as it is
6414 // likely to be considered a defect.
6415
6416 // C++ 5.5p2
6417 // [...] to its first operand, which shall be of class T or of a class of
6418 // which T is an unambiguous and accessible base class. [p3: a pointer to
6419 // such a class]
6420 QualType LHSType = LHS.get()->getType();
6421 if (isIndirect) {
6422 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
6423 LHSType = Ptr->getPointeeType();
6424 else {
6425 Diag(Loc, diag::err_bad_memptr_lhs)
6426 << OpSpelling << 1 << LHSType
6428 return QualType();
6429 }
6430 }
6431
6432 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
6433 // If we want to check the hierarchy, we need a complete type.
6434 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
6435 OpSpelling, (int)isIndirect)) {
6436 return QualType();
6437 }
6438
6439 if (!IsDerivedFrom(Loc, LHSType, Class)) {
6440 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6441 << (int)isIndirect << LHS.get()->getType();
6442 return QualType();
6443 }
6444
6445 CXXCastPath BasePath;
6447 LHSType, Class, Loc,
6448 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6449 &BasePath))
6450 return QualType();
6451
6452 // Cast LHS to type of use.
6453 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6454 if (isIndirect)
6455 UseType = Context.getPointerType(UseType);
6456 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6457 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6458 &BasePath);
6459 }
6460
6461 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6462 // Diagnose use of pointer-to-member type which when used as
6463 // the functional cast in a pointer-to-member expression.
6464 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6465 return QualType();
6466 }
6467
6468 // C++ 5.5p2
6469 // The result is an object or a function of the type specified by the
6470 // second operand.
6471 // The cv qualifiers are the union of those in the pointer and the left side,
6472 // in accordance with 5.5p5 and 5.2.5.
6473 QualType Result = MemPtr->getPointeeType();
6475
6476 // C++0x [expr.mptr.oper]p6:
6477 // In a .* expression whose object expression is an rvalue, the program is
6478 // ill-formed if the second operand is a pointer to member function with
6479 // ref-qualifier &. In a ->* expression or in a .* expression whose object
6480 // expression is an lvalue, the program is ill-formed if the second operand
6481 // is a pointer to member function with ref-qualifier &&.
6482 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6483 switch (Proto->getRefQualifier()) {
6484 case RQ_None:
6485 // Do nothing
6486 break;
6487
6488 case RQ_LValue:
6489 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6490 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6491 // is (exactly) 'const'.
6492 if (Proto->isConst() && !Proto->isVolatile())
6494 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6495 : diag::ext_pointer_to_const_ref_member_on_rvalue);
6496 else
6497 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6498 << RHSType << 1 << LHS.get()->getSourceRange();
6499 }
6500 break;
6501
6502 case RQ_RValue:
6503 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6504 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6505 << RHSType << 0 << LHS.get()->getSourceRange();
6506 break;
6507 }
6508 }
6509
6510 // C++ [expr.mptr.oper]p6:
6511 // The result of a .* expression whose second operand is a pointer
6512 // to a data member is of the same value category as its
6513 // first operand. The result of a .* expression whose second
6514 // operand is a pointer to a member function is a prvalue. The
6515 // result of an ->* expression is an lvalue if its second operand
6516 // is a pointer to data member and a prvalue otherwise.
6517 if (Result->isFunctionType()) {
6518 VK = VK_PRValue;
6519 return Context.BoundMemberTy;
6520 } else if (isIndirect) {
6521 VK = VK_LValue;
6522 } else {
6523 VK = LHS.get()->getValueKind();
6524 }
6525
6526 return Result;
6527}
6528
6529/// Try to convert a type to another according to C++11 5.16p3.
6530///
6531/// This is part of the parameter validation for the ? operator. If either
6532/// value operand is a class type, the two operands are attempted to be
6533/// converted to each other. This function does the conversion in one direction.
6534/// It returns true if the program is ill-formed and has already been diagnosed
6535/// as such.
6536static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6537 SourceLocation QuestionLoc,
6538 bool &HaveConversion,
6539 QualType &ToType) {
6540 HaveConversion = false;
6541 ToType = To->getType();
6542
6543 InitializationKind Kind =
6545 // C++11 5.16p3
6546 // The process for determining whether an operand expression E1 of type T1
6547 // can be converted to match an operand expression E2 of type T2 is defined
6548 // as follows:
6549 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6550 // implicitly converted to type "lvalue reference to T2", subject to the
6551 // constraint that in the conversion the reference must bind directly to
6552 // an lvalue.
6553 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6554 // implicitly converted to the type "rvalue reference to R2", subject to
6555 // the constraint that the reference must bind directly.
6556 if (To->isGLValue()) {
6557 QualType T = Self.Context.getReferenceQualifiedType(To);
6559
6560 InitializationSequence InitSeq(Self, Entity, Kind, From);
6561 if (InitSeq.isDirectReferenceBinding()) {
6562 ToType = T;
6563 HaveConversion = true;
6564 return false;
6565 }
6566
6567 if (InitSeq.isAmbiguous())
6568 return InitSeq.Diagnose(Self, Entity, Kind, From);
6569 }
6570
6571 // -- If E2 is an rvalue, or if the conversion above cannot be done:
6572 // -- if E1 and E2 have class type, and the underlying class types are
6573 // the same or one is a base class of the other:
6574 QualType FTy = From->getType();
6575 QualType TTy = To->getType();
6576 const RecordType *FRec = FTy->getAs<RecordType>();
6577 const RecordType *TRec = TTy->getAs<RecordType>();
6578 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6579 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6580 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6581 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6582 // E1 can be converted to match E2 if the class of T2 is the
6583 // same type as, or a base class of, the class of T1, and
6584 // [cv2 > cv1].
6585 if (FRec == TRec || FDerivedFromT) {
6586 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6588 InitializationSequence InitSeq(Self, Entity, Kind, From);
6589 if (InitSeq) {
6590 HaveConversion = true;
6591 return false;
6592 }
6593
6594 if (InitSeq.isAmbiguous())
6595 return InitSeq.Diagnose(Self, Entity, Kind, From);
6596 }
6597 }
6598
6599 return false;
6600 }
6601
6602 // -- Otherwise: E1 can be converted to match E2 if E1 can be
6603 // implicitly converted to the type that expression E2 would have
6604 // if E2 were converted to an rvalue (or the type it has, if E2 is
6605 // an rvalue).
6606 //
6607 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6608 // to the array-to-pointer or function-to-pointer conversions.
6609 TTy = TTy.getNonLValueExprType(Self.Context);
6610
6612 InitializationSequence InitSeq(Self, Entity, Kind, From);
6613 HaveConversion = !InitSeq.Failed();
6614 ToType = TTy;
6615 if (InitSeq.isAmbiguous())
6616 return InitSeq.Diagnose(Self, Entity, Kind, From);
6617
6618 return false;
6619}
6620
6621/// Try to find a common type for two according to C++0x 5.16p5.
6622///
6623/// This is part of the parameter validation for the ? operator. If either
6624/// value operand is a class type, overload resolution is used to find a
6625/// conversion to a common type.
6627 SourceLocation QuestionLoc) {
6628 Expr *Args[2] = { LHS.get(), RHS.get() };
6629 OverloadCandidateSet CandidateSet(QuestionLoc,
6631 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6632 CandidateSet);
6633
6635 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6636 case OR_Success: {
6637 // We found a match. Perform the conversions on the arguments and move on.
6638 ExprResult LHSRes = Self.PerformImplicitConversion(
6639 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6641 if (LHSRes.isInvalid())
6642 break;
6643 LHS = LHSRes;
6644
6645 ExprResult RHSRes = Self.PerformImplicitConversion(
6646 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6648 if (RHSRes.isInvalid())
6649 break;
6650 RHS = RHSRes;
6651 if (Best->Function)
6652 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6653 return false;
6654 }
6655
6657
6658 // Emit a better diagnostic if one of the expressions is a null pointer
6659 // constant and the other is a pointer type. In this case, the user most
6660 // likely forgot to take the address of the other expression.
6661 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6662 return true;
6663
6664 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6665 << LHS.get()->getType() << RHS.get()->getType()
6666 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6667 return true;
6668
6669 case OR_Ambiguous:
6670 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6671 << LHS.get()->getType() << RHS.get()->getType()
6672 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6673 // FIXME: Print the possible common types by printing the return types of
6674 // the viable candidates.
6675 break;
6676
6677 case OR_Deleted:
6678 llvm_unreachable("Conditional operator has only built-in overloads");
6679 }
6680 return true;
6681}
6682
6683/// Perform an "extended" implicit conversion as returned by
6684/// TryClassUnification.
6687 InitializationKind Kind =
6689 Expr *Arg = E.get();
6690 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6691 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6692 if (Result.isInvalid())
6693 return true;
6694
6695 E = Result;
6696 return false;
6697}
6698
6699// Check the condition operand of ?: to see if it is valid for the GCC
6700// extension.
6702 QualType CondTy) {
6703 if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6704 return false;
6705 const QualType EltTy =
6706 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6707 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6708 return EltTy->isIntegralType(Ctx);
6709}
6710
6712 QualType CondTy) {
6713 if (!CondTy->isSveVLSBuiltinType())
6714 return false;
6715 const QualType EltTy =
6716 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6717 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6718 return EltTy->isIntegralType(Ctx);
6719}
6720
6722 ExprResult &RHS,
6723 SourceLocation QuestionLoc) {
6726
6727 QualType CondType = Cond.get()->getType();
6728 const auto *CondVT = CondType->castAs<VectorType>();
6729 QualType CondElementTy = CondVT->getElementType();
6730 unsigned CondElementCount = CondVT->getNumElements();
6731 QualType LHSType = LHS.get()->getType();
6732 const auto *LHSVT = LHSType->getAs<VectorType>();
6733 QualType RHSType = RHS.get()->getType();
6734 const auto *RHSVT = RHSType->getAs<VectorType>();
6735
6736 QualType ResultType;
6737
6738
6739 if (LHSVT && RHSVT) {
6740 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6741 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6742 << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6743 return {};
6744 }
6745
6746 // If both are vector types, they must be the same type.
6747 if (!Context.hasSameType(LHSType, RHSType)) {
6748 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6749 << LHSType << RHSType;
6750 return {};
6751 }
6752 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6753 } else if (LHSVT || RHSVT) {
6754 ResultType = CheckVectorOperands(
6755 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6756 /*AllowBoolConversions*/ false,
6757 /*AllowBoolOperation*/ true,
6758 /*ReportInvalid*/ true);
6759 if (ResultType.isNull())
6760 return {};
6761 } else {
6762 // Both are scalar.
6763 LHSType = LHSType.getUnqualifiedType();
6764 RHSType = RHSType.getUnqualifiedType();
6765 QualType ResultElementTy =
6766 Context.hasSameType(LHSType, RHSType)
6767 ? Context.getCommonSugaredType(LHSType, RHSType)
6768 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6770
6771 if (ResultElementTy->isEnumeralType()) {
6772 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6773 << ResultElementTy;
6774 return {};
6775 }
6776 if (CondType->isExtVectorType())
6777 ResultType =
6778 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6779 else
6780 ResultType = Context.getVectorType(
6781 ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);
6782
6783 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6784 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6785 }
6786
6787 assert(!ResultType.isNull() && ResultType->isVectorType() &&
6788 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6789 "Result should have been a vector type");
6790 auto *ResultVectorTy = ResultType->castAs<VectorType>();
6791 QualType ResultElementTy = ResultVectorTy->getElementType();
6792 unsigned ResultElementCount = ResultVectorTy->getNumElements();
6793
6794 if (ResultElementCount != CondElementCount) {
6795 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6796 << ResultType;
6797 return {};
6798 }
6799
6800 if (Context.getTypeSize(ResultElementTy) !=
6801 Context.getTypeSize(CondElementTy)) {
6802 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6803 << ResultType;
6804 return {};
6805 }
6806
6807 return ResultType;
6808}
6809
6811 ExprResult &LHS,
6812 ExprResult &RHS,
6813 SourceLocation QuestionLoc) {
6816
6817 QualType CondType = Cond.get()->getType();
6818 const auto *CondBT = CondType->castAs<BuiltinType>();
6819 QualType CondElementTy = CondBT->getSveEltType(Context);
6820 llvm::ElementCount CondElementCount =
6822
6823 QualType LHSType = LHS.get()->getType();
6824 const auto *LHSBT =
6825 LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6826 QualType RHSType = RHS.get()->getType();
6827 const auto *RHSBT =
6828 RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6829
6830 QualType ResultType;
6831
6832 if (LHSBT && RHSBT) {
6833 // If both are sizeless vector types, they must be the same type.
6834 if (!Context.hasSameType(LHSType, RHSType)) {
6835 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6836 << LHSType << RHSType;
6837 return QualType();
6838 }
6839 ResultType = LHSType;
6840 } else if (LHSBT || RHSBT) {
6841 ResultType = CheckSizelessVectorOperands(
6842 LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6843 if (ResultType.isNull())
6844 return QualType();
6845 } else {
6846 // Both are scalar so splat
6847 QualType ResultElementTy;
6848 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6849 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6850
6851 if (Context.hasSameType(LHSType, RHSType))
6852 ResultElementTy = LHSType;
6853 else
6854 ResultElementTy =
6855 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6856
6857 if (ResultElementTy->isEnumeralType()) {
6858 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6859 << ResultElementTy;
6860 return QualType();
6861 }
6862
6863 ResultType = Context.getScalableVectorType(
6864 ResultElementTy, CondElementCount.getKnownMinValue());
6865
6866 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6867 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6868 }
6869
6870 assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&
6871 "Result should have been a vector type");
6872 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6873 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6874 llvm::ElementCount ResultElementCount =
6875 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6876
6877 if (ResultElementCount != CondElementCount) {
6878 Diag(QuestionLoc, diag::err_conditional_vector_size)
6879 << CondType << ResultType;
6880 return QualType();
6881 }
6882
6883 if (Context.getTypeSize(ResultElementTy) !=
6884 Context.getTypeSize(CondElementTy)) {
6885 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6886 << CondType << ResultType;
6887 return QualType();
6888 }
6889
6890 return ResultType;
6891}
6892
6894 ExprResult &RHS, ExprValueKind &VK,
6895 ExprObjectKind &OK,
6896 SourceLocation QuestionLoc) {
6897 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6898 // pointers.
6899
6900 // Assume r-value.
6901 VK = VK_PRValue;
6902 OK = OK_Ordinary;
6903 bool IsVectorConditional =
6905
6906 bool IsSizelessVectorConditional =
6908 Cond.get()->getType());
6909
6910 // C++11 [expr.cond]p1
6911 // The first expression is contextually converted to bool.
6912 if (!Cond.get()->isTypeDependent()) {
6913 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6915 : CheckCXXBooleanCondition(Cond.get());
6916 if (CondRes.isInvalid())
6917 return QualType();
6918 Cond = CondRes;
6919 } else {
6920 // To implement C++, the first expression typically doesn't alter the result
6921 // type of the conditional, however the GCC compatible vector extension
6922 // changes the result type to be that of the conditional. Since we cannot
6923 // know if this is a vector extension here, delay the conversion of the
6924 // LHS/RHS below until later.
6925 return Context.DependentTy;
6926 }
6927
6928
6929 // Either of the arguments dependent?
6930 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6931 return Context.DependentTy;
6932
6933 // C++11 [expr.cond]p2
6934 // If either the second or the third operand has type (cv) void, ...
6935 QualType LTy = LHS.get()->getType();
6936 QualType RTy = RHS.get()->getType();
6937 bool LVoid = LTy->isVoidType();
6938 bool RVoid = RTy->isVoidType();
6939 if (LVoid || RVoid) {
6940 // ... one of the following shall hold:
6941 // -- The second or the third operand (but not both) is a (possibly
6942 // parenthesized) throw-expression; the result is of the type
6943 // and value category of the other.
6944 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6945 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6946
6947 // Void expressions aren't legal in the vector-conditional expressions.
6948 if (IsVectorConditional) {
6949 SourceRange DiagLoc =
6950 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6951 bool IsThrow = LVoid ? LThrow : RThrow;
6952 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6953 << DiagLoc << IsThrow;
6954 return QualType();
6955 }
6956
6957 if (LThrow != RThrow) {
6958 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6959 VK = NonThrow->getValueKind();
6960 // DR (no number yet): the result is a bit-field if the
6961 // non-throw-expression operand is a bit-field.
6962 OK = NonThrow->getObjectKind();
6963 return NonThrow->getType();
6964 }
6965
6966 // -- Both the second and third operands have type void; the result is of
6967 // type void and is a prvalue.
6968 if (LVoid && RVoid)
6969 return Context.getCommonSugaredType(LTy, RTy);
6970
6971 // Neither holds, error.
6972 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6973 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6974 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6975 return QualType();
6976 }
6977
6978 // Neither is void.
6979 if (IsVectorConditional)
6980 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6981
6982 if (IsSizelessVectorConditional)
6983 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6984
6985 // WebAssembly tables are not allowed as conditional LHS or RHS.
6986 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
6987 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
6988 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6989 return QualType();
6990 }
6991
6992 // C++11 [expr.cond]p3
6993 // Otherwise, if the second and third operand have different types, and
6994 // either has (cv) class type [...] an attempt is made to convert each of
6995 // those operands to the type of the other.
6996 if (!Context.hasSameType(LTy, RTy) &&
6997 (LTy->isRecordType() || RTy->isRecordType())) {
6998 // These return true if a single direction is already ambiguous.
6999 QualType L2RType, R2LType;
7000 bool HaveL2R, HaveR2L;
7001 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
7002 return QualType();
7003 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
7004 return QualType();
7005
7006 // If both can be converted, [...] the program is ill-formed.
7007 if (HaveL2R && HaveR2L) {
7008 Diag(QuestionLoc, diag::err_conditional_ambiguous)
7009 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7010 return QualType();
7011 }
7012
7013 // If exactly one conversion is possible, that conversion is applied to
7014 // the chosen operand and the converted operands are used in place of the
7015 // original operands for the remainder of this section.
7016 if (HaveL2R) {
7017 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
7018 return QualType();
7019 LTy = LHS.get()->getType();
7020 } else if (HaveR2L) {
7021 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
7022 return QualType();
7023 RTy = RHS.get()->getType();
7024 }
7025 }
7026
7027 // C++11 [expr.cond]p3
7028 // if both are glvalues of the same value category and the same type except
7029 // for cv-qualification, an attempt is made to convert each of those
7030 // operands to the type of the other.
7031 // FIXME:
7032 // Resolving a defect in P0012R1: we extend this to cover all cases where
7033 // one of the operands is reference-compatible with the other, in order
7034 // to support conditionals between functions differing in noexcept. This
7035 // will similarly cover difference in array bounds after P0388R4.
7036 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
7037 // that instead?
7038 ExprValueKind LVK = LHS.get()->getValueKind();
7039 ExprValueKind RVK = RHS.get()->getValueKind();
7040 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
7041 // DerivedToBase was already handled by the class-specific case above.
7042 // FIXME: Should we allow ObjC conversions here?
7043 const ReferenceConversions AllowedConversions =
7044 ReferenceConversions::Qualification |
7045 ReferenceConversions::NestedQualification |
7046 ReferenceConversions::Function;
7047
7048 ReferenceConversions RefConv;
7049 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
7051 !(RefConv & ~AllowedConversions) &&
7052 // [...] subject to the constraint that the reference must bind
7053 // directly [...]
7054 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
7055 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
7056 RTy = RHS.get()->getType();
7057 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
7059 !(RefConv & ~AllowedConversions) &&
7060 !LHS.get()->refersToBitField() &&
7061 !LHS.get()->refersToVectorElement()) {
7062 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
7063 LTy = LHS.get()->getType();
7064 }
7065 }
7066
7067 // C++11 [expr.cond]p4
7068 // If the second and third operands are glvalues of the same value
7069 // category and have the same type, the result is of that type and
7070 // value category and it is a bit-field if the second or the third
7071 // operand is a bit-field, or if both are bit-fields.
7072 // We only extend this to bitfields, not to the crazy other kinds of
7073 // l-values.
7074 bool Same = Context.hasSameType(LTy, RTy);
7075 if (Same && LVK == RVK && LVK != VK_PRValue &&
7078 VK = LHS.get()->getValueKind();
7079 if (LHS.get()->getObjectKind() == OK_BitField ||
7080 RHS.get()->getObjectKind() == OK_BitField)
7081 OK = OK_BitField;
7082 return Context.getCommonSugaredType(LTy, RTy);
7083 }
7084
7085 // C++11 [expr.cond]p5
7086 // Otherwise, the result is a prvalue. If the second and third operands
7087 // do not have the same type, and either has (cv) class type, ...
7088 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
7089 // ... overload resolution is used to determine the conversions (if any)
7090 // to be applied to the operands. If the overload resolution fails, the
7091 // program is ill-formed.
7092 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
7093 return QualType();
7094 }
7095
7096 // C++11 [expr.cond]p6
7097 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
7098 // conversions are performed on the second and third operands.
7101 if (LHS.isInvalid() || RHS.isInvalid())
7102 return QualType();
7103 LTy = LHS.get()->getType();
7104 RTy = RHS.get()->getType();
7105
7106 // After those conversions, one of the following shall hold:
7107 // -- The second and third operands have the same type; the result
7108 // is of that type. If the operands have class type, the result
7109 // is a prvalue temporary of the result type, which is
7110 // copy-initialized from either the second operand or the third
7111 // operand depending on the value of the first operand.
7112 if (Context.hasSameType(LTy, RTy)) {
7113 if (LTy->isRecordType()) {
7114 // The operands have class type. Make a temporary copy.
7117 if (LHSCopy.isInvalid())
7118 return QualType();
7119
7122 if (RHSCopy.isInvalid())
7123 return QualType();
7124
7125 LHS = LHSCopy;
7126 RHS = RHSCopy;
7127 }
7128 return Context.getCommonSugaredType(LTy, RTy);
7129 }
7130
7131 // Extension: conditional operator involving vector types.
7132 if (LTy->isVectorType() || RTy->isVectorType())
7133 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
7134 /*AllowBothBool*/ true,
7135 /*AllowBoolConversions*/ false,
7136 /*AllowBoolOperation*/ false,
7137 /*ReportInvalid*/ true);
7138
7139 // -- The second and third operands have arithmetic or enumeration type;
7140 // the usual arithmetic conversions are performed to bring them to a
7141 // common type, and the result is of that type.
7142 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
7143 QualType ResTy =
7144 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7145 if (LHS.isInvalid() || RHS.isInvalid())
7146 return QualType();
7147 if (ResTy.isNull()) {
7148 Diag(QuestionLoc,
7149 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
7150 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7151 return QualType();
7152 }
7153
7154 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7155 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7156
7157 return ResTy;
7158 }
7159
7160 // -- The second and third operands have pointer type, or one has pointer
7161 // type and the other is a null pointer constant, or both are null
7162 // pointer constants, at least one of which is non-integral; pointer
7163 // conversions and qualification conversions are performed to bring them
7164 // to their composite pointer type. The result is of the composite
7165 // pointer type.
7166 // -- The second and third operands have pointer to member type, or one has
7167 // pointer to member type and the other is a null pointer constant;
7168 // pointer to member conversions and qualification conversions are
7169 // performed to bring them to a common type, whose cv-qualification
7170 // shall match the cv-qualification of either the second or the third
7171 // operand. The result is of the common type.
7172 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
7173 if (!Composite.isNull())
7174 return Composite;
7175
7176 // Similarly, attempt to find composite type of two objective-c pointers.
7177 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
7178 if (LHS.isInvalid() || RHS.isInvalid())
7179 return QualType();
7180 if (!Composite.isNull())
7181 return Composite;
7182
7183 // Check if we are using a null with a non-pointer type.
7184 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7185 return QualType();
7186
7187 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7188 << LHS.get()->getType() << RHS.get()->getType()
7189 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7190 return QualType();
7191}
7192
7194 Expr *&E1, Expr *&E2,
7195 bool ConvertArgs) {
7196 assert(getLangOpts().CPlusPlus && "This function assumes C++");
7197
7198 // C++1z [expr]p14:
7199 // The composite pointer type of two operands p1 and p2 having types T1
7200 // and T2
7201 QualType T1 = E1->getType(), T2 = E2->getType();
7202
7203 // where at least one is a pointer or pointer to member type or
7204 // std::nullptr_t is:
7205 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
7206 T1->isNullPtrType();
7207 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
7208 T2->isNullPtrType();
7209 if (!T1IsPointerLike && !T2IsPointerLike)
7210 return QualType();
7211
7212 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
7213 // This can't actually happen, following the standard, but we also use this
7214 // to implement the end of [expr.conv], which hits this case.
7215 //
7216 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
7217 if (T1IsPointerLike &&
7219 if (ConvertArgs)
7220 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
7221 ? CK_NullToMemberPointer
7222 : CK_NullToPointer).get();
7223 return T1;
7224 }
7225 if (T2IsPointerLike &&
7227 if (ConvertArgs)
7228 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
7229 ? CK_NullToMemberPointer
7230 : CK_NullToPointer).get();
7231 return T2;
7232 }
7233
7234 // Now both have to be pointers or member pointers.
7235 if (!T1IsPointerLike || !T2IsPointerLike)
7236 return QualType();
7237 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
7238 "nullptr_t should be a null pointer constant");
7239
7240 struct Step {
7241 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
7242 // Qualifiers to apply under the step kind.
7243 Qualifiers Quals;
7244 /// The class for a pointer-to-member; a constant array type with a bound
7245 /// (if any) for an array.
7246 const Type *ClassOrBound;
7247
7248 Step(Kind K, const Type *ClassOrBound = nullptr)
7249 : K(K), ClassOrBound(ClassOrBound) {}
7250 QualType rebuild(ASTContext &Ctx, QualType T) const {
7251 T = Ctx.getQualifiedType(T, Quals);
7252 switch (K) {
7253 case Pointer:
7254 return Ctx.getPointerType(T);
7255 case MemberPointer:
7256 return Ctx.getMemberPointerType(T, ClassOrBound);
7257 case ObjCPointer:
7258 return Ctx.getObjCObjectPointerType(T);
7259 case Array:
7260 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
7261 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
7262 ArraySizeModifier::Normal, 0);
7263 else
7264 return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);
7265 }
7266 llvm_unreachable("unknown step kind");
7267 }
7268 };
7269
7271
7272 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7273 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7274 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
7275 // respectively;
7276 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
7277 // to member of C2 of type cv2 U2" for some non-function type U, where
7278 // C1 is reference-related to C2 or C2 is reference-related to C1, the
7279 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
7280 // respectively;
7281 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
7282 // T2;
7283 //
7284 // Dismantle T1 and T2 to simultaneously determine whether they are similar
7285 // and to prepare to form the cv-combined type if so.
7286 QualType Composite1 = T1;
7287 QualType Composite2 = T2;
7288 unsigned NeedConstBefore = 0;
7289 while (true) {
7290 assert(!Composite1.isNull() && !Composite2.isNull());
7291
7292 Qualifiers Q1, Q2;
7293 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
7294 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
7295
7296 // Top-level qualifiers are ignored. Merge at all lower levels.
7297 if (!Steps.empty()) {
7298 // Find the qualifier union: (approximately) the unique minimal set of
7299 // qualifiers that is compatible with both types.
7301 Q2.getCVRUQualifiers());
7302
7303 // Under one level of pointer or pointer-to-member, we can change to an
7304 // unambiguous compatible address space.
7305 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
7306 Quals.setAddressSpace(Q1.getAddressSpace());
7307 } else if (Steps.size() == 1) {
7308 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
7309 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
7310 if (MaybeQ1 == MaybeQ2) {
7311 // Exception for ptr size address spaces. Should be able to choose
7312 // either address space during comparison.
7315 MaybeQ1 = true;
7316 else
7317 return QualType(); // No unique best address space.
7318 }
7319 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
7320 : Q2.getAddressSpace());
7321 } else {
7322 return QualType();
7323 }
7324
7325 // FIXME: In C, we merge __strong and none to __strong at the top level.
7326 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
7327 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
7328 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7329 assert(Steps.size() == 1);
7330 else
7331 return QualType();
7332
7333 // Mismatched lifetime qualifiers never compatibly include each other.
7334 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
7335 Quals.setObjCLifetime(Q1.getObjCLifetime());
7336 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7337 assert(Steps.size() == 1);
7338 else
7339 return QualType();
7340
7341 Steps.back().Quals = Quals;
7342 if (Q1 != Quals || Q2 != Quals)
7343 NeedConstBefore = Steps.size() - 1;
7344 }
7345
7346 // FIXME: Can we unify the following with UnwrapSimilarTypes?
7347
7348 const ArrayType *Arr1, *Arr2;
7349 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
7350 (Arr2 = Context.getAsArrayType(Composite2))) {
7351 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
7352 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
7353 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
7354 Composite1 = Arr1->getElementType();
7355 Composite2 = Arr2->getElementType();
7356 Steps.emplace_back(Step::Array, CAT1);
7357 continue;
7358 }
7359 bool IAT1 = isa<IncompleteArrayType>(Arr1);
7360 bool IAT2 = isa<IncompleteArrayType>(Arr2);
7361 if ((IAT1 && IAT2) ||
7362 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
7363 ((bool)CAT1 != (bool)CAT2) &&
7364 (Steps.empty() || Steps.back().K != Step::Array))) {
7365 // In C++20 onwards, we can unify an array of N T with an array of
7366 // a different or unknown bound. But we can't form an array whose
7367 // element type is an array of unknown bound by doing so.
7368 Composite1 = Arr1->getElementType();
7369 Composite2 = Arr2->getElementType();
7370 Steps.emplace_back(Step::Array);
7371 if (CAT1 || CAT2)
7372 NeedConstBefore = Steps.size();
7373 continue;
7374 }
7375 }
7376
7377 const PointerType *Ptr1, *Ptr2;
7378 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
7379 (Ptr2 = Composite2->getAs<PointerType>())) {
7380 Composite1 = Ptr1->getPointeeType();
7381 Composite2 = Ptr2->getPointeeType();
7382 Steps.emplace_back(Step::Pointer);
7383 continue;
7384 }
7385
7386 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
7387 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
7388 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
7389 Composite1 = ObjPtr1->getPointeeType();
7390 Composite2 = ObjPtr2->getPointeeType();
7391 Steps.emplace_back(Step::ObjCPointer);
7392 continue;
7393 }
7394
7395 const MemberPointerType *MemPtr1, *MemPtr2;
7396 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
7397 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
7398 Composite1 = MemPtr1->getPointeeType();
7399 Composite2 = MemPtr2->getPointeeType();
7400
7401 // At the top level, we can perform a base-to-derived pointer-to-member
7402 // conversion:
7403 //
7404 // - [...] where C1 is reference-related to C2 or C2 is
7405 // reference-related to C1
7406 //
7407 // (Note that the only kinds of reference-relatedness in scope here are
7408 // "same type or derived from".) At any other level, the class must
7409 // exactly match.
7410 const Type *Class = nullptr;
7411 QualType Cls1(MemPtr1->getClass(), 0);
7412 QualType Cls2(MemPtr2->getClass(), 0);
7413 if (Context.hasSameType(Cls1, Cls2))
7414 Class = MemPtr1->getClass();
7415 else if (Steps.empty())
7416 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7417 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7418 if (!Class)
7419 return QualType();
7420
7421 Steps.emplace_back(Step::MemberPointer, Class);
7422 continue;
7423 }
7424
7425 // Special case: at the top level, we can decompose an Objective-C pointer
7426 // and a 'cv void *'. Unify the qualifiers.
7427 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7428 Composite2->isObjCObjectPointerType()) ||
7429 (Composite1->isObjCObjectPointerType() &&
7430 Composite2->isVoidPointerType()))) {
7431 Composite1 = Composite1->getPointeeType();
7432 Composite2 = Composite2->getPointeeType();
7433 Steps.emplace_back(Step::Pointer);
7434 continue;
7435 }
7436
7437 // FIXME: block pointer types?
7438
7439 // Cannot unwrap any more types.
7440 break;
7441 }
7442
7443 // - if T1 or T2 is "pointer to noexcept function" and the other type is
7444 // "pointer to function", where the function types are otherwise the same,
7445 // "pointer to function";
7446 // - if T1 or T2 is "pointer to member of C1 of type function", the other
7447 // type is "pointer to member of C2 of type noexcept function", and C1
7448 // is reference-related to C2 or C2 is reference-related to C1, where
7449 // the function types are otherwise the same, "pointer to member of C2 of
7450 // type function" or "pointer to member of C1 of type function",
7451 // respectively;
7452 //
7453 // We also support 'noreturn' here, so as a Clang extension we generalize the
7454 // above to:
7455 //
7456 // - [Clang] If T1 and T2 are both of type "pointer to function" or
7457 // "pointer to member function" and the pointee types can be unified
7458 // by a function pointer conversion, that conversion is applied
7459 // before checking the following rules.
7460 //
7461 // We've already unwrapped down to the function types, and we want to merge
7462 // rather than just convert, so do this ourselves rather than calling
7463 // IsFunctionConversion.
7464 //
7465 // FIXME: In order to match the standard wording as closely as possible, we
7466 // currently only do this under a single level of pointers. Ideally, we would
7467 // allow this in general, and set NeedConstBefore to the relevant depth on
7468 // the side(s) where we changed anything. If we permit that, we should also
7469 // consider this conversion when determining type similarity and model it as
7470 // a qualification conversion.
7471 if (Steps.size() == 1) {
7472 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7473 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7474 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7475 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7476
7477 // The result is noreturn if both operands are.
7478 bool Noreturn =
7479 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7480 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7481 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7482
7483 // The result is nothrow if both operands are.
7484 SmallVector<QualType, 8> ExceptionTypeStorage;
7486 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7488
7489 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7490 FPT1->getParamTypes(), EPI1);
7491 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7492 FPT2->getParamTypes(), EPI2);
7493 }
7494 }
7495 }
7496
7497 // There are some more conversions we can perform under exactly one pointer.
7498 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7499 !Context.hasSameType(Composite1, Composite2)) {
7500 // - if T1 or T2 is "pointer to cv1 void" and the other type is
7501 // "pointer to cv2 T", where T is an object type or void,
7502 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7503 if (Composite1->isVoidType() && Composite2->isObjectType())
7504 Composite2 = Composite1;
7505 else if (Composite2->isVoidType() && Composite1->isObjectType())
7506 Composite1 = Composite2;
7507 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7508 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7509 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7510 // T1, respectively;
7511 //
7512 // The "similar type" handling covers all of this except for the "T1 is a
7513 // base class of T2" case in the definition of reference-related.
7514 else if (IsDerivedFrom(Loc, Composite1, Composite2))
7515 Composite1 = Composite2;
7516 else if (IsDerivedFrom(Loc, Composite2, Composite1))
7517 Composite2 = Composite1;
7518 }
7519
7520 // At this point, either the inner types are the same or we have failed to
7521 // find a composite pointer type.
7522 if (!Context.hasSameType(Composite1, Composite2))
7523 return QualType();
7524
7525 // Per C++ [conv.qual]p3, add 'const' to every level before the last
7526 // differing qualifier.
7527 for (unsigned I = 0; I != NeedConstBefore; ++I)
7528 Steps[I].Quals.addConst();
7529
7530 // Rebuild the composite type.
7531 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7532 for (auto &S : llvm::reverse(Steps))
7533 Composite = S.rebuild(Context, Composite);
7534
7535 if (ConvertArgs) {
7536 // Convert the expressions to the composite pointer type.
7537 InitializedEntity Entity =
7539 InitializationKind Kind =
7541
7542 InitializationSequence E1ToC(*this, Entity, Kind, E1);
7543 if (!E1ToC)
7544 return QualType();
7545
7546 InitializationSequence E2ToC(*this, Entity, Kind, E2);
7547 if (!E2ToC)
7548 return QualType();
7549
7550 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7551 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7552 if (E1Result.isInvalid())
7553 return QualType();
7554 E1 = E1Result.get();
7555
7556 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7557 if (E2Result.isInvalid())
7558 return QualType();
7559 E2 = E2Result.get();
7560 }
7561
7562 return Composite;
7563}
7564
7566 if (!E)
7567 return ExprError();
7568
7569 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7570
7571 // If the result is a glvalue, we shouldn't bind it.
7572 if (E->isGLValue())
7573 return E;
7574
7575 // In ARC, calls that return a retainable type can return retained,
7576 // in which case we have to insert a consuming cast.
7577 if (getLangOpts().ObjCAutoRefCount &&
7579
7580 bool ReturnsRetained;
7581
7582 // For actual calls, we compute this by examining the type of the
7583 // called value.
7584 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7585 Expr *Callee = Call->getCallee()->IgnoreParens();
7586 QualType T = Callee->getType();
7587
7588 if (T == Context.BoundMemberTy) {
7589 // Handle pointer-to-members.
7590 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7591 T = BinOp->getRHS()->getType();
7592 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7593 T = Mem->getMemberDecl()->getType();
7594 }
7595
7596 if (const PointerType *Ptr = T->getAs<PointerType>())
7597 T = Ptr->getPointeeType();
7598 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7599 T = Ptr->getPointeeType();
7600 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7601 T = MemPtr->getPointeeType();
7602
7603 auto *FTy = T->castAs<FunctionType>();
7604 ReturnsRetained = FTy->getExtInfo().getProducesResult();
7605
7606 // ActOnStmtExpr arranges things so that StmtExprs of retainable
7607 // type always produce a +1 object.
7608 } else if (isa<StmtExpr>(E)) {
7609 ReturnsRetained = true;
7610
7611 // We hit this case with the lambda conversion-to-block optimization;
7612 // we don't want any extra casts here.
7613 } else if (isa<CastExpr>(E) &&
7614 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7615 return E;
7616
7617 // For message sends and property references, we try to find an
7618 // actual method. FIXME: we should infer retention by selector in
7619 // cases where we don't have an actual method.
7620 } else {
7621 ObjCMethodDecl *D = nullptr;
7622 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7623 D = Send->getMethodDecl();
7624 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7625 D = BoxedExpr->getBoxingMethod();
7626 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7627 // Don't do reclaims if we're using the zero-element array
7628 // constant.
7629 if (ArrayLit->getNumElements() == 0 &&
7631 return E;
7632
7633 D = ArrayLit->getArrayWithObjectsMethod();
7634 } else if (ObjCDictionaryLiteral *DictLit
7635 = dyn_cast<ObjCDictionaryLiteral>(E)) {
7636 // Don't do reclaims if we're using the zero-element dictionary
7637 // constant.
7638 if (DictLit->getNumElements() == 0 &&
7640 return E;
7641
7642 D = DictLit->getDictWithObjectsMethod();
7643 }
7644
7645 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7646
7647 // Don't do reclaims on performSelector calls; despite their
7648 // return type, the invoked method doesn't necessarily actually
7649 // return an object.
7650 if (!ReturnsRetained &&
7651 D && D->getMethodFamily() == OMF_performSelector)
7652 return E;
7653 }
7654
7655 // Don't reclaim an object of Class type.
7656 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7657 return E;
7658
7660
7661 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7662 : CK_ARCReclaimReturnedObject);
7663 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7665 }
7666
7669
7670 if (!getLangOpts().CPlusPlus)
7671 return E;
7672
7673 // Search for the base element type (cf. ASTContext::getBaseElementType) with
7674 // a fast path for the common case that the type is directly a RecordType.
7676 const RecordType *RT = nullptr;
7677 while (!RT) {
7678 switch (T->getTypeClass()) {
7679 case Type::Record:
7680 RT = cast<RecordType>(T);
7681 break;
7682 case Type::ConstantArray:
7683 case Type::IncompleteArray:
7684 case Type::VariableArray:
7685 case Type::DependentSizedArray:
7686 T = cast<ArrayType>(T)->getElementType().getTypePtr();
7687 break;
7688 default:
7689 return E;
7690 }
7691 }
7692
7693 // That should be enough to guarantee that this type is complete, if we're
7694 // not processing a decltype expression.
7695 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7696 if (RD->isInvalidDecl() || RD->isDependentContext())
7697 return E;
7698
7699 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7701 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7702
7703 if (Destructor) {
7706 PDiag(diag::err_access_dtor_temp)
7707 << E->getType());
7709 return ExprError();
7710
7711 // If destructor is trivial, we can avoid the extra copy.
7712 if (Destructor->isTrivial())
7713 return E;
7714
7715 // We need a cleanup, but we don't need to remember the temporary.
7717 }
7718
7721
7722 if (IsDecltype)
7723 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7724
7725 return Bind;
7726}
7727
7730 if (SubExpr.isInvalid())
7731 return ExprError();
7732
7733 return MaybeCreateExprWithCleanups(SubExpr.get());
7734}
7735
7737 assert(SubExpr && "subexpression can't be null!");
7738
7740
7741 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7742 assert(ExprCleanupObjects.size() >= FirstCleanup);
7743 assert(Cleanup.exprNeedsCleanups() ||
7744 ExprCleanupObjects.size() == FirstCleanup);
7746 return SubExpr;
7747
7748 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7749 ExprCleanupObjects.size() - FirstCleanup);
7750
7752 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7754
7755 return E;
7756}
7757
7759 assert(SubStmt && "sub-statement can't be null!");
7760
7762
7764 return SubStmt;
7765
7766 // FIXME: In order to attach the temporaries, wrap the statement into
7767 // a StmtExpr; currently this is only used for asm statements.
7768 // This is hacky, either create a new CXXStmtWithTemporaries statement or
7769 // a new AsmStmtWithTemporaries.
7770 CompoundStmt *CompStmt =
7773 Expr *E = new (Context)
7775 /*FIXME TemplateDepth=*/0);
7777}
7778
7780 assert(ExprEvalContexts.back().ExprContext ==
7782 "not in a decltype expression");
7783
7785 if (Result.isInvalid())
7786 return ExprError();
7787 E = Result.get();
7788
7789 // C++11 [expr.call]p11:
7790 // If a function call is a prvalue of object type,
7791 // -- if the function call is either
7792 // -- the operand of a decltype-specifier, or
7793 // -- the right operand of a comma operator that is the operand of a
7794 // decltype-specifier,
7795 // a temporary object is not introduced for the prvalue.
7796
7797 // Recursively rebuild ParenExprs and comma expressions to strip out the
7798 // outermost CXXBindTemporaryExpr, if any.
7799 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7800 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7801 if (SubExpr.isInvalid())
7802 return ExprError();
7803 if (SubExpr.get() == PE->getSubExpr())
7804 return E;
7805 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7806 }
7807 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7808 if (BO->getOpcode() == BO_Comma) {
7809 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7810 if (RHS.isInvalid())
7811 return ExprError();
7812 if (RHS.get() == BO->getRHS())
7813 return E;
7814 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7815 BO->getType(), BO->getValueKind(),
7816 BO->getObjectKind(), BO->getOperatorLoc(),
7817 BO->getFPFeatures());
7818 }
7819 }
7820
7821 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7822 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7823 : nullptr;
7824 if (TopCall)
7825 E = TopCall;
7826 else
7827 TopBind = nullptr;
7828
7829 // Disable the special decltype handling now.
7830 ExprEvalContexts.back().ExprContext =
7832
7834 if (Result.isInvalid())
7835 return ExprError();
7836 E = Result.get();
7837
7838 // In MS mode, don't perform any extra checking of call return types within a
7839 // decltype expression.
7840 if (getLangOpts().MSVCCompat)
7841 return E;
7842
7843 // Perform the semantic checks we delayed until this point.
7844 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7845 I != N; ++I) {
7846 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7847 if (Call == TopCall)
7848 continue;
7849
7850 if (CheckCallReturnType(Call->getCallReturnType(Context),
7851 Call->getBeginLoc(), Call, Call->getDirectCallee()))
7852 return ExprError();
7853 }
7854
7855 // Now all relevant types are complete, check the destructors are accessible
7856 // and non-deleted, and annotate them on the temporaries.
7857 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7858 I != N; ++I) {
7860 ExprEvalContexts.back().DelayedDecltypeBinds[I];
7861 if (Bind == TopBind)
7862 continue;
7863
7864 CXXTemporary *Temp = Bind->getTemporary();
7865
7866 CXXRecordDecl *RD =
7867 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7870
7871 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7872 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7873 PDiag(diag::err_access_dtor_temp)
7874 << Bind->getType());
7875 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7876 return ExprError();
7877
7878 // We need a cleanup, but we don't need to remember the temporary.
7880 }
7881
7882 // Possibly strip off the top CXXBindTemporaryExpr.
7883 return E;
7884}
7885
7886/// Note a set of 'operator->' functions that were used for a member access.
7888 ArrayRef<FunctionDecl *> OperatorArrows) {
7889 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7890 // FIXME: Make this configurable?
7891 unsigned Limit = 9;
7892 if (OperatorArrows.size() > Limit) {
7893 // Produce Limit-1 normal notes and one 'skipping' note.
7894 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7895 SkipCount = OperatorArrows.size() - (Limit - 1);
7896 }
7897
7898 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7899 if (I == SkipStart) {
7900 S.Diag(OperatorArrows[I]->getLocation(),
7901 diag::note_operator_arrows_suppressed)
7902 << SkipCount;
7903 I += SkipCount;
7904 } else {
7905 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7906 << OperatorArrows[I]->getCallResultType();
7907 ++I;
7908 }
7909 }
7910}
7911
7913 SourceLocation OpLoc,
7914 tok::TokenKind OpKind,
7915 ParsedType &ObjectType,
7916 bool &MayBePseudoDestructor) {
7917 // Since this might be a postfix expression, get rid of ParenListExprs.
7919 if (Result.isInvalid()) return ExprError();
7920 Base = Result.get();
7921
7923 if (Result.isInvalid()) return ExprError();
7924 Base = Result.get();
7925
7926 QualType BaseType = Base->getType();
7927 MayBePseudoDestructor = false;
7928 if (BaseType->isDependentType()) {
7929 // If we have a pointer to a dependent type and are using the -> operator,
7930 // the object type is the type that the pointer points to. We might still
7931 // have enough information about that type to do something useful.
7932 if (OpKind == tok::arrow)
7933 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7934 BaseType = Ptr->getPointeeType();
7935
7936 ObjectType = ParsedType::make(BaseType);
7937 MayBePseudoDestructor = true;
7938 return Base;
7939 }
7940
7941 // C++ [over.match.oper]p8:
7942 // [...] When operator->returns, the operator-> is applied to the value
7943 // returned, with the original second operand.
7944 if (OpKind == tok::arrow) {
7945 QualType StartingType = BaseType;
7946 bool NoArrowOperatorFound = false;
7947 bool FirstIteration = true;
7948 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7949 // The set of types we've considered so far.
7951 SmallVector<FunctionDecl*, 8> OperatorArrows;
7952 CTypes.insert(Context.getCanonicalType(BaseType));
7953
7954 while (BaseType->isRecordType()) {
7955 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7956 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7957 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7958 noteOperatorArrows(*this, OperatorArrows);
7959 Diag(OpLoc, diag::note_operator_arrow_depth)
7960 << getLangOpts().ArrowDepth;
7961 return ExprError();
7962 }
7963
7965 S, Base, OpLoc,
7966 // When in a template specialization and on the first loop iteration,
7967 // potentially give the default diagnostic (with the fixit in a
7968 // separate note) instead of having the error reported back to here
7969 // and giving a diagnostic with a fixit attached to the error itself.
7970 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7971 ? nullptr
7972 : &NoArrowOperatorFound);
7973 if (Result.isInvalid()) {
7974 if (NoArrowOperatorFound) {
7975 if (FirstIteration) {
7976 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7977 << BaseType << 1 << Base->getSourceRange()
7978 << FixItHint::CreateReplacement(OpLoc, ".");
7979 OpKind = tok::period;
7980 break;
7981 }
7982 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7983 << BaseType << Base->getSourceRange();
7984 CallExpr *CE = dyn_cast<CallExpr>(Base);
7985 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7986 Diag(CD->getBeginLoc(),
7987 diag::note_member_reference_arrow_from_operator_arrow);
7988 }
7989 }
7990 return ExprError();
7991 }
7992 Base = Result.get();
7993 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7994 OperatorArrows.push_back(OpCall->getDirectCallee());
7995 BaseType = Base->getType();
7996 CanQualType CBaseType = Context.getCanonicalType(BaseType);
7997 if (!CTypes.insert(CBaseType).second) {
7998 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7999 noteOperatorArrows(*this, OperatorArrows);
8000 return ExprError();
8001 }
8002 FirstIteration = false;
8003 }
8004
8005 if (OpKind == tok::arrow) {
8006 if (BaseType->isPointerType())
8007 BaseType = BaseType->getPointeeType();
8008 else if (auto *AT = Context.getAsArrayType(BaseType))
8009 BaseType = AT->getElementType();
8010 }
8011 }
8012
8013 // Objective-C properties allow "." access on Objective-C pointer types,
8014 // so adjust the base type to the object type itself.
8015 if (BaseType->isObjCObjectPointerType())
8016 BaseType = BaseType->getPointeeType();
8017
8018 // C++ [basic.lookup.classref]p2:
8019 // [...] If the type of the object expression is of pointer to scalar
8020 // type, the unqualified-id is looked up in the context of the complete
8021 // postfix-expression.
8022 //
8023 // This also indicates that we could be parsing a pseudo-destructor-name.
8024 // Note that Objective-C class and object types can be pseudo-destructor
8025 // expressions or normal member (ivar or property) access expressions, and
8026 // it's legal for the type to be incomplete if this is a pseudo-destructor
8027 // call. We'll do more incomplete-type checks later in the lookup process,
8028 // so just skip this check for ObjC types.
8029 if (!BaseType->isRecordType()) {
8030 ObjectType = ParsedType::make(BaseType);
8031 MayBePseudoDestructor = true;
8032 return Base;
8033 }
8034
8035 // The object type must be complete (or dependent), or
8036 // C++11 [expr.prim.general]p3:
8037 // Unlike the object expression in other contexts, *this is not required to
8038 // be of complete type for purposes of class member access (5.2.5) outside
8039 // the member function body.
8040 if (!BaseType->isDependentType() &&
8042 RequireCompleteType(OpLoc, BaseType,
8043 diag::err_incomplete_member_access)) {
8044 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
8045 }
8046
8047 // C++ [basic.lookup.classref]p2:
8048 // If the id-expression in a class member access (5.2.5) is an
8049 // unqualified-id, and the type of the object expression is of a class
8050 // type C (or of pointer to a class type C), the unqualified-id is looked
8051 // up in the scope of class C. [...]
8052 ObjectType = ParsedType::make(BaseType);
8053 return Base;
8054}
8055
8056static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
8057 tok::TokenKind &OpKind, SourceLocation OpLoc) {
8058 if (Base->hasPlaceholderType()) {
8060 if (result.isInvalid()) return true;
8061 Base = result.get();
8062 }
8063 ObjectType = Base->getType();
8064
8065 // C++ [expr.pseudo]p2:
8066 // The left-hand side of the dot operator shall be of scalar type. The
8067 // left-hand side of the arrow operator shall be of pointer to scalar type.
8068 // This scalar type is the object type.
8069 // Note that this is rather different from the normal handling for the
8070 // arrow operator.
8071 if (OpKind == tok::arrow) {
8072 // The operator requires a prvalue, so perform lvalue conversions.
8073 // Only do this if we might plausibly end with a pointer, as otherwise
8074 // this was likely to be intended to be a '.'.
8075 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
8076 ObjectType->isFunctionType()) {
8078 if (BaseResult.isInvalid())
8079 return true;
8080 Base = BaseResult.get();
8081 ObjectType = Base->getType();
8082 }
8083
8084 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
8085 ObjectType = Ptr->getPointeeType();
8086 } else if (!Base->isTypeDependent()) {
8087 // The user wrote "p->" when they probably meant "p."; fix it.
8088 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8089 << ObjectType << true
8090 << FixItHint::CreateReplacement(OpLoc, ".");
8091 if (S.isSFINAEContext())
8092 return true;
8093
8094 OpKind = tok::period;
8095 }
8096 }
8097
8098 return false;
8099}
8100
8101/// Check if it's ok to try and recover dot pseudo destructor calls on
8102/// pointer objects.
8103static bool
8105 QualType DestructedType) {
8106 // If this is a record type, check if its destructor is callable.
8107 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
8108 if (RD->hasDefinition())
8110 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
8111 return false;
8112 }
8113
8114 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
8115 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
8116 DestructedType->isVectorType();
8117}
8118
8120 SourceLocation OpLoc,
8121 tok::TokenKind OpKind,
8122 const CXXScopeSpec &SS,
8123 TypeSourceInfo *ScopeTypeInfo,
8124 SourceLocation CCLoc,
8125 SourceLocation TildeLoc,
8126 PseudoDestructorTypeStorage Destructed) {
8127 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
8128
8129 QualType ObjectType;
8130 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8131 return ExprError();
8132
8133 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
8134 !ObjectType->isVectorType()) {
8135 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
8136 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
8137 else {
8138 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
8139 << ObjectType << Base->getSourceRange();
8140 return ExprError();
8141 }
8142 }
8143
8144 // C++ [expr.pseudo]p2:
8145 // [...] The cv-unqualified versions of the object type and of the type
8146 // designated by the pseudo-destructor-name shall be the same type.
8147 if (DestructedTypeInfo) {
8148 QualType DestructedType = DestructedTypeInfo->getType();
8149 SourceLocation DestructedTypeStart =
8150 DestructedTypeInfo->getTypeLoc().getBeginLoc();
8151 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
8152 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
8153 // Detect dot pseudo destructor calls on pointer objects, e.g.:
8154 // Foo *foo;
8155 // foo.~Foo();
8156 if (OpKind == tok::period && ObjectType->isPointerType() &&
8157 Context.hasSameUnqualifiedType(DestructedType,
8158 ObjectType->getPointeeType())) {
8159 auto Diagnostic =
8160 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8161 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
8162
8163 // Issue a fixit only when the destructor is valid.
8165 *this, DestructedType))
8167
8168 // Recover by setting the object type to the destructed type and the
8169 // operator to '->'.
8170 ObjectType = DestructedType;
8171 OpKind = tok::arrow;
8172 } else {
8173 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
8174 << ObjectType << DestructedType << Base->getSourceRange()
8175 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8176
8177 // Recover by setting the destructed type to the object type.
8178 DestructedType = ObjectType;
8179 DestructedTypeInfo =
8180 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
8181 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8182 }
8183 } else if (DestructedType.getObjCLifetime() !=
8184 ObjectType.getObjCLifetime()) {
8185
8186 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
8187 // Okay: just pretend that the user provided the correctly-qualified
8188 // type.
8189 } else {
8190 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
8191 << ObjectType << DestructedType << Base->getSourceRange()
8192 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8193 }
8194
8195 // Recover by setting the destructed type to the object type.
8196 DestructedType = ObjectType;
8197 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
8198 DestructedTypeStart);
8199 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8200 }
8201 }
8202 }
8203
8204 // C++ [expr.pseudo]p2:
8205 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
8206 // form
8207 //
8208 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
8209 //
8210 // shall designate the same scalar type.
8211 if (ScopeTypeInfo) {
8212 QualType ScopeType = ScopeTypeInfo->getType();
8213 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
8214 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
8215
8216 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
8217 diag::err_pseudo_dtor_type_mismatch)
8218 << ObjectType << ScopeType << Base->getSourceRange()
8219 << ScopeTypeInfo->getTypeLoc().getSourceRange();
8220
8221 ScopeType = QualType();
8222 ScopeTypeInfo = nullptr;
8223 }
8224 }
8225
8226 Expr *Result
8228 OpKind == tok::arrow, OpLoc,
8230 ScopeTypeInfo,
8231 CCLoc,
8232 TildeLoc,
8233 Destructed);
8234
8235 return Result;
8236}
8237
8239 SourceLocation OpLoc,
8240 tok::TokenKind OpKind,
8241 CXXScopeSpec &SS,
8242 UnqualifiedId &FirstTypeName,
8243 SourceLocation CCLoc,
8244 SourceLocation TildeLoc,
8245 UnqualifiedId &SecondTypeName) {
8246 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8247 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8248 "Invalid first type name in pseudo-destructor");
8249 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8250 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8251 "Invalid second type name in pseudo-destructor");
8252
8253 QualType ObjectType;
8254 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8255 return ExprError();
8256
8257 // Compute the object type that we should use for name lookup purposes. Only
8258 // record types and dependent types matter.
8259 ParsedType ObjectTypePtrForLookup;
8260 if (!SS.isSet()) {
8261 if (ObjectType->isRecordType())
8262 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
8263 else if (ObjectType->isDependentType())
8264 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
8265 }
8266
8267 // Convert the name of the type being destructed (following the ~) into a
8268 // type (with source-location information).
8269 QualType DestructedType;
8270 TypeSourceInfo *DestructedTypeInfo = nullptr;
8271 PseudoDestructorTypeStorage Destructed;
8272 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8273 ParsedType T = getTypeName(*SecondTypeName.Identifier,
8274 SecondTypeName.StartLocation,
8275 S, &SS, true, false, ObjectTypePtrForLookup,
8276 /*IsCtorOrDtorName*/true);
8277 if (!T &&
8278 ((SS.isSet() && !computeDeclContext(SS, false)) ||
8279 (!SS.isSet() && ObjectType->isDependentType()))) {
8280 // The name of the type being destroyed is a dependent name, and we
8281 // couldn't find anything useful in scope. Just store the identifier and
8282 // it's location, and we'll perform (qualified) name lookup again at
8283 // template instantiation time.
8284 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
8285 SecondTypeName.StartLocation);
8286 } else if (!T) {
8287 Diag(SecondTypeName.StartLocation,
8288 diag::err_pseudo_dtor_destructor_non_type)
8289 << SecondTypeName.Identifier << ObjectType;
8290 if (isSFINAEContext())
8291 return ExprError();
8292
8293 // Recover by assuming we had the right type all along.
8294 DestructedType = ObjectType;
8295 } else
8296 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
8297 } else {
8298 // Resolve the template-id to a type.
8299 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
8300 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8301 TemplateId->NumArgs);
8303 SS,
8304 TemplateId->TemplateKWLoc,
8305 TemplateId->Template,
8306 TemplateId->Name,
8307 TemplateId->TemplateNameLoc,
8308 TemplateId->LAngleLoc,
8309 TemplateArgsPtr,
8310 TemplateId->RAngleLoc,
8311 /*IsCtorOrDtorName*/true);
8312 if (T.isInvalid() || !T.get()) {
8313 // Recover by assuming we had the right type all along.
8314 DestructedType = ObjectType;
8315 } else
8316 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
8317 }
8318
8319 // If we've performed some kind of recovery, (re-)build the type source
8320 // information.
8321 if (!DestructedType.isNull()) {
8322 if (!DestructedTypeInfo)
8323 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
8324 SecondTypeName.StartLocation);
8325 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8326 }
8327
8328 // Convert the name of the scope type (the type prior to '::') into a type.
8329 TypeSourceInfo *ScopeTypeInfo = nullptr;
8330 QualType ScopeType;
8331 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8332 FirstTypeName.Identifier) {
8333 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8334 ParsedType T = getTypeName(*FirstTypeName.Identifier,
8335 FirstTypeName.StartLocation,
8336 S, &SS, true, false, ObjectTypePtrForLookup,
8337 /*IsCtorOrDtorName*/true);
8338 if (!T) {
8339 Diag(FirstTypeName.StartLocation,
8340 diag::err_pseudo_dtor_destructor_non_type)
8341 << FirstTypeName.Identifier << ObjectType;
8342
8343 if (isSFINAEContext())
8344 return ExprError();
8345
8346 // Just drop this type. It's unnecessary anyway.
8347 ScopeType = QualType();
8348 } else
8349 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
8350 } else {
8351 // Resolve the template-id to a type.
8352 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
8353 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8354 TemplateId->NumArgs);
8356 SS,
8357 TemplateId->TemplateKWLoc,
8358 TemplateId->Template,
8359 TemplateId->Name,
8360 TemplateId->TemplateNameLoc,
8361 TemplateId->LAngleLoc,
8362 TemplateArgsPtr,
8363 TemplateId->RAngleLoc,
8364 /*IsCtorOrDtorName*/true);
8365 if (T.isInvalid() || !T.get()) {
8366 // Recover by dropping this type.
8367 ScopeType = QualType();
8368 } else
8369 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
8370 }
8371 }
8372
8373 if (!ScopeType.isNull() && !ScopeTypeInfo)
8374 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
8375 FirstTypeName.StartLocation);
8376
8377
8378 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
8379 ScopeTypeInfo, CCLoc, TildeLoc,
8380 Destructed);
8381}
8382
8384 SourceLocation OpLoc,
8385 tok::TokenKind OpKind,
8386 SourceLocation TildeLoc,
8387 const DeclSpec& DS) {
8388 QualType ObjectType;
8389 QualType T;
8390 TypeLocBuilder TLB;
8391 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8392 return ExprError();
8393
8394 switch (DS.getTypeSpecType()) {
8396 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
8397 return true;
8398 }
8400 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
8401 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
8402 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
8403 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
8404 break;
8405 }
8408 DS.getBeginLoc(), DS.getEllipsisLoc());
8410 cast<PackIndexingType>(T.getTypePtr())->getPattern(),
8411 DS.getBeginLoc());
8413 PITL.setEllipsisLoc(DS.getEllipsisLoc());
8414 break;
8415 }
8416 default:
8417 llvm_unreachable("Unsupported type in pseudo destructor");
8418 }
8419 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
8420 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
8421
8422 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
8423 nullptr, SourceLocation(), TildeLoc,
8424 Destructed);
8425}
8426
8428 SourceLocation RParen) {
8429 // If the operand is an unresolved lookup expression, the expression is ill-
8430 // formed per [over.over]p1, because overloaded function names cannot be used
8431 // without arguments except in explicit contexts.
8432 ExprResult R = CheckPlaceholderExpr(Operand);
8433 if (R.isInvalid())
8434 return R;
8435
8437 if (R.isInvalid())
8438 return ExprError();
8439
8440 Operand = R.get();
8441
8442 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8443 Operand->HasSideEffects(Context, false)) {
8444 // The expression operand for noexcept is in an unevaluated expression
8445 // context, so side effects could result in unintended consequences.
8446 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8447 }
8448
8449 CanThrowResult CanThrow = canThrow(Operand);
8450 return new (Context)
8451 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8452}
8453
8455 Expr *Operand, SourceLocation RParen) {
8456 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8457}
8458
8460 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8461 DeclRefExpr *LHS = nullptr;
8462 bool IsCompoundAssign = false;
8463 bool isIncrementDecrementUnaryOp = false;
8464 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8465 if (BO->getLHS()->getType()->isDependentType() ||
8466 BO->getRHS()->getType()->isDependentType()) {
8467 if (BO->getOpcode() != BO_Assign)
8468 return;
8469 } else if (!BO->isAssignmentOp())
8470 return;
8471 else
8472 IsCompoundAssign = BO->isCompoundAssignmentOp();
8473 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8474 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8475 if (COCE->getOperator() != OO_Equal)
8476 return;
8477 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8478 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8479 if (!UO->isIncrementDecrementOp())
8480 return;
8481 isIncrementDecrementUnaryOp = true;
8482 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8483 }
8484 if (!LHS)
8485 return;
8486 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8487 if (!VD)
8488 return;
8489 // Don't decrement RefsMinusAssignments if volatile variable with compound
8490 // assignment (+=, ...) or increment/decrement unary operator to avoid
8491 // potential unused-but-set-variable warning.
8492 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8494 return;
8495 auto iter = RefsMinusAssignments.find(VD);
8496 if (iter == RefsMinusAssignments.end())
8497 return;
8498 iter->getSecond()--;
8499}
8500
8501/// Perform the conversions required for an expression used in a
8502/// context that ignores the result.
8505
8506 if (E->hasPlaceholderType()) {
8508 if (result.isInvalid()) return E;
8509 E = result.get();
8510 }
8511
8512 if (getLangOpts().CPlusPlus) {
8513 // The C++11 standard defines the notion of a discarded-value expression;
8514 // normally, we don't need to do anything to handle it, but if it is a
8515 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8516 // conversion.
8519 if (Res.isInvalid())
8520 return E;
8521 E = Res.get();
8522 } else {
8523 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8524 // it occurs as a discarded-value expression.
8526 }
8527
8528 // C++1z:
8529 // If the expression is a prvalue after this optional conversion, the
8530 // temporary materialization conversion is applied.
8531 //
8532 // We do not materialize temporaries by default in order to avoid creating
8533 // unnecessary temporary objects. If we skip this step, IR generation is
8534 // able to synthesize the storage for itself in the aggregate case, and
8535 // adding the extra node to the AST is just clutter.
8537 E->isPRValue() && !E->getType()->isVoidType()) {
8539 if (Res.isInvalid())
8540 return E;
8541 E = Res.get();
8542 }
8543 return E;
8544 }
8545
8546 // C99 6.3.2.1:
8547 // [Except in specific positions,] an lvalue that does not have
8548 // array type is converted to the value stored in the
8549 // designated object (and is no longer an lvalue).
8550 if (E->isPRValue()) {
8551 // In C, function designators (i.e. expressions of function type)
8552 // are r-values, but we still want to do function-to-pointer decay
8553 // on them. This is both technically correct and convenient for
8554 // some clients.
8557
8558 return E;
8559 }
8560
8561 // GCC seems to also exclude expressions of incomplete enum type.
8562 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8563 if (!T->getDecl()->isComplete()) {
8564 // FIXME: stupid workaround for a codegen bug!
8565 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8566 return E;
8567 }
8568 }
8569
8571 if (Res.isInvalid())
8572 return E;
8573 E = Res.get();
8574
8575 if (!E->getType()->isVoidType())
8577 diag::err_incomplete_type);
8578 return E;
8579}
8580
8582 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8583 // it occurs as an unevaluated operand.
8585
8586 return E;
8587}
8588
8589// If we can unambiguously determine whether Var can never be used
8590// in a constant expression, return true.
8591// - if the variable and its initializer are non-dependent, then
8592// we can unambiguously check if the variable is a constant expression.
8593// - if the initializer is not value dependent - we can determine whether
8594// it can be used to initialize a constant expression. If Init can not
8595// be used to initialize a constant expression we conclude that Var can
8596// never be a constant expression.
8597// - FXIME: if the initializer is dependent, we can still do some analysis and
8598// identify certain cases unambiguously as non-const by using a Visitor:
8599// - such as those that involve odr-use of a ParmVarDecl, involve a new
8600// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8603 if (isa<ParmVarDecl>(Var)) return true;
8604 const VarDecl *DefVD = nullptr;
8605
8606 // If there is no initializer - this can not be a constant expression.
8607 const Expr *Init = Var->getAnyInitializer(DefVD);
8608 if (!Init)
8609 return true;
8610 assert(DefVD);
8611 if (DefVD->isWeak())
8612 return false;
8613
8614 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8615 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8616 // of value-dependent expressions, and use it here to determine whether the
8617 // initializer is a potential constant expression.
8618 return false;
8619 }
8620
8622}
8623
8624/// Check if the current lambda has any potential captures
8625/// that must be captured by any of its enclosing lambdas that are ready to
8626/// capture. If there is a lambda that can capture a nested
8627/// potential-capture, go ahead and do so. Also, check to see if any
8628/// variables are uncaptureable or do not involve an odr-use so do not
8629/// need to be captured.
8630
8632 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8633
8634 assert(!S.isUnevaluatedContext());
8635 assert(S.CurContext->isDependentContext());
8636#ifndef NDEBUG
8637 DeclContext *DC = S.CurContext;
8638 while (isa_and_nonnull<CapturedDecl>(DC))
8639 DC = DC->getParent();
8640 assert(
8641 CurrentLSI->CallOperator == DC &&
8642 "The current call operator must be synchronized with Sema's CurContext");
8643#endif // NDEBUG
8644
8645 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8646
8647 // All the potentially captureable variables in the current nested
8648 // lambda (within a generic outer lambda), must be captured by an
8649 // outer lambda that is enclosed within a non-dependent context.
8650 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8651 // If the variable is clearly identified as non-odr-used and the full
8652 // expression is not instantiation dependent, only then do we not
8653 // need to check enclosing lambda's for speculative captures.
8654 // For e.g.:
8655 // Even though 'x' is not odr-used, it should be captured.
8656 // int test() {
8657 // const int x = 10;
8658 // auto L = [=](auto a) {
8659 // (void) +x + a;
8660 // };
8661 // }
8662 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8663 !IsFullExprInstantiationDependent)
8664 return;
8665
8666 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8667 if (!UnderlyingVar)
8668 return;
8669
8670 // If we have a capture-capable lambda for the variable, go ahead and
8671 // capture the variable in that lambda (and all its enclosing lambdas).
8672 if (const std::optional<unsigned> Index =
8674 S.FunctionScopes, Var, S))
8675 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8676 const bool IsVarNeverAConstantExpression =
8678 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8679 // This full expression is not instantiation dependent or the variable
8680 // can not be used in a constant expression - which means
8681 // this variable must be odr-used here, so diagnose a
8682 // capture violation early, if the variable is un-captureable.
8683 // This is purely for diagnosing errors early. Otherwise, this
8684 // error would get diagnosed when the lambda becomes capture ready.
8685 QualType CaptureType, DeclRefType;
8686 SourceLocation ExprLoc = VarExpr->getExprLoc();
8687 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8688 /*EllipsisLoc*/ SourceLocation(),
8689 /*BuildAndDiagnose*/false, CaptureType,
8690 DeclRefType, nullptr)) {
8691 // We will never be able to capture this variable, and we need
8692 // to be able to in any and all instantiations, so diagnose it.
8693 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8694 /*EllipsisLoc*/ SourceLocation(),
8695 /*BuildAndDiagnose*/true, CaptureType,
8696 DeclRefType, nullptr);
8697 }
8698 }
8699 });
8700
8701 // Check if 'this' needs to be captured.
8702 if (CurrentLSI->hasPotentialThisCapture()) {
8703 // If we have a capture-capable lambda for 'this', go ahead and capture
8704 // 'this' in that lambda (and all its enclosing lambdas).
8705 if (const std::optional<unsigned> Index =
8707 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8708 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8710 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8711 &FunctionScopeIndexOfCapturableLambda);
8712 }
8713 }
8714
8715 // Reset all the potential captures at the end of each full-expression.
8716 CurrentLSI->clearPotentialCaptures();
8717}
8718
8721 const TypoCorrection &TC) {
8722 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8723 Consumer.getLookupResult().getLookupKind());
8724 const CXXScopeSpec *SS = Consumer.getSS();
8725 CXXScopeSpec NewSS;
8726
8727 // Use an approprate CXXScopeSpec for building the expr.
8728 if (auto *NNS = TC.getCorrectionSpecifier())
8730 else if (SS && !TC.WillReplaceSpecifier())
8731 NewSS = *SS;
8732
8733 if (auto *ND = TC.getFoundDecl()) {
8734 R.setLookupName(ND->getDeclName());
8735 R.addDecl(ND);
8736 if (ND->isCXXClassMember()) {
8737 // Figure out the correct naming class to add to the LookupResult.
8738 CXXRecordDecl *Record = nullptr;
8739 if (auto *NNS = TC.getCorrectionSpecifier())
8740 Record = NNS->getAsType()->getAsCXXRecordDecl();
8741 if (!Record)
8742 Record =
8743 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8744 if (Record)
8746
8747 // Detect and handle the case where the decl might be an implicit
8748 // member.
8750 NewSS, R, Consumer.isAddressOfOperand()))
8752 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8753 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8754 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8755 return SemaRef.ObjC().LookupInObjCMethod(R, Consumer.getScope(),
8756 Ivar->getIdentifier());
8757 }
8758 }
8759
8760 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8761 /*AcceptInvalidDecl*/ true);
8762}
8763
8764namespace {
8765class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8767
8768public:
8769 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8770 : TypoExprs(TypoExprs) {}
8771 bool VisitTypoExpr(TypoExpr *TE) {
8772 TypoExprs.insert(TE);
8773 return true;
8774 }
8775};
8776
8777class TransformTypos : public TreeTransform<TransformTypos> {
8778 typedef TreeTransform<TransformTypos> BaseTransform;
8779
8780 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8781 // process of being initialized.
8782 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8783 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8784 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8785 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8786
8787 /// Emit diagnostics for all of the TypoExprs encountered.
8788 ///
8789 /// If the TypoExprs were successfully corrected, then the diagnostics should
8790 /// suggest the corrections. Otherwise the diagnostics will not suggest
8791 /// anything (having been passed an empty TypoCorrection).
8792 ///
8793 /// If we've failed to correct due to ambiguous corrections, we need to
8794 /// be sure to pass empty corrections and replacements. Otherwise it's
8795 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8796 /// and we don't want to report those diagnostics.
8797 void EmitAllDiagnostics(bool IsAmbiguous) {
8798 for (TypoExpr *TE : TypoExprs) {
8799 auto &State = SemaRef.getTypoExprState(TE);
8800 if (State.DiagHandler) {
8801 TypoCorrection TC = IsAmbiguous
8802 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8803 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8804
8805 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8806 // TypoCorrection, replacing the existing decls. This ensures the right
8807 // NamedDecl is used in diagnostics e.g. in the case where overload
8808 // resolution was used to select one from several possible decls that
8809 // had been stored in the TypoCorrection.
8810 if (auto *ND = getDeclFromExpr(
8811 Replacement.isInvalid() ? nullptr : Replacement.get()))
8812 TC.setCorrectionDecl(ND);
8813
8814 State.DiagHandler(TC);
8815 }
8816 SemaRef.clearDelayedTypo(TE);
8817 }
8818 }
8819
8820 /// Try to advance the typo correction state of the first unfinished TypoExpr.
8821 /// We allow advancement of the correction stream by removing it from the
8822 /// TransformCache which allows `TransformTypoExpr` to advance during the
8823 /// next transformation attempt.
8824 ///
8825 /// Any substitution attempts for the previous TypoExprs (which must have been
8826 /// finished) will need to be retried since it's possible that they will now
8827 /// be invalid given the latest advancement.
8828 ///
8829 /// We need to be sure that we're making progress - it's possible that the
8830 /// tree is so malformed that the transform never makes it to the
8831 /// `TransformTypoExpr`.
8832 ///
8833 /// Returns true if there are any untried correction combinations.
8834 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8835 for (auto *TE : TypoExprs) {
8836 auto &State = SemaRef.getTypoExprState(TE);
8837 TransformCache.erase(TE);
8838 if (!State.Consumer->hasMadeAnyCorrectionProgress())
8839 return false;
8840 if (!State.Consumer->finished())
8841 return true;
8842 State.Consumer->resetCorrectionStream();
8843 }
8844 return false;
8845 }
8846
8848 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8849 E = OverloadResolution[OE];
8850
8851 if (!E)
8852 return nullptr;
8853 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8854 return DRE->getFoundDecl();
8855 if (auto *ME = dyn_cast<MemberExpr>(E))
8856 return ME->getFoundDecl();
8857 // FIXME: Add any other expr types that could be seen by the delayed typo
8858 // correction TreeTransform for which the corresponding TypoCorrection could
8859 // contain multiple decls.
8860 return nullptr;
8861 }
8862
8863 ExprResult TryTransform(Expr *E) {
8864 Sema::SFINAETrap Trap(SemaRef);
8865 ExprResult Res = TransformExpr(E);
8866 if (Trap.hasErrorOccurred() || Res.isInvalid())
8867 return ExprError();
8868
8869 return ExprFilter(Res.get());
8870 }
8871
8872 // Since correcting typos may intoduce new TypoExprs, this function
8873 // checks for new TypoExprs and recurses if it finds any. Note that it will
8874 // only succeed if it is able to correct all typos in the given expression.
8875 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8876 if (Res.isInvalid()) {
8877 return Res;
8878 }
8879 // Check to see if any new TypoExprs were created. If so, we need to recurse
8880 // to check their validity.
8881 Expr *FixedExpr = Res.get();
8882
8883 auto SavedTypoExprs = std::move(TypoExprs);
8884 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8885 TypoExprs.clear();
8886 AmbiguousTypoExprs.clear();
8887
8888 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8889 if (!TypoExprs.empty()) {
8890 // Recurse to handle newly created TypoExprs. If we're not able to
8891 // handle them, discard these TypoExprs.
8892 ExprResult RecurResult =
8893 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8894 if (RecurResult.isInvalid()) {
8895 Res = ExprError();
8896 // Recursive corrections didn't work, wipe them away and don't add
8897 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8898 // since we don't want to clear them twice. Note: it's possible the
8899 // TypoExprs were created recursively and thus won't be in our
8900 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8901 auto &SemaTypoExprs = SemaRef.TypoExprs;
8902 for (auto *TE : TypoExprs) {
8903 TransformCache.erase(TE);
8904 SemaRef.clearDelayedTypo(TE);
8905
8906 auto SI = find(SemaTypoExprs, TE);
8907 if (SI != SemaTypoExprs.end()) {
8908 SemaTypoExprs.erase(SI);
8909 }
8910 }
8911 } else {
8912 // TypoExpr is valid: add newly created TypoExprs since we were
8913 // able to correct them.
8914 Res = RecurResult;
8915 SavedTypoExprs.set_union(TypoExprs);
8916 }
8917 }
8918
8919 TypoExprs = std::move(SavedTypoExprs);
8920 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8921
8922 return Res;
8923 }
8924
8925 // Try to transform the given expression, looping through the correction
8926 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8927 //
8928 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8929 // true and this method immediately will return an `ExprError`.
8930 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8931 ExprResult Res;
8932 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8933 SemaRef.TypoExprs.clear();
8934
8935 while (true) {
8936 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8937
8938 // Recursion encountered an ambiguous correction. This means that our
8939 // correction itself is ambiguous, so stop now.
8940 if (IsAmbiguous)
8941 break;
8942
8943 // If the transform is still valid after checking for any new typos,
8944 // it's good to go.
8945 if (!Res.isInvalid())
8946 break;
8947
8948 // The transform was invalid, see if we have any TypoExprs with untried
8949 // correction candidates.
8950 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8951 break;
8952 }
8953
8954 // If we found a valid result, double check to make sure it's not ambiguous.
8955 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8956 auto SavedTransformCache =
8957 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8958
8959 // Ensure none of the TypoExprs have multiple typo correction candidates
8960 // with the same edit length that pass all the checks and filters.
8961 while (!AmbiguousTypoExprs.empty()) {
8962 auto TE = AmbiguousTypoExprs.back();
8963
8964 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8965 // and invalidating our TypoExprState, so always fetch it instead of storing.
8966 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8967
8968 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8969 TypoCorrection Next;
8970 do {
8971 // Fetch the next correction by erasing the typo from the cache and calling
8972 // `TryTransform` which will iterate through corrections in
8973 // `TransformTypoExpr`.
8974 TransformCache.erase(TE);
8975 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8976
8977 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8978 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8979 SavedTransformCache.erase(TE);
8980 Res = ExprError();
8981 IsAmbiguous = true;
8982 break;
8983 }
8984 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8985 Next.getEditDistance(false) == TC.getEditDistance(false));
8986
8987 if (IsAmbiguous)
8988 break;
8989
8990 AmbiguousTypoExprs.remove(TE);
8991 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8992 TransformCache[TE] = SavedTransformCache[TE];
8993 }
8994 TransformCache = std::move(SavedTransformCache);
8995 }
8996
8997 // Wipe away any newly created TypoExprs that we don't know about. Since we
8998 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8999 // possible if a `TypoExpr` is created during a transformation but then
9000 // fails before we can discover it.
9001 auto &SemaTypoExprs = SemaRef.TypoExprs;
9002 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
9003 auto TE = *Iterator;
9004 auto FI = find(TypoExprs, TE);
9005 if (FI != TypoExprs.end()) {
9006 Iterator++;
9007 continue;
9008 }
9009 SemaRef.clearDelayedTypo(TE);
9010 Iterator = SemaTypoExprs.erase(Iterator);
9011 }
9012 SemaRef.TypoExprs = std::move(SavedTypoExprs);
9013
9014 return Res;
9015 }
9016
9017public:
9018 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
9019 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
9020
9021 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
9022 MultiExprArg Args,
9023 SourceLocation RParenLoc,
9024 Expr *ExecConfig = nullptr) {
9025 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
9026 RParenLoc, ExecConfig);
9027 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
9028 if (Result.isUsable()) {
9029 Expr *ResultCall = Result.get();
9030 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
9031 ResultCall = BE->getSubExpr();
9032 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
9033 OverloadResolution[OE] = CE->getCallee();
9034 }
9035 }
9036 return Result;
9037 }
9038
9039 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
9040
9041 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
9042
9043 ExprResult Transform(Expr *E) {
9044 bool IsAmbiguous = false;
9045 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
9046
9047 if (!Res.isUsable())
9048 FindTypoExprs(TypoExprs).TraverseStmt(E);
9049
9050 EmitAllDiagnostics(IsAmbiguous);
9051
9052 return Res;
9053 }
9054
9055 ExprResult TransformTypoExpr(TypoExpr *E) {
9056 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
9057 // cached transformation result if there is one and the TypoExpr isn't the
9058 // first one that was encountered.
9059 auto &CacheEntry = TransformCache[E];
9060 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
9061 return CacheEntry;
9062 }
9063
9064 auto &State = SemaRef.getTypoExprState(E);
9065 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
9066
9067 // For the first TypoExpr and an uncached TypoExpr, find the next likely
9068 // typo correction and return it.
9069 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
9070 if (InitDecl && TC.getFoundDecl() == InitDecl)
9071 continue;
9072 // FIXME: If we would typo-correct to an invalid declaration, it's
9073 // probably best to just suppress all errors from this typo correction.
9074 ExprResult NE = State.RecoveryHandler ?
9075 State.RecoveryHandler(SemaRef, E, TC) :
9076 attemptRecovery(SemaRef, *State.Consumer, TC);
9077 if (!NE.isInvalid()) {
9078 // Check whether there may be a second viable correction with the same
9079 // edit distance; if so, remember this TypoExpr may have an ambiguous
9080 // correction so it can be more thoroughly vetted later.
9081 TypoCorrection Next;
9082 if ((Next = State.Consumer->peekNextCorrection()) &&
9083 Next.getEditDistance(false) == TC.getEditDistance(false)) {
9084 AmbiguousTypoExprs.insert(E);
9085 } else {
9086 AmbiguousTypoExprs.remove(E);
9087 }
9088 assert(!NE.isUnset() &&
9089 "Typo was transformed into a valid-but-null ExprResult");
9090 return CacheEntry = NE;
9091 }
9092 }
9093 return CacheEntry = ExprError();
9094 }
9095};
9096}
9097
9100 bool RecoverUncorrectedTypos,
9101 llvm::function_ref<ExprResult(Expr *)> Filter) {
9102 // If the current evaluation context indicates there are uncorrected typos
9103 // and the current expression isn't guaranteed to not have typos, try to
9104 // resolve any TypoExpr nodes that might be in the expression.
9105 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
9106 (E->isTypeDependent() || E->isValueDependent() ||
9108 auto TyposResolved = DelayedTypos.size();
9109 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
9110 TyposResolved -= DelayedTypos.size();
9111 if (Result.isInvalid() || Result.get() != E) {
9112 ExprEvalContexts.back().NumTypos -= TyposResolved;
9113 if (Result.isInvalid() && RecoverUncorrectedTypos) {
9114 struct TyposReplace : TreeTransform<TyposReplace> {
9115 TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
9116 ExprResult TransformTypoExpr(clang::TypoExpr *E) {
9117 return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
9118 E->getEndLoc(), {});
9119 }
9120 } TT(*this);
9121 return TT.TransformExpr(E);
9122 }
9123 return Result;
9124 }
9125 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
9126 }
9127 return E;
9128}
9129
9131 bool DiscardedValue, bool IsConstexpr,
9132 bool IsTemplateArgument) {
9133 ExprResult FullExpr = FE;
9134
9135 if (!FullExpr.get())
9136 return ExprError();
9137
9138 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
9139 return ExprError();
9140
9141 if (DiscardedValue) {
9142 // Top-level expressions default to 'id' when we're in a debugger.
9143 if (getLangOpts().DebuggerCastResultToId &&
9144 FullExpr.get()->getType() == Context.UnknownAnyTy) {
9146 if (FullExpr.isInvalid())
9147 return ExprError();
9148 }
9149
9151 if (FullExpr.isInvalid())
9152 return ExprError();
9153
9155 if (FullExpr.isInvalid())
9156 return ExprError();
9157
9158 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
9159 }
9160
9161 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
9162 /*RecoverUncorrectedTypos=*/true);
9163 if (FullExpr.isInvalid())
9164 return ExprError();
9165
9166 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
9167
9168 // At the end of this full expression (which could be a deeply nested
9169 // lambda), if there is a potential capture within the nested lambda,
9170 // have the outer capture-able lambda try and capture it.
9171 // Consider the following code:
9172 // void f(int, int);
9173 // void f(const int&, double);
9174 // void foo() {
9175 // const int x = 10, y = 20;
9176 // auto L = [=](auto a) {
9177 // auto M = [=](auto b) {
9178 // f(x, b); <-- requires x to be captured by L and M
9179 // f(y, a); <-- requires y to be captured by L, but not all Ms
9180 // };
9181 // };
9182 // }
9183
9184 // FIXME: Also consider what happens for something like this that involves
9185 // the gnu-extension statement-expressions or even lambda-init-captures:
9186 // void f() {
9187 // const int n = 0;
9188 // auto L = [&](auto a) {
9189 // +n + ({ 0; a; });
9190 // };
9191 // }
9192 //
9193 // Here, we see +n, and then the full-expression 0; ends, so we don't
9194 // capture n (and instead remove it from our list of potential captures),
9195 // and then the full-expression +n + ({ 0; }); ends, but it's too late
9196 // for us to see that we need to capture n after all.
9197
9198 LambdaScopeInfo *const CurrentLSI =
9199 getCurLambda(/*IgnoreCapturedRegions=*/true);
9200 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
9201 // even if CurContext is not a lambda call operator. Refer to that Bug Report
9202 // for an example of the code that might cause this asynchrony.
9203 // By ensuring we are in the context of a lambda's call operator
9204 // we can fix the bug (we only need to check whether we need to capture
9205 // if we are within a lambda's body); but per the comments in that
9206 // PR, a proper fix would entail :
9207 // "Alternative suggestion:
9208 // - Add to Sema an integer holding the smallest (outermost) scope
9209 // index that we are *lexically* within, and save/restore/set to
9210 // FunctionScopes.size() in InstantiatingTemplate's
9211 // constructor/destructor.
9212 // - Teach the handful of places that iterate over FunctionScopes to
9213 // stop at the outermost enclosing lexical scope."
9214 DeclContext *DC = CurContext;
9215 while (isa_and_nonnull<CapturedDecl>(DC))
9216 DC = DC->getParent();
9217 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
9218 if (IsInLambdaDeclContext && CurrentLSI &&
9219 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
9221 *this);
9223}
9224
9226 if (!FullStmt) return StmtError();
9227
9228 return MaybeCreateStmtWithCleanups(FullStmt);
9229}
9230
9233 CXXScopeSpec &SS,
9234 const DeclarationNameInfo &TargetNameInfo) {
9235 DeclarationName TargetName = TargetNameInfo.getName();
9236 if (!TargetName)
9237 return IER_DoesNotExist;
9238
9239 // If the name itself is dependent, then the result is dependent.
9240 if (TargetName.isDependentName())
9241 return IER_Dependent;
9242
9243 // Do the redeclaration lookup in the current scope.
9244 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
9245 RedeclarationKind::NotForRedeclaration);
9246 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
9248
9249 switch (R.getResultKind()) {
9254 return IER_Exists;
9255
9257 return IER_DoesNotExist;
9258
9260 return IER_Dependent;
9261 }
9262
9263 llvm_unreachable("Invalid LookupResult Kind!");
9264}
9265
9268 bool IsIfExists, CXXScopeSpec &SS,
9269 UnqualifiedId &Name) {
9270 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9271
9272 // Check for an unexpanded parameter pack.
9273 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
9274 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
9275 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
9276 return IER_Error;
9277
9278 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
9279}
9280
9282 return BuildExprRequirement(E, /*IsSimple=*/true,
9283 /*NoexceptLoc=*/SourceLocation(),
9284 /*ReturnTypeRequirement=*/{});
9285}
9286
9288 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
9289 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
9290 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
9291 "Exactly one of TypeName and TemplateId must be specified.");
9292 TypeSourceInfo *TSI = nullptr;
9293 if (TypeName) {
9294 QualType T =
9296 SS.getWithLocInContext(Context), *TypeName, NameLoc,
9297 &TSI, /*DeducedTSTContext=*/false);
9298 if (T.isNull())
9299 return nullptr;
9300 } else {
9301 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
9302 TemplateId->NumArgs);
9303 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
9304 TemplateId->TemplateKWLoc,
9305 TemplateId->Template, TemplateId->Name,
9306 TemplateId->TemplateNameLoc,
9307 TemplateId->LAngleLoc, ArgsPtr,
9308 TemplateId->RAngleLoc);
9309 if (T.isInvalid())
9310 return nullptr;
9311 if (GetTypeFromParser(T.get(), &TSI).isNull())
9312 return nullptr;
9313 }
9314 return BuildTypeRequirement(TSI);
9315}
9316
9319 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
9320 /*ReturnTypeRequirement=*/{});
9321}
9322
9325 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9326 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
9327 // C++2a [expr.prim.req.compound] p1.3.3
9328 // [..] the expression is deduced against an invented function template
9329 // F [...] F is a void function template with a single type template
9330 // parameter T declared with the constrained-parameter. Form a new
9331 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
9332 // around the constrained-parameter. F has a single parameter whose
9333 // type-specifier is cv T followed by the abstract-declarator. [...]
9334 //
9335 // The cv part is done in the calling function - we get the concept with
9336 // arguments and the abstract declarator with the correct CV qualification and
9337 // have to synthesize T and the single parameter of F.
9338 auto &II = Context.Idents.get("expr-type");
9341 SourceLocation(), Depth,
9342 /*Index=*/0, &II,
9343 /*Typename=*/true,
9344 /*ParameterPack=*/false,
9345 /*HasTypeConstraint=*/true);
9346
9347 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
9348 /*EllipsisLoc=*/SourceLocation(),
9349 /*AllowUnexpandedPack=*/true))
9350 // Just produce a requirement with no type requirements.
9351 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
9352
9355 ArrayRef<NamedDecl *>(TParam),
9357 /*RequiresClause=*/nullptr);
9358 return BuildExprRequirement(
9359 E, /*IsSimple=*/false, NoexceptLoc,
9361}
9362
9365 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9368 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9370 ReturnTypeRequirement.isDependent())
9372 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9374 else if (ReturnTypeRequirement.isSubstitutionFailure())
9376 else if (ReturnTypeRequirement.isTypeConstraint()) {
9377 // C++2a [expr.prim.req]p1.3.3
9378 // The immediately-declared constraint ([temp]) of decltype((E)) shall
9379 // be satisfied.
9381 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9382 QualType MatchedType =
9385 Args.push_back(TemplateArgument(MatchedType));
9386
9387 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9388
9389 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false);
9390 MLTAL.addOuterRetainedLevels(TPL->getDepth());
9391 const TypeConstraint *TC = Param->getTypeConstraint();
9392 assert(TC && "Type Constraint cannot be null here");
9393 auto *IDC = TC->getImmediatelyDeclaredConstraint();
9394 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
9395 ExprResult Constraint = SubstExpr(IDC, MLTAL);
9396 if (Constraint.isInvalid()) {
9398 concepts::createSubstDiagAt(*this, IDC->getExprLoc(),
9399 [&](llvm::raw_ostream &OS) {
9400 IDC->printPretty(OS, /*Helper=*/nullptr,
9401 getPrintingPolicy());
9402 }),
9403 IsSimple, NoexceptLoc, ReturnTypeRequirement);
9404 }
9405 SubstitutedConstraintExpr =
9406 cast<ConceptSpecializationExpr>(Constraint.get());
9407 if (!SubstitutedConstraintExpr->isSatisfied())
9409 }
9410 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9411 ReturnTypeRequirement, Status,
9412 SubstitutedConstraintExpr);
9413}
9414
9417 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9418 bool IsSimple, SourceLocation NoexceptLoc,
9420 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9421 IsSimple, NoexceptLoc,
9422 ReturnTypeRequirement);
9423}
9424
9428}
9429
9433 return new (Context) concepts::TypeRequirement(SubstDiag);
9434}
9435
9437 return BuildNestedRequirement(Constraint);
9438}
9439
9442 ConstraintSatisfaction Satisfaction;
9443 if (!Constraint->isInstantiationDependent() &&
9444 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9445 Constraint->getSourceRange(), Satisfaction))
9446 return nullptr;
9447 return new (Context) concepts::NestedRequirement(Context, Constraint,
9448 Satisfaction);
9449}
9450
9452Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9453 const ASTConstraintSatisfaction &Satisfaction) {
9455 InvalidConstraintEntity,
9457}
9458
9461 ArrayRef<ParmVarDecl *> LocalParameters,
9462 Scope *BodyScope) {
9463 assert(BodyScope);
9464
9466 RequiresKWLoc);
9467
9468 PushDeclContext(BodyScope, Body);
9469
9470 for (ParmVarDecl *Param : LocalParameters) {
9471 if (Param->hasDefaultArg())
9472 // C++2a [expr.prim.req] p4
9473 // [...] A local parameter of a requires-expression shall not have a
9474 // default argument. [...]
9475 Diag(Param->getDefaultArgRange().getBegin(),
9476 diag::err_requires_expr_local_parameter_default_argument);
9477 // Ignore default argument and move on
9478
9479 Param->setDeclContext(Body);
9480 // If this has an identifier, add it to the scope stack.
9481 if (Param->getIdentifier()) {
9482 CheckShadow(BodyScope, Param);
9483 PushOnScopeChains(Param, BodyScope);
9484 }
9485 }
9486 return Body;
9487}
9488
9490 assert(CurContext && "DeclContext imbalance!");
9492 assert(CurContext && "Popped translation unit!");
9493}
9494
9496 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
9497 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
9498 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
9499 SourceLocation ClosingBraceLoc) {
9500 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
9501 LocalParameters, RParenLoc, Requirements,
9502 ClosingBraceLoc);
9504 return ExprError();
9505 return RE;
9506}
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::@1653::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:2852
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:2497
bool isArrayForm() const
Definition: ExprCXX.h:2523
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2547
Expr * getArgument()
Definition: ExprCXX.h:2538
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:2240
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:4125
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:2616
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 a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2181
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:2923
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:7521
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:8609
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:2565
TypeSourceInfo * getTypeSourceInfo() const
Definition: ExprCXX.h:2581
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:13941
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition: Sema.h:13944
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:14368
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:7484
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:9725
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:13490
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:14938
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:9655
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:1089
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:2225
@ 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