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->isPointerType() || QT->isReferenceType())
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 MarkFunctionReferenced(StartLoc, OperatorDelete);
3810
3811 // Check access and ambiguity of destructor if we're going to call it.
3812 // Note that this is required even for a virtual delete.
3813 bool IsVirtualDelete = false;
3814 if (PointeeRD) {
3815 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3816 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3817 PDiag(diag::err_access_dtor) << PointeeElem);
3818 IsVirtualDelete = Dtor->isVirtual();
3819 }
3820 }
3821
3822 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3823
3824 // Convert the operand to the type of the first parameter of operator
3825 // delete. This is only necessary if we selected a destroying operator
3826 // delete that we are going to call (non-virtually); converting to void*
3827 // is trivial and left to AST consumers to handle.
3828 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3829 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3830 Qualifiers Qs = Pointee.getQualifiers();
3831 if (Qs.hasCVRQualifiers()) {
3832 // Qualifiers are irrelevant to this conversion; we're only looking
3833 // for access and ambiguity.
3837 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3838 }
3839 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3840 if (Ex.isInvalid())
3841 return ExprError();
3842 }
3843 }
3844
3846 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3847 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3848 AnalyzeDeleteExprMismatch(Result);
3849 return Result;
3850}
3851
3853 bool IsDelete,
3854 FunctionDecl *&Operator) {
3855
3857 IsDelete ? OO_Delete : OO_New);
3858
3859 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3861 assert(!R.empty() && "implicitly declared allocation functions not found");
3862 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3863
3864 // We do our own custom access checks below.
3866
3867 SmallVector<Expr *, 8> Args(TheCall->arguments());
3868 OverloadCandidateSet Candidates(R.getNameLoc(),
3870 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3871 FnOvl != FnOvlEnd; ++FnOvl) {
3872 // Even member operator new/delete are implicitly treated as
3873 // static, so don't use AddMemberCandidate.
3874 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3875
3876 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3877 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3878 /*ExplicitTemplateArgs=*/nullptr, Args,
3879 Candidates,
3880 /*SuppressUserConversions=*/false);
3881 continue;
3882 }
3883
3884 FunctionDecl *Fn = cast<FunctionDecl>(D);
3885 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3886 /*SuppressUserConversions=*/false);
3887 }
3888
3889 SourceRange Range = TheCall->getSourceRange();
3890
3891 // Do the resolution.
3893 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3894 case OR_Success: {
3895 // Got one!
3896 FunctionDecl *FnDecl = Best->Function;
3897 assert(R.getNamingClass() == nullptr &&
3898 "class members should not be considered");
3899
3901 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3902 << (IsDelete ? 1 : 0) << Range;
3903 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3904 << R.getLookupName() << FnDecl->getSourceRange();
3905 return true;
3906 }
3907
3908 Operator = FnDecl;
3909 return false;
3910 }
3911
3913 Candidates.NoteCandidates(
3915 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3916 << R.getLookupName() << Range),
3917 S, OCD_AllCandidates, Args);
3918 return true;
3919
3920 case OR_Ambiguous:
3921 Candidates.NoteCandidates(
3923 S.PDiag(diag::err_ovl_ambiguous_call)
3924 << R.getLookupName() << Range),
3925 S, OCD_AmbiguousCandidates, Args);
3926 return true;
3927
3928 case OR_Deleted:
3930 Candidates, Best->Function, Args);
3931 return true;
3932 }
3933 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3934}
3935
3936ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3937 bool IsDelete) {
3938 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3939 if (!getLangOpts().CPlusPlus) {
3940 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3941 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3942 << "C++";
3943 return ExprError();
3944 }
3945 // CodeGen assumes it can find the global new and delete to call,
3946 // so ensure that they are declared.
3948
3949 FunctionDecl *OperatorNewOrDelete = nullptr;
3950 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3951 OperatorNewOrDelete))
3952 return ExprError();
3953 assert(OperatorNewOrDelete && "should be found");
3954
3955 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3956 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3957
3958 TheCall->setType(OperatorNewOrDelete->getReturnType());
3959 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3960 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3961 InitializedEntity Entity =
3964 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3965 if (Arg.isInvalid())
3966 return ExprError();
3967 TheCall->setArg(i, Arg.get());
3968 }
3969 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3970 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3971 "Callee expected to be implicit cast to a builtin function pointer");
3972 Callee->setType(OperatorNewOrDelete->getType());
3973
3974 return TheCallResult;
3975}
3976
3978 bool IsDelete, bool CallCanBeVirtual,
3979 bool WarnOnNonAbstractTypes,
3980 SourceLocation DtorLoc) {
3981 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3982 return;
3983
3984 // C++ [expr.delete]p3:
3985 // In the first alternative (delete object), if the static type of the
3986 // object to be deleted is different from its dynamic type, the static
3987 // type shall be a base class of the dynamic type of the object to be
3988 // deleted and the static type shall have a virtual destructor or the
3989 // behavior is undefined.
3990 //
3991 const CXXRecordDecl *PointeeRD = dtor->getParent();
3992 // Note: a final class cannot be derived from, no issue there
3993 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3994 return;
3995
3996 // If the superclass is in a system header, there's nothing that can be done.
3997 // The `delete` (where we emit the warning) can be in a system header,
3998 // what matters for this warning is where the deleted type is defined.
3999 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4000 return;
4001
4002 QualType ClassType = dtor->getFunctionObjectParameterType();
4003 if (PointeeRD->isAbstract()) {
4004 // If the class is abstract, we warn by default, because we're
4005 // sure the code has undefined behavior.
4006 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4007 << ClassType;
4008 } else if (WarnOnNonAbstractTypes) {
4009 // Otherwise, if this is not an array delete, it's a bit suspect,
4010 // but not necessarily wrong.
4011 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4012 << ClassType;
4013 }
4014 if (!IsDelete) {
4015 std::string TypeStr;
4016 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4017 Diag(DtorLoc, diag::note_delete_non_virtual)
4018 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4019 }
4020}
4021
4023 SourceLocation StmtLoc,
4024 ConditionKind CK) {
4025 ExprResult E =
4026 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4027 if (E.isInvalid())
4028 return ConditionError();
4029 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
4031}
4032
4034 SourceLocation StmtLoc,
4035 ConditionKind CK) {
4036 if (ConditionVar->isInvalidDecl())
4037 return ExprError();
4038
4039 QualType T = ConditionVar->getType();
4040
4041 // C++ [stmt.select]p2:
4042 // The declarator shall not specify a function or an array.
4043 if (T->isFunctionType())
4044 return ExprError(Diag(ConditionVar->getLocation(),
4045 diag::err_invalid_use_of_function_type)
4046 << ConditionVar->getSourceRange());
4047 else if (T->isArrayType())
4048 return ExprError(Diag(ConditionVar->getLocation(),
4049 diag::err_invalid_use_of_array_type)
4050 << ConditionVar->getSourceRange());
4051
4053 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4054 ConditionVar->getLocation());
4055
4056 switch (CK) {
4058 return CheckBooleanCondition(StmtLoc, Condition.get());
4059
4061 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4062
4064 return CheckSwitchCondition(StmtLoc, Condition.get());
4065 }
4066
4067 llvm_unreachable("unexpected condition kind");
4068}
4069
4070ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4071 // C++11 6.4p4:
4072 // The value of a condition that is an initialized declaration in a statement
4073 // other than a switch statement is the value of the declared variable
4074 // implicitly converted to type bool. If that conversion is ill-formed, the
4075 // program is ill-formed.
4076 // The value of a condition that is an expression is the value of the
4077 // expression, implicitly converted to bool.
4078 //
4079 // C++23 8.5.2p2
4080 // If the if statement is of the form if constexpr, the value of the condition
4081 // is contextually converted to bool and the converted expression shall be
4082 // a constant expression.
4083 //
4084
4086 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4087 return E;
4088
4089 // FIXME: Return this value to the caller so they don't need to recompute it.
4090 llvm::APSInt Cond;
4092 E.get(), &Cond,
4093 diag::err_constexpr_if_condition_expression_is_not_constant);
4094 return E;
4095}
4096
4097bool
4099 // Look inside the implicit cast, if it exists.
4100 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4101 From = Cast->getSubExpr();
4102
4103 // A string literal (2.13.4) that is not a wide string literal can
4104 // be converted to an rvalue of type "pointer to char"; a wide
4105 // string literal can be converted to an rvalue of type "pointer
4106 // to wchar_t" (C++ 4.2p2).
4107 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4108 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4109 if (const BuiltinType *ToPointeeType
4110 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4111 // This conversion is considered only when there is an
4112 // explicit appropriate pointer target type (C++ 4.2p2).
4113 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4114 switch (StrLit->getKind()) {
4118 // We don't allow UTF literals to be implicitly converted
4119 break;
4121 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4122 ToPointeeType->getKind() == BuiltinType::Char_S);
4125 QualType(ToPointeeType, 0));
4127 assert(false && "Unevaluated string literal in expression");
4128 break;
4129 }
4130 }
4131 }
4132
4133 return false;
4134}
4135
4137 SourceLocation CastLoc,
4138 QualType Ty,
4139 CastKind Kind,
4140 CXXMethodDecl *Method,
4141 DeclAccessPair FoundDecl,
4142 bool HadMultipleCandidates,
4143 Expr *From) {
4144 switch (Kind) {
4145 default: llvm_unreachable("Unhandled cast kind!");
4146 case CK_ConstructorConversion: {
4147 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4148 SmallVector<Expr*, 8> ConstructorArgs;
4149
4150 if (S.RequireNonAbstractType(CastLoc, Ty,
4151 diag::err_allocation_of_abstract_type))
4152 return ExprError();
4153
4154 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4155 ConstructorArgs))
4156 return ExprError();
4157
4158 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4160 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4161 return ExprError();
4162
4164 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4165 ConstructorArgs, HadMultipleCandidates,
4166 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4168 if (Result.isInvalid())
4169 return ExprError();
4170
4171 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4172 }
4173
4174 case CK_UserDefinedConversion: {
4175 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4176
4177 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4178 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4179 return ExprError();
4180
4181 // Create an implicit call expr that calls it.
4182 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4183 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4184 HadMultipleCandidates);
4185 if (Result.isInvalid())
4186 return ExprError();
4187 // Record usage of conversion in an implicit cast.
4188 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4189 CK_UserDefinedConversion, Result.get(),
4190 nullptr, Result.get()->getValueKind(),
4192
4193 return S.MaybeBindToTemporary(Result.get());
4194 }
4195 }
4196}
4197
4200 const ImplicitConversionSequence &ICS,
4201 AssignmentAction Action,
4203 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4205 !From->getType()->isRecordType())
4206 return From;
4207
4208 switch (ICS.getKind()) {
4210 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4211 Action, CCK);
4212 if (Res.isInvalid())
4213 return ExprError();
4214 From = Res.get();
4215 break;
4216 }
4217
4219
4222 QualType BeforeToType;
4223 assert(FD && "no conversion function for user-defined conversion seq");
4224 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4225 CastKind = CK_UserDefinedConversion;
4226
4227 // If the user-defined conversion is specified by a conversion function,
4228 // the initial standard conversion sequence converts the source type to
4229 // the implicit object parameter of the conversion function.
4230 BeforeToType = Context.getTagDeclType(Conv->getParent());
4231 } else {
4232 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4233 CastKind = CK_ConstructorConversion;
4234 // Do no conversion if dealing with ... for the first conversion.
4236 // If the user-defined conversion is specified by a constructor, the
4237 // initial standard conversion sequence converts the source type to
4238 // the type required by the argument of the constructor
4239 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4240 }
4241 }
4242 // Watch out for ellipsis conversion.
4244 ExprResult Res =
4245 PerformImplicitConversion(From, BeforeToType,
4247 CCK);
4248 if (Res.isInvalid())
4249 return ExprError();
4250 From = Res.get();
4251 }
4252
4254 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4255 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4257
4258 if (CastArg.isInvalid())
4259 return ExprError();
4260
4261 From = CastArg.get();
4262
4263 // C++ [over.match.oper]p7:
4264 // [...] the second standard conversion sequence of a user-defined
4265 // conversion sequence is not applied.
4267 return From;
4268
4269 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4270 AA_Converting, CCK);
4271 }
4272
4274 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4275 PDiag(diag::err_typecheck_ambiguous_condition)
4276 << From->getSourceRange());
4277 return ExprError();
4278
4281 llvm_unreachable("bad conversion");
4282
4285 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4286 bool Diagnosed = DiagnoseAssignmentResult(
4287 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4288 ToType, From->getType(), From, Action);
4289 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4290 return ExprError();
4291 }
4292
4293 // Everything went well.
4294 return From;
4295}
4296
4297// adjustVectorType - Compute the intermediate cast type casting elements of the
4298// from type to the elements of the to type without resizing the vector.
4300 QualType ToType, QualType *ElTy = nullptr) {
4301 auto *ToVec = ToType->castAs<VectorType>();
4302 QualType ElType = ToVec->getElementType();
4303 if (ElTy)
4304 *ElTy = ElType;
4305 if (!FromTy->isVectorType())
4306 return ElType;
4307 auto *FromVec = FromTy->castAs<VectorType>();
4308 return Context.getExtVectorType(ElType, FromVec->getNumElements());
4309}
4310
4313 const StandardConversionSequence& SCS,
4314 AssignmentAction Action,
4316 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4318
4319 // Overall FIXME: we are recomputing too many types here and doing far too
4320 // much extra work. What this means is that we need to keep track of more
4321 // information that is computed when we try the implicit conversion initially,
4322 // so that we don't need to recompute anything here.
4323 QualType FromType = From->getType();
4324
4325 if (SCS.CopyConstructor) {
4326 // FIXME: When can ToType be a reference type?
4327 assert(!ToType->isReferenceType());
4328 if (SCS.Second == ICK_Derived_To_Base) {
4329 SmallVector<Expr*, 8> ConstructorArgs;
4331 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4332 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4333 return ExprError();
4334 return BuildCXXConstructExpr(
4335 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4336 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4337 /*HadMultipleCandidates*/ false,
4338 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4340 }
4341 return BuildCXXConstructExpr(
4342 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4344 /*HadMultipleCandidates*/ false,
4345 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4347 }
4348
4349 // Resolve overloaded function references.
4350 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4353 true, Found);
4354 if (!Fn)
4355 return ExprError();
4356
4357 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4358 return ExprError();
4359
4361 if (Res.isInvalid())
4362 return ExprError();
4363
4364 // We might get back another placeholder expression if we resolved to a
4365 // builtin.
4366 Res = CheckPlaceholderExpr(Res.get());
4367 if (Res.isInvalid())
4368 return ExprError();
4369
4370 From = Res.get();
4371 FromType = From->getType();
4372 }
4373
4374 // If we're converting to an atomic type, first convert to the corresponding
4375 // non-atomic type.
4376 QualType ToAtomicType;
4377 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4378 ToAtomicType = ToType;
4379 ToType = ToAtomic->getValueType();
4380 }
4381
4382 QualType InitialFromType = FromType;
4383 // Perform the first implicit conversion.
4384 switch (SCS.First) {
4385 case ICK_Identity:
4386 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4387 FromType = FromAtomic->getValueType().getUnqualifiedType();
4388 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4389 From, /*BasePath=*/nullptr, VK_PRValue,
4391 }
4392 break;
4393
4394 case ICK_Lvalue_To_Rvalue: {
4395 assert(From->getObjectKind() != OK_ObjCProperty);
4396 ExprResult FromRes = DefaultLvalueConversion(From);
4397 if (FromRes.isInvalid())
4398 return ExprError();
4399
4400 From = FromRes.get();
4401 FromType = From->getType();
4402 break;
4403 }
4404
4406 FromType = Context.getArrayDecayedType(FromType);
4407 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4408 /*BasePath=*/nullptr, CCK)
4409 .get();
4410 break;
4411
4413 FromType = Context.getArrayParameterType(FromType);
4414 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4415 /*BasePath=*/nullptr, CCK)
4416 .get();
4417 break;
4418
4420 FromType = Context.getPointerType(FromType);
4421 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4422 VK_PRValue, /*BasePath=*/nullptr, CCK)
4423 .get();
4424 break;
4425
4426 default:
4427 llvm_unreachable("Improper first standard conversion");
4428 }
4429
4430 // Perform the second implicit conversion
4431 switch (SCS.Second) {
4432 case ICK_Identity:
4433 // C++ [except.spec]p5:
4434 // [For] assignment to and initialization of pointers to functions,
4435 // pointers to member functions, and references to functions: the
4436 // target entity shall allow at least the exceptions allowed by the
4437 // source value in the assignment or initialization.
4438 switch (Action) {
4439 case AA_Assigning:
4440 case AA_Initializing:
4441 // Note, function argument passing and returning are initialization.
4442 case AA_Passing:
4443 case AA_Returning:
4444 case AA_Sending:
4446 if (CheckExceptionSpecCompatibility(From, ToType))
4447 return ExprError();
4448 break;
4449
4450 case AA_Casting:
4451 case AA_Converting:
4452 // Casts and implicit conversions are not initialization, so are not
4453 // checked for exception specification mismatches.
4454 break;
4455 }
4456 // Nothing else to do.
4457 break;
4458
4461 QualType ElTy = ToType;
4462 QualType StepTy = ToType;
4463 if (ToType->isVectorType())
4464 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4465 if (ElTy->isBooleanType()) {
4466 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4468 "only enums with fixed underlying type can promote to bool");
4469 From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,
4470 /*BasePath=*/nullptr, CCK)
4471 .get();
4472 } else {
4473 From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,
4474 /*BasePath=*/nullptr, CCK)
4475 .get();
4476 }
4477 break;
4478 }
4479
4482 QualType StepTy = ToType;
4483 if (ToType->isVectorType())
4484 StepTy = adjustVectorType(Context, FromType, ToType);
4485 From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,
4486 /*BasePath=*/nullptr, CCK)
4487 .get();
4488 break;
4489 }
4490
4493 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4494 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4495 CastKind CK;
4496 if (FromEl->isRealFloatingType()) {
4497 if (ToEl->isRealFloatingType())
4498 CK = CK_FloatingComplexCast;
4499 else
4500 CK = CK_FloatingComplexToIntegralComplex;
4501 } else if (ToEl->isRealFloatingType()) {
4502 CK = CK_IntegralComplexToFloatingComplex;
4503 } else {
4504 CK = CK_IntegralComplexCast;
4505 }
4506 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4507 CCK)
4508 .get();
4509 break;
4510 }
4511
4512 case ICK_Floating_Integral: {
4513 QualType ElTy = ToType;
4514 QualType StepTy = ToType;
4515 if (ToType->isVectorType())
4516 StepTy = adjustVectorType(Context, FromType, ToType, &ElTy);
4517 if (ElTy->isRealFloatingType())
4518 From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,
4519 /*BasePath=*/nullptr, CCK)
4520 .get();
4521 else
4522 From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,
4523 /*BasePath=*/nullptr, CCK)
4524 .get();
4525 break;
4526 }
4527
4529 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4530 "Attempting implicit fixed point conversion without a fixed "
4531 "point operand");
4532 if (FromType->isFloatingType())
4533 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4534 VK_PRValue,
4535 /*BasePath=*/nullptr, CCK).get();
4536 else if (ToType->isFloatingType())
4537 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4538 VK_PRValue,
4539 /*BasePath=*/nullptr, CCK).get();
4540 else if (FromType->isIntegralType(Context))
4541 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4542 VK_PRValue,
4543 /*BasePath=*/nullptr, CCK).get();
4544 else if (ToType->isIntegralType(Context))
4545 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4546 VK_PRValue,
4547 /*BasePath=*/nullptr, CCK).get();
4548 else if (ToType->isBooleanType())
4549 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4550 VK_PRValue,
4551 /*BasePath=*/nullptr, CCK).get();
4552 else
4553 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4554 VK_PRValue,
4555 /*BasePath=*/nullptr, CCK).get();
4556 break;
4557
4559 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4560 /*BasePath=*/nullptr, CCK).get();
4561 break;
4562
4565 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4566 // Diagnose incompatible Objective-C conversions
4567 if (Action == AA_Initializing || Action == AA_Assigning)
4568 Diag(From->getBeginLoc(),
4569 diag::ext_typecheck_convert_incompatible_pointer)
4570 << ToType << From->getType() << Action << From->getSourceRange()
4571 << 0;
4572 else
4573 Diag(From->getBeginLoc(),
4574 diag::ext_typecheck_convert_incompatible_pointer)
4575 << From->getType() << ToType << Action << From->getSourceRange()
4576 << 0;
4577
4578 if (From->getType()->isObjCObjectPointerType() &&
4579 ToType->isObjCObjectPointerType())
4581 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4582 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
4583 From->getType())) {
4584 if (Action == AA_Initializing)
4585 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4586 else
4587 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4588 << (Action == AA_Casting) << From->getType() << ToType
4589 << From->getSourceRange();
4590 }
4591
4592 // Defer address space conversion to the third conversion.
4593 QualType FromPteeType = From->getType()->getPointeeType();
4594 QualType ToPteeType = ToType->getPointeeType();
4595 QualType NewToType = ToType;
4596 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4597 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4598 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4599 NewToType = Context.getAddrSpaceQualType(NewToType,
4600 FromPteeType.getAddressSpace());
4601 if (ToType->isObjCObjectPointerType())
4602 NewToType = Context.getObjCObjectPointerType(NewToType);
4603 else if (ToType->isBlockPointerType())
4604 NewToType = Context.getBlockPointerType(NewToType);
4605 else
4606 NewToType = Context.getPointerType(NewToType);
4607 }
4608
4609 CastKind Kind;
4610 CXXCastPath BasePath;
4611 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4612 return ExprError();
4613
4614 // Make sure we extend blocks if necessary.
4615 // FIXME: doing this here is really ugly.
4616 if (Kind == CK_BlockPointerToObjCPointerCast) {
4617 ExprResult E = From;
4619 From = E.get();
4620 }
4622 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4623 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4624 .get();
4625 break;
4626 }
4627
4628 case ICK_Pointer_Member: {
4629 CastKind Kind;
4630 CXXCastPath BasePath;
4631 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4632 return ExprError();
4633 if (CheckExceptionSpecCompatibility(From, ToType))
4634 return ExprError();
4635
4636 // We may not have been able to figure out what this member pointer resolved
4637 // to up until this exact point. Attempt to lock-in it's inheritance model.
4639 (void)isCompleteType(From->getExprLoc(), From->getType());
4640 (void)isCompleteType(From->getExprLoc(), ToType);
4641 }
4642
4643 From =
4644 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4645 break;
4646 }
4647
4649 // Perform half-to-boolean conversion via float.
4650 if (From->getType()->isHalfType()) {
4651 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4652 FromType = Context.FloatTy;
4653 }
4654 QualType ElTy = FromType;
4655 QualType StepTy = ToType;
4656 if (FromType->isVectorType()) {
4657 if (getLangOpts().HLSL)
4658 StepTy = adjustVectorType(Context, FromType, ToType);
4659 ElTy = FromType->castAs<VectorType>()->getElementType();
4660 }
4661
4662 From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),
4663 VK_PRValue,
4664 /*BasePath=*/nullptr, CCK)
4665 .get();
4666 break;
4667 }
4668
4669 case ICK_Derived_To_Base: {
4670 CXXCastPath BasePath;
4672 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4673 From->getSourceRange(), &BasePath, CStyle))
4674 return ExprError();
4675
4676 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4677 CK_DerivedToBase, From->getValueKind(),
4678 &BasePath, CCK).get();
4679 break;
4680 }
4681
4683 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4684 /*BasePath=*/nullptr, CCK)
4685 .get();
4686 break;
4687
4690 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4691 /*BasePath=*/nullptr, CCK)
4692 .get();
4693 break;
4694
4695 case ICK_Vector_Splat: {
4696 // Vector splat from any arithmetic type to a vector.
4697 Expr *Elem = prepareVectorSplat(ToType, From).get();
4698 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4699 /*BasePath=*/nullptr, CCK)
4700 .get();
4701 break;
4702 }
4703
4704 case ICK_Complex_Real:
4705 // Case 1. x -> _Complex y
4706 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4707 QualType ElType = ToComplex->getElementType();
4708 bool isFloatingComplex = ElType->isRealFloatingType();
4709
4710 // x -> y
4711 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4712 // do nothing
4713 } else if (From->getType()->isRealFloatingType()) {
4714 From = ImpCastExprToType(From, ElType,
4715 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4716 } else {
4717 assert(From->getType()->isIntegerType());
4718 From = ImpCastExprToType(From, ElType,
4719 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4720 }
4721 // y -> _Complex y
4722 From = ImpCastExprToType(From, ToType,
4723 isFloatingComplex ? CK_FloatingRealToComplex
4724 : CK_IntegralRealToComplex).get();
4725
4726 // Case 2. _Complex x -> y
4727 } else {
4728 auto *FromComplex = From->getType()->castAs<ComplexType>();
4729 QualType ElType = FromComplex->getElementType();
4730 bool isFloatingComplex = ElType->isRealFloatingType();
4731
4732 // _Complex x -> x
4733 From = ImpCastExprToType(From, ElType,
4734 isFloatingComplex ? CK_FloatingComplexToReal
4735 : CK_IntegralComplexToReal,
4736 VK_PRValue, /*BasePath=*/nullptr, CCK)
4737 .get();
4738
4739 // x -> y
4740 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4741 // do nothing
4742 } else if (ToType->isRealFloatingType()) {
4743 From = ImpCastExprToType(From, ToType,
4744 isFloatingComplex ? CK_FloatingCast
4745 : CK_IntegralToFloating,
4746 VK_PRValue, /*BasePath=*/nullptr, CCK)
4747 .get();
4748 } else {
4749 assert(ToType->isIntegerType());
4750 From = ImpCastExprToType(From, ToType,
4751 isFloatingComplex ? CK_FloatingToIntegral
4752 : CK_IntegralCast,
4753 VK_PRValue, /*BasePath=*/nullptr, CCK)
4754 .get();
4755 }
4756 }
4757 break;
4758
4760 LangAS AddrSpaceL =
4762 LangAS AddrSpaceR =
4764 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4765 "Invalid cast");
4766 CastKind Kind =
4767 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4768 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4769 VK_PRValue, /*BasePath=*/nullptr, CCK)
4770 .get();
4771 break;
4772 }
4773
4775 ExprResult FromRes = From;
4778 if (FromRes.isInvalid())
4779 return ExprError();
4780 From = FromRes.get();
4781 assert ((ConvTy == Sema::Compatible) &&
4782 "Improper transparent union conversion");
4783 (void)ConvTy;
4784 break;
4785 }
4786
4789 From = ImpCastExprToType(From, ToType,
4790 CK_ZeroToOCLOpaqueType,
4791 From->getValueKind()).get();
4792 break;
4793
4798 case ICK_Qualification:
4805 llvm_unreachable("Improper second standard conversion");
4806 }
4807
4808 if (SCS.Dimension != ICK_Identity) {
4809 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
4810 // vectors or matrices.
4811
4812 // TODO: Support HLSL matrices.
4813 assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&
4814 "Dimension conversion for matrix types is not implemented yet.");
4815 assert(ToType->isVectorType() &&
4816 "Dimension conversion is only supported for vector types.");
4817 switch (SCS.Dimension) {
4818 case ICK_HLSL_Vector_Splat: {
4819 // Vector splat from any arithmetic type to a vector.
4820 Expr *Elem = prepareVectorSplat(ToType, From).get();
4821 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4822 /*BasePath=*/nullptr, CCK)
4823 .get();
4824 break;
4825 }
4827 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a
4828 // vector to a smaller vector, this can only operate on arguments where
4829 // the source and destination types are ExtVectors.
4830 assert(From->getType()->isExtVectorType() && ToType->isExtVectorType() &&
4831 "HLSL vector truncation should only apply to ExtVectors");
4832 auto *FromVec = From->getType()->castAs<VectorType>();
4833 auto *ToVec = ToType->castAs<VectorType>();
4834 QualType ElType = FromVec->getElementType();
4835 QualType TruncTy =
4836 Context.getExtVectorType(ElType, ToVec->getNumElements());
4837 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
4838 From->getValueKind())
4839 .get();
4840 break;
4841 }
4842 case ICK_Identity:
4843 default:
4844 llvm_unreachable("Improper element standard conversion");
4845 }
4846 }
4847
4848 switch (SCS.Third) {
4849 case ICK_Identity:
4850 // Nothing to do.
4851 break;
4852
4854 // If both sides are functions (or pointers/references to them), there could
4855 // be incompatible exception declarations.
4856 if (CheckExceptionSpecCompatibility(From, ToType))
4857 return ExprError();
4858
4859 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4860 /*BasePath=*/nullptr, CCK)
4861 .get();
4862 break;
4863
4864 case ICK_Qualification: {
4865 ExprValueKind VK = From->getValueKind();
4866 CastKind CK = CK_NoOp;
4867
4868 if (ToType->isReferenceType() &&
4869 ToType->getPointeeType().getAddressSpace() !=
4870 From->getType().getAddressSpace())
4871 CK = CK_AddressSpaceConversion;
4872
4873 if (ToType->isPointerType() &&
4874 ToType->getPointeeType().getAddressSpace() !=
4876 CK = CK_AddressSpaceConversion;
4877
4878 if (!isCast(CCK) &&
4879 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4881 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4882 << InitialFromType << ToType;
4883 }
4884
4885 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4886 /*BasePath=*/nullptr, CCK)
4887 .get();
4888
4890 !getLangOpts().WritableStrings) {
4891 Diag(From->getBeginLoc(),
4893 ? diag::ext_deprecated_string_literal_conversion
4894 : diag::warn_deprecated_string_literal_conversion)
4895 << ToType.getNonReferenceType();
4896 }
4897
4898 break;
4899 }
4900
4901 default:
4902 llvm_unreachable("Improper third standard conversion");
4903 }
4904
4905 // If this conversion sequence involved a scalar -> atomic conversion, perform
4906 // that conversion now.
4907 if (!ToAtomicType.isNull()) {
4908 assert(Context.hasSameType(
4909 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4910 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4911 VK_PRValue, nullptr, CCK)
4912 .get();
4913 }
4914
4915 // Materialize a temporary if we're implicitly converting to a reference
4916 // type. This is not required by the C++ rules but is necessary to maintain
4917 // AST invariants.
4918 if (ToType->isReferenceType() && From->isPRValue()) {
4920 if (Res.isInvalid())
4921 return ExprError();
4922 From = Res.get();
4923 }
4924
4925 // If this conversion sequence succeeded and involved implicitly converting a
4926 // _Nullable type to a _Nonnull one, complain.
4927 if (!isCast(CCK))
4928 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4929 From->getBeginLoc());
4930
4931 return From;
4932}
4933
4934/// Checks that type T is not a VLA.
4935///
4936/// @returns @c true if @p T is VLA and a diagnostic was emitted,
4937/// @c false otherwise.
4939 clang::tok::TokenKind TypeTraitID) {
4940 if (!T->getType()->isVariableArrayType())
4941 return false;
4942
4943 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported)
4944 << 1 << TypeTraitID;
4945 return true;
4946}
4947
4948/// Check the completeness of a type in a unary type trait.
4949///
4950/// If the particular type trait requires a complete type, tries to complete
4951/// it. If completing the type fails, a diagnostic is emitted and false
4952/// returned. If completing the type succeeds or no completion was required,
4953/// returns true.
4956 QualType ArgTy) {
4957 // C++0x [meta.unary.prop]p3:
4958 // For all of the class templates X declared in this Clause, instantiating
4959 // that template with a template argument that is a class template
4960 // specialization may result in the implicit instantiation of the template
4961 // argument if and only if the semantics of X require that the argument
4962 // must be a complete type.
4963 // We apply this rule to all the type trait expressions used to implement
4964 // these class templates. We also try to follow any GCC documented behavior
4965 // in these expressions to ensure portability of standard libraries.
4966 switch (UTT) {
4967 default: llvm_unreachable("not a UTT");
4968 // is_complete_type somewhat obviously cannot require a complete type.
4969 case UTT_IsCompleteType:
4970 // Fall-through
4971
4972 // These traits are modeled on the type predicates in C++0x
4973 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4974 // requiring a complete type, as whether or not they return true cannot be
4975 // impacted by the completeness of the type.
4976 case UTT_IsVoid:
4977 case UTT_IsIntegral:
4978 case UTT_IsFloatingPoint:
4979 case UTT_IsArray:
4980 case UTT_IsBoundedArray:
4981 case UTT_IsPointer:
4982 case UTT_IsNullPointer:
4983 case UTT_IsReferenceable:
4984 case UTT_IsLvalueReference:
4985 case UTT_IsRvalueReference:
4986 case UTT_IsMemberFunctionPointer:
4987 case UTT_IsMemberObjectPointer:
4988 case UTT_IsEnum:
4989 case UTT_IsScopedEnum:
4990 case UTT_IsUnion:
4991 case UTT_IsClass:
4992 case UTT_IsFunction:
4993 case UTT_IsReference:
4994 case UTT_IsArithmetic:
4995 case UTT_IsFundamental:
4996 case UTT_IsObject:
4997 case UTT_IsScalar:
4998 case UTT_IsCompound:
4999 case UTT_IsMemberPointer:
5000 // Fall-through
5001
5002 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
5003 // which requires some of its traits to have the complete type. However,
5004 // the completeness of the type cannot impact these traits' semantics, and
5005 // so they don't require it. This matches the comments on these traits in
5006 // Table 49.
5007 case UTT_IsConst:
5008 case UTT_IsVolatile:
5009 case UTT_IsSigned:
5010 case UTT_IsUnboundedArray:
5011 case UTT_IsUnsigned:
5012
5013 // This type trait always returns false, checking the type is moot.
5014 case UTT_IsInterfaceClass:
5015 return true;
5016
5017 // C++14 [meta.unary.prop]:
5018 // If T is a non-union class type, T shall be a complete type.
5019 case UTT_IsEmpty:
5020 case UTT_IsPolymorphic:
5021 case UTT_IsAbstract:
5022 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
5023 if (!RD->isUnion())
5024 return !S.RequireCompleteType(
5025 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5026 return true;
5027
5028 // C++14 [meta.unary.prop]:
5029 // If T is a class type, T shall be a complete type.
5030 case UTT_IsFinal:
5031 case UTT_IsSealed:
5032 if (ArgTy->getAsCXXRecordDecl())
5033 return !S.RequireCompleteType(
5034 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5035 return true;
5036
5037 // LWG3823: T shall be an array type, a complete type, or cv void.
5038 case UTT_IsAggregate:
5039 if (ArgTy->isArrayType() || ArgTy->isVoidType())
5040 return true;
5041
5042 return !S.RequireCompleteType(
5043 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5044
5045 // C++1z [meta.unary.prop]:
5046 // remove_all_extents_t<T> shall be a complete type or cv void.
5047 case UTT_IsTrivial:
5048 case UTT_IsTriviallyCopyable:
5049 case UTT_IsStandardLayout:
5050 case UTT_IsPOD:
5051 case UTT_IsLiteral:
5052 case UTT_IsBitwiseCloneable:
5053 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
5054 // impose the same constraints.
5055 case UTT_IsTriviallyRelocatable:
5056 case UTT_IsTriviallyEqualityComparable:
5057 case UTT_CanPassInRegs:
5058 // Per the GCC type traits documentation, T shall be a complete type, cv void,
5059 // or an array of unknown bound. But GCC actually imposes the same constraints
5060 // as above.
5061 case UTT_HasNothrowAssign:
5062 case UTT_HasNothrowMoveAssign:
5063 case UTT_HasNothrowConstructor:
5064 case UTT_HasNothrowCopy:
5065 case UTT_HasTrivialAssign:
5066 case UTT_HasTrivialMoveAssign:
5067 case UTT_HasTrivialDefaultConstructor:
5068 case UTT_HasTrivialMoveConstructor:
5069 case UTT_HasTrivialCopy:
5070 case UTT_HasTrivialDestructor:
5071 case UTT_HasVirtualDestructor:
5072 // has_unique_object_representations<T> when T is an array is defined in terms
5073 // of has_unique_object_representations<remove_all_extents_t<T>>, so the base
5074 // type needs to be complete even if the type is an incomplete array type.
5075 case UTT_HasUniqueObjectRepresentations:
5076 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
5077 [[fallthrough]];
5078
5079 // C++1z [meta.unary.prop]:
5080 // T shall be a complete type, cv void, or an array of unknown bound.
5081 case UTT_IsDestructible:
5082 case UTT_IsNothrowDestructible:
5083 case UTT_IsTriviallyDestructible:
5084 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
5085 return true;
5086
5087 return !S.RequireCompleteType(
5088 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5089 }
5090}
5091
5093 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
5094 bool (CXXRecordDecl::*HasTrivial)() const,
5095 bool (CXXRecordDecl::*HasNonTrivial)() const,
5096 bool (CXXMethodDecl::*IsDesiredOp)() const)
5097{
5098 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5099 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
5100 return true;
5101
5102 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
5103 DeclarationNameInfo NameInfo(Name, KeyLoc);
5105 if (Self.LookupQualifiedName(Res, RD)) {
5106 bool FoundOperator = false;
5107 Res.suppressDiagnostics();
5108 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
5109 Op != OpEnd; ++Op) {
5110 if (isa<FunctionTemplateDecl>(*Op))
5111 continue;
5112
5113 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
5114 if((Operator->*IsDesiredOp)()) {
5115 FoundOperator = true;
5116 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
5117 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5118 if (!CPT || !CPT->isNothrow())
5119 return false;
5120 }
5121 }
5122 return FoundOperator;
5123 }
5124 return false;
5125}
5126
5128 const CXXRecordDecl *Decl,
5129 SourceLocation KeyLoc) {
5130 if (Decl->isUnion())
5131 return false;
5132 if (Decl->isLambda())
5133 return Decl->isCapturelessLambda();
5134
5135 {
5136 EnterExpressionEvaluationContext UnevaluatedContext(
5138 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5140
5141 // const ClassT& obj;
5142 OpaqueValueExpr Operand(
5143 {}, Decl->getTypeForDecl()->getCanonicalTypeUnqualified().withConst(),
5145 UnresolvedSet<16> Functions;
5146 // obj == obj;
5147 S.LookupBinOp(S.TUScope, {}, BinaryOperatorKind::BO_EQ, Functions);
5148
5149 auto Result = S.CreateOverloadedBinOp(KeyLoc, BinaryOperatorKind::BO_EQ,
5150 Functions, &Operand, &Operand);
5151 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5152 return false;
5153
5154 const auto *CallExpr = dyn_cast<CXXOperatorCallExpr>(Result.get());
5155 if (!CallExpr)
5156 return false;
5157 const auto *Callee = CallExpr->getDirectCallee();
5158 auto ParamT = Callee->getParamDecl(0)->getType();
5159 if (!Callee->isDefaulted())
5160 return false;
5161 if (!ParamT->isReferenceType() && !Decl->isTriviallyCopyable())
5162 return false;
5163 if (ParamT.getNonReferenceType()->getUnqualifiedDesugaredType() !=
5164 Decl->getTypeForDecl())
5165 return false;
5166 }
5167
5168 return llvm::all_of(Decl->bases(),
5169 [&](const CXXBaseSpecifier &BS) {
5170 if (const auto *RD = BS.getType()->getAsCXXRecordDecl())
5171 return HasNonDeletedDefaultedEqualityComparison(
5172 S, RD, KeyLoc);
5173 return true;
5174 }) &&
5175 llvm::all_of(Decl->fields(), [&](const FieldDecl *FD) {
5176 auto Type = FD->getType();
5177 if (Type->isArrayType())
5178 Type = Type->getBaseElementTypeUnsafe()
5179 ->getCanonicalTypeUnqualified();
5180
5181 if (Type->isReferenceType() || Type->isEnumeralType())
5182 return false;
5183 if (const auto *RD = Type->getAsCXXRecordDecl())
5184 return HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc);
5185 return true;
5186 });
5187}
5188
5190 QualType CanonicalType = Type.getCanonicalType();
5191 if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
5192 CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
5193 return false;
5194
5195 if (const auto *RD = CanonicalType->getAsCXXRecordDecl()) {
5196 if (!HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc))
5197 return false;
5198 }
5199
5201 CanonicalType, /*CheckIfTriviallyCopyable=*/false);
5202}
5203
5205 SourceLocation KeyLoc,
5206 TypeSourceInfo *TInfo) {
5207 QualType T = TInfo->getType();
5208 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5209
5210 ASTContext &C = Self.Context;
5211 switch(UTT) {
5212 default: llvm_unreachable("not a UTT");
5213 // Type trait expressions corresponding to the primary type category
5214 // predicates in C++0x [meta.unary.cat].
5215 case UTT_IsVoid:
5216 return T->isVoidType();
5217 case UTT_IsIntegral:
5218 return T->isIntegralType(C);
5219 case UTT_IsFloatingPoint:
5220 return T->isFloatingType();
5221 case UTT_IsArray:
5222 // Zero-sized arrays aren't considered arrays in partial specializations,
5223 // so __is_array shouldn't consider them arrays either.
5224 if (const auto *CAT = C.getAsConstantArrayType(T))
5225 return CAT->getSize() != 0;
5226 return T->isArrayType();
5227 case UTT_IsBoundedArray:
5228 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_bounded_array))
5229 return false;
5230 // Zero-sized arrays aren't considered arrays in partial specializations,
5231 // so __is_bounded_array shouldn't consider them arrays either.
5232 if (const auto *CAT = C.getAsConstantArrayType(T))
5233 return CAT->getSize() != 0;
5234 return T->isArrayType() && !T->isIncompleteArrayType();
5235 case UTT_IsUnboundedArray:
5236 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_unbounded_array))
5237 return false;
5238 return T->isIncompleteArrayType();
5239 case UTT_IsPointer:
5240 return T->isAnyPointerType();
5241 case UTT_IsNullPointer:
5242 return T->isNullPtrType();
5243 case UTT_IsLvalueReference:
5244 return T->isLValueReferenceType();
5245 case UTT_IsRvalueReference:
5246 return T->isRValueReferenceType();
5247 case UTT_IsMemberFunctionPointer:
5249 case UTT_IsMemberObjectPointer:
5250 return T->isMemberDataPointerType();
5251 case UTT_IsEnum:
5252 return T->isEnumeralType();
5253 case UTT_IsScopedEnum:
5254 return T->isScopedEnumeralType();
5255 case UTT_IsUnion:
5256 return T->isUnionType();
5257 case UTT_IsClass:
5258 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
5259 case UTT_IsFunction:
5260 return T->isFunctionType();
5261
5262 // Type trait expressions which correspond to the convenient composition
5263 // predicates in C++0x [meta.unary.comp].
5264 case UTT_IsReference:
5265 return T->isReferenceType();
5266 case UTT_IsArithmetic:
5267 return T->isArithmeticType() && !T->isEnumeralType();
5268 case UTT_IsFundamental:
5269 return T->isFundamentalType();
5270 case UTT_IsObject:
5271 return T->isObjectType();
5272 case UTT_IsScalar:
5273 // Note: semantic analysis depends on Objective-C lifetime types to be
5274 // considered scalar types. However, such types do not actually behave
5275 // like scalar types at run time (since they may require retain/release
5276 // operations), so we report them as non-scalar.
5277 if (T->isObjCLifetimeType()) {
5278 switch (T.getObjCLifetime()) {
5281 return true;
5282
5286 return false;
5287 }
5288 }
5289
5290 return T->isScalarType();
5291 case UTT_IsCompound:
5292 return T->isCompoundType();
5293 case UTT_IsMemberPointer:
5294 return T->isMemberPointerType();
5295
5296 // Type trait expressions which correspond to the type property predicates
5297 // in C++0x [meta.unary.prop].
5298 case UTT_IsConst:
5299 return T.isConstQualified();
5300 case UTT_IsVolatile:
5301 return T.isVolatileQualified();
5302 case UTT_IsTrivial:
5303 return T.isTrivialType(C);
5304 case UTT_IsTriviallyCopyable:
5305 return T.isTriviallyCopyableType(C);
5306 case UTT_IsStandardLayout:
5307 return T->isStandardLayoutType();
5308 case UTT_IsPOD:
5309 return T.isPODType(C);
5310 case UTT_IsLiteral:
5311 return T->isLiteralType(C);
5312 case UTT_IsEmpty:
5313 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5314 return !RD->isUnion() && RD->isEmpty();
5315 return false;
5316 case UTT_IsPolymorphic:
5317 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5318 return !RD->isUnion() && RD->isPolymorphic();
5319 return false;
5320 case UTT_IsAbstract:
5321 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5322 return !RD->isUnion() && RD->isAbstract();
5323 return false;
5324 case UTT_IsAggregate:
5325 // Report vector extensions and complex types as aggregates because they
5326 // support aggregate initialization. GCC mirrors this behavior for vectors
5327 // but not _Complex.
5328 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5330 // __is_interface_class only returns true when CL is invoked in /CLR mode and
5331 // even then only when it is used with the 'interface struct ...' syntax
5332 // Clang doesn't support /CLR which makes this type trait moot.
5333 case UTT_IsInterfaceClass:
5334 return false;
5335 case UTT_IsFinal:
5336 case UTT_IsSealed:
5337 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5338 return RD->hasAttr<FinalAttr>();
5339 return false;
5340 case UTT_IsSigned:
5341 // Enum types should always return false.
5342 // Floating points should always return true.
5343 return T->isFloatingType() ||
5345 case UTT_IsUnsigned:
5346 // Enum types should always return false.
5347 return T->isUnsignedIntegerType() && !T->isEnumeralType();
5348
5349 // Type trait expressions which query classes regarding their construction,
5350 // destruction, and copying. Rather than being based directly on the
5351 // related type predicates in the standard, they are specified by both
5352 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5353 // specifications.
5354 //
5355 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5356 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5357 //
5358 // Note that these builtins do not behave as documented in g++: if a class
5359 // has both a trivial and a non-trivial special member of a particular kind,
5360 // they return false! For now, we emulate this behavior.
5361 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5362 // does not correctly compute triviality in the presence of multiple special
5363 // members of the same kind. Revisit this once the g++ bug is fixed.
5364 case UTT_HasTrivialDefaultConstructor:
5365 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5366 // If __is_pod (type) is true then the trait is true, else if type is
5367 // a cv class or union type (or array thereof) with a trivial default
5368 // constructor ([class.ctor]) then the trait is true, else it is false.
5369 if (T.isPODType(C))
5370 return true;
5371 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5372 return RD->hasTrivialDefaultConstructor() &&
5374 return false;
5375 case UTT_HasTrivialMoveConstructor:
5376 // This trait is implemented by MSVC 2012 and needed to parse the
5377 // standard library headers. Specifically this is used as the logic
5378 // behind std::is_trivially_move_constructible (20.9.4.3).
5379 if (T.isPODType(C))
5380 return true;
5381 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5383 return false;
5384 case UTT_HasTrivialCopy:
5385 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5386 // If __is_pod (type) is true or type is a reference type then
5387 // the trait is true, else if type is a cv class or union type
5388 // with a trivial copy constructor ([class.copy]) then the trait
5389 // is true, else it is false.
5390 if (T.isPODType(C) || T->isReferenceType())
5391 return true;
5392 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5393 return RD->hasTrivialCopyConstructor() &&
5395 return false;
5396 case UTT_HasTrivialMoveAssign:
5397 // This trait is implemented by MSVC 2012 and needed to parse the
5398 // standard library headers. Specifically it is used as the logic
5399 // behind std::is_trivially_move_assignable (20.9.4.3)
5400 if (T.isPODType(C))
5401 return true;
5402 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5404 return false;
5405 case UTT_HasTrivialAssign:
5406 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5407 // If type is const qualified or is a reference type then the
5408 // trait is false. Otherwise if __is_pod (type) is true then the
5409 // trait is true, else if type is a cv class or union type with
5410 // a trivial copy assignment ([class.copy]) then the trait is
5411 // true, else it is false.
5412 // Note: the const and reference restrictions are interesting,
5413 // given that const and reference members don't prevent a class
5414 // from having a trivial copy assignment operator (but do cause
5415 // errors if the copy assignment operator is actually used, q.v.
5416 // [class.copy]p12).
5417
5418 if (T.isConstQualified())
5419 return false;
5420 if (T.isPODType(C))
5421 return true;
5422 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5423 return RD->hasTrivialCopyAssignment() &&
5425 return false;
5426 case UTT_IsDestructible:
5427 case UTT_IsTriviallyDestructible:
5428 case UTT_IsNothrowDestructible:
5429 // C++14 [meta.unary.prop]:
5430 // For reference types, is_destructible<T>::value is true.
5431 if (T->isReferenceType())
5432 return true;
5433
5434 // Objective-C++ ARC: autorelease types don't require destruction.
5435 if (T->isObjCLifetimeType() &&
5436 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5437 return true;
5438
5439 // C++14 [meta.unary.prop]:
5440 // For incomplete types and function types, is_destructible<T>::value is
5441 // false.
5442 if (T->isIncompleteType() || T->isFunctionType())
5443 return false;
5444
5445 // A type that requires destruction (via a non-trivial destructor or ARC
5446 // lifetime semantics) is not trivially-destructible.
5447 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5448 return false;
5449
5450 // C++14 [meta.unary.prop]:
5451 // For object types and given U equal to remove_all_extents_t<T>, if the
5452 // expression std::declval<U&>().~U() is well-formed when treated as an
5453 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
5454 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5455 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5456 if (!Destructor)
5457 return false;
5458 // C++14 [dcl.fct.def.delete]p2:
5459 // A program that refers to a deleted function implicitly or
5460 // explicitly, other than to declare it, is ill-formed.
5461 if (Destructor->isDeleted())
5462 return false;
5463 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5464 return false;
5465 if (UTT == UTT_IsNothrowDestructible) {
5466 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5467 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5468 if (!CPT || !CPT->isNothrow())
5469 return false;
5470 }
5471 }
5472 return true;
5473
5474 case UTT_HasTrivialDestructor:
5475 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5476 // If __is_pod (type) is true or type is a reference type
5477 // then the trait is true, else if type is a cv class or union
5478 // type (or array thereof) with a trivial destructor
5479 // ([class.dtor]) then the trait is true, else it is
5480 // false.
5481 if (T.isPODType(C) || T->isReferenceType())
5482 return true;
5483
5484 // Objective-C++ ARC: autorelease types don't require destruction.
5485 if (T->isObjCLifetimeType() &&
5486 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5487 return true;
5488
5489 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5490 return RD->hasTrivialDestructor();
5491 return false;
5492 // TODO: Propagate nothrowness for implicitly declared special members.
5493 case UTT_HasNothrowAssign:
5494 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5495 // If type is const qualified or is a reference type then the
5496 // trait is false. Otherwise if __has_trivial_assign (type)
5497 // is true then the trait is true, else if type is a cv class
5498 // or union type with copy assignment operators that are known
5499 // not to throw an exception then the trait is true, else it is
5500 // false.
5501 if (C.getBaseElementType(T).isConstQualified())
5502 return false;
5503 if (T->isReferenceType())
5504 return false;
5505 if (T.isPODType(C) || T->isObjCLifetimeType())
5506 return true;
5507
5508 if (const RecordType *RT = T->getAs<RecordType>())
5509 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5513 return false;
5514 case UTT_HasNothrowMoveAssign:
5515 // This trait is implemented by MSVC 2012 and needed to parse the
5516 // standard library headers. Specifically this is used as the logic
5517 // behind std::is_nothrow_move_assignable (20.9.4.3).
5518 if (T.isPODType(C))
5519 return true;
5520
5521 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5522 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5526 return false;
5527 case UTT_HasNothrowCopy:
5528 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5529 // If __has_trivial_copy (type) is true then the trait is true, else
5530 // if type is a cv class or union type with copy constructors that are
5531 // known not to throw an exception then the trait is true, else it is
5532 // false.
5533 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5534 return true;
5535 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5536 if (RD->hasTrivialCopyConstructor() &&
5538 return true;
5539
5540 bool FoundConstructor = false;
5541 unsigned FoundTQs;
5542 for (const auto *ND : Self.LookupConstructors(RD)) {
5543 // A template constructor is never a copy constructor.
5544 // FIXME: However, it may actually be selected at the actual overload
5545 // resolution point.
5546 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5547 continue;
5548 // UsingDecl itself is not a constructor
5549 if (isa<UsingDecl>(ND))
5550 continue;
5551 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5552 if (Constructor->isCopyConstructor(FoundTQs)) {
5553 FoundConstructor = true;
5554 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5555 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5556 if (!CPT)
5557 return false;
5558 // TODO: check whether evaluating default arguments can throw.
5559 // For now, we'll be conservative and assume that they can throw.
5560 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5561 return false;
5562 }
5563 }
5564
5565 return FoundConstructor;
5566 }
5567 return false;
5568 case UTT_HasNothrowConstructor:
5569 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5570 // If __has_trivial_constructor (type) is true then the trait is
5571 // true, else if type is a cv class or union type (or array
5572 // thereof) with a default constructor that is known not to
5573 // throw an exception then the trait is true, else it is false.
5574 if (T.isPODType(C) || T->isObjCLifetimeType())
5575 return true;
5576 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5577 if (RD->hasTrivialDefaultConstructor() &&
5579 return true;
5580
5581 bool FoundConstructor = false;
5582 for (const auto *ND : Self.LookupConstructors(RD)) {
5583 // FIXME: In C++0x, a constructor template can be a default constructor.
5584 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5585 continue;
5586 // UsingDecl itself is not a constructor
5587 if (isa<UsingDecl>(ND))
5588 continue;
5589 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5590 if (Constructor->isDefaultConstructor()) {
5591 FoundConstructor = true;
5592 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5593 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5594 if (!CPT)
5595 return false;
5596 // FIXME: check whether evaluating default arguments can throw.
5597 // For now, we'll be conservative and assume that they can throw.
5598 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5599 return false;
5600 }
5601 }
5602 return FoundConstructor;
5603 }
5604 return false;
5605 case UTT_HasVirtualDestructor:
5606 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5607 // If type is a class type with a virtual destructor ([class.dtor])
5608 // then the trait is true, else it is false.
5609 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5610 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5611 return Destructor->isVirtual();
5612 return false;
5613
5614 // These type trait expressions are modeled on the specifications for the
5615 // Embarcadero C++0x type trait functions:
5616 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5617 case UTT_IsCompleteType:
5618 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5619 // Returns True if and only if T is a complete type at the point of the
5620 // function call.
5621 return !T->isIncompleteType();
5622 case UTT_HasUniqueObjectRepresentations:
5623 return C.hasUniqueObjectRepresentations(T);
5624 case UTT_IsTriviallyRelocatable:
5625 return T.isTriviallyRelocatableType(C);
5626 case UTT_IsBitwiseCloneable:
5627 return T.isBitwiseCloneableType(C);
5628 case UTT_IsReferenceable:
5629 return T.isReferenceable();
5630 case UTT_CanPassInRegs:
5631 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())
5632 return RD->canPassInRegisters();
5633 Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;
5634 return false;
5635 case UTT_IsTriviallyEqualityComparable:
5636 return isTriviallyEqualityComparableType(Self, T, KeyLoc);
5637 }
5638}
5639
5640static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,
5641 const TypeSourceInfo *Rhs, SourceLocation KeyLoc);
5642
5644 Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs,
5645 SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator) {
5646
5647 QualType LhsT = Lhs->getType();
5648 QualType RhsT = Rhs->getType();
5649
5650 // C++0x [meta.rel]p4:
5651 // Given the following function prototype:
5652 //
5653 // template <class T>
5654 // typename add_rvalue_reference<T>::type create();
5655 //
5656 // the predicate condition for a template specialization
5657 // is_convertible<From, To> shall be satisfied if and only if
5658 // the return expression in the following code would be
5659 // well-formed, including any implicit conversions to the return
5660 // type of the function:
5661 //
5662 // To test() {
5663 // return create<From>();
5664 // }
5665 //
5666 // Access checking is performed as if in a context unrelated to To and
5667 // From. Only the validity of the immediate context of the expression
5668 // of the return-statement (including conversions to the return type)
5669 // is considered.
5670 //
5671 // We model the initialization as a copy-initialization of a temporary
5672 // of the appropriate type, which for this expression is identical to the
5673 // return statement (since NRVO doesn't apply).
5674
5675 // Functions aren't allowed to return function or array types.
5676 if (RhsT->isFunctionType() || RhsT->isArrayType())
5677 return ExprError();
5678
5679 // A function definition requires a complete, non-abstract return type.
5680 if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) ||
5681 Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT))
5682 return ExprError();
5683
5684 // Compute the result of add_rvalue_reference.
5685 if (LhsT->isObjectType() || LhsT->isFunctionType())
5686 LhsT = Self.Context.getRValueReferenceType(LhsT);
5687
5688 // Build a fake source and destination for initialization.
5690 Expr *From = new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5691 OpaqueValueExpr(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5693 InitializationKind Kind =
5695
5696 // Perform the initialization in an unevaluated context within a SFINAE
5697 // trap at translation unit scope.
5700 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5701 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5702 InitializationSequence Init(Self, To, Kind, From);
5703 if (Init.Failed())
5704 return ExprError();
5705
5706 ExprResult Result = Init.Perform(Self, To, Kind, From);
5707 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5708 return ExprError();
5709
5710 return Result;
5711}
5712
5714 SourceLocation KWLoc,
5716 SourceLocation RParenLoc,
5717 bool IsDependent) {
5718 if (IsDependent)
5719 return false;
5720
5721 if (Kind <= UTT_Last)
5722 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]);
5723
5724 // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary
5725 // alongside the IsConstructible traits to avoid duplication.
5726 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary &&
5727 Kind != BTT_ReferenceConstructsFromTemporary &&
5728 Kind != BTT_ReferenceConvertsFromTemporary)
5729 return EvaluateBinaryTypeTrait(S, Kind, Args[0],
5730 Args[1], RParenLoc);
5731
5732 switch (Kind) {
5733 case clang::BTT_ReferenceBindsToTemporary:
5734 case clang::BTT_ReferenceConstructsFromTemporary:
5735 case clang::BTT_ReferenceConvertsFromTemporary:
5736 case clang::TT_IsConstructible:
5737 case clang::TT_IsNothrowConstructible:
5738 case clang::TT_IsTriviallyConstructible: {
5739 // C++11 [meta.unary.prop]:
5740 // is_trivially_constructible is defined as:
5741 //
5742 // is_constructible<T, Args...>::value is true and the variable
5743 // definition for is_constructible, as defined below, is known to call
5744 // no operation that is not trivial.
5745 //
5746 // The predicate condition for a template specialization
5747 // is_constructible<T, Args...> shall be satisfied if and only if the
5748 // following variable definition would be well-formed for some invented
5749 // variable t:
5750 //
5751 // T t(create<Args>()...);
5752 assert(!Args.empty());
5753
5754 // Precondition: T and all types in the parameter pack Args shall be
5755 // complete types, (possibly cv-qualified) void, or arrays of
5756 // unknown bound.
5757 for (const auto *TSI : Args) {
5758 QualType ArgTy = TSI->getType();
5759 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5760 continue;
5761
5762 if (S.RequireCompleteType(KWLoc, ArgTy,
5763 diag::err_incomplete_type_used_in_type_trait_expr))
5764 return false;
5765 }
5766
5767 // Make sure the first argument is not incomplete nor a function type.
5768 QualType T = Args[0]->getType();
5769 if (T->isIncompleteType() || T->isFunctionType())
5770 return false;
5771
5772 // Make sure the first argument is not an abstract type.
5774 if (RD && RD->isAbstract())
5775 return false;
5776
5777 llvm::BumpPtrAllocator OpaqueExprAllocator;
5778 SmallVector<Expr *, 2> ArgExprs;
5779 ArgExprs.reserve(Args.size() - 1);
5780 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5781 QualType ArgTy = Args[I]->getType();
5782 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5783 ArgTy = S.Context.getRValueReferenceType(ArgTy);
5784 ArgExprs.push_back(
5785 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5786 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5789 }
5790
5791 // Perform the initialization in an unevaluated context within a SFINAE
5792 // trap at translation unit scope.
5795 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5799 InitializationKind InitKind(
5800 Kind == clang::BTT_ReferenceConvertsFromTemporary
5801 ? InitializationKind::CreateCopy(KWLoc, KWLoc)
5802 : InitializationKind::CreateDirect(KWLoc, KWLoc, RParenLoc));
5803 InitializationSequence Init(S, To, InitKind, ArgExprs);
5804 if (Init.Failed())
5805 return false;
5806
5807 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5808 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5809 return false;
5810
5811 if (Kind == clang::TT_IsConstructible)
5812 return true;
5813
5814 if (Kind == clang::BTT_ReferenceBindsToTemporary ||
5815 Kind == clang::BTT_ReferenceConstructsFromTemporary ||
5816 Kind == clang::BTT_ReferenceConvertsFromTemporary) {
5817 if (!T->isReferenceType())
5818 return false;
5819
5820 if (!Init.isDirectReferenceBinding())
5821 return true;
5822
5823 if (Kind == clang::BTT_ReferenceBindsToTemporary)
5824 return false;
5825
5826 QualType U = Args[1]->getType();
5827 if (U->isReferenceType())
5828 return false;
5829
5831 S.Context.getPointerType(T.getNonReferenceType()));
5833 S.Context.getPointerType(U.getNonReferenceType()));
5834 return !CheckConvertibilityForTypeTraits(S, UPtr, TPtr, RParenLoc,
5835 OpaqueExprAllocator)
5836 .isInvalid();
5837 }
5838
5839 if (Kind == clang::TT_IsNothrowConstructible)
5840 return S.canThrow(Result.get()) == CT_Cannot;
5841
5842 if (Kind == clang::TT_IsTriviallyConstructible) {
5843 // Under Objective-C ARC and Weak, if the destination has non-trivial
5844 // Objective-C lifetime, this is a non-trivial construction.
5845 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5846 return false;
5847
5848 // The initialization succeeded; now make sure there are no non-trivial
5849 // calls.
5850 return !Result.get()->hasNonTrivialCall(S.Context);
5851 }
5852
5853 llvm_unreachable("unhandled type trait");
5854 return false;
5855 }
5856 default: llvm_unreachable("not a TT");
5857 }
5858
5859 return false;
5860}
5861
5862namespace {
5863void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5864 SourceLocation KWLoc) {
5865 TypeTrait Replacement;
5866 switch (Kind) {
5867 case UTT_HasNothrowAssign:
5868 case UTT_HasNothrowMoveAssign:
5869 Replacement = BTT_IsNothrowAssignable;
5870 break;
5871 case UTT_HasNothrowCopy:
5872 case UTT_HasNothrowConstructor:
5873 Replacement = TT_IsNothrowConstructible;
5874 break;
5875 case UTT_HasTrivialAssign:
5876 case UTT_HasTrivialMoveAssign:
5877 Replacement = BTT_IsTriviallyAssignable;
5878 break;
5879 case UTT_HasTrivialCopy:
5880 Replacement = UTT_IsTriviallyCopyable;
5881 break;
5882 case UTT_HasTrivialDefaultConstructor:
5883 case UTT_HasTrivialMoveConstructor:
5884 Replacement = TT_IsTriviallyConstructible;
5885 break;
5886 case UTT_HasTrivialDestructor:
5887 Replacement = UTT_IsTriviallyDestructible;
5888 break;
5889 default:
5890 return;
5891 }
5892 S.Diag(KWLoc, diag::warn_deprecated_builtin)
5893 << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5894}
5895}
5896
5897bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
5898 if (Arity && N != Arity) {
5899 Diag(Loc, diag::err_type_trait_arity)
5900 << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
5901 return false;
5902 }
5903
5904 if (!Arity && N == 0) {
5905 Diag(Loc, diag::err_type_trait_arity)
5906 << 1 << 1 << 1 << (int)N << SourceRange(Loc);
5907 return false;
5908 }
5909 return true;
5910}
5911
5913 Bool,
5914};
5915
5917 return TypeTraitReturnType::Bool;
5918}
5919
5922 SourceLocation RParenLoc) {
5923 if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
5924 return ExprError();
5925
5927 *this, Kind, KWLoc, Args[0]->getType()))
5928 return ExprError();
5929
5930 DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5931
5932 bool Dependent = false;
5933 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5934 if (Args[I]->getType()->isDependentType()) {
5935 Dependent = true;
5936 break;
5937 }
5938 }
5939
5940 switch (GetReturnType(Kind)) {
5941 case TypeTraitReturnType::Bool: {
5942 bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc,
5943 Dependent);
5945 KWLoc, Kind, Args, RParenLoc, Result);
5946 }
5947 }
5948 llvm_unreachable("unhandled type trait return type");
5949}
5950
5953 SourceLocation RParenLoc) {
5955 ConvertedArgs.reserve(Args.size());
5956
5957 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5958 TypeSourceInfo *TInfo;
5959 QualType T = GetTypeFromParser(Args[I], &TInfo);
5960 if (!TInfo)
5961 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5962
5963 ConvertedArgs.push_back(TInfo);
5964 }
5965
5966 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5967}
5968
5970 const TypeSourceInfo *Rhs, SourceLocation KeyLoc) {
5971 QualType LhsT = Lhs->getType();
5972 QualType RhsT = Rhs->getType();
5973
5974 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5975 "Cannot evaluate traits of dependent types");
5976
5977 switch(BTT) {
5978 case BTT_IsBaseOf: {
5979 // C++0x [meta.rel]p2
5980 // Base is a base class of Derived without regard to cv-qualifiers or
5981 // Base and Derived are not unions and name the same class type without
5982 // regard to cv-qualifiers.
5983
5984 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5985 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5986 if (!rhsRecord || !lhsRecord) {
5987 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5988 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5989 if (!LHSObjTy || !RHSObjTy)
5990 return false;
5991
5992 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5993 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5994 if (!BaseInterface || !DerivedInterface)
5995 return false;
5996
5997 if (Self.RequireCompleteType(
5998 Rhs->getTypeLoc().getBeginLoc(), RhsT,
5999 diag::err_incomplete_type_used_in_type_trait_expr))
6000 return false;
6001
6002 return BaseInterface->isSuperClassOf(DerivedInterface);
6003 }
6004
6005 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
6006 == (lhsRecord == rhsRecord));
6007
6008 // Unions are never base classes, and never have base classes.
6009 // It doesn't matter if they are complete or not. See PR#41843
6010 if (lhsRecord && lhsRecord->getDecl()->isUnion())
6011 return false;
6012 if (rhsRecord && rhsRecord->getDecl()->isUnion())
6013 return false;
6014
6015 if (lhsRecord == rhsRecord)
6016 return true;
6017
6018 // C++0x [meta.rel]p2:
6019 // If Base and Derived are class types and are different types
6020 // (ignoring possible cv-qualifiers) then Derived shall be a
6021 // complete type.
6022 if (Self.RequireCompleteType(
6023 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6024 diag::err_incomplete_type_used_in_type_trait_expr))
6025 return false;
6026
6027 return cast<CXXRecordDecl>(rhsRecord->getDecl())
6028 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
6029 }
6030 case BTT_IsSame:
6031 return Self.Context.hasSameType(LhsT, RhsT);
6032 case BTT_TypeCompatible: {
6033 // GCC ignores cv-qualifiers on arrays for this builtin.
6034 Qualifiers LhsQuals, RhsQuals;
6035 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
6036 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
6037 return Self.Context.typesAreCompatible(Lhs, Rhs);
6038 }
6039 case BTT_IsConvertible:
6040 case BTT_IsConvertibleTo:
6041 case BTT_IsNothrowConvertible: {
6042 if (RhsT->isVoidType())
6043 return LhsT->isVoidType();
6044 llvm::BumpPtrAllocator OpaqueExprAllocator;
6046 OpaqueExprAllocator);
6047 if (Result.isInvalid())
6048 return false;
6049
6050 if (BTT != BTT_IsNothrowConvertible)
6051 return true;
6052
6053 return Self.canThrow(Result.get()) == CT_Cannot;
6054 }
6055
6056 case BTT_IsAssignable:
6057 case BTT_IsNothrowAssignable:
6058 case BTT_IsTriviallyAssignable: {
6059 // C++11 [meta.unary.prop]p3:
6060 // is_trivially_assignable is defined as:
6061 // is_assignable<T, U>::value is true and the assignment, as defined by
6062 // is_assignable, is known to call no operation that is not trivial
6063 //
6064 // is_assignable is defined as:
6065 // The expression declval<T>() = declval<U>() is well-formed when
6066 // treated as an unevaluated operand (Clause 5).
6067 //
6068 // For both, T and U shall be complete types, (possibly cv-qualified)
6069 // void, or arrays of unknown bound.
6070 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
6071 Self.RequireCompleteType(
6072 Lhs->getTypeLoc().getBeginLoc(), LhsT,
6073 diag::err_incomplete_type_used_in_type_trait_expr))
6074 return false;
6075 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
6076 Self.RequireCompleteType(
6077 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6078 diag::err_incomplete_type_used_in_type_trait_expr))
6079 return false;
6080
6081 // cv void is never assignable.
6082 if (LhsT->isVoidType() || RhsT->isVoidType())
6083 return false;
6084
6085 // Build expressions that emulate the effect of declval<T>() and
6086 // declval<U>().
6087 if (LhsT->isObjectType() || LhsT->isFunctionType())
6088 LhsT = Self.Context.getRValueReferenceType(LhsT);
6089 if (RhsT->isObjectType() || RhsT->isFunctionType())
6090 RhsT = Self.Context.getRValueReferenceType(RhsT);
6091 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
6093 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
6095
6096 // Attempt the assignment in an unevaluated context within a SFINAE
6097 // trap at translation unit scope.
6100 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
6101 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
6102 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
6103 &Rhs);
6104 if (Result.isInvalid())
6105 return false;
6106
6107 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
6108 Self.CheckUnusedVolatileAssignment(Result.get());
6109
6110 if (SFINAE.hasErrorOccurred())
6111 return false;
6112
6113 if (BTT == BTT_IsAssignable)
6114 return true;
6115
6116 if (BTT == BTT_IsNothrowAssignable)
6117 return Self.canThrow(Result.get()) == CT_Cannot;
6118
6119 if (BTT == BTT_IsTriviallyAssignable) {
6120 // Under Objective-C ARC and Weak, if the destination has non-trivial
6121 // Objective-C lifetime, this is a non-trivial assignment.
6123 return false;
6124
6125 return !Result.get()->hasNonTrivialCall(Self.Context);
6126 }
6127
6128 llvm_unreachable("unhandled type trait");
6129 return false;
6130 }
6131 case BTT_IsLayoutCompatible: {
6132 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType())
6133 Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,
6134 diag::err_incomplete_type);
6135 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType())
6136 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6137 diag::err_incomplete_type);
6138
6139 DiagnoseVLAInCXXTypeTrait(Self, Lhs, tok::kw___is_layout_compatible);
6140 DiagnoseVLAInCXXTypeTrait(Self, Rhs, tok::kw___is_layout_compatible);
6141
6142 return Self.IsLayoutCompatible(LhsT, RhsT);
6143 }
6144 case BTT_IsPointerInterconvertibleBaseOf: {
6145 if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() &&
6146 !Self.getASTContext().hasSameUnqualifiedType(LhsT, RhsT)) {
6147 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6148 diag::err_incomplete_type);
6149 }
6150
6152 tok::kw___is_pointer_interconvertible_base_of);
6154 tok::kw___is_pointer_interconvertible_base_of);
6155
6156 return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs);
6157 }
6158 case BTT_IsDeducible: {
6159 const auto *TSTToBeDeduced = cast<DeducedTemplateSpecializationType>(LhsT);
6160 sema::TemplateDeductionInfo Info(KeyLoc);
6161 return Self.DeduceTemplateArgumentsFromType(
6162 TSTToBeDeduced->getTemplateName().getAsTemplateDecl(), RhsT,
6164 }
6165 default:
6166 llvm_unreachable("not a BTT");
6167 }
6168 llvm_unreachable("Unknown type trait or not implemented");
6169}
6170
6172 SourceLocation KWLoc,
6173 ParsedType Ty,
6174 Expr* DimExpr,
6175 SourceLocation RParen) {
6176 TypeSourceInfo *TSInfo;
6177 QualType T = GetTypeFromParser(Ty, &TSInfo);
6178 if (!TSInfo)
6180
6181 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
6182}
6183
6185 QualType T, Expr *DimExpr,
6186 SourceLocation KeyLoc) {
6187 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
6188
6189 switch(ATT) {
6190 case ATT_ArrayRank:
6191 if (T->isArrayType()) {
6192 unsigned Dim = 0;
6193 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6194 ++Dim;
6195 T = AT->getElementType();
6196 }
6197 return Dim;
6198 }
6199 return 0;
6200
6201 case ATT_ArrayExtent: {
6202 llvm::APSInt Value;
6203 uint64_t Dim;
6204 if (Self.VerifyIntegerConstantExpression(
6205 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
6206 .isInvalid())
6207 return 0;
6208 if (Value.isSigned() && Value.isNegative()) {
6209 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
6210 << DimExpr->getSourceRange();
6211 return 0;
6212 }
6213 Dim = Value.getLimitedValue();
6214
6215 if (T->isArrayType()) {
6216 unsigned D = 0;
6217 bool Matched = false;
6218 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6219 if (Dim == D) {
6220 Matched = true;
6221 break;
6222 }
6223 ++D;
6224 T = AT->getElementType();
6225 }
6226
6227 if (Matched && T->isArrayType()) {
6228 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
6229 return CAT->getLimitedSize();
6230 }
6231 }
6232 return 0;
6233 }
6234 }
6235 llvm_unreachable("Unknown type trait or not implemented");
6236}
6237
6239 SourceLocation KWLoc,
6240 TypeSourceInfo *TSInfo,
6241 Expr* DimExpr,
6242 SourceLocation RParen) {
6243 QualType T = TSInfo->getType();
6244
6245 // FIXME: This should likely be tracked as an APInt to remove any host
6246 // assumptions about the width of size_t on the target.
6247 uint64_t Value = 0;
6248 if (!T->isDependentType())
6249 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
6250
6251 // While the specification for these traits from the Embarcadero C++
6252 // compiler's documentation says the return type is 'unsigned int', Clang
6253 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
6254 // compiler, there is no difference. On several other platforms this is an
6255 // important distinction.
6256 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
6257 RParen, Context.getSizeType());
6258}
6259
6261 SourceLocation KWLoc,
6262 Expr *Queried,
6263 SourceLocation RParen) {
6264 // If error parsing the expression, ignore.
6265 if (!Queried)
6266 return ExprError();
6267
6268 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
6269
6270 return Result;
6271}
6272
6274 switch (ET) {
6275 case ET_IsLValueExpr: return E->isLValue();
6276 case ET_IsRValueExpr:
6277 return E->isPRValue();
6278 }
6279 llvm_unreachable("Expression trait not covered by switch");
6280}
6281
6283 SourceLocation KWLoc,
6284 Expr *Queried,
6285 SourceLocation RParen) {
6286 if (Queried->isTypeDependent()) {
6287 // Delay type-checking for type-dependent expressions.
6288 } else if (Queried->hasPlaceholderType()) {
6289 ExprResult PE = CheckPlaceholderExpr(Queried);
6290 if (PE.isInvalid()) return ExprError();
6291 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
6292 }
6293
6294 bool Value = EvaluateExpressionTrait(ET, Queried);
6295
6296 return new (Context)
6297 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
6298}
6299
6301 ExprValueKind &VK,
6303 bool isIndirect) {
6304 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
6305 "placeholders should have been weeded out by now");
6306
6307 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
6308 // temporary materialization conversion otherwise.
6309 if (isIndirect)
6310 LHS = DefaultLvalueConversion(LHS.get());
6311 else if (LHS.get()->isPRValue())
6313 if (LHS.isInvalid())
6314 return QualType();
6315
6316 // The RHS always undergoes lvalue conversions.
6317 RHS = DefaultLvalueConversion(RHS.get());
6318 if (RHS.isInvalid()) return QualType();
6319
6320 const char *OpSpelling = isIndirect ? "->*" : ".*";
6321 // C++ 5.5p2
6322 // The binary operator .* [p3: ->*] binds its second operand, which shall
6323 // be of type "pointer to member of T" (where T is a completely-defined
6324 // class type) [...]
6325 QualType RHSType = RHS.get()->getType();
6326 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
6327 if (!MemPtr) {
6328 Diag(Loc, diag::err_bad_memptr_rhs)
6329 << OpSpelling << RHSType << RHS.get()->getSourceRange();
6330 return QualType();
6331 }
6332
6333 QualType Class(MemPtr->getClass(), 0);
6334
6335 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
6336 // member pointer points must be completely-defined. However, there is no
6337 // reason for this semantic distinction, and the rule is not enforced by
6338 // other compilers. Therefore, we do not check this property, as it is
6339 // likely to be considered a defect.
6340
6341 // C++ 5.5p2
6342 // [...] to its first operand, which shall be of class T or of a class of
6343 // which T is an unambiguous and accessible base class. [p3: a pointer to
6344 // such a class]
6345 QualType LHSType = LHS.get()->getType();
6346 if (isIndirect) {
6347 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
6348 LHSType = Ptr->getPointeeType();
6349 else {
6350 Diag(Loc, diag::err_bad_memptr_lhs)
6351 << OpSpelling << 1 << LHSType
6353 return QualType();
6354 }
6355 }
6356
6357 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
6358 // If we want to check the hierarchy, we need a complete type.
6359 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
6360 OpSpelling, (int)isIndirect)) {
6361 return QualType();
6362 }
6363
6364 if (!IsDerivedFrom(Loc, LHSType, Class)) {
6365 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6366 << (int)isIndirect << LHS.get()->getType();
6367 return QualType();
6368 }
6369
6370 CXXCastPath BasePath;
6372 LHSType, Class, Loc,
6373 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6374 &BasePath))
6375 return QualType();
6376
6377 // Cast LHS to type of use.
6378 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6379 if (isIndirect)
6380 UseType = Context.getPointerType(UseType);
6381 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6382 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6383 &BasePath);
6384 }
6385
6386 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6387 // Diagnose use of pointer-to-member type which when used as
6388 // the functional cast in a pointer-to-member expression.
6389 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6390 return QualType();
6391 }
6392
6393 // C++ 5.5p2
6394 // The result is an object or a function of the type specified by the
6395 // second operand.
6396 // The cv qualifiers are the union of those in the pointer and the left side,
6397 // in accordance with 5.5p5 and 5.2.5.
6398 QualType Result = MemPtr->getPointeeType();
6400
6401 // C++0x [expr.mptr.oper]p6:
6402 // In a .* expression whose object expression is an rvalue, the program is
6403 // ill-formed if the second operand is a pointer to member function with
6404 // ref-qualifier &. In a ->* expression or in a .* expression whose object
6405 // expression is an lvalue, the program is ill-formed if the second operand
6406 // is a pointer to member function with ref-qualifier &&.
6407 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6408 switch (Proto->getRefQualifier()) {
6409 case RQ_None:
6410 // Do nothing
6411 break;
6412
6413 case RQ_LValue:
6414 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6415 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6416 // is (exactly) 'const'.
6417 if (Proto->isConst() && !Proto->isVolatile())
6419 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6420 : diag::ext_pointer_to_const_ref_member_on_rvalue);
6421 else
6422 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6423 << RHSType << 1 << LHS.get()->getSourceRange();
6424 }
6425 break;
6426
6427 case RQ_RValue:
6428 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6429 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6430 << RHSType << 0 << LHS.get()->getSourceRange();
6431 break;
6432 }
6433 }
6434
6435 // C++ [expr.mptr.oper]p6:
6436 // The result of a .* expression whose second operand is a pointer
6437 // to a data member is of the same value category as its
6438 // first operand. The result of a .* expression whose second
6439 // operand is a pointer to a member function is a prvalue. The
6440 // result of an ->* expression is an lvalue if its second operand
6441 // is a pointer to data member and a prvalue otherwise.
6442 if (Result->isFunctionType()) {
6443 VK = VK_PRValue;
6444 return Context.BoundMemberTy;
6445 } else if (isIndirect) {
6446 VK = VK_LValue;
6447 } else {
6448 VK = LHS.get()->getValueKind();
6449 }
6450
6451 return Result;
6452}
6453
6454/// Try to convert a type to another according to C++11 5.16p3.
6455///
6456/// This is part of the parameter validation for the ? operator. If either
6457/// value operand is a class type, the two operands are attempted to be
6458/// converted to each other. This function does the conversion in one direction.
6459/// It returns true if the program is ill-formed and has already been diagnosed
6460/// as such.
6461static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6462 SourceLocation QuestionLoc,
6463 bool &HaveConversion,
6464 QualType &ToType) {
6465 HaveConversion = false;
6466 ToType = To->getType();
6467
6468 InitializationKind Kind =
6470 // C++11 5.16p3
6471 // The process for determining whether an operand expression E1 of type T1
6472 // can be converted to match an operand expression E2 of type T2 is defined
6473 // as follows:
6474 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6475 // implicitly converted to type "lvalue reference to T2", subject to the
6476 // constraint that in the conversion the reference must bind directly to
6477 // an lvalue.
6478 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6479 // implicitly converted to the type "rvalue reference to R2", subject to
6480 // the constraint that the reference must bind directly.
6481 if (To->isGLValue()) {
6482 QualType T = Self.Context.getReferenceQualifiedType(To);
6484
6485 InitializationSequence InitSeq(Self, Entity, Kind, From);
6486 if (InitSeq.isDirectReferenceBinding()) {
6487 ToType = T;
6488 HaveConversion = true;
6489 return false;
6490 }
6491
6492 if (InitSeq.isAmbiguous())
6493 return InitSeq.Diagnose(Self, Entity, Kind, From);
6494 }
6495
6496 // -- If E2 is an rvalue, or if the conversion above cannot be done:
6497 // -- if E1 and E2 have class type, and the underlying class types are
6498 // the same or one is a base class of the other:
6499 QualType FTy = From->getType();
6500 QualType TTy = To->getType();
6501 const RecordType *FRec = FTy->getAs<RecordType>();
6502 const RecordType *TRec = TTy->getAs<RecordType>();
6503 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6504 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6505 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6506 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6507 // E1 can be converted to match E2 if the class of T2 is the
6508 // same type as, or a base class of, the class of T1, and
6509 // [cv2 > cv1].
6510 if (FRec == TRec || FDerivedFromT) {
6511 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6513 InitializationSequence InitSeq(Self, Entity, Kind, From);
6514 if (InitSeq) {
6515 HaveConversion = true;
6516 return false;
6517 }
6518
6519 if (InitSeq.isAmbiguous())
6520 return InitSeq.Diagnose(Self, Entity, Kind, From);
6521 }
6522 }
6523
6524 return false;
6525 }
6526
6527 // -- Otherwise: E1 can be converted to match E2 if E1 can be
6528 // implicitly converted to the type that expression E2 would have
6529 // if E2 were converted to an rvalue (or the type it has, if E2 is
6530 // an rvalue).
6531 //
6532 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6533 // to the array-to-pointer or function-to-pointer conversions.
6534 TTy = TTy.getNonLValueExprType(Self.Context);
6535
6537 InitializationSequence InitSeq(Self, Entity, Kind, From);
6538 HaveConversion = !InitSeq.Failed();
6539 ToType = TTy;
6540 if (InitSeq.isAmbiguous())
6541 return InitSeq.Diagnose(Self, Entity, Kind, From);
6542
6543 return false;
6544}
6545
6546/// Try to find a common type for two according to C++0x 5.16p5.
6547///
6548/// This is part of the parameter validation for the ? operator. If either
6549/// value operand is a class type, overload resolution is used to find a
6550/// conversion to a common type.
6552 SourceLocation QuestionLoc) {
6553 Expr *Args[2] = { LHS.get(), RHS.get() };
6554 OverloadCandidateSet CandidateSet(QuestionLoc,
6556 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6557 CandidateSet);
6558
6560 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6561 case OR_Success: {
6562 // We found a match. Perform the conversions on the arguments and move on.
6563 ExprResult LHSRes = Self.PerformImplicitConversion(
6564 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6566 if (LHSRes.isInvalid())
6567 break;
6568 LHS = LHSRes;
6569
6570 ExprResult RHSRes = Self.PerformImplicitConversion(
6571 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6573 if (RHSRes.isInvalid())
6574 break;
6575 RHS = RHSRes;
6576 if (Best->Function)
6577 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6578 return false;
6579 }
6580
6582
6583 // Emit a better diagnostic if one of the expressions is a null pointer
6584 // constant and the other is a pointer type. In this case, the user most
6585 // likely forgot to take the address of the other expression.
6586 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6587 return true;
6588
6589 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6590 << LHS.get()->getType() << RHS.get()->getType()
6591 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6592 return true;
6593
6594 case OR_Ambiguous:
6595 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6596 << LHS.get()->getType() << RHS.get()->getType()
6597 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6598 // FIXME: Print the possible common types by printing the return types of
6599 // the viable candidates.
6600 break;
6601
6602 case OR_Deleted:
6603 llvm_unreachable("Conditional operator has only built-in overloads");
6604 }
6605 return true;
6606}
6607
6608/// Perform an "extended" implicit conversion as returned by
6609/// TryClassUnification.
6612 InitializationKind Kind =
6614 Expr *Arg = E.get();
6615 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6616 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6617 if (Result.isInvalid())
6618 return true;
6619
6620 E = Result;
6621 return false;
6622}
6623
6624// Check the condition operand of ?: to see if it is valid for the GCC
6625// extension.
6627 QualType CondTy) {
6628 if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6629 return false;
6630 const QualType EltTy =
6631 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6632 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6633 return EltTy->isIntegralType(Ctx);
6634}
6635
6637 QualType CondTy) {
6638 if (!CondTy->isSveVLSBuiltinType())
6639 return false;
6640 const QualType EltTy =
6641 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6642 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6643 return EltTy->isIntegralType(Ctx);
6644}
6645
6647 ExprResult &RHS,
6648 SourceLocation QuestionLoc) {
6651
6652 QualType CondType = Cond.get()->getType();
6653 const auto *CondVT = CondType->castAs<VectorType>();
6654 QualType CondElementTy = CondVT->getElementType();
6655 unsigned CondElementCount = CondVT->getNumElements();
6656 QualType LHSType = LHS.get()->getType();
6657 const auto *LHSVT = LHSType->getAs<VectorType>();
6658 QualType RHSType = RHS.get()->getType();
6659 const auto *RHSVT = RHSType->getAs<VectorType>();
6660
6661 QualType ResultType;
6662
6663
6664 if (LHSVT && RHSVT) {
6665 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6666 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6667 << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6668 return {};
6669 }
6670
6671 // If both are vector types, they must be the same type.
6672 if (!Context.hasSameType(LHSType, RHSType)) {
6673 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6674 << LHSType << RHSType;
6675 return {};
6676 }
6677 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6678 } else if (LHSVT || RHSVT) {
6679 ResultType = CheckVectorOperands(
6680 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6681 /*AllowBoolConversions*/ false,
6682 /*AllowBoolOperation*/ true,
6683 /*ReportInvalid*/ true);
6684 if (ResultType.isNull())
6685 return {};
6686 } else {
6687 // Both are scalar.
6688 LHSType = LHSType.getUnqualifiedType();
6689 RHSType = RHSType.getUnqualifiedType();
6690 QualType ResultElementTy =
6691 Context.hasSameType(LHSType, RHSType)
6692 ? Context.getCommonSugaredType(LHSType, RHSType)
6693 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6695
6696 if (ResultElementTy->isEnumeralType()) {
6697 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6698 << ResultElementTy;
6699 return {};
6700 }
6701 if (CondType->isExtVectorType())
6702 ResultType =
6703 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6704 else
6705 ResultType = Context.getVectorType(
6706 ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);
6707
6708 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6709 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6710 }
6711
6712 assert(!ResultType.isNull() && ResultType->isVectorType() &&
6713 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6714 "Result should have been a vector type");
6715 auto *ResultVectorTy = ResultType->castAs<VectorType>();
6716 QualType ResultElementTy = ResultVectorTy->getElementType();
6717 unsigned ResultElementCount = ResultVectorTy->getNumElements();
6718
6719 if (ResultElementCount != CondElementCount) {
6720 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6721 << ResultType;
6722 return {};
6723 }
6724
6725 if (Context.getTypeSize(ResultElementTy) !=
6726 Context.getTypeSize(CondElementTy)) {
6727 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6728 << ResultType;
6729 return {};
6730 }
6731
6732 return ResultType;
6733}
6734
6736 ExprResult &LHS,
6737 ExprResult &RHS,
6738 SourceLocation QuestionLoc) {
6741
6742 QualType CondType = Cond.get()->getType();
6743 const auto *CondBT = CondType->castAs<BuiltinType>();
6744 QualType CondElementTy = CondBT->getSveEltType(Context);
6745 llvm::ElementCount CondElementCount =
6747
6748 QualType LHSType = LHS.get()->getType();
6749 const auto *LHSBT =
6750 LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6751 QualType RHSType = RHS.get()->getType();
6752 const auto *RHSBT =
6753 RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6754
6755 QualType ResultType;
6756
6757 if (LHSBT && RHSBT) {
6758 // If both are sizeless vector types, they must be the same type.
6759 if (!Context.hasSameType(LHSType, RHSType)) {
6760 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6761 << LHSType << RHSType;
6762 return QualType();
6763 }
6764 ResultType = LHSType;
6765 } else if (LHSBT || RHSBT) {
6766 ResultType = CheckSizelessVectorOperands(
6767 LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6768 if (ResultType.isNull())
6769 return QualType();
6770 } else {
6771 // Both are scalar so splat
6772 QualType ResultElementTy;
6773 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6774 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6775
6776 if (Context.hasSameType(LHSType, RHSType))
6777 ResultElementTy = LHSType;
6778 else
6779 ResultElementTy =
6780 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6781
6782 if (ResultElementTy->isEnumeralType()) {
6783 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6784 << ResultElementTy;
6785 return QualType();
6786 }
6787
6788 ResultType = Context.getScalableVectorType(
6789 ResultElementTy, CondElementCount.getKnownMinValue());
6790
6791 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6792 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6793 }
6794
6795 assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&
6796 "Result should have been a vector type");
6797 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6798 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6799 llvm::ElementCount ResultElementCount =
6800 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6801
6802 if (ResultElementCount != CondElementCount) {
6803 Diag(QuestionLoc, diag::err_conditional_vector_size)
6804 << CondType << ResultType;
6805 return QualType();
6806 }
6807
6808 if (Context.getTypeSize(ResultElementTy) !=
6809 Context.getTypeSize(CondElementTy)) {
6810 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6811 << CondType << ResultType;
6812 return QualType();
6813 }
6814
6815 return ResultType;
6816}
6817
6819 ExprResult &RHS, ExprValueKind &VK,
6820 ExprObjectKind &OK,
6821 SourceLocation QuestionLoc) {
6822 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6823 // pointers.
6824
6825 // Assume r-value.
6826 VK = VK_PRValue;
6827 OK = OK_Ordinary;
6828 bool IsVectorConditional =
6830
6831 bool IsSizelessVectorConditional =
6833 Cond.get()->getType());
6834
6835 // C++11 [expr.cond]p1
6836 // The first expression is contextually converted to bool.
6837 if (!Cond.get()->isTypeDependent()) {
6838 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6840 : CheckCXXBooleanCondition(Cond.get());
6841 if (CondRes.isInvalid())
6842 return QualType();
6843 Cond = CondRes;
6844 } else {
6845 // To implement C++, the first expression typically doesn't alter the result
6846 // type of the conditional, however the GCC compatible vector extension
6847 // changes the result type to be that of the conditional. Since we cannot
6848 // know if this is a vector extension here, delay the conversion of the
6849 // LHS/RHS below until later.
6850 return Context.DependentTy;
6851 }
6852
6853
6854 // Either of the arguments dependent?
6855 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6856 return Context.DependentTy;
6857
6858 // C++11 [expr.cond]p2
6859 // If either the second or the third operand has type (cv) void, ...
6860 QualType LTy = LHS.get()->getType();
6861 QualType RTy = RHS.get()->getType();
6862 bool LVoid = LTy->isVoidType();
6863 bool RVoid = RTy->isVoidType();
6864 if (LVoid || RVoid) {
6865 // ... one of the following shall hold:
6866 // -- The second or the third operand (but not both) is a (possibly
6867 // parenthesized) throw-expression; the result is of the type
6868 // and value category of the other.
6869 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6870 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6871
6872 // Void expressions aren't legal in the vector-conditional expressions.
6873 if (IsVectorConditional) {
6874 SourceRange DiagLoc =
6875 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6876 bool IsThrow = LVoid ? LThrow : RThrow;
6877 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6878 << DiagLoc << IsThrow;
6879 return QualType();
6880 }
6881
6882 if (LThrow != RThrow) {
6883 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6884 VK = NonThrow->getValueKind();
6885 // DR (no number yet): the result is a bit-field if the
6886 // non-throw-expression operand is a bit-field.
6887 OK = NonThrow->getObjectKind();
6888 return NonThrow->getType();
6889 }
6890
6891 // -- Both the second and third operands have type void; the result is of
6892 // type void and is a prvalue.
6893 if (LVoid && RVoid)
6894 return Context.getCommonSugaredType(LTy, RTy);
6895
6896 // Neither holds, error.
6897 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6898 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6899 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6900 return QualType();
6901 }
6902
6903 // Neither is void.
6904 if (IsVectorConditional)
6905 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6906
6907 if (IsSizelessVectorConditional)
6908 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6909
6910 // WebAssembly tables are not allowed as conditional LHS or RHS.
6911 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
6912 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
6913 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6914 return QualType();
6915 }
6916
6917 // C++11 [expr.cond]p3
6918 // Otherwise, if the second and third operand have different types, and
6919 // either has (cv) class type [...] an attempt is made to convert each of
6920 // those operands to the type of the other.
6921 if (!Context.hasSameType(LTy, RTy) &&
6922 (LTy->isRecordType() || RTy->isRecordType())) {
6923 // These return true if a single direction is already ambiguous.
6924 QualType L2RType, R2LType;
6925 bool HaveL2R, HaveR2L;
6926 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6927 return QualType();
6928 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6929 return QualType();
6930
6931 // If both can be converted, [...] the program is ill-formed.
6932 if (HaveL2R && HaveR2L) {
6933 Diag(QuestionLoc, diag::err_conditional_ambiguous)
6934 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6935 return QualType();
6936 }
6937
6938 // If exactly one conversion is possible, that conversion is applied to
6939 // the chosen operand and the converted operands are used in place of the
6940 // original operands for the remainder of this section.
6941 if (HaveL2R) {
6942 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6943 return QualType();
6944 LTy = LHS.get()->getType();
6945 } else if (HaveR2L) {
6946 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6947 return QualType();
6948 RTy = RHS.get()->getType();
6949 }
6950 }
6951
6952 // C++11 [expr.cond]p3
6953 // if both are glvalues of the same value category and the same type except
6954 // for cv-qualification, an attempt is made to convert each of those
6955 // operands to the type of the other.
6956 // FIXME:
6957 // Resolving a defect in P0012R1: we extend this to cover all cases where
6958 // one of the operands is reference-compatible with the other, in order
6959 // to support conditionals between functions differing in noexcept. This
6960 // will similarly cover difference in array bounds after P0388R4.
6961 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6962 // that instead?
6963 ExprValueKind LVK = LHS.get()->getValueKind();
6964 ExprValueKind RVK = RHS.get()->getValueKind();
6965 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6966 // DerivedToBase was already handled by the class-specific case above.
6967 // FIXME: Should we allow ObjC conversions here?
6968 const ReferenceConversions AllowedConversions =
6969 ReferenceConversions::Qualification |
6970 ReferenceConversions::NestedQualification |
6971 ReferenceConversions::Function;
6972
6973 ReferenceConversions RefConv;
6974 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6976 !(RefConv & ~AllowedConversions) &&
6977 // [...] subject to the constraint that the reference must bind
6978 // directly [...]
6979 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6980 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6981 RTy = RHS.get()->getType();
6982 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6984 !(RefConv & ~AllowedConversions) &&
6985 !LHS.get()->refersToBitField() &&
6986 !LHS.get()->refersToVectorElement()) {
6987 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6988 LTy = LHS.get()->getType();
6989 }
6990 }
6991
6992 // C++11 [expr.cond]p4
6993 // If the second and third operands are glvalues of the same value
6994 // category and have the same type, the result is of that type and
6995 // value category and it is a bit-field if the second or the third
6996 // operand is a bit-field, or if both are bit-fields.
6997 // We only extend this to bitfields, not to the crazy other kinds of
6998 // l-values.
6999 bool Same = Context.hasSameType(LTy, RTy);
7000 if (Same && LVK == RVK && LVK != VK_PRValue &&
7003 VK = LHS.get()->getValueKind();
7004 if (LHS.get()->getObjectKind() == OK_BitField ||
7005 RHS.get()->getObjectKind() == OK_BitField)
7006 OK = OK_BitField;
7007 return Context.getCommonSugaredType(LTy, RTy);
7008 }
7009
7010 // C++11 [expr.cond]p5
7011 // Otherwise, the result is a prvalue. If the second and third operands
7012 // do not have the same type, and either has (cv) class type, ...
7013 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
7014 // ... overload resolution is used to determine the conversions (if any)
7015 // to be applied to the operands. If the overload resolution fails, the
7016 // program is ill-formed.
7017 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
7018 return QualType();
7019 }
7020
7021 // C++11 [expr.cond]p6
7022 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
7023 // conversions are performed on the second and third operands.
7026 if (LHS.isInvalid() || RHS.isInvalid())
7027 return QualType();
7028 LTy = LHS.get()->getType();
7029 RTy = RHS.get()->getType();
7030
7031 // After those conversions, one of the following shall hold:
7032 // -- The second and third operands have the same type; the result
7033 // is of that type. If the operands have class type, the result
7034 // is a prvalue temporary of the result type, which is
7035 // copy-initialized from either the second operand or the third
7036 // operand depending on the value of the first operand.
7037 if (Context.hasSameType(LTy, RTy)) {
7038 if (LTy->isRecordType()) {
7039 // The operands have class type. Make a temporary copy.
7042 if (LHSCopy.isInvalid())
7043 return QualType();
7044
7047 if (RHSCopy.isInvalid())
7048 return QualType();
7049
7050 LHS = LHSCopy;
7051 RHS = RHSCopy;
7052 }
7053 return Context.getCommonSugaredType(LTy, RTy);
7054 }
7055
7056 // Extension: conditional operator involving vector types.
7057 if (LTy->isVectorType() || RTy->isVectorType())
7058 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
7059 /*AllowBothBool*/ true,
7060 /*AllowBoolConversions*/ false,
7061 /*AllowBoolOperation*/ false,
7062 /*ReportInvalid*/ true);
7063
7064 // -- The second and third operands have arithmetic or enumeration type;
7065 // the usual arithmetic conversions are performed to bring them to a
7066 // common type, and the result is of that type.
7067 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
7068 QualType ResTy =
7069 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7070 if (LHS.isInvalid() || RHS.isInvalid())
7071 return QualType();
7072 if (ResTy.isNull()) {
7073 Diag(QuestionLoc,
7074 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
7075 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7076 return QualType();
7077 }
7078
7079 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7080 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7081
7082 return ResTy;
7083 }
7084
7085 // -- The second and third operands have pointer type, or one has pointer
7086 // type and the other is a null pointer constant, or both are null
7087 // pointer constants, at least one of which is non-integral; pointer
7088 // conversions and qualification conversions are performed to bring them
7089 // to their composite pointer type. The result is of the composite
7090 // pointer type.
7091 // -- The second and third operands have pointer to member type, or one has
7092 // pointer to member type and the other is a null pointer constant;
7093 // pointer to member conversions and qualification conversions are
7094 // performed to bring them to a common type, whose cv-qualification
7095 // shall match the cv-qualification of either the second or the third
7096 // operand. The result is of the common type.
7097 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
7098 if (!Composite.isNull())
7099 return Composite;
7100
7101 // Similarly, attempt to find composite type of two objective-c pointers.
7102 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
7103 if (LHS.isInvalid() || RHS.isInvalid())
7104 return QualType();
7105 if (!Composite.isNull())
7106 return Composite;
7107
7108 // Check if we are using a null with a non-pointer type.
7109 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7110 return QualType();
7111
7112 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7113 << LHS.get()->getType() << RHS.get()->getType()
7114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7115 return QualType();
7116}
7117
7119 Expr *&E1, Expr *&E2,
7120 bool ConvertArgs) {
7121 assert(getLangOpts().CPlusPlus && "This function assumes C++");
7122
7123 // C++1z [expr]p14:
7124 // The composite pointer type of two operands p1 and p2 having types T1
7125 // and T2
7126 QualType T1 = E1->getType(), T2 = E2->getType();
7127
7128 // where at least one is a pointer or pointer to member type or
7129 // std::nullptr_t is:
7130 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
7131 T1->isNullPtrType();
7132 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
7133 T2->isNullPtrType();
7134 if (!T1IsPointerLike && !T2IsPointerLike)
7135 return QualType();
7136
7137 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
7138 // This can't actually happen, following the standard, but we also use this
7139 // to implement the end of [expr.conv], which hits this case.
7140 //
7141 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
7142 if (T1IsPointerLike &&
7144 if (ConvertArgs)
7145 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
7146 ? CK_NullToMemberPointer
7147 : CK_NullToPointer).get();
7148 return T1;
7149 }
7150 if (T2IsPointerLike &&
7152 if (ConvertArgs)
7153 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
7154 ? CK_NullToMemberPointer
7155 : CK_NullToPointer).get();
7156 return T2;
7157 }
7158
7159 // Now both have to be pointers or member pointers.
7160 if (!T1IsPointerLike || !T2IsPointerLike)
7161 return QualType();
7162 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
7163 "nullptr_t should be a null pointer constant");
7164
7165 struct Step {
7166 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
7167 // Qualifiers to apply under the step kind.
7168 Qualifiers Quals;
7169 /// The class for a pointer-to-member; a constant array type with a bound
7170 /// (if any) for an array.
7171 const Type *ClassOrBound;
7172
7173 Step(Kind K, const Type *ClassOrBound = nullptr)
7174 : K(K), ClassOrBound(ClassOrBound) {}
7175 QualType rebuild(ASTContext &Ctx, QualType T) const {
7176 T = Ctx.getQualifiedType(T, Quals);
7177 switch (K) {
7178 case Pointer:
7179 return Ctx.getPointerType(T);
7180 case MemberPointer:
7181 return Ctx.getMemberPointerType(T, ClassOrBound);
7182 case ObjCPointer:
7183 return Ctx.getObjCObjectPointerType(T);
7184 case Array:
7185 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
7186 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
7187 ArraySizeModifier::Normal, 0);
7188 else
7189 return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);
7190 }
7191 llvm_unreachable("unknown step kind");
7192 }
7193 };
7194
7196
7197 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7198 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7199 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
7200 // respectively;
7201 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
7202 // to member of C2 of type cv2 U2" for some non-function type U, where
7203 // C1 is reference-related to C2 or C2 is reference-related to C1, the
7204 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
7205 // respectively;
7206 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
7207 // T2;
7208 //
7209 // Dismantle T1 and T2 to simultaneously determine whether they are similar
7210 // and to prepare to form the cv-combined type if so.
7211 QualType Composite1 = T1;
7212 QualType Composite2 = T2;
7213 unsigned NeedConstBefore = 0;
7214 while (true) {
7215 assert(!Composite1.isNull() && !Composite2.isNull());
7216
7217 Qualifiers Q1, Q2;
7218 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
7219 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
7220
7221 // Top-level qualifiers are ignored. Merge at all lower levels.
7222 if (!Steps.empty()) {
7223 // Find the qualifier union: (approximately) the unique minimal set of
7224 // qualifiers that is compatible with both types.
7226 Q2.getCVRUQualifiers());
7227
7228 // Under one level of pointer or pointer-to-member, we can change to an
7229 // unambiguous compatible address space.
7230 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
7231 Quals.setAddressSpace(Q1.getAddressSpace());
7232 } else if (Steps.size() == 1) {
7233 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
7234 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
7235 if (MaybeQ1 == MaybeQ2) {
7236 // Exception for ptr size address spaces. Should be able to choose
7237 // either address space during comparison.
7240 MaybeQ1 = true;
7241 else
7242 return QualType(); // No unique best address space.
7243 }
7244 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
7245 : Q2.getAddressSpace());
7246 } else {
7247 return QualType();
7248 }
7249
7250 // FIXME: In C, we merge __strong and none to __strong at the top level.
7251 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
7252 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
7253 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7254 assert(Steps.size() == 1);
7255 else
7256 return QualType();
7257
7258 // Mismatched lifetime qualifiers never compatibly include each other.
7259 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
7260 Quals.setObjCLifetime(Q1.getObjCLifetime());
7261 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7262 assert(Steps.size() == 1);
7263 else
7264 return QualType();
7265
7266 Steps.back().Quals = Quals;
7267 if (Q1 != Quals || Q2 != Quals)
7268 NeedConstBefore = Steps.size() - 1;
7269 }
7270
7271 // FIXME: Can we unify the following with UnwrapSimilarTypes?
7272
7273 const ArrayType *Arr1, *Arr2;
7274 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
7275 (Arr2 = Context.getAsArrayType(Composite2))) {
7276 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
7277 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
7278 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
7279 Composite1 = Arr1->getElementType();
7280 Composite2 = Arr2->getElementType();
7281 Steps.emplace_back(Step::Array, CAT1);
7282 continue;
7283 }
7284 bool IAT1 = isa<IncompleteArrayType>(Arr1);
7285 bool IAT2 = isa<IncompleteArrayType>(Arr2);
7286 if ((IAT1 && IAT2) ||
7287 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
7288 ((bool)CAT1 != (bool)CAT2) &&
7289 (Steps.empty() || Steps.back().K != Step::Array))) {
7290 // In C++20 onwards, we can unify an array of N T with an array of
7291 // a different or unknown bound. But we can't form an array whose
7292 // element type is an array of unknown bound by doing so.
7293 Composite1 = Arr1->getElementType();
7294 Composite2 = Arr2->getElementType();
7295 Steps.emplace_back(Step::Array);
7296 if (CAT1 || CAT2)
7297 NeedConstBefore = Steps.size();
7298 continue;
7299 }
7300 }
7301
7302 const PointerType *Ptr1, *Ptr2;
7303 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
7304 (Ptr2 = Composite2->getAs<PointerType>())) {
7305 Composite1 = Ptr1->getPointeeType();
7306 Composite2 = Ptr2->getPointeeType();
7307 Steps.emplace_back(Step::Pointer);
7308 continue;
7309 }
7310
7311 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
7312 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
7313 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
7314 Composite1 = ObjPtr1->getPointeeType();
7315 Composite2 = ObjPtr2->getPointeeType();
7316 Steps.emplace_back(Step::ObjCPointer);
7317 continue;
7318 }
7319
7320 const MemberPointerType *MemPtr1, *MemPtr2;
7321 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
7322 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
7323 Composite1 = MemPtr1->getPointeeType();
7324 Composite2 = MemPtr2->getPointeeType();
7325
7326 // At the top level, we can perform a base-to-derived pointer-to-member
7327 // conversion:
7328 //
7329 // - [...] where C1 is reference-related to C2 or C2 is
7330 // reference-related to C1
7331 //
7332 // (Note that the only kinds of reference-relatedness in scope here are
7333 // "same type or derived from".) At any other level, the class must
7334 // exactly match.
7335 const Type *Class = nullptr;
7336 QualType Cls1(MemPtr1->getClass(), 0);
7337 QualType Cls2(MemPtr2->getClass(), 0);
7338 if (Context.hasSameType(Cls1, Cls2))
7339 Class = MemPtr1->getClass();
7340 else if (Steps.empty())
7341 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7342 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7343 if (!Class)
7344 return QualType();
7345
7346 Steps.emplace_back(Step::MemberPointer, Class);
7347 continue;
7348 }
7349
7350 // Special case: at the top level, we can decompose an Objective-C pointer
7351 // and a 'cv void *'. Unify the qualifiers.
7352 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7353 Composite2->isObjCObjectPointerType()) ||
7354 (Composite1->isObjCObjectPointerType() &&
7355 Composite2->isVoidPointerType()))) {
7356 Composite1 = Composite1->getPointeeType();
7357 Composite2 = Composite2->getPointeeType();
7358 Steps.emplace_back(Step::Pointer);
7359 continue;
7360 }
7361
7362 // FIXME: block pointer types?
7363
7364 // Cannot unwrap any more types.
7365 break;
7366 }
7367
7368 // - if T1 or T2 is "pointer to noexcept function" and the other type is
7369 // "pointer to function", where the function types are otherwise the same,
7370 // "pointer to function";
7371 // - if T1 or T2 is "pointer to member of C1 of type function", the other
7372 // type is "pointer to member of C2 of type noexcept function", and C1
7373 // is reference-related to C2 or C2 is reference-related to C1, where
7374 // the function types are otherwise the same, "pointer to member of C2 of
7375 // type function" or "pointer to member of C1 of type function",
7376 // respectively;
7377 //
7378 // We also support 'noreturn' here, so as a Clang extension we generalize the
7379 // above to:
7380 //
7381 // - [Clang] If T1 and T2 are both of type "pointer to function" or
7382 // "pointer to member function" and the pointee types can be unified
7383 // by a function pointer conversion, that conversion is applied
7384 // before checking the following rules.
7385 //
7386 // We've already unwrapped down to the function types, and we want to merge
7387 // rather than just convert, so do this ourselves rather than calling
7388 // IsFunctionConversion.
7389 //
7390 // FIXME: In order to match the standard wording as closely as possible, we
7391 // currently only do this under a single level of pointers. Ideally, we would
7392 // allow this in general, and set NeedConstBefore to the relevant depth on
7393 // the side(s) where we changed anything. If we permit that, we should also
7394 // consider this conversion when determining type similarity and model it as
7395 // a qualification conversion.
7396 if (Steps.size() == 1) {
7397 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7398 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7399 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7400 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7401
7402 // The result is noreturn if both operands are.
7403 bool Noreturn =
7404 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7405 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7406 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7407
7408 // The result is nothrow if both operands are.
7409 SmallVector<QualType, 8> ExceptionTypeStorage;
7411 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7413
7414 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7415 FPT1->getParamTypes(), EPI1);
7416 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7417 FPT2->getParamTypes(), EPI2);
7418 }
7419 }
7420 }
7421
7422 // There are some more conversions we can perform under exactly one pointer.
7423 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7424 !Context.hasSameType(Composite1, Composite2)) {
7425 // - if T1 or T2 is "pointer to cv1 void" and the other type is
7426 // "pointer to cv2 T", where T is an object type or void,
7427 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7428 if (Composite1->isVoidType() && Composite2->isObjectType())
7429 Composite2 = Composite1;
7430 else if (Composite2->isVoidType() && Composite1->isObjectType())
7431 Composite1 = Composite2;
7432 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7433 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7434 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7435 // T1, respectively;
7436 //
7437 // The "similar type" handling covers all of this except for the "T1 is a
7438 // base class of T2" case in the definition of reference-related.
7439 else if (IsDerivedFrom(Loc, Composite1, Composite2))
7440 Composite1 = Composite2;
7441 else if (IsDerivedFrom(Loc, Composite2, Composite1))
7442 Composite2 = Composite1;
7443 }
7444
7445 // At this point, either the inner types are the same or we have failed to
7446 // find a composite pointer type.
7447 if (!Context.hasSameType(Composite1, Composite2))
7448 return QualType();
7449
7450 // Per C++ [conv.qual]p3, add 'const' to every level before the last
7451 // differing qualifier.
7452 for (unsigned I = 0; I != NeedConstBefore; ++I)
7453 Steps[I].Quals.addConst();
7454
7455 // Rebuild the composite type.
7456 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7457 for (auto &S : llvm::reverse(Steps))
7458 Composite = S.rebuild(Context, Composite);
7459
7460 if (ConvertArgs) {
7461 // Convert the expressions to the composite pointer type.
7462 InitializedEntity Entity =
7464 InitializationKind Kind =
7466
7467 InitializationSequence E1ToC(*this, Entity, Kind, E1);
7468 if (!E1ToC)
7469 return QualType();
7470
7471 InitializationSequence E2ToC(*this, Entity, Kind, E2);
7472 if (!E2ToC)
7473 return QualType();
7474
7475 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7476 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7477 if (E1Result.isInvalid())
7478 return QualType();
7479 E1 = E1Result.get();
7480
7481 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7482 if (E2Result.isInvalid())
7483 return QualType();
7484 E2 = E2Result.get();
7485 }
7486
7487 return Composite;
7488}
7489
7491 if (!E)
7492 return ExprError();
7493
7494 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7495
7496 // If the result is a glvalue, we shouldn't bind it.
7497 if (E->isGLValue())
7498 return E;
7499
7500 // In ARC, calls that return a retainable type can return retained,
7501 // in which case we have to insert a consuming cast.
7502 if (getLangOpts().ObjCAutoRefCount &&
7504
7505 bool ReturnsRetained;
7506
7507 // For actual calls, we compute this by examining the type of the
7508 // called value.
7509 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7510 Expr *Callee = Call->getCallee()->IgnoreParens();
7511 QualType T = Callee->getType();
7512
7513 if (T == Context.BoundMemberTy) {
7514 // Handle pointer-to-members.
7515 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7516 T = BinOp->getRHS()->getType();
7517 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7518 T = Mem->getMemberDecl()->getType();
7519 }
7520
7521 if (const PointerType *Ptr = T->getAs<PointerType>())
7522 T = Ptr->getPointeeType();
7523 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7524 T = Ptr->getPointeeType();
7525 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7526 T = MemPtr->getPointeeType();
7527
7528 auto *FTy = T->castAs<FunctionType>();
7529 ReturnsRetained = FTy->getExtInfo().getProducesResult();
7530
7531 // ActOnStmtExpr arranges things so that StmtExprs of retainable
7532 // type always produce a +1 object.
7533 } else if (isa<StmtExpr>(E)) {
7534 ReturnsRetained = true;
7535
7536 // We hit this case with the lambda conversion-to-block optimization;
7537 // we don't want any extra casts here.
7538 } else if (isa<CastExpr>(E) &&
7539 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7540 return E;
7541
7542 // For message sends and property references, we try to find an
7543 // actual method. FIXME: we should infer retention by selector in
7544 // cases where we don't have an actual method.
7545 } else {
7546 ObjCMethodDecl *D = nullptr;
7547 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7548 D = Send->getMethodDecl();
7549 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7550 D = BoxedExpr->getBoxingMethod();
7551 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7552 // Don't do reclaims if we're using the zero-element array
7553 // constant.
7554 if (ArrayLit->getNumElements() == 0 &&
7556 return E;
7557
7558 D = ArrayLit->getArrayWithObjectsMethod();
7559 } else if (ObjCDictionaryLiteral *DictLit
7560 = dyn_cast<ObjCDictionaryLiteral>(E)) {
7561 // Don't do reclaims if we're using the zero-element dictionary
7562 // constant.
7563 if (DictLit->getNumElements() == 0 &&
7565 return E;
7566
7567 D = DictLit->getDictWithObjectsMethod();
7568 }
7569
7570 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7571
7572 // Don't do reclaims on performSelector calls; despite their
7573 // return type, the invoked method doesn't necessarily actually
7574 // return an object.
7575 if (!ReturnsRetained &&
7576 D && D->getMethodFamily() == OMF_performSelector)
7577 return E;
7578 }
7579
7580 // Don't reclaim an object of Class type.
7581 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7582 return E;
7583
7585
7586 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7587 : CK_ARCReclaimReturnedObject);
7588 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7590 }
7591
7594
7595 if (!getLangOpts().CPlusPlus)
7596 return E;
7597
7598 // Search for the base element type (cf. ASTContext::getBaseElementType) with
7599 // a fast path for the common case that the type is directly a RecordType.
7601 const RecordType *RT = nullptr;
7602 while (!RT) {
7603 switch (T->getTypeClass()) {
7604 case Type::Record:
7605 RT = cast<RecordType>(T);
7606 break;
7607 case Type::ConstantArray:
7608 case Type::IncompleteArray:
7609 case Type::VariableArray:
7610 case Type::DependentSizedArray:
7611 T = cast<ArrayType>(T)->getElementType().getTypePtr();
7612 break;
7613 default:
7614 return E;
7615 }
7616 }
7617
7618 // That should be enough to guarantee that this type is complete, if we're
7619 // not processing a decltype expression.
7620 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7621 if (RD->isInvalidDecl() || RD->isDependentContext())
7622 return E;
7623
7624 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7626 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7627
7628 if (Destructor) {
7631 PDiag(diag::err_access_dtor_temp)
7632 << E->getType());
7634 return ExprError();
7635
7636 // If destructor is trivial, we can avoid the extra copy.
7637 if (Destructor->isTrivial())
7638 return E;
7639
7640 // We need a cleanup, but we don't need to remember the temporary.
7642 }
7643
7646
7647 if (IsDecltype)
7648 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7649
7650 return Bind;
7651}
7652
7655 if (SubExpr.isInvalid())
7656 return ExprError();
7657
7658 return MaybeCreateExprWithCleanups(SubExpr.get());
7659}
7660
7662 assert(SubExpr && "subexpression can't be null!");
7663
7665
7666 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7667 assert(ExprCleanupObjects.size() >= FirstCleanup);
7668 assert(Cleanup.exprNeedsCleanups() ||
7669 ExprCleanupObjects.size() == FirstCleanup);
7671 return SubExpr;
7672
7673 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7674 ExprCleanupObjects.size() - FirstCleanup);
7675
7677 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7679
7680 return E;
7681}
7682
7684 assert(SubStmt && "sub-statement can't be null!");
7685
7687
7689 return SubStmt;
7690
7691 // FIXME: In order to attach the temporaries, wrap the statement into
7692 // a StmtExpr; currently this is only used for asm statements.
7693 // This is hacky, either create a new CXXStmtWithTemporaries statement or
7694 // a new AsmStmtWithTemporaries.
7695 CompoundStmt *CompStmt =
7698 Expr *E = new (Context)
7700 /*FIXME TemplateDepth=*/0);
7702}
7703
7705 assert(ExprEvalContexts.back().ExprContext ==
7707 "not in a decltype expression");
7708
7710 if (Result.isInvalid())
7711 return ExprError();
7712 E = Result.get();
7713
7714 // C++11 [expr.call]p11:
7715 // If a function call is a prvalue of object type,
7716 // -- if the function call is either
7717 // -- the operand of a decltype-specifier, or
7718 // -- the right operand of a comma operator that is the operand of a
7719 // decltype-specifier,
7720 // a temporary object is not introduced for the prvalue.
7721
7722 // Recursively rebuild ParenExprs and comma expressions to strip out the
7723 // outermost CXXBindTemporaryExpr, if any.
7724 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7725 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7726 if (SubExpr.isInvalid())
7727 return ExprError();
7728 if (SubExpr.get() == PE->getSubExpr())
7729 return E;
7730 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7731 }
7732 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7733 if (BO->getOpcode() == BO_Comma) {
7734 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7735 if (RHS.isInvalid())
7736 return ExprError();
7737 if (RHS.get() == BO->getRHS())
7738 return E;
7739 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7740 BO->getType(), BO->getValueKind(),
7741 BO->getObjectKind(), BO->getOperatorLoc(),
7742 BO->getFPFeatures());
7743 }
7744 }
7745
7746 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7747 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7748 : nullptr;
7749 if (TopCall)
7750 E = TopCall;
7751 else
7752 TopBind = nullptr;
7753
7754 // Disable the special decltype handling now.
7755 ExprEvalContexts.back().ExprContext =
7757
7759 if (Result.isInvalid())
7760 return ExprError();
7761 E = Result.get();
7762
7763 // In MS mode, don't perform any extra checking of call return types within a
7764 // decltype expression.
7765 if (getLangOpts().MSVCCompat)
7766 return E;
7767
7768 // Perform the semantic checks we delayed until this point.
7769 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7770 I != N; ++I) {
7771 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7772 if (Call == TopCall)
7773 continue;
7774
7775 if (CheckCallReturnType(Call->getCallReturnType(Context),
7776 Call->getBeginLoc(), Call, Call->getDirectCallee()))
7777 return ExprError();
7778 }
7779
7780 // Now all relevant types are complete, check the destructors are accessible
7781 // and non-deleted, and annotate them on the temporaries.
7782 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7783 I != N; ++I) {
7785 ExprEvalContexts.back().DelayedDecltypeBinds[I];
7786 if (Bind == TopBind)
7787 continue;
7788
7789 CXXTemporary *Temp = Bind->getTemporary();
7790
7791 CXXRecordDecl *RD =
7792 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7795
7796 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7797 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7798 PDiag(diag::err_access_dtor_temp)
7799 << Bind->getType());
7800 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7801 return ExprError();
7802
7803 // We need a cleanup, but we don't need to remember the temporary.
7805 }
7806
7807 // Possibly strip off the top CXXBindTemporaryExpr.
7808 return E;
7809}
7810
7811/// Note a set of 'operator->' functions that were used for a member access.
7813 ArrayRef<FunctionDecl *> OperatorArrows) {
7814 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7815 // FIXME: Make this configurable?
7816 unsigned Limit = 9;
7817 if (OperatorArrows.size() > Limit) {
7818 // Produce Limit-1 normal notes and one 'skipping' note.
7819 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7820 SkipCount = OperatorArrows.size() - (Limit - 1);
7821 }
7822
7823 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7824 if (I == SkipStart) {
7825 S.Diag(OperatorArrows[I]->getLocation(),
7826 diag::note_operator_arrows_suppressed)
7827 << SkipCount;
7828 I += SkipCount;
7829 } else {
7830 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7831 << OperatorArrows[I]->getCallResultType();
7832 ++I;
7833 }
7834 }
7835}
7836
7838 SourceLocation OpLoc,
7839 tok::TokenKind OpKind,
7840 ParsedType &ObjectType,
7841 bool &MayBePseudoDestructor) {
7842 // Since this might be a postfix expression, get rid of ParenListExprs.
7844 if (Result.isInvalid()) return ExprError();
7845 Base = Result.get();
7846
7848 if (Result.isInvalid()) return ExprError();
7849 Base = Result.get();
7850
7851 QualType BaseType = Base->getType();
7852 MayBePseudoDestructor = false;
7853 if (BaseType->isDependentType()) {
7854 // If we have a pointer to a dependent type and are using the -> operator,
7855 // the object type is the type that the pointer points to. We might still
7856 // have enough information about that type to do something useful.
7857 if (OpKind == tok::arrow)
7858 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7859 BaseType = Ptr->getPointeeType();
7860
7861 ObjectType = ParsedType::make(BaseType);
7862 MayBePseudoDestructor = true;
7863 return Base;
7864 }
7865
7866 // C++ [over.match.oper]p8:
7867 // [...] When operator->returns, the operator-> is applied to the value
7868 // returned, with the original second operand.
7869 if (OpKind == tok::arrow) {
7870 QualType StartingType = BaseType;
7871 bool NoArrowOperatorFound = false;
7872 bool FirstIteration = true;
7873 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7874 // The set of types we've considered so far.
7876 SmallVector<FunctionDecl*, 8> OperatorArrows;
7877 CTypes.insert(Context.getCanonicalType(BaseType));
7878
7879 while (BaseType->isRecordType()) {
7880 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7881 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7882 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7883 noteOperatorArrows(*this, OperatorArrows);
7884 Diag(OpLoc, diag::note_operator_arrow_depth)
7885 << getLangOpts().ArrowDepth;
7886 return ExprError();
7887 }
7888
7890 S, Base, OpLoc,
7891 // When in a template specialization and on the first loop iteration,
7892 // potentially give the default diagnostic (with the fixit in a
7893 // separate note) instead of having the error reported back to here
7894 // and giving a diagnostic with a fixit attached to the error itself.
7895 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7896 ? nullptr
7897 : &NoArrowOperatorFound);
7898 if (Result.isInvalid()) {
7899 if (NoArrowOperatorFound) {
7900 if (FirstIteration) {
7901 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7902 << BaseType << 1 << Base->getSourceRange()
7903 << FixItHint::CreateReplacement(OpLoc, ".");
7904 OpKind = tok::period;
7905 break;
7906 }
7907 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7908 << BaseType << Base->getSourceRange();
7909 CallExpr *CE = dyn_cast<CallExpr>(Base);
7910 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7911 Diag(CD->getBeginLoc(),
7912 diag::note_member_reference_arrow_from_operator_arrow);
7913 }
7914 }
7915 return ExprError();
7916 }
7917 Base = Result.get();
7918 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7919 OperatorArrows.push_back(OpCall->getDirectCallee());
7920 BaseType = Base->getType();
7921 CanQualType CBaseType = Context.getCanonicalType(BaseType);
7922 if (!CTypes.insert(CBaseType).second) {
7923 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7924 noteOperatorArrows(*this, OperatorArrows);
7925 return ExprError();
7926 }
7927 FirstIteration = false;
7928 }
7929
7930 if (OpKind == tok::arrow) {
7931 if (BaseType->isPointerType())
7932 BaseType = BaseType->getPointeeType();
7933 else if (auto *AT = Context.getAsArrayType(BaseType))
7934 BaseType = AT->getElementType();
7935 }
7936 }
7937
7938 // Objective-C properties allow "." access on Objective-C pointer types,
7939 // so adjust the base type to the object type itself.
7940 if (BaseType->isObjCObjectPointerType())
7941 BaseType = BaseType->getPointeeType();
7942
7943 // C++ [basic.lookup.classref]p2:
7944 // [...] If the type of the object expression is of pointer to scalar
7945 // type, the unqualified-id is looked up in the context of the complete
7946 // postfix-expression.
7947 //
7948 // This also indicates that we could be parsing a pseudo-destructor-name.
7949 // Note that Objective-C class and object types can be pseudo-destructor
7950 // expressions or normal member (ivar or property) access expressions, and
7951 // it's legal for the type to be incomplete if this is a pseudo-destructor
7952 // call. We'll do more incomplete-type checks later in the lookup process,
7953 // so just skip this check for ObjC types.
7954 if (!BaseType->isRecordType()) {
7955 ObjectType = ParsedType::make(BaseType);
7956 MayBePseudoDestructor = true;
7957 return Base;
7958 }
7959
7960 // The object type must be complete (or dependent), or
7961 // C++11 [expr.prim.general]p3:
7962 // Unlike the object expression in other contexts, *this is not required to
7963 // be of complete type for purposes of class member access (5.2.5) outside
7964 // the member function body.
7965 if (!BaseType->isDependentType() &&
7967 RequireCompleteType(OpLoc, BaseType,
7968 diag::err_incomplete_member_access)) {
7969 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7970 }
7971
7972 // C++ [basic.lookup.classref]p2:
7973 // If the id-expression in a class member access (5.2.5) is an
7974 // unqualified-id, and the type of the object expression is of a class
7975 // type C (or of pointer to a class type C), the unqualified-id is looked
7976 // up in the scope of class C. [...]
7977 ObjectType = ParsedType::make(BaseType);
7978 return Base;
7979}
7980
7981static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7982 tok::TokenKind &OpKind, SourceLocation OpLoc) {
7983 if (Base->hasPlaceholderType()) {
7985 if (result.isInvalid()) return true;
7986 Base = result.get();
7987 }
7988 ObjectType = Base->getType();
7989
7990 // C++ [expr.pseudo]p2:
7991 // The left-hand side of the dot operator shall be of scalar type. The
7992 // left-hand side of the arrow operator shall be of pointer to scalar type.
7993 // This scalar type is the object type.
7994 // Note that this is rather different from the normal handling for the
7995 // arrow operator.
7996 if (OpKind == tok::arrow) {
7997 // The operator requires a prvalue, so perform lvalue conversions.
7998 // Only do this if we might plausibly end with a pointer, as otherwise
7999 // this was likely to be intended to be a '.'.
8000 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
8001 ObjectType->isFunctionType()) {
8003 if (BaseResult.isInvalid())
8004 return true;
8005 Base = BaseResult.get();
8006 ObjectType = Base->getType();
8007 }
8008
8009 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
8010 ObjectType = Ptr->getPointeeType();
8011 } else if (!Base->isTypeDependent()) {
8012 // The user wrote "p->" when they probably meant "p."; fix it.
8013 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8014 << ObjectType << true
8015 << FixItHint::CreateReplacement(OpLoc, ".");
8016 if (S.isSFINAEContext())
8017 return true;
8018
8019 OpKind = tok::period;
8020 }
8021 }
8022
8023 return false;
8024}
8025
8026/// Check if it's ok to try and recover dot pseudo destructor calls on
8027/// pointer objects.
8028static bool
8030 QualType DestructedType) {
8031 // If this is a record type, check if its destructor is callable.
8032 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
8033 if (RD->hasDefinition())
8035 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
8036 return false;
8037 }
8038
8039 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
8040 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
8041 DestructedType->isVectorType();
8042}
8043
8045 SourceLocation OpLoc,
8046 tok::TokenKind OpKind,
8047 const CXXScopeSpec &SS,
8048 TypeSourceInfo *ScopeTypeInfo,
8049 SourceLocation CCLoc,
8050 SourceLocation TildeLoc,
8051 PseudoDestructorTypeStorage Destructed) {
8052 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
8053
8054 QualType ObjectType;
8055 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8056 return ExprError();
8057
8058 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
8059 !ObjectType->isVectorType()) {
8060 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
8061 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
8062 else {
8063 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
8064 << ObjectType << Base->getSourceRange();
8065 return ExprError();
8066 }
8067 }
8068
8069 // C++ [expr.pseudo]p2:
8070 // [...] The cv-unqualified versions of the object type and of the type
8071 // designated by the pseudo-destructor-name shall be the same type.
8072 if (DestructedTypeInfo) {
8073 QualType DestructedType = DestructedTypeInfo->getType();
8074 SourceLocation DestructedTypeStart =
8075 DestructedTypeInfo->getTypeLoc().getBeginLoc();
8076 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
8077 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
8078 // Detect dot pseudo destructor calls on pointer objects, e.g.:
8079 // Foo *foo;
8080 // foo.~Foo();
8081 if (OpKind == tok::period && ObjectType->isPointerType() &&
8082 Context.hasSameUnqualifiedType(DestructedType,
8083 ObjectType->getPointeeType())) {
8084 auto Diagnostic =
8085 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8086 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
8087
8088 // Issue a fixit only when the destructor is valid.
8090 *this, DestructedType))
8092
8093 // Recover by setting the object type to the destructed type and the
8094 // operator to '->'.
8095 ObjectType = DestructedType;
8096 OpKind = tok::arrow;
8097 } else {
8098 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
8099 << ObjectType << DestructedType << Base->getSourceRange()
8100 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8101
8102 // Recover by setting the destructed type to the object type.
8103 DestructedType = ObjectType;
8104 DestructedTypeInfo =
8105 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
8106 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8107 }
8108 } else if (DestructedType.getObjCLifetime() !=
8109 ObjectType.getObjCLifetime()) {
8110
8111 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
8112 // Okay: just pretend that the user provided the correctly-qualified
8113 // type.
8114 } else {
8115 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
8116 << ObjectType << DestructedType << Base->getSourceRange()
8117 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8118 }
8119
8120 // Recover by setting the destructed type to the object type.
8121 DestructedType = ObjectType;
8122 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
8123 DestructedTypeStart);
8124 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8125 }
8126 }
8127 }
8128
8129 // C++ [expr.pseudo]p2:
8130 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
8131 // form
8132 //
8133 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
8134 //
8135 // shall designate the same scalar type.
8136 if (ScopeTypeInfo) {
8137 QualType ScopeType = ScopeTypeInfo->getType();
8138 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
8139 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
8140
8141 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
8142 diag::err_pseudo_dtor_type_mismatch)
8143 << ObjectType << ScopeType << Base->getSourceRange()
8144 << ScopeTypeInfo->getTypeLoc().getSourceRange();
8145
8146 ScopeType = QualType();
8147 ScopeTypeInfo = nullptr;
8148 }
8149 }
8150
8151 Expr *Result
8153 OpKind == tok::arrow, OpLoc,
8155 ScopeTypeInfo,
8156 CCLoc,
8157 TildeLoc,
8158 Destructed);
8159
8160 return Result;
8161}
8162
8164 SourceLocation OpLoc,
8165 tok::TokenKind OpKind,
8166 CXXScopeSpec &SS,
8167 UnqualifiedId &FirstTypeName,
8168 SourceLocation CCLoc,
8169 SourceLocation TildeLoc,
8170 UnqualifiedId &SecondTypeName) {
8171 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8172 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8173 "Invalid first type name in pseudo-destructor");
8174 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8175 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8176 "Invalid second type name in pseudo-destructor");
8177
8178 QualType ObjectType;
8179 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8180 return ExprError();
8181
8182 // Compute the object type that we should use for name lookup purposes. Only
8183 // record types and dependent types matter.
8184 ParsedType ObjectTypePtrForLookup;
8185 if (!SS.isSet()) {
8186 if (ObjectType->isRecordType())
8187 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
8188 else if (ObjectType->isDependentType())
8189 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
8190 }
8191
8192 // Convert the name of the type being destructed (following the ~) into a
8193 // type (with source-location information).
8194 QualType DestructedType;
8195 TypeSourceInfo *DestructedTypeInfo = nullptr;
8196 PseudoDestructorTypeStorage Destructed;
8197 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8198 ParsedType T = getTypeName(*SecondTypeName.Identifier,
8199 SecondTypeName.StartLocation,
8200 S, &SS, true, false, ObjectTypePtrForLookup,
8201 /*IsCtorOrDtorName*/true);
8202 if (!T &&
8203 ((SS.isSet() && !computeDeclContext(SS, false)) ||
8204 (!SS.isSet() && ObjectType->isDependentType()))) {
8205 // The name of the type being destroyed is a dependent name, and we
8206 // couldn't find anything useful in scope. Just store the identifier and
8207 // it's location, and we'll perform (qualified) name lookup again at
8208 // template instantiation time.
8209 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
8210 SecondTypeName.StartLocation);
8211 } else if (!T) {
8212 Diag(SecondTypeName.StartLocation,
8213 diag::err_pseudo_dtor_destructor_non_type)
8214 << SecondTypeName.Identifier << ObjectType;
8215 if (isSFINAEContext())
8216 return ExprError();
8217
8218 // Recover by assuming we had the right type all along.
8219 DestructedType = ObjectType;
8220 } else
8221 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
8222 } else {
8223 // Resolve the template-id to a type.
8224 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
8225 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8226 TemplateId->NumArgs);
8228 SS,
8229 TemplateId->TemplateKWLoc,
8230 TemplateId->Template,
8231 TemplateId->Name,
8232 TemplateId->TemplateNameLoc,
8233 TemplateId->LAngleLoc,
8234 TemplateArgsPtr,
8235 TemplateId->RAngleLoc,
8236 /*IsCtorOrDtorName*/true);
8237 if (T.isInvalid() || !T.get()) {
8238 // Recover by assuming we had the right type all along.
8239 DestructedType = ObjectType;
8240 } else
8241 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
8242 }
8243
8244 // If we've performed some kind of recovery, (re-)build the type source
8245 // information.
8246 if (!DestructedType.isNull()) {
8247 if (!DestructedTypeInfo)
8248 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
8249 SecondTypeName.StartLocation);
8250 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8251 }
8252
8253 // Convert the name of the scope type (the type prior to '::') into a type.
8254 TypeSourceInfo *ScopeTypeInfo = nullptr;
8255 QualType ScopeType;
8256 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8257 FirstTypeName.Identifier) {
8258 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8259 ParsedType T = getTypeName(*FirstTypeName.Identifier,
8260 FirstTypeName.StartLocation,
8261 S, &SS, true, false, ObjectTypePtrForLookup,
8262 /*IsCtorOrDtorName*/true);
8263 if (!T) {
8264 Diag(FirstTypeName.StartLocation,
8265 diag::err_pseudo_dtor_destructor_non_type)
8266 << FirstTypeName.Identifier << ObjectType;
8267
8268 if (isSFINAEContext())
8269 return ExprError();
8270
8271 // Just drop this type. It's unnecessary anyway.
8272 ScopeType = QualType();
8273 } else
8274 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
8275 } else {
8276 // Resolve the template-id to a type.
8277 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
8278 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8279 TemplateId->NumArgs);
8281 SS,
8282 TemplateId->TemplateKWLoc,
8283 TemplateId->Template,
8284 TemplateId->Name,
8285 TemplateId->TemplateNameLoc,
8286 TemplateId->LAngleLoc,
8287 TemplateArgsPtr,
8288 TemplateId->RAngleLoc,
8289 /*IsCtorOrDtorName*/true);
8290 if (T.isInvalid() || !T.get()) {
8291 // Recover by dropping this type.
8292 ScopeType = QualType();
8293 } else
8294 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
8295 }
8296 }
8297
8298 if (!ScopeType.isNull() && !ScopeTypeInfo)
8299 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
8300 FirstTypeName.StartLocation);
8301
8302
8303 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
8304 ScopeTypeInfo, CCLoc, TildeLoc,
8305 Destructed);
8306}
8307
8309 SourceLocation OpLoc,
8310 tok::TokenKind OpKind,
8311 SourceLocation TildeLoc,
8312 const DeclSpec& DS) {
8313 QualType ObjectType;
8314 QualType T;
8315 TypeLocBuilder TLB;
8316 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8317 return ExprError();
8318
8319 switch (DS.getTypeSpecType()) {
8321 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
8322 return true;
8323 }
8325 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
8326 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
8327 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
8328 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
8329 break;
8330 }
8333 DS.getBeginLoc(), DS.getEllipsisLoc());
8335 cast<PackIndexingType>(T.getTypePtr())->getPattern(),
8336 DS.getBeginLoc());
8338 PITL.setEllipsisLoc(DS.getEllipsisLoc());
8339 break;
8340 }
8341 default:
8342 llvm_unreachable("Unsupported type in pseudo destructor");
8343 }
8344 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
8345 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
8346
8347 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
8348 nullptr, SourceLocation(), TildeLoc,
8349 Destructed);
8350}
8351
8353 SourceLocation RParen) {
8354 // If the operand is an unresolved lookup expression, the expression is ill-
8355 // formed per [over.over]p1, because overloaded function names cannot be used
8356 // without arguments except in explicit contexts.
8357 ExprResult R = CheckPlaceholderExpr(Operand);
8358 if (R.isInvalid())
8359 return R;
8360
8362 if (R.isInvalid())
8363 return ExprError();
8364
8365 Operand = R.get();
8366
8367 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8368 Operand->HasSideEffects(Context, false)) {
8369 // The expression operand for noexcept is in an unevaluated expression
8370 // context, so side effects could result in unintended consequences.
8371 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8372 }
8373
8374 CanThrowResult CanThrow = canThrow(Operand);
8375 return new (Context)
8376 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8377}
8378
8380 Expr *Operand, SourceLocation RParen) {
8381 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8382}
8383
8385 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8386 DeclRefExpr *LHS = nullptr;
8387 bool IsCompoundAssign = false;
8388 bool isIncrementDecrementUnaryOp = false;
8389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8390 if (BO->getLHS()->getType()->isDependentType() ||
8391 BO->getRHS()->getType()->isDependentType()) {
8392 if (BO->getOpcode() != BO_Assign)
8393 return;
8394 } else if (!BO->isAssignmentOp())
8395 return;
8396 else
8397 IsCompoundAssign = BO->isCompoundAssignmentOp();
8398 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8399 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8400 if (COCE->getOperator() != OO_Equal)
8401 return;
8402 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8403 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8404 if (!UO->isIncrementDecrementOp())
8405 return;
8406 isIncrementDecrementUnaryOp = true;
8407 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8408 }
8409 if (!LHS)
8410 return;
8411 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8412 if (!VD)
8413 return;
8414 // Don't decrement RefsMinusAssignments if volatile variable with compound
8415 // assignment (+=, ...) or increment/decrement unary operator to avoid
8416 // potential unused-but-set-variable warning.
8417 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8419 return;
8420 auto iter = RefsMinusAssignments.find(VD);
8421 if (iter == RefsMinusAssignments.end())
8422 return;
8423 iter->getSecond()--;
8424}
8425
8426/// Perform the conversions required for an expression used in a
8427/// context that ignores the result.
8430
8431 if (E->hasPlaceholderType()) {
8433 if (result.isInvalid()) return E;
8434 E = result.get();
8435 }
8436
8437 if (getLangOpts().CPlusPlus) {
8438 // The C++11 standard defines the notion of a discarded-value expression;
8439 // normally, we don't need to do anything to handle it, but if it is a
8440 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8441 // conversion.
8444 if (Res.isInvalid())
8445 return E;
8446 E = Res.get();
8447 } else {
8448 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8449 // it occurs as a discarded-value expression.
8451 }
8452
8453 // C++1z:
8454 // If the expression is a prvalue after this optional conversion, the
8455 // temporary materialization conversion is applied.
8456 //
8457 // We do not materialize temporaries by default in order to avoid creating
8458 // unnecessary temporary objects. If we skip this step, IR generation is
8459 // able to synthesize the storage for itself in the aggregate case, and
8460 // adding the extra node to the AST is just clutter.
8462 E->isPRValue() && !E->getType()->isVoidType()) {
8464 if (Res.isInvalid())
8465 return E;
8466 E = Res.get();
8467 }
8468 return E;
8469 }
8470
8471 // C99 6.3.2.1:
8472 // [Except in specific positions,] an lvalue that does not have
8473 // array type is converted to the value stored in the
8474 // designated object (and is no longer an lvalue).
8475 if (E->isPRValue()) {
8476 // In C, function designators (i.e. expressions of function type)
8477 // are r-values, but we still want to do function-to-pointer decay
8478 // on them. This is both technically correct and convenient for
8479 // some clients.
8482
8483 return E;
8484 }
8485
8486 // GCC seems to also exclude expressions of incomplete enum type.
8487 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8488 if (!T->getDecl()->isComplete()) {
8489 // FIXME: stupid workaround for a codegen bug!
8490 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8491 return E;
8492 }
8493 }
8494
8496 if (Res.isInvalid())
8497 return E;
8498 E = Res.get();
8499
8500 if (!E->getType()->isVoidType())
8502 diag::err_incomplete_type);
8503 return E;
8504}
8505
8507 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8508 // it occurs as an unevaluated operand.
8510
8511 return E;
8512}
8513
8514// If we can unambiguously determine whether Var can never be used
8515// in a constant expression, return true.
8516// - if the variable and its initializer are non-dependent, then
8517// we can unambiguously check if the variable is a constant expression.
8518// - if the initializer is not value dependent - we can determine whether
8519// it can be used to initialize a constant expression. If Init can not
8520// be used to initialize a constant expression we conclude that Var can
8521// never be a constant expression.
8522// - FXIME: if the initializer is dependent, we can still do some analysis and
8523// identify certain cases unambiguously as non-const by using a Visitor:
8524// - such as those that involve odr-use of a ParmVarDecl, involve a new
8525// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8528 if (isa<ParmVarDecl>(Var)) return true;
8529 const VarDecl *DefVD = nullptr;
8530
8531 // If there is no initializer - this can not be a constant expression.
8532 const Expr *Init = Var->getAnyInitializer(DefVD);
8533 if (!Init)
8534 return true;
8535 assert(DefVD);
8536 if (DefVD->isWeak())
8537 return false;
8538
8539 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8540 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8541 // of value-dependent expressions, and use it here to determine whether the
8542 // initializer is a potential constant expression.
8543 return false;
8544 }
8545
8547}
8548
8549/// Check if the current lambda has any potential captures
8550/// that must be captured by any of its enclosing lambdas that are ready to
8551/// capture. If there is a lambda that can capture a nested
8552/// potential-capture, go ahead and do so. Also, check to see if any
8553/// variables are uncaptureable or do not involve an odr-use so do not
8554/// need to be captured.
8555
8557 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8558
8559 assert(!S.isUnevaluatedContext());
8560 assert(S.CurContext->isDependentContext());
8561#ifndef NDEBUG
8562 DeclContext *DC = S.CurContext;
8563 while (isa_and_nonnull<CapturedDecl>(DC))
8564 DC = DC->getParent();
8565 assert(
8566 CurrentLSI->CallOperator == DC &&
8567 "The current call operator must be synchronized with Sema's CurContext");
8568#endif // NDEBUG
8569
8570 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8571
8572 // All the potentially captureable variables in the current nested
8573 // lambda (within a generic outer lambda), must be captured by an
8574 // outer lambda that is enclosed within a non-dependent context.
8575 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8576 // If the variable is clearly identified as non-odr-used and the full
8577 // expression is not instantiation dependent, only then do we not
8578 // need to check enclosing lambda's for speculative captures.
8579 // For e.g.:
8580 // Even though 'x' is not odr-used, it should be captured.
8581 // int test() {
8582 // const int x = 10;
8583 // auto L = [=](auto a) {
8584 // (void) +x + a;
8585 // };
8586 // }
8587 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8588 !IsFullExprInstantiationDependent)
8589 return;
8590
8591 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8592 if (!UnderlyingVar)
8593 return;
8594
8595 // If we have a capture-capable lambda for the variable, go ahead and
8596 // capture the variable in that lambda (and all its enclosing lambdas).
8597 if (const std::optional<unsigned> Index =
8599 S.FunctionScopes, Var, S))
8600 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8601 const bool IsVarNeverAConstantExpression =
8603 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8604 // This full expression is not instantiation dependent or the variable
8605 // can not be used in a constant expression - which means
8606 // this variable must be odr-used here, so diagnose a
8607 // capture violation early, if the variable is un-captureable.
8608 // This is purely for diagnosing errors early. Otherwise, this
8609 // error would get diagnosed when the lambda becomes capture ready.
8610 QualType CaptureType, DeclRefType;
8611 SourceLocation ExprLoc = VarExpr->getExprLoc();
8612 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8613 /*EllipsisLoc*/ SourceLocation(),
8614 /*BuildAndDiagnose*/false, CaptureType,
8615 DeclRefType, nullptr)) {
8616 // We will never be able to capture this variable, and we need
8617 // to be able to in any and all instantiations, so diagnose it.
8618 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8619 /*EllipsisLoc*/ SourceLocation(),
8620 /*BuildAndDiagnose*/true, CaptureType,
8621 DeclRefType, nullptr);
8622 }
8623 }
8624 });
8625
8626 // Check if 'this' needs to be captured.
8627 if (CurrentLSI->hasPotentialThisCapture()) {
8628 // If we have a capture-capable lambda for 'this', go ahead and capture
8629 // 'this' in that lambda (and all its enclosing lambdas).
8630 if (const std::optional<unsigned> Index =
8632 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8633 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8635 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8636 &FunctionScopeIndexOfCapturableLambda);
8637 }
8638 }
8639
8640 // Reset all the potential captures at the end of each full-expression.
8641 CurrentLSI->clearPotentialCaptures();
8642}
8643
8646 const TypoCorrection &TC) {
8647 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8648 Consumer.getLookupResult().getLookupKind());
8649 const CXXScopeSpec *SS = Consumer.getSS();
8650 CXXScopeSpec NewSS;
8651
8652 // Use an approprate CXXScopeSpec for building the expr.
8653 if (auto *NNS = TC.getCorrectionSpecifier())
8655 else if (SS && !TC.WillReplaceSpecifier())
8656 NewSS = *SS;
8657
8658 if (auto *ND = TC.getFoundDecl()) {
8659 R.setLookupName(ND->getDeclName());
8660 R.addDecl(ND);
8661 if (ND->isCXXClassMember()) {
8662 // Figure out the correct naming class to add to the LookupResult.
8663 CXXRecordDecl *Record = nullptr;
8664 if (auto *NNS = TC.getCorrectionSpecifier())
8665 Record = NNS->getAsType()->getAsCXXRecordDecl();
8666 if (!Record)
8667 Record =
8668 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8669 if (Record)
8671
8672 // Detect and handle the case where the decl might be an implicit
8673 // member.
8675 NewSS, R, Consumer.isAddressOfOperand()))
8677 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8678 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8679 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8680 return SemaRef.ObjC().LookupInObjCMethod(R, Consumer.getScope(),
8681 Ivar->getIdentifier());
8682 }
8683 }
8684
8685 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8686 /*AcceptInvalidDecl*/ true);
8687}
8688
8689namespace {
8690class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8692
8693public:
8694 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8695 : TypoExprs(TypoExprs) {}
8696 bool VisitTypoExpr(TypoExpr *TE) {
8697 TypoExprs.insert(TE);
8698 return true;
8699 }
8700};
8701
8702class TransformTypos : public TreeTransform<TransformTypos> {
8703 typedef TreeTransform<TransformTypos> BaseTransform;
8704
8705 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8706 // process of being initialized.
8707 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8708 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8709 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8710 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8711
8712 /// Emit diagnostics for all of the TypoExprs encountered.
8713 ///
8714 /// If the TypoExprs were successfully corrected, then the diagnostics should
8715 /// suggest the corrections. Otherwise the diagnostics will not suggest
8716 /// anything (having been passed an empty TypoCorrection).
8717 ///
8718 /// If we've failed to correct due to ambiguous corrections, we need to
8719 /// be sure to pass empty corrections and replacements. Otherwise it's
8720 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8721 /// and we don't want to report those diagnostics.
8722 void EmitAllDiagnostics(bool IsAmbiguous) {
8723 for (TypoExpr *TE : TypoExprs) {
8724 auto &State = SemaRef.getTypoExprState(TE);
8725 if (State.DiagHandler) {
8726 TypoCorrection TC = IsAmbiguous
8727 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8728 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8729
8730 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8731 // TypoCorrection, replacing the existing decls. This ensures the right
8732 // NamedDecl is used in diagnostics e.g. in the case where overload
8733 // resolution was used to select one from several possible decls that
8734 // had been stored in the TypoCorrection.
8735 if (auto *ND = getDeclFromExpr(
8736 Replacement.isInvalid() ? nullptr : Replacement.get()))
8737 TC.setCorrectionDecl(ND);
8738
8739 State.DiagHandler(TC);
8740 }
8741 SemaRef.clearDelayedTypo(TE);
8742 }
8743 }
8744
8745 /// Try to advance the typo correction state of the first unfinished TypoExpr.
8746 /// We allow advancement of the correction stream by removing it from the
8747 /// TransformCache which allows `TransformTypoExpr` to advance during the
8748 /// next transformation attempt.
8749 ///
8750 /// Any substitution attempts for the previous TypoExprs (which must have been
8751 /// finished) will need to be retried since it's possible that they will now
8752 /// be invalid given the latest advancement.
8753 ///
8754 /// We need to be sure that we're making progress - it's possible that the
8755 /// tree is so malformed that the transform never makes it to the
8756 /// `TransformTypoExpr`.
8757 ///
8758 /// Returns true if there are any untried correction combinations.
8759 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8760 for (auto *TE : TypoExprs) {
8761 auto &State = SemaRef.getTypoExprState(TE);
8762 TransformCache.erase(TE);
8763 if (!State.Consumer->hasMadeAnyCorrectionProgress())
8764 return false;
8765 if (!State.Consumer->finished())
8766 return true;
8767 State.Consumer->resetCorrectionStream();
8768 }
8769 return false;
8770 }
8771
8773 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8774 E = OverloadResolution[OE];
8775
8776 if (!E)
8777 return nullptr;
8778 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8779 return DRE->getFoundDecl();
8780 if (auto *ME = dyn_cast<MemberExpr>(E))
8781 return ME->getFoundDecl();
8782 // FIXME: Add any other expr types that could be seen by the delayed typo
8783 // correction TreeTransform for which the corresponding TypoCorrection could
8784 // contain multiple decls.
8785 return nullptr;
8786 }
8787
8788 ExprResult TryTransform(Expr *E) {
8789 Sema::SFINAETrap Trap(SemaRef);
8790 ExprResult Res = TransformExpr(E);
8791 if (Trap.hasErrorOccurred() || Res.isInvalid())
8792 return ExprError();
8793
8794 return ExprFilter(Res.get());
8795 }
8796
8797 // Since correcting typos may intoduce new TypoExprs, this function
8798 // checks for new TypoExprs and recurses if it finds any. Note that it will
8799 // only succeed if it is able to correct all typos in the given expression.
8800 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8801 if (Res.isInvalid()) {
8802 return Res;
8803 }
8804 // Check to see if any new TypoExprs were created. If so, we need to recurse
8805 // to check their validity.
8806 Expr *FixedExpr = Res.get();
8807
8808 auto SavedTypoExprs = std::move(TypoExprs);
8809 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8810 TypoExprs.clear();
8811 AmbiguousTypoExprs.clear();
8812
8813 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8814 if (!TypoExprs.empty()) {
8815 // Recurse to handle newly created TypoExprs. If we're not able to
8816 // handle them, discard these TypoExprs.
8817 ExprResult RecurResult =
8818 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8819 if (RecurResult.isInvalid()) {
8820 Res = ExprError();
8821 // Recursive corrections didn't work, wipe them away and don't add
8822 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8823 // since we don't want to clear them twice. Note: it's possible the
8824 // TypoExprs were created recursively and thus won't be in our
8825 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8826 auto &SemaTypoExprs = SemaRef.TypoExprs;
8827 for (auto *TE : TypoExprs) {
8828 TransformCache.erase(TE);
8829 SemaRef.clearDelayedTypo(TE);
8830
8831 auto SI = find(SemaTypoExprs, TE);
8832 if (SI != SemaTypoExprs.end()) {
8833 SemaTypoExprs.erase(SI);
8834 }
8835 }
8836 } else {
8837 // TypoExpr is valid: add newly created TypoExprs since we were
8838 // able to correct them.
8839 Res = RecurResult;
8840 SavedTypoExprs.set_union(TypoExprs);
8841 }
8842 }
8843
8844 TypoExprs = std::move(SavedTypoExprs);
8845 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8846
8847 return Res;
8848 }
8849
8850 // Try to transform the given expression, looping through the correction
8851 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8852 //
8853 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8854 // true and this method immediately will return an `ExprError`.
8855 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8856 ExprResult Res;
8857 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8858 SemaRef.TypoExprs.clear();
8859
8860 while (true) {
8861 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8862
8863 // Recursion encountered an ambiguous correction. This means that our
8864 // correction itself is ambiguous, so stop now.
8865 if (IsAmbiguous)
8866 break;
8867
8868 // If the transform is still valid after checking for any new typos,
8869 // it's good to go.
8870 if (!Res.isInvalid())
8871 break;
8872
8873 // The transform was invalid, see if we have any TypoExprs with untried
8874 // correction candidates.
8875 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8876 break;
8877 }
8878
8879 // If we found a valid result, double check to make sure it's not ambiguous.
8880 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8881 auto SavedTransformCache =
8882 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8883
8884 // Ensure none of the TypoExprs have multiple typo correction candidates
8885 // with the same edit length that pass all the checks and filters.
8886 while (!AmbiguousTypoExprs.empty()) {
8887 auto TE = AmbiguousTypoExprs.back();
8888
8889 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8890 // and invalidating our TypoExprState, so always fetch it instead of storing.
8891 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8892
8893 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8894 TypoCorrection Next;
8895 do {
8896 // Fetch the next correction by erasing the typo from the cache and calling
8897 // `TryTransform` which will iterate through corrections in
8898 // `TransformTypoExpr`.
8899 TransformCache.erase(TE);
8900 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8901
8902 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8903 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8904 SavedTransformCache.erase(TE);
8905 Res = ExprError();
8906 IsAmbiguous = true;
8907 break;
8908 }
8909 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8910 Next.getEditDistance(false) == TC.getEditDistance(false));
8911
8912 if (IsAmbiguous)
8913 break;
8914
8915 AmbiguousTypoExprs.remove(TE);
8916 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8917 TransformCache[TE] = SavedTransformCache[TE];
8918 }
8919 TransformCache = std::move(SavedTransformCache);
8920 }
8921
8922 // Wipe away any newly created TypoExprs that we don't know about. Since we
8923 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8924 // possible if a `TypoExpr` is created during a transformation but then
8925 // fails before we can discover it.
8926 auto &SemaTypoExprs = SemaRef.TypoExprs;
8927 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8928 auto TE = *Iterator;
8929 auto FI = find(TypoExprs, TE);
8930 if (FI != TypoExprs.end()) {
8931 Iterator++;
8932 continue;
8933 }
8934 SemaRef.clearDelayedTypo(TE);
8935 Iterator = SemaTypoExprs.erase(Iterator);
8936 }
8937 SemaRef.TypoExprs = std::move(SavedTypoExprs);
8938
8939 return Res;
8940 }
8941
8942public:
8943 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8944 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8945
8946 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8947 MultiExprArg Args,
8948 SourceLocation RParenLoc,
8949 Expr *ExecConfig = nullptr) {
8950 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8951 RParenLoc, ExecConfig);
8952 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8953 if (Result.isUsable()) {
8954 Expr *ResultCall = Result.get();
8955 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8956 ResultCall = BE->getSubExpr();
8957 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8958 OverloadResolution[OE] = CE->getCallee();
8959 }
8960 }
8961 return Result;
8962 }
8963
8964 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8965
8966 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8967
8968 ExprResult Transform(Expr *E) {
8969 bool IsAmbiguous = false;
8970 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8971
8972 if (!Res.isUsable())
8973 FindTypoExprs(TypoExprs).TraverseStmt(E);
8974
8975 EmitAllDiagnostics(IsAmbiguous);
8976
8977 return Res;
8978 }
8979
8980 ExprResult TransformTypoExpr(TypoExpr *E) {
8981 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8982 // cached transformation result if there is one and the TypoExpr isn't the
8983 // first one that was encountered.
8984 auto &CacheEntry = TransformCache[E];
8985 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8986 return CacheEntry;
8987 }
8988
8989 auto &State = SemaRef.getTypoExprState(E);
8990 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8991
8992 // For the first TypoExpr and an uncached TypoExpr, find the next likely
8993 // typo correction and return it.
8994 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8995 if (InitDecl && TC.getFoundDecl() == InitDecl)
8996 continue;
8997 // FIXME: If we would typo-correct to an invalid declaration, it's
8998 // probably best to just suppress all errors from this typo correction.
8999 ExprResult NE = State.RecoveryHandler ?
9000 State.RecoveryHandler(SemaRef, E, TC) :
9001 attemptRecovery(SemaRef, *State.Consumer, TC);
9002 if (!NE.isInvalid()) {
9003 // Check whether there may be a second viable correction with the same
9004 // edit distance; if so, remember this TypoExpr may have an ambiguous
9005 // correction so it can be more thoroughly vetted later.
9006 TypoCorrection Next;
9007 if ((Next = State.Consumer->peekNextCorrection()) &&
9008 Next.getEditDistance(false) == TC.getEditDistance(false)) {
9009 AmbiguousTypoExprs.insert(E);
9010 } else {
9011 AmbiguousTypoExprs.remove(E);
9012 }
9013 assert(!NE.isUnset() &&
9014 "Typo was transformed into a valid-but-null ExprResult");
9015 return CacheEntry = NE;
9016 }
9017 }
9018 return CacheEntry = ExprError();
9019 }
9020};
9021}
9022
9025 bool RecoverUncorrectedTypos,
9026 llvm::function_ref<ExprResult(Expr *)> Filter) {
9027 // If the current evaluation context indicates there are uncorrected typos
9028 // and the current expression isn't guaranteed to not have typos, try to
9029 // resolve any TypoExpr nodes that might be in the expression.
9030 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
9031 (E->isTypeDependent() || E->isValueDependent() ||
9033 auto TyposResolved = DelayedTypos.size();
9034 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
9035 TyposResolved -= DelayedTypos.size();
9036 if (Result.isInvalid() || Result.get() != E) {
9037 ExprEvalContexts.back().NumTypos -= TyposResolved;
9038 if (Result.isInvalid() && RecoverUncorrectedTypos) {
9039 struct TyposReplace : TreeTransform<TyposReplace> {
9040 TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
9041 ExprResult TransformTypoExpr(clang::TypoExpr *E) {
9042 return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
9043 E->getEndLoc(), {});
9044 }
9045 } TT(*this);
9046 return TT.TransformExpr(E);
9047 }
9048 return Result;
9049 }
9050 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
9051 }
9052 return E;
9053}
9054
9056 bool DiscardedValue, bool IsConstexpr,
9057 bool IsTemplateArgument) {
9058 ExprResult FullExpr = FE;
9059
9060 if (!FullExpr.get())
9061 return ExprError();
9062
9063 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
9064 return ExprError();
9065
9066 if (DiscardedValue) {
9067 // Top-level expressions default to 'id' when we're in a debugger.
9068 if (getLangOpts().DebuggerCastResultToId &&
9069 FullExpr.get()->getType() == Context.UnknownAnyTy) {
9071 if (FullExpr.isInvalid())
9072 return ExprError();
9073 }
9074
9076 if (FullExpr.isInvalid())
9077 return ExprError();
9078
9080 if (FullExpr.isInvalid())
9081 return ExprError();
9082
9083 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
9084 }
9085
9086 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
9087 /*RecoverUncorrectedTypos=*/true);
9088 if (FullExpr.isInvalid())
9089 return ExprError();
9090
9091 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
9092
9093 // At the end of this full expression (which could be a deeply nested
9094 // lambda), if there is a potential capture within the nested lambda,
9095 // have the outer capture-able lambda try and capture it.
9096 // Consider the following code:
9097 // void f(int, int);
9098 // void f(const int&, double);
9099 // void foo() {
9100 // const int x = 10, y = 20;
9101 // auto L = [=](auto a) {
9102 // auto M = [=](auto b) {
9103 // f(x, b); <-- requires x to be captured by L and M
9104 // f(y, a); <-- requires y to be captured by L, but not all Ms
9105 // };
9106 // };
9107 // }
9108
9109 // FIXME: Also consider what happens for something like this that involves
9110 // the gnu-extension statement-expressions or even lambda-init-captures:
9111 // void f() {
9112 // const int n = 0;
9113 // auto L = [&](auto a) {
9114 // +n + ({ 0; a; });
9115 // };
9116 // }
9117 //
9118 // Here, we see +n, and then the full-expression 0; ends, so we don't
9119 // capture n (and instead remove it from our list of potential captures),
9120 // and then the full-expression +n + ({ 0; }); ends, but it's too late
9121 // for us to see that we need to capture n after all.
9122
9123 LambdaScopeInfo *const CurrentLSI =
9124 getCurLambda(/*IgnoreCapturedRegions=*/true);
9125 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
9126 // even if CurContext is not a lambda call operator. Refer to that Bug Report
9127 // for an example of the code that might cause this asynchrony.
9128 // By ensuring we are in the context of a lambda's call operator
9129 // we can fix the bug (we only need to check whether we need to capture
9130 // if we are within a lambda's body); but per the comments in that
9131 // PR, a proper fix would entail :
9132 // "Alternative suggestion:
9133 // - Add to Sema an integer holding the smallest (outermost) scope
9134 // index that we are *lexically* within, and save/restore/set to
9135 // FunctionScopes.size() in InstantiatingTemplate's
9136 // constructor/destructor.
9137 // - Teach the handful of places that iterate over FunctionScopes to
9138 // stop at the outermost enclosing lexical scope."
9139 DeclContext *DC = CurContext;
9140 while (isa_and_nonnull<CapturedDecl>(DC))
9141 DC = DC->getParent();
9142 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
9143 if (IsInLambdaDeclContext && CurrentLSI &&
9144 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
9146 *this);
9148}
9149
9151 if (!FullStmt) return StmtError();
9152
9153 return MaybeCreateStmtWithCleanups(FullStmt);
9154}
9155
9158 CXXScopeSpec &SS,
9159 const DeclarationNameInfo &TargetNameInfo) {
9160 DeclarationName TargetName = TargetNameInfo.getName();
9161 if (!TargetName)
9162 return IER_DoesNotExist;
9163
9164 // If the name itself is dependent, then the result is dependent.
9165 if (TargetName.isDependentName())
9166 return IER_Dependent;
9167
9168 // Do the redeclaration lookup in the current scope.
9169 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
9170 RedeclarationKind::NotForRedeclaration);
9171 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
9173
9174 switch (R.getResultKind()) {
9179 return IER_Exists;
9180
9182 return IER_DoesNotExist;
9183
9185 return IER_Dependent;
9186 }
9187
9188 llvm_unreachable("Invalid LookupResult Kind!");
9189}
9190
9193 bool IsIfExists, CXXScopeSpec &SS,
9194 UnqualifiedId &Name) {
9195 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9196
9197 // Check for an unexpanded parameter pack.
9198 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
9199 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
9200 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
9201 return IER_Error;
9202
9203 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
9204}
9205
9207 return BuildExprRequirement(E, /*IsSimple=*/true,
9208 /*NoexceptLoc=*/SourceLocation(),
9209 /*ReturnTypeRequirement=*/{});
9210}
9211
9213 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
9214 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
9215 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
9216 "Exactly one of TypeName and TemplateId must be specified.");
9217 TypeSourceInfo *TSI = nullptr;
9218 if (TypeName) {
9219 QualType T =
9221 SS.getWithLocInContext(Context), *TypeName, NameLoc,
9222 &TSI, /*DeducedTSTContext=*/false);
9223 if (T.isNull())
9224 return nullptr;
9225 } else {
9226 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
9227 TemplateId->NumArgs);
9228 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
9229 TemplateId->TemplateKWLoc,
9230 TemplateId->Template, TemplateId->Name,
9231 TemplateId->TemplateNameLoc,
9232 TemplateId->LAngleLoc, ArgsPtr,
9233 TemplateId->RAngleLoc);
9234 if (T.isInvalid())
9235 return nullptr;
9236 if (GetTypeFromParser(T.get(), &TSI).isNull())
9237 return nullptr;
9238 }
9239 return BuildTypeRequirement(TSI);
9240}
9241
9244 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
9245 /*ReturnTypeRequirement=*/{});
9246}
9247
9250 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9251 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
9252 // C++2a [expr.prim.req.compound] p1.3.3
9253 // [..] the expression is deduced against an invented function template
9254 // F [...] F is a void function template with a single type template
9255 // parameter T declared with the constrained-parameter. Form a new
9256 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
9257 // around the constrained-parameter. F has a single parameter whose
9258 // type-specifier is cv T followed by the abstract-declarator. [...]
9259 //
9260 // The cv part is done in the calling function - we get the concept with
9261 // arguments and the abstract declarator with the correct CV qualification and
9262 // have to synthesize T and the single parameter of F.
9263 auto &II = Context.Idents.get("expr-type");
9266 SourceLocation(), Depth,
9267 /*Index=*/0, &II,
9268 /*Typename=*/true,
9269 /*ParameterPack=*/false,
9270 /*HasTypeConstraint=*/true);
9271
9272 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
9273 /*EllipsisLoc=*/SourceLocation(),
9274 /*AllowUnexpandedPack=*/true))
9275 // Just produce a requirement with no type requirements.
9276 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
9277
9280 ArrayRef<NamedDecl *>(TParam),
9282 /*RequiresClause=*/nullptr);
9283 return BuildExprRequirement(
9284 E, /*IsSimple=*/false, NoexceptLoc,
9286}
9287
9290 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9293 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9295 ReturnTypeRequirement.isDependent())
9297 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9299 else if (ReturnTypeRequirement.isSubstitutionFailure())
9301 else if (ReturnTypeRequirement.isTypeConstraint()) {
9302 // C++2a [expr.prim.req]p1.3.3
9303 // The immediately-declared constraint ([temp]) of decltype((E)) shall
9304 // be satisfied.
9306 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9307 QualType MatchedType =
9310 Args.push_back(TemplateArgument(MatchedType));
9311
9312 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9313
9314 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false);
9315 MLTAL.addOuterRetainedLevels(TPL->getDepth());
9316 const TypeConstraint *TC = Param->getTypeConstraint();
9317 assert(TC && "Type Constraint cannot be null here");
9318 auto *IDC = TC->getImmediatelyDeclaredConstraint();
9319 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
9320 ExprResult Constraint = SubstExpr(IDC, MLTAL);
9321 if (Constraint.isInvalid()) {
9323 concepts::createSubstDiagAt(*this, IDC->getExprLoc(),
9324 [&](llvm::raw_ostream &OS) {
9325 IDC->printPretty(OS, /*Helper=*/nullptr,
9326 getPrintingPolicy());
9327 }),
9328 IsSimple, NoexceptLoc, ReturnTypeRequirement);
9329 }
9330 SubstitutedConstraintExpr =
9331 cast<ConceptSpecializationExpr>(Constraint.get());
9332 if (!SubstitutedConstraintExpr->isSatisfied())
9334 }
9335 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9336 ReturnTypeRequirement, Status,
9337 SubstitutedConstraintExpr);
9338}
9339
9342 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9343 bool IsSimple, SourceLocation NoexceptLoc,
9345 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9346 IsSimple, NoexceptLoc,
9347 ReturnTypeRequirement);
9348}
9349
9353}
9354
9358 return new (Context) concepts::TypeRequirement(SubstDiag);
9359}
9360
9362 return BuildNestedRequirement(Constraint);
9363}
9364
9367 ConstraintSatisfaction Satisfaction;
9368 if (!Constraint->isInstantiationDependent() &&
9369 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9370 Constraint->getSourceRange(), Satisfaction))
9371 return nullptr;
9372 return new (Context) concepts::NestedRequirement(Context, Constraint,
9373 Satisfaction);
9374}
9375
9377Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9378 const ASTConstraintSatisfaction &Satisfaction) {
9380 InvalidConstraintEntity,
9382}
9383
9386 ArrayRef<ParmVarDecl *> LocalParameters,
9387 Scope *BodyScope) {
9388 assert(BodyScope);
9389
9391 RequiresKWLoc);
9392
9393 PushDeclContext(BodyScope, Body);
9394
9395 for (ParmVarDecl *Param : LocalParameters) {
9396 if (Param->hasDefaultArg())
9397 // C++2a [expr.prim.req] p4
9398 // [...] A local parameter of a requires-expression shall not have a
9399 // default argument. [...]
9400 Diag(Param->getDefaultArgRange().getBegin(),
9401 diag::err_requires_expr_local_parameter_default_argument);
9402 // Ignore default argument and move on
9403
9404 Param->setDeclContext(Body);
9405 // If this has an identifier, add it to the scope stack.
9406 if (Param->getIdentifier()) {
9407 CheckShadow(BodyScope, Param);
9408 PushOnScopeChains(Param, BodyScope);
9409 }
9410 }
9411 return Body;
9412}
9413
9415 assert(CurContext && "DeclContext imbalance!");
9417 assert(CurContext && "Popped translation unit!");
9418}
9419
9421 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
9422 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
9423 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
9424 SourceLocation ClosingBraceLoc) {
9425 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
9426 LocalParameters, RParenLoc, Requirements,
9427 ClosingBraceLoc);
9429 return ExprError();
9430 return RE;
9431}
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
Expr * E
enum clang::sema::@1651::IndirectLocalPathEntry::EntryKind Kind
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition: Darwin.cpp:3287
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 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:14482
This file provides some common utility functions for processing Lambdas.
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
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:186
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:1100
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2822
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:663
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:1130
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:2625
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2641
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:2191
CanQualType VoidPtrTy
Definition: ASTContext.h:1145
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
CanQualType DependentTy
Definition: ASTContext.h:1146
CanQualType NullPtrTy
Definition: ASTContext.h:1145
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:1634
IdentifierTable & Idents
Definition: ASTContext.h:659
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:796
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:1119
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:1146
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:2207
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:1146
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2114
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2672
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:2391
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1118
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1147
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:1612
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:2202
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:778
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2230
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:1844
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2050
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:2422
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2395
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:3540
QualType getElementType() const
Definition: Type.h:3552
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7573
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:6368
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:4804
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6355
Pointer to a block type.
Definition: Type.h:3371
This class is used for builtin types like 'int'.
Definition: Type.h:3000
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:1095
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:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2440
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2502
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:2799
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:899
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isVirtual() const
Definition: DeclCXX.h:2115
bool isUsualDeallocationFunction(SmallVectorImpl< const FunctionDecl * > &PreventedBy) const
Determine whether this is a usual deallocation function (C++ [basic.stc.dynamic.deallocation]p2),...
Definition: DeclCXX.cpp:2380
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition: DeclCXX.cpp:2490
QualType getFunctionObjectParameterType() const
Definition: DeclCXX.h:2210
bool isConst() const
Definition: DeclCXX.h:2112
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2468
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:4124
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:1342
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1335
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1241
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1367
base_class_range bases()
Definition: DeclCXX.h:619
bool hasTrivialMoveConstructor() const
Determine whether this class has a trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1302
bool hasTrivialCopyConstructor() const
Determine whether this class has a trivial copy constructor (C++ [class.copy]p6, C++11 [class....
Definition: DeclCXX.h:1279
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition: DeclCXX.h:1215
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:1329
capture_const_range captures() const
Definition: DeclCXX.h:1101
ctor_range ctors() const
Definition: DeclCXX.h:681
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition: DeclCXX.h:1222
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition: DeclCXX.h:1403
bool hasNonTrivialMoveConstructor() const
Determine whether this class has a non-trivial move constructor (C++11 [class.copy]p12)
Definition: DeclCXX.h:1314
bool hasDefinition() const
Definition: DeclCXX.h:571
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1190
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1978
bool hasNonTrivialMoveAssignment() const
Determine whether this class has a non-trivial move assignment operator (C++11 [class....
Definition: DeclCXX.h:1349
bool hasNonTrivialDefaultConstructor() const
Determine whether this class has a non-trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1248
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1289
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1597
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:1090
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:1566
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:1469
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:3108
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
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:3578
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:1358
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1309
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2095
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1828
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1742
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:557
TST getTypeSpecType() const
Definition: DeclSpec.h:534
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:572
static const TST TST_typename_pack_indexing
Definition: DeclSpec.h:313
ParsedType getRepAsType() const
Definition: DeclSpec.h:544
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:620
Expr * getRepAsExpr() const
Definition: DeclSpec.h:552
static const TST TST_decltype
Definition: DeclSpec.h:311
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:579
static const TST TST_decltype_auto
Definition: DeclSpec.h:312
static const TST TST_error
Definition: DeclSpec.h:325
SourceRange getTypeofParensRange() const
Definition: DeclSpec.h:589
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
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:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:812
void setImplicit(bool I=true)
Definition: DeclBase.h:600
DeclContext * getDeclContext()
Definition: DeclBase.h:454
bool hasAttr() const
Definition: DeclBase.h:583
@ 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:860
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:433
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:1900
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:6334
bool isDeduced() const
Definition: Type.h:6356
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:3840
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4840
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4054
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5962
EnumDecl * getDecl() const
Definition: Type.h:5969
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1444
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:919
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:4042
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:3354
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:4383
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3967
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3680
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:4973
unsigned getNumParams() const
Definition: Type.h:5226
QualType getParamType(unsigned i) const
Definition: Type.h:5228
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5350
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5345
Declaration of a template function.
Definition: DeclTemplate.h:957
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4463
bool getNoReturn() const
Definition: Type.h:4437
bool getProducesResult() const
Definition: Type.h:4438
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4278
ExtInfo getExtInfo() const
Definition: Type.h:4612
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:5029
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:7482
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3807
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:8570
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:3796
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:496
bool hasGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:729
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
Definition: LangOptions.h:642
bool hasHiddenGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:744
bool hasProtectedGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:739
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:4289
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:3482
QualType getPointeeType() const
Definition: Type.h:3498
const Type * getClass() const
Definition: Type.h:3512
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:1808
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:7392
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7404
Represents a class type in Objective C.
Definition: Type.h:7138
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:7371
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:3161
QualType getPointeeType() const
Definition: Type.h:3171
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:7827
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3469
@ 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:7925
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:7743
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7869
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7783
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:7944
QualType getCanonicalType() const
Definition: Type.h:7795
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7837
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2837
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:7789
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:4141
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition: Decl.h:4270
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
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:2029
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition: DeclCXX.cpp:2176
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:256
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:3010
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:10040
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12080
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:12110
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
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:6321
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:803
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
Definition: SemaType.cpp:2010
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:7857
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8999
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition: Sema.h:9014
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:9002
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:9044
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:407
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
VariadicCallType
Definition: Sema.h:2333
@ VariadicDoesNotApply
Definition: Sema.h:2338
@ VariadicFunction
Definition: Sema.h:2334
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:8469
@ IER_DoesNotExist
The symbol does not exist.
Definition: Sema.h:8474
@ IER_Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
Definition: Sema.h:8478
@ IER_Error
An error occurred.
Definition: Sema.h:8481
@ IER_Exists
The symbol exists.
Definition: Sema.h:8471
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:1539
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:1164
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:20110
ConditionKind
Definition: Sema.h:7355
@ 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:940
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:10132
@ AR_inaccessible
Definition: Sema.h:1335
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:18182
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:16917
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:10050
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1731
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:1547
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:1057
ASTContext & Context
Definition: Sema.h:1002
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:618
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:597
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:7807
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1204
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:7249
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1495
ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19391
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:747
ASTContext & getASTContext() const
Definition: Sema.h:600
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:18673
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15062
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9491
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:694
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:6118
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:908
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:2186
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:7971
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:3237
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:595
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
@ UPPC_IfExists
Microsoft __if_exists.
Definition: Sema.h:13922
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition: Sema.h:13925
const LangOptions & getLangOpts() const
Definition: Sema.h:593
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:7206
SemaOpenACC & OpenACC()
Definition: Sema.h:1209
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:1001
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:14345
const LangOptions & LangOpts
Definition: Sema.h:1000
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:2389
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:7445
SemaHLSL & HLSL()
Definition: Sema.h:1169
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:17240
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:72
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:19790
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:6471
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:777
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:10300
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6468
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:9686
void MarkThisReferenced(CXXThisExpr *This)
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:635
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3163
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7788
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9597
static bool isCast(CheckedConversionKind CCK)
Definition: Sema.h:2103
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7583
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1137
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:5771
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:7829
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:7780
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1527
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7583
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7585
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7664
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:7410
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:7982
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4081
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20694
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17139
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:13471
SourceManager & getSourceManager() const
Definition: Sema.h:598
@ TryCapture_Implicit
Definition: Sema.h:6598
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition: Sema.h:8053
AssignmentAction
Definition: Sema.h:6479
@ AA_Returning
Definition: Sema.h:6482
@ AA_Passing_CFAudited
Definition: Sema.h:6487
@ AA_Initializing
Definition: Sema.h:6484
@ AA_Converting
Definition: Sema.h:6483
@ AA_Assigning
Definition: Sema.h:6480
@ AA_Passing
Definition: Sema.h:6481
@ AA_Casting
Definition: Sema.h:6486
@ AA_Sending
Definition: Sema.h:6485
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:3372
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:215
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:8170
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:14915
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:7978
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:10011
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:287
ASTConsumer & Consumer
Definition: Sema.h:1003
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:6475
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:120
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16353
@ 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:9470
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5645
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:19984
SemaPPC & PPC()
Definition: Sema.h:1224
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8885
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:963
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:20624
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:7989
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17658
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7930
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1306
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:1004
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:511
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9616
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:1763
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:9484
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:16584
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:17839
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:5881
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1947
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:20889
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:7975
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9069
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:2723
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:7342
IdentifierResolver IdResolver
Definition: Sema.h:3003
const TypoExprState & getTypoExprState(TypoExpr *TE) const
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:7298
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:8172
@ AFS_Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition: Sema.h:8180
@ AFS_Class
Only look for allocation functions in the scope of the allocated class.
Definition: Sema.h:8177
@ AFS_Global
Only look for allocation functions in the global scope.
Definition: Sema.h:8174
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:5302
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:8277
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:4407
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:3763
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:228
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:243
Represents a declaration of a type.
Definition: Decl.h:3363
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:7714
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:7725
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:1874
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:2474
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:8006
bool isVoidType() const
Definition: Type.h:8295
bool isBooleanType() const
Definition: Type.h:8423
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2889
bool isIncompleteArrayType() const
Definition: Type.h:8072
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:8271
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:8018
bool isFundamentalType() const
Tests whether the type is categorized as a fundamental type.
Definition: Type.h:7959
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isArrayType() const
Definition: Type.h:8064
bool isArithmeticType() const
Definition: Type.cpp:2281
bool isPointerType() const
Definition: Type.h:7996
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8335
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isReferenceType() const
Definition: Type.h:8010
bool isEnumeralType() const
Definition: Type.h:8096
bool isScalarType() const
Definition: Type.h:8394
bool isInterfaceType() const
Definition: Type.cpp:651
bool isVariableArrayType() const
Definition: Type.h:8076
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2507
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:8108
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2545
bool isMemberDataPointerType() const
Definition: Type.h:8057
bool isLValueReferenceType() const
Definition: Type.h:8014
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
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:8100
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8348
bool isHalfType() const
Definition: Type.h:8299
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:2464
bool isCompoundType() const
Tests whether the type is categorized as a compound type.
Definition: Type.h:7970
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8466
bool isMemberPointerType() const
Definition: Type.h:8046
bool isMatrixType() const
Definition: Type.h:8122
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2970
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2690
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4961
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2421
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4904
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:7992
bool isObjCObjectPointerType() const
Definition: Type.h:8134
bool isStructureOrClassType() const
Definition: Type.cpp:657
bool isMemberFunctionPointerType() const
Definition: Type.h:8050
bool isVectorType() const
Definition: Type.h:8104
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:8000
bool isClassType() const
Definition: Type.cpp:623
TypeClass getTypeClass() const
Definition: Type.h:2316
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:4910
bool isNullPtrType() const
Definition: Type.h:8328
bool isRecordType() const
Definition: Type.h:8092
bool isObjCRetainableType() const
Definition: Type.cpp:4941
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:6767
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:1025
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1083
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition: DeclSpec.h:1053
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1107
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1077
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:5353
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3303
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:3991
unsigned getNumElements() const
Definition: Type.h:4006
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:1095
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:179
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:146
@ 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:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:151
@ 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:247
@ 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:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
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:387
@ 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:456
@ 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:121
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:90
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:1309
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1318
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1248
ArrayTypeInfo Arr
Definition: DeclSpec.h:1638
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1256
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5032
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5035
Extra information about a function prototype.
Definition: Type.h:5058
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5065
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5059
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4264
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:10140
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