clang 19.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/Template.h"
47#include "llvm/ADT/APInt.h"
48#include "llvm/ADT/STLExtras.h"
49#include "llvm/ADT/STLForwardCompat.h"
50#include "llvm/ADT/StringExtras.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/TypeSize.h"
53#include <optional>
54using namespace clang;
55using namespace sema;
56
57/// Handle the result of the special case name lookup for inheriting
58/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
59/// constructor names in member using declarations, even if 'X' is not the
60/// name of the corresponding type.
62 SourceLocation NameLoc,
63 const IdentifierInfo &Name) {
65
66 // Convert the nested-name-specifier into a type.
68 switch (NNS->getKind()) {
71 Type = QualType(NNS->getAsType(), 0);
72 break;
73
75 // Strip off the last layer of the nested-name-specifier and build a
76 // typename type for it.
77 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
80 break;
81
86 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
87 }
88
89 // This reference to the type is located entirely at the location of the
90 // final identifier in the qualified-id.
93}
94
96 SourceLocation NameLoc, Scope *S,
97 CXXScopeSpec &SS, bool EnteringContext) {
98 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
99 assert(CurClass && &II == CurClass->getIdentifier() &&
100 "not a constructor name");
101
102 // When naming a constructor as a member of a dependent context (eg, in a
103 // friend declaration or an inherited constructor declaration), form an
104 // unresolved "typename" type.
105 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
107 SS.getScopeRep(), &II);
108 return ParsedType::make(T);
109 }
110
111 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
112 return ParsedType();
113
114 // Find the injected-class-name declaration. Note that we make no attempt to
115 // diagnose cases where the injected-class-name is shadowed: the only
116 // declaration that can validly shadow the injected-class-name is a
117 // non-static data member, and if the class contains both a non-static data
118 // member and a constructor then it is ill-formed (we check that in
119 // CheckCompletedCXXClass).
120 CXXRecordDecl *InjectedClassName = nullptr;
121 for (NamedDecl *ND : CurClass->lookup(&II)) {
122 auto *RD = dyn_cast<CXXRecordDecl>(ND);
123 if (RD && RD->isInjectedClassName()) {
124 InjectedClassName = RD;
125 break;
126 }
127 }
128 if (!InjectedClassName) {
129 if (!CurClass->isInvalidDecl()) {
130 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
131 // properly. Work around it here for now.
133 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
134 }
135 return ParsedType();
136 }
137
138 QualType T = Context.getTypeDeclType(InjectedClassName);
139 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
140 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
141
142 return ParsedType::make(T);
143}
144
146 SourceLocation NameLoc, Scope *S,
147 CXXScopeSpec &SS, ParsedType ObjectTypePtr,
148 bool EnteringContext) {
149 // Determine where to perform name lookup.
150
151 // FIXME: This area of the standard is very messy, and the current
152 // wording is rather unclear about which scopes we search for the
153 // destructor name; see core issues 399 and 555. Issue 399 in
154 // particular shows where the current description of destructor name
155 // lookup is completely out of line with existing practice, e.g.,
156 // this appears to be ill-formed:
157 //
158 // namespace N {
159 // template <typename T> struct S {
160 // ~S();
161 // };
162 // }
163 //
164 // void f(N::S<int>* s) {
165 // s->N::S<int>::~S();
166 // }
167 //
168 // See also PR6358 and PR6359.
169 //
170 // For now, we accept all the cases in which the name given could plausibly
171 // be interpreted as a correct destructor name, issuing off-by-default
172 // extension diagnostics on the cases that don't strictly conform to the
173 // C++20 rules. This basically means we always consider looking in the
174 // nested-name-specifier prefix, the complete nested-name-specifier, and
175 // the scope, and accept if we find the expected type in any of the three
176 // places.
177
178 if (SS.isInvalid())
179 return nullptr;
180
181 // Whether we've failed with a diagnostic already.
182 bool Failed = false;
183
186
187 // If we have an object type, it's because we are in a
188 // pseudo-destructor-expression or a member access expression, and
189 // we know what type we're looking for.
190 QualType SearchType =
191 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
192
193 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
194 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
195 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
196 if (!Type)
197 return false;
198
199 if (SearchType.isNull() || SearchType->isDependentType())
200 return true;
201
203 return Context.hasSameUnqualifiedType(T, SearchType);
204 };
205
206 unsigned NumAcceptableResults = 0;
207 for (NamedDecl *D : Found) {
208 if (IsAcceptableResult(D))
209 ++NumAcceptableResults;
210
211 // Don't list a class twice in the lookup failure diagnostic if it's
212 // found by both its injected-class-name and by the name in the enclosing
213 // scope.
214 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
215 if (RD->isInjectedClassName())
216 D = cast<NamedDecl>(RD->getParent());
217
218 if (FoundDeclSet.insert(D).second)
219 FoundDecls.push_back(D);
220 }
221
222 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
223 // results, and all non-matching results if we have a search type. It's not
224 // clear what the right behavior is if destructor lookup hits an ambiguity,
225 // but other compilers do generally accept at least some kinds of
226 // ambiguity.
227 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
228 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
229 LookupResult::Filter F = Found.makeFilter();
230 while (F.hasNext()) {
231 NamedDecl *D = F.next();
232 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
233 Diag(D->getLocation(), diag::note_destructor_type_here)
235 else
236 Diag(D->getLocation(), diag::note_destructor_nontype_here);
237
238 if (!IsAcceptableResult(D))
239 F.erase();
240 }
241 F.done();
242 }
243
244 if (Found.isAmbiguous())
245 Failed = true;
246
247 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
248 if (IsAcceptableResult(Type)) {
250 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
251 return CreateParsedType(
254 }
255 }
256
257 return nullptr;
258 };
259
260 bool IsDependent = false;
261
262 auto LookupInObjectType = [&]() -> ParsedType {
263 if (Failed || SearchType.isNull())
264 return nullptr;
265
266 IsDependent |= SearchType->isDependentType();
267
268 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
269 DeclContext *LookupCtx = computeDeclContext(SearchType);
270 if (!LookupCtx)
271 return nullptr;
272 LookupQualifiedName(Found, LookupCtx);
273 return CheckLookupResult(Found);
274 };
275
276 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
277 if (Failed)
278 return nullptr;
279
280 IsDependent |= isDependentScopeSpecifier(LookupSS);
281 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
282 if (!LookupCtx)
283 return nullptr;
284
285 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
286 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
287 Failed = true;
288 return nullptr;
289 }
290 LookupQualifiedName(Found, LookupCtx);
291 return CheckLookupResult(Found);
292 };
293
294 auto LookupInScope = [&]() -> ParsedType {
295 if (Failed || !S)
296 return nullptr;
297
298 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
299 LookupName(Found, S);
300 return CheckLookupResult(Found);
301 };
302
303 // C++2a [basic.lookup.qual]p6:
304 // In a qualified-id of the form
305 //
306 // nested-name-specifier[opt] type-name :: ~ type-name
307 //
308 // the second type-name is looked up in the same scope as the first.
309 //
310 // We interpret this as meaning that if you do a dual-scope lookup for the
311 // first name, you also do a dual-scope lookup for the second name, per
312 // C++ [basic.lookup.classref]p4:
313 //
314 // If the id-expression in a class member access is a qualified-id of the
315 // form
316 //
317 // class-name-or-namespace-name :: ...
318 //
319 // the class-name-or-namespace-name following the . or -> is first looked
320 // up in the class of the object expression and the name, if found, is used.
321 // Otherwise, it is looked up in the context of the entire
322 // postfix-expression.
323 //
324 // This looks in the same scopes as for an unqualified destructor name:
325 //
326 // C++ [basic.lookup.classref]p3:
327 // If the unqualified-id is ~ type-name, the type-name is looked up
328 // in the context of the entire postfix-expression. If the type T
329 // of the object expression is of a class type C, the type-name is
330 // also looked up in the scope of class C. At least one of the
331 // lookups shall find a name that refers to cv T.
332 //
333 // FIXME: The intent is unclear here. Should type-name::~type-name look in
334 // the scope anyway if it finds a non-matching name declared in the class?
335 // If both lookups succeed and find a dependent result, which result should
336 // we retain? (Same question for p->~type-name().)
337
338 if (NestedNameSpecifier *Prefix =
339 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
340 // This is
341 //
342 // nested-name-specifier type-name :: ~ type-name
343 //
344 // Look for the second type-name in the nested-name-specifier.
345 CXXScopeSpec PrefixSS;
346 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
347 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
348 return T;
349 } else {
350 // This is one of
351 //
352 // type-name :: ~ type-name
353 // ~ type-name
354 //
355 // Look in the scope and (if any) the object type.
356 if (ParsedType T = LookupInScope())
357 return T;
358 if (ParsedType T = LookupInObjectType())
359 return T;
360 }
361
362 if (Failed)
363 return nullptr;
364
365 if (IsDependent) {
366 // We didn't find our type, but that's OK: it's dependent anyway.
367
368 // FIXME: What if we have no nested-name-specifier?
369 QualType T =
371 SS.getWithLocInContext(Context), II, NameLoc);
372 return ParsedType::make(T);
373 }
374
375 // The remaining cases are all non-standard extensions imitating the behavior
376 // of various other compilers.
377 unsigned NumNonExtensionDecls = FoundDecls.size();
378
379 if (SS.isSet()) {
380 // For compatibility with older broken C++ rules and existing code,
381 //
382 // nested-name-specifier :: ~ type-name
383 //
384 // also looks for type-name within the nested-name-specifier.
385 if (ParsedType T = LookupInNestedNameSpec(SS)) {
386 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
387 << SS.getRange()
389 ("::" + II.getName()).str());
390 return T;
391 }
392
393 // For compatibility with other compilers and older versions of Clang,
394 //
395 // nested-name-specifier type-name :: ~ type-name
396 //
397 // also looks for type-name in the scope. Unfortunately, we can't
398 // reasonably apply this fallback for dependent nested-name-specifiers.
399 if (SS.isValid() && SS.getScopeRep()->getPrefix()) {
400 if (ParsedType T = LookupInScope()) {
401 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
403 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
405 return T;
406 }
407 }
408 }
409
410 // We didn't find anything matching; tell the user what we did find (if
411 // anything).
412
413 // Don't tell the user about declarations we shouldn't have found.
414 FoundDecls.resize(NumNonExtensionDecls);
415
416 // List types before non-types.
417 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
418 [](NamedDecl *A, NamedDecl *B) {
419 return isa<TypeDecl>(A->getUnderlyingDecl()) >
420 isa<TypeDecl>(B->getUnderlyingDecl());
421 });
422
423 // Suggest a fixit to properly name the destroyed type.
424 auto MakeFixItHint = [&]{
425 const CXXRecordDecl *Destroyed = nullptr;
426 // FIXME: If we have a scope specifier, suggest its last component?
427 if (!SearchType.isNull())
428 Destroyed = SearchType->getAsCXXRecordDecl();
429 else if (S)
430 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
431 if (Destroyed)
433 Destroyed->getNameAsString());
434 return FixItHint();
435 };
436
437 if (FoundDecls.empty()) {
438 // FIXME: Attempt typo-correction?
439 Diag(NameLoc, diag::err_undeclared_destructor_name)
440 << &II << MakeFixItHint();
441 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
442 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
443 assert(!SearchType.isNull() &&
444 "should only reject a type result if we have a search type");
446 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
447 << T << SearchType << MakeFixItHint();
448 } else {
449 Diag(NameLoc, diag::err_destructor_expr_nontype)
450 << &II << MakeFixItHint();
451 }
452 } else {
453 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
454 : diag::err_destructor_expr_mismatch)
455 << &II << SearchType << MakeFixItHint();
456 }
457
458 for (NamedDecl *FoundD : FoundDecls) {
459 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
460 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
462 else
463 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
464 << FoundD;
465 }
466
467 return nullptr;
468}
469
471 ParsedType ObjectType) {
473 return nullptr;
474
476 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
477 return nullptr;
478 }
479
481 "unexpected type in getDestructorType");
483
484 // If we know the type of the object, check that the correct destructor
485 // type was named now; we can give better diagnostics this way.
486 QualType SearchType = GetTypeFromParser(ObjectType);
487 if (!SearchType.isNull() && !SearchType->isDependentType() &&
488 !Context.hasSameUnqualifiedType(T, SearchType)) {
489 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
490 << T << SearchType;
491 return nullptr;
492 }
493
494 return ParsedType::make(T);
495}
496
498 const UnqualifiedId &Name, bool IsUDSuffix) {
499 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
500 if (!IsUDSuffix) {
501 // [over.literal] p8
502 //
503 // double operator""_Bq(long double); // OK: not a reserved identifier
504 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
505 const IdentifierInfo *II = Name.Identifier;
507 SourceLocation Loc = Name.getEndLoc();
509 if (auto Hint = FixItHint::CreateReplacement(
510 Name.getSourceRange(),
511 (StringRef("operator\"\"") + II->getName()).str());
512 isReservedInAllContexts(Status)) {
513 Diag(Loc, diag::warn_reserved_extern_symbol)
514 << II << static_cast<int>(Status) << Hint;
515 } else {
516 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
517 }
518 }
519 }
520
521 if (!SS.isValid())
522 return false;
523
524 switch (SS.getScopeRep()->getKind()) {
528 // Per C++11 [over.literal]p2, literal operators can only be declared at
529 // namespace scope. Therefore, this unqualified-id cannot name anything.
530 // Reject it early, because we have no AST representation for this in the
531 // case where the scope is dependent.
532 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
533 << SS.getScopeRep();
534 return true;
535
540 return false;
541 }
542
543 llvm_unreachable("unknown nested name specifier kind");
544}
545
546/// Build a C++ typeid expression with a type operand.
548 SourceLocation TypeidLoc,
549 TypeSourceInfo *Operand,
550 SourceLocation RParenLoc) {
551 // C++ [expr.typeid]p4:
552 // The top-level cv-qualifiers of the lvalue expression or the type-id
553 // that is the operand of typeid are always ignored.
554 // If the type of the type-id is a class type or a reference to a class
555 // type, the class shall be completely-defined.
556 Qualifiers Quals;
557 QualType T
558 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
559 Quals);
560 if (T->getAs<RecordType>() &&
561 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
562 return ExprError();
563
565 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
566
567 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
568 return ExprError();
569
570 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
571 SourceRange(TypeidLoc, RParenLoc));
572}
573
574/// Build a C++ typeid expression with an expression operand.
576 SourceLocation TypeidLoc,
577 Expr *E,
578 SourceLocation RParenLoc) {
579 bool WasEvaluated = false;
580 if (E && !E->isTypeDependent()) {
581 if (E->hasPlaceholderType()) {
583 if (result.isInvalid()) return ExprError();
584 E = result.get();
585 }
586
587 QualType T = E->getType();
588 if (const RecordType *RecordT = T->getAs<RecordType>()) {
589 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
590 // C++ [expr.typeid]p3:
591 // [...] If the type of the expression is a class type, the class
592 // shall be completely-defined.
593 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
594 return ExprError();
595
596 // C++ [expr.typeid]p3:
597 // When typeid is applied to an expression other than an glvalue of a
598 // polymorphic class type [...] [the] expression is an unevaluated
599 // operand. [...]
600 if (RecordD->isPolymorphic() && E->isGLValue()) {
601 if (isUnevaluatedContext()) {
602 // The operand was processed in unevaluated context, switch the
603 // context and recheck the subexpression.
605 if (Result.isInvalid())
606 return ExprError();
607 E = Result.get();
608 }
609
610 // We require a vtable to query the type at run time.
611 MarkVTableUsed(TypeidLoc, RecordD);
612 WasEvaluated = true;
613 }
614 }
615
617 if (Result.isInvalid())
618 return ExprError();
619 E = Result.get();
620
621 // C++ [expr.typeid]p4:
622 // [...] If the type of the type-id is a reference to a possibly
623 // cv-qualified type, the result of the typeid expression refers to a
624 // std::type_info object representing the cv-unqualified referenced
625 // type.
626 Qualifiers Quals;
627 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
628 if (!Context.hasSameType(T, UnqualT)) {
629 T = UnqualT;
630 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
631 }
632 }
633
635 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
636 << E->getType());
637 else if (!inTemplateInstantiation() &&
638 E->HasSideEffects(Context, WasEvaluated)) {
639 // The expression operand for typeid is in an unevaluated expression
640 // context, so side effects could result in unintended consequences.
641 Diag(E->getExprLoc(), WasEvaluated
642 ? diag::warn_side_effects_typeid
643 : diag::warn_side_effects_unevaluated_context);
644 }
645
646 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
647 SourceRange(TypeidLoc, RParenLoc));
648}
649
650/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
653 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
654 // typeid is not supported in OpenCL.
655 if (getLangOpts().OpenCLCPlusPlus) {
656 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
657 << "typeid");
658 }
659
660 // Find the std::type_info type.
661 if (!getStdNamespace())
662 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
663
664 if (!CXXTypeInfoDecl) {
665 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
666 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
669 // Microsoft's typeinfo doesn't have type_info in std but in the global
670 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
671 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
674 }
675 if (!CXXTypeInfoDecl)
676 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
677 }
678
679 if (!getLangOpts().RTTI) {
680 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
681 }
682
684
685 if (isType) {
686 // The operand is a type; handle it as such.
687 TypeSourceInfo *TInfo = nullptr;
689 &TInfo);
690 if (T.isNull())
691 return ExprError();
692
693 if (!TInfo)
694 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
695
696 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
697 }
698
699 // The operand is an expression.
701 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
702
703 if (!getLangOpts().RTTIData && !Result.isInvalid())
704 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
705 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
706 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
707 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
709 return Result;
710}
711
712/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
713/// a single GUID.
714static void
717 // Optionally remove one level of pointer, reference or array indirection.
718 const Type *Ty = QT.getTypePtr();
719 if (QT->isPointerType() || QT->isReferenceType())
720 Ty = QT->getPointeeType().getTypePtr();
721 else if (QT->isArrayType())
722 Ty = Ty->getBaseElementTypeUnsafe();
723
724 const auto *TD = Ty->getAsTagDecl();
725 if (!TD)
726 return;
727
728 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
729 UuidAttrs.insert(Uuid);
730 return;
731 }
732
733 // __uuidof can grab UUIDs from template arguments.
734 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
735 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
736 for (const TemplateArgument &TA : TAL.asArray()) {
737 const UuidAttr *UuidForTA = nullptr;
738 if (TA.getKind() == TemplateArgument::Type)
739 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
740 else if (TA.getKind() == TemplateArgument::Declaration)
741 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
742
743 if (UuidForTA)
744 UuidAttrs.insert(UuidForTA);
745 }
746 }
747}
748
749/// Build a Microsoft __uuidof expression with a type operand.
751 SourceLocation TypeidLoc,
752 TypeSourceInfo *Operand,
753 SourceLocation RParenLoc) {
754 MSGuidDecl *Guid = nullptr;
755 if (!Operand->getType()->isDependentType()) {
757 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
758 if (UuidAttrs.empty())
759 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
760 if (UuidAttrs.size() > 1)
761 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
762 Guid = UuidAttrs.back()->getGuidDecl();
763 }
764
765 return new (Context)
766 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
767}
768
769/// Build a Microsoft __uuidof expression with an expression operand.
771 Expr *E, SourceLocation RParenLoc) {
772 MSGuidDecl *Guid = nullptr;
773 if (!E->getType()->isDependentType()) {
775 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
777 } else {
779 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
780 if (UuidAttrs.empty())
781 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
782 if (UuidAttrs.size() > 1)
783 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
784 Guid = UuidAttrs.back()->getGuidDecl();
785 }
786 }
787
788 return new (Context)
789 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
790}
791
792/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
795 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
796 QualType GuidType = Context.getMSGuidType();
797 GuidType.addConst();
798
799 if (isType) {
800 // The operand is a type; handle it as such.
801 TypeSourceInfo *TInfo = nullptr;
803 &TInfo);
804 if (T.isNull())
805 return ExprError();
806
807 if (!TInfo)
808 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
809
810 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
811 }
812
813 // The operand is an expression.
814 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
815}
816
817/// ActOnCXXBoolLiteral - Parse {true,false} literals.
820 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
821 "Unknown C++ Boolean value!");
822 return new (Context)
823 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
824}
825
826/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
830}
831
832/// ActOnCXXThrow - Parse throw expressions.
835 bool IsThrownVarInScope = false;
836 if (Ex) {
837 // C++0x [class.copymove]p31:
838 // When certain criteria are met, an implementation is allowed to omit the
839 // copy/move construction of a class object [...]
840 //
841 // - in a throw-expression, when the operand is the name of a
842 // non-volatile automatic object (other than a function or catch-
843 // clause parameter) whose scope does not extend beyond the end of the
844 // innermost enclosing try-block (if there is one), the copy/move
845 // operation from the operand to the exception object (15.1) can be
846 // omitted by constructing the automatic object directly into the
847 // exception object
848 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
849 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());
850 Var && Var->hasLocalStorage() &&
851 !Var->getType().isVolatileQualified()) {
852 for (; S; S = S->getParent()) {
853 if (S->isDeclScope(Var)) {
854 IsThrownVarInScope = true;
855 break;
856 }
857
858 // FIXME: Many of the scope checks here seem incorrect.
859 if (S->getFlags() &
862 break;
863 }
864 }
865 }
866
867 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
868}
869
871 bool IsThrownVarInScope) {
872 const llvm::Triple &T = Context.getTargetInfo().getTriple();
873 const bool IsOpenMPGPUTarget =
874 getLangOpts().OpenMPIsTargetDevice && (T.isNVPTX() || T.isAMDGCN());
875 // Don't report an error if 'throw' is used in system headers or in an OpenMP
876 // target region compiled for a GPU architecture.
877 if (!IsOpenMPGPUTarget && !getLangOpts().CXXExceptions &&
878 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
879 // Delay error emission for the OpenMP device code.
880 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
881 }
882
883 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
884 if (IsOpenMPGPUTarget)
885 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
886
887 // Exceptions aren't allowed in CUDA device code.
888 if (getLangOpts().CUDA)
889 CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
890 << "throw" << llvm::to_underlying(CUDA().CurrentTarget());
891
892 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
893 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
894
895 // Exceptions that escape a compute construct are ill-formed.
896 if (getLangOpts().OpenACC && getCurScope() &&
897 getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))
898 Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)
899 << /*throw*/ 2 << /*out of*/ 0;
900
901 if (Ex && !Ex->isTypeDependent()) {
902 // Initialize the exception result. This implicitly weeds out
903 // abstract types or types with inaccessible copy constructors.
904
905 // C++0x [class.copymove]p31:
906 // When certain criteria are met, an implementation is allowed to omit the
907 // copy/move construction of a class object [...]
908 //
909 // - in a throw-expression, when the operand is the name of a
910 // non-volatile automatic object (other than a function or
911 // catch-clause
912 // parameter) whose scope does not extend beyond the end of the
913 // innermost enclosing try-block (if there is one), the copy/move
914 // operation from the operand to the exception object (15.1) can be
915 // omitted by constructing the automatic object directly into the
916 // exception object
917 NamedReturnInfo NRInfo =
918 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
919
920 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
921 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
922 return ExprError();
923
924 InitializedEntity Entity =
925 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
926 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
927 if (Res.isInvalid())
928 return ExprError();
929 Ex = Res.get();
930 }
931
932 // PPC MMA non-pointer types are not allowed as throw expr types.
933 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
934 CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
935
936 return new (Context)
937 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
938}
939
940static void
942 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
943 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
944 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
945 bool ParentIsPublic) {
946 for (const CXXBaseSpecifier &BS : RD->bases()) {
947 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
948 bool NewSubobject;
949 // Virtual bases constitute the same subobject. Non-virtual bases are
950 // always distinct subobjects.
951 if (BS.isVirtual())
952 NewSubobject = VBases.insert(BaseDecl).second;
953 else
954 NewSubobject = true;
955
956 if (NewSubobject)
957 ++SubobjectsSeen[BaseDecl];
958
959 // Only add subobjects which have public access throughout the entire chain.
960 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
961 if (PublicPath)
962 PublicSubobjectsSeen.insert(BaseDecl);
963
964 // Recurse on to each base subobject.
965 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
966 PublicPath);
967 }
968}
969
972 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
973 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
974 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
975 SubobjectsSeen[RD] = 1;
976 PublicSubobjectsSeen.insert(RD);
977 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
978 /*ParentIsPublic=*/true);
979
980 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
981 // Skip ambiguous objects.
982 if (SubobjectsSeen[PublicSubobject] > 1)
983 continue;
984
985 Objects.push_back(PublicSubobject);
986 }
987}
988
989/// CheckCXXThrowOperand - Validate the operand of a throw.
991 QualType ExceptionObjectTy, Expr *E) {
992 // If the type of the exception would be an incomplete type or a pointer
993 // to an incomplete type other than (cv) void the program is ill-formed.
994 QualType Ty = ExceptionObjectTy;
995 bool isPointer = false;
996 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
997 Ty = Ptr->getPointeeType();
998 isPointer = true;
999 }
1000
1001 // Cannot throw WebAssembly reference type.
1002 if (Ty.isWebAssemblyReferenceType()) {
1003 Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
1004 return true;
1005 }
1006
1007 // Cannot throw WebAssembly table.
1008 if (isPointer && Ty.isWebAssemblyReferenceType()) {
1009 Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();
1010 return true;
1011 }
1012
1013 if (!isPointer || !Ty->isVoidType()) {
1014 if (RequireCompleteType(ThrowLoc, Ty,
1015 isPointer ? diag::err_throw_incomplete_ptr
1016 : diag::err_throw_incomplete,
1017 E->getSourceRange()))
1018 return true;
1019
1020 if (!isPointer && Ty->isSizelessType()) {
1021 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
1022 return true;
1023 }
1024
1025 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
1026 diag::err_throw_abstract_type, E))
1027 return true;
1028 }
1029
1030 // If the exception has class type, we need additional handling.
1032 if (!RD)
1033 return false;
1034
1035 // If we are throwing a polymorphic class type or pointer thereof,
1036 // exception handling will make use of the vtable.
1037 MarkVTableUsed(ThrowLoc, RD);
1038
1039 // If a pointer is thrown, the referenced object will not be destroyed.
1040 if (isPointer)
1041 return false;
1042
1043 // If the class has a destructor, we must be able to call it.
1044 if (!RD->hasIrrelevantDestructor()) {
1048 PDiag(diag::err_access_dtor_exception) << Ty);
1050 return true;
1051 }
1052 }
1053
1054 // The MSVC ABI creates a list of all types which can catch the exception
1055 // object. This list also references the appropriate copy constructor to call
1056 // if the object is caught by value and has a non-trivial copy constructor.
1058 // We are only interested in the public, unambiguous bases contained within
1059 // the exception object. Bases which are ambiguous or otherwise
1060 // inaccessible are not catchable types.
1061 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1062 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1063
1064 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1065 // Attempt to lookup the copy constructor. Various pieces of machinery
1066 // will spring into action, like template instantiation, which means this
1067 // cannot be a simple walk of the class's decls. Instead, we must perform
1068 // lookup and overload resolution.
1069 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1070 if (!CD || CD->isDeleted())
1071 continue;
1072
1073 // Mark the constructor referenced as it is used by this throw expression.
1075
1076 // Skip this copy constructor if it is trivial, we don't need to record it
1077 // in the catchable type data.
1078 if (CD->isTrivial())
1079 continue;
1080
1081 // The copy constructor is non-trivial, create a mapping from this class
1082 // type to this constructor.
1083 // N.B. The selection of copy constructor is not sensitive to this
1084 // particular throw-site. Lookup will be performed at the catch-site to
1085 // ensure that the copy constructor is, in fact, accessible (via
1086 // friendship or any other means).
1088
1089 // We don't keep the instantiated default argument expressions around so
1090 // we must rebuild them here.
1091 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1092 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1093 return true;
1094 }
1095 }
1096 }
1097
1098 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1099 // the runtime with no ability for the compiler to request additional
1100 // alignment. Warn if the exception type requires alignment beyond the minimum
1101 // guaranteed by the target C++ runtime.
1103 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1104 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1105 if (ExnObjAlign < TypeAlign) {
1106 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1107 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1108 << Ty << (unsigned)TypeAlign.getQuantity()
1109 << (unsigned)ExnObjAlign.getQuantity();
1110 }
1111 }
1112 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1113 if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1114 auto Ty = Dtor->getType();
1115 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1116 if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&
1117 !FT->isNothrow())
1118 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1119 }
1120 }
1121 }
1122
1123 return false;
1124}
1125
1127 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1128 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1129
1130 QualType ClassType = ThisTy->getPointeeType();
1131 LambdaScopeInfo *CurLSI = nullptr;
1132 DeclContext *CurDC = CurSemaContext;
1133
1134 // Iterate through the stack of lambdas starting from the innermost lambda to
1135 // the outermost lambda, checking if '*this' is ever captured by copy - since
1136 // that could change the cv-qualifiers of the '*this' object.
1137 // The object referred to by '*this' starts out with the cv-qualifiers of its
1138 // member function. We then start with the innermost lambda and iterate
1139 // outward checking to see if any lambda performs a by-copy capture of '*this'
1140 // - and if so, any nested lambda must respect the 'constness' of that
1141 // capturing lamdbda's call operator.
1142 //
1143
1144 // Since the FunctionScopeInfo stack is representative of the lexical
1145 // nesting of the lambda expressions during initial parsing (and is the best
1146 // place for querying information about captures about lambdas that are
1147 // partially processed) and perhaps during instantiation of function templates
1148 // that contain lambda expressions that need to be transformed BUT not
1149 // necessarily during instantiation of a nested generic lambda's function call
1150 // operator (which might even be instantiated at the end of the TU) - at which
1151 // time the DeclContext tree is mature enough to query capture information
1152 // reliably - we use a two pronged approach to walk through all the lexically
1153 // enclosing lambda expressions:
1154 //
1155 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1156 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1157 // enclosed by the call-operator of the LSI below it on the stack (while
1158 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1159 // the stack represents the innermost lambda.
1160 //
1161 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1162 // represents a lambda's call operator. If it does, we must be instantiating
1163 // a generic lambda's call operator (represented by the Current LSI, and
1164 // should be the only scenario where an inconsistency between the LSI and the
1165 // DeclContext should occur), so climb out the DeclContexts if they
1166 // represent lambdas, while querying the corresponding closure types
1167 // regarding capture information.
1168
1169 // 1) Climb down the function scope info stack.
1170 for (int I = FunctionScopes.size();
1171 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1172 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1173 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1174 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1175 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1176
1177 if (!CurLSI->isCXXThisCaptured())
1178 continue;
1179
1180 auto C = CurLSI->getCXXThisCapture();
1181
1182 if (C.isCopyCapture()) {
1183 if (CurLSI->lambdaCaptureShouldBeConst())
1184 ClassType.addConst();
1185 return ASTCtx.getPointerType(ClassType);
1186 }
1187 }
1188
1189 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1190 // can happen during instantiation of its nested generic lambda call
1191 // operator); 2. if we're in a lambda scope (lambda body).
1192 if (CurLSI && isLambdaCallOperator(CurDC)) {
1194 "While computing 'this' capture-type for a generic lambda, when we "
1195 "run out of enclosing LSI's, yet the enclosing DC is a "
1196 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1197 "lambda call oeprator");
1198 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1199
1200 auto IsThisCaptured =
1201 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1202 IsConst = false;
1203 IsByCopy = false;
1204 for (auto &&C : Closure->captures()) {
1205 if (C.capturesThis()) {
1206 if (C.getCaptureKind() == LCK_StarThis)
1207 IsByCopy = true;
1208 if (Closure->getLambdaCallOperator()->isConst())
1209 IsConst = true;
1210 return true;
1211 }
1212 }
1213 return false;
1214 };
1215
1216 bool IsByCopyCapture = false;
1217 bool IsConstCapture = false;
1218 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1219 while (Closure &&
1220 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1221 if (IsByCopyCapture) {
1222 if (IsConstCapture)
1223 ClassType.addConst();
1224 return ASTCtx.getPointerType(ClassType);
1225 }
1226 Closure = isLambdaCallOperator(Closure->getParent())
1227 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1228 : nullptr;
1229 }
1230 }
1231 return ThisTy;
1232}
1233
1237
1238 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1239 if (method && method->isImplicitObjectMemberFunction())
1240 ThisTy = method->getThisType().getNonReferenceType();
1241 }
1242
1244 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1245
1246 // This is a lambda call operator that is being instantiated as a default
1247 // initializer. DC must point to the enclosing class type, so we can recover
1248 // the 'this' type from it.
1249 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1250 // There are no cv-qualifiers for 'this' within default initializers,
1251 // per [expr.prim.general]p4.
1252 ThisTy = Context.getPointerType(ClassTy);
1253 }
1254
1255 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1256 // might need to be adjusted if the lambda or any of its enclosing lambda's
1257 // captures '*this' by copy.
1258 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1261 return ThisTy;
1262}
1263
1265 Decl *ContextDecl,
1266 Qualifiers CXXThisTypeQuals,
1267 bool Enabled)
1268 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1269{
1270 if (!Enabled || !ContextDecl)
1271 return;
1272
1273 CXXRecordDecl *Record = nullptr;
1274 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1275 Record = Template->getTemplatedDecl();
1276 else
1277 Record = cast<CXXRecordDecl>(ContextDecl);
1278
1280 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1281
1283 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1284
1285 this->Enabled = true;
1286}
1287
1288
1290 if (Enabled) {
1291 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1292 }
1293}
1294
1296 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1297 assert(!LSI->isCXXThisCaptured());
1298 // [=, this] {}; // until C++20: Error: this when = is the default
1300 !Sema.getLangOpts().CPlusPlus20)
1301 return;
1302 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1304 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1305}
1306
1308 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1309 const bool ByCopy) {
1310 // We don't need to capture this in an unevaluated context.
1311 if (isUnevaluatedContext() && !Explicit)
1312 return true;
1313
1314 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1315
1316 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1317 ? *FunctionScopeIndexToStopAt
1318 : FunctionScopes.size() - 1;
1319
1320 // Check that we can capture the *enclosing object* (referred to by '*this')
1321 // by the capturing-entity/closure (lambda/block/etc) at
1322 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1323
1324 // Note: The *enclosing object* can only be captured by-value by a
1325 // closure that is a lambda, using the explicit notation:
1326 // [*this] { ... }.
1327 // Every other capture of the *enclosing object* results in its by-reference
1328 // capture.
1329
1330 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1331 // stack), we can capture the *enclosing object* only if:
1332 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1333 // - or, 'L' has an implicit capture.
1334 // AND
1335 // -- there is no enclosing closure
1336 // -- or, there is some enclosing closure 'E' that has already captured the
1337 // *enclosing object*, and every intervening closure (if any) between 'E'
1338 // and 'L' can implicitly capture the *enclosing object*.
1339 // -- or, every enclosing closure can implicitly capture the
1340 // *enclosing object*
1341
1342
1343 unsigned NumCapturingClosures = 0;
1344 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1345 if (CapturingScopeInfo *CSI =
1346 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1347 if (CSI->CXXThisCaptureIndex != 0) {
1348 // 'this' is already being captured; there isn't anything more to do.
1349 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1350 break;
1351 }
1352 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1354 // This context can't implicitly capture 'this'; fail out.
1355 if (BuildAndDiagnose) {
1357 Diag(Loc, diag::err_this_capture)
1358 << (Explicit && idx == MaxFunctionScopesIndex);
1359 if (!Explicit)
1360 buildLambdaThisCaptureFixit(*this, LSI);
1361 }
1362 return true;
1363 }
1364 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1365 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1366 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1367 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1368 (Explicit && idx == MaxFunctionScopesIndex)) {
1369 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1370 // iteration through can be an explicit capture, all enclosing closures,
1371 // if any, must perform implicit captures.
1372
1373 // This closure can capture 'this'; continue looking upwards.
1374 NumCapturingClosures++;
1375 continue;
1376 }
1377 // This context can't implicitly capture 'this'; fail out.
1378 if (BuildAndDiagnose) {
1380 Diag(Loc, diag::err_this_capture)
1381 << (Explicit && idx == MaxFunctionScopesIndex);
1382 }
1383 if (!Explicit)
1384 buildLambdaThisCaptureFixit(*this, LSI);
1385 return true;
1386 }
1387 break;
1388 }
1389 if (!BuildAndDiagnose) return false;
1390
1391 // If we got here, then the closure at MaxFunctionScopesIndex on the
1392 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1393 // (including implicit by-reference captures in any enclosing closures).
1394
1395 // In the loop below, respect the ByCopy flag only for the closure requesting
1396 // the capture (i.e. first iteration through the loop below). Ignore it for
1397 // all enclosing closure's up to NumCapturingClosures (since they must be
1398 // implicitly capturing the *enclosing object* by reference (see loop
1399 // above)).
1400 assert((!ByCopy ||
1401 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1402 "Only a lambda can capture the enclosing object (referred to by "
1403 "*this) by copy");
1404 QualType ThisTy = getCurrentThisType();
1405 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1406 --idx, --NumCapturingClosures) {
1407 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1408
1409 // The type of the corresponding data member (not a 'this' pointer if 'by
1410 // copy').
1411 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1412
1413 bool isNested = NumCapturingClosures > 1;
1414 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1415 }
1416 return false;
1417}
1418
1420 // C++20 [expr.prim.this]p1:
1421 // The keyword this names a pointer to the object for which an
1422 // implicit object member function is invoked or a non-static
1423 // data member's initializer is evaluated.
1424 QualType ThisTy = getCurrentThisType();
1425
1426 if (CheckCXXThisType(Loc, ThisTy))
1427 return ExprError();
1428
1429 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1430}
1431
1433 if (!Type.isNull())
1434 return false;
1435
1436 // C++20 [expr.prim.this]p3:
1437 // If a declaration declares a member function or member function template
1438 // of a class X, the expression this is a prvalue of type
1439 // "pointer to cv-qualifier-seq X" wherever X is the current class between
1440 // the optional cv-qualifier-seq and the end of the function-definition,
1441 // member-declarator, or declarator. It shall not appear within the
1442 // declaration of either a static member function or an explicit object
1443 // member function of the current class (although its type and value
1444 // category are defined within such member functions as they are within
1445 // an implicit object member function).
1447 if (const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1448 Method && Method->isExplicitObjectMemberFunction()) {
1449 Diag(Loc, diag::err_invalid_this_use) << 1;
1451 Diag(Loc, diag::err_invalid_this_use) << 1;
1452 } else {
1453 Diag(Loc, diag::err_invalid_this_use) << 0;
1454 }
1455 return true;
1456}
1457
1459 bool IsImplicit) {
1460 auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);
1461 MarkThisReferenced(This);
1462 return This;
1463}
1464
1466 CheckCXXThisCapture(This->getExprLoc());
1467 if (This->isTypeDependent())
1468 return;
1469
1470 // Check if 'this' is captured by value in a lambda with a dependent explicit
1471 // object parameter, and mark it as type-dependent as well if so.
1472 auto IsDependent = [&]() {
1473 for (auto *Scope : llvm::reverse(FunctionScopes)) {
1474 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
1475 if (!LSI)
1476 continue;
1477
1478 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
1479 LSI->AfterParameterList)
1480 return false;
1481
1482 // If this lambda captures 'this' by value, then 'this' is dependent iff
1483 // this lambda has a dependent explicit object parameter. If we can't
1484 // determine whether it does (e.g. because the CXXMethodDecl's type is
1485 // null), assume it doesn't.
1486 if (LSI->isCXXThisCaptured()) {
1487 if (!LSI->getCXXThisCapture().isCopyCapture())
1488 continue;
1489
1490 const auto *MD = LSI->CallOperator;
1491 if (MD->getType().isNull())
1492 return false;
1493
1494 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
1495 return Ty && MD->isExplicitObjectMemberFunction() &&
1496 Ty->getParamType(0)->isDependentType();
1497 }
1498 }
1499 return false;
1500 }();
1501
1502 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);
1503}
1504
1506 // If we're outside the body of a member function, then we'll have a specified
1507 // type for 'this'.
1509 return false;
1510
1511 // Determine whether we're looking into a class that's currently being
1512 // defined.
1513 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1514 return Class && Class->isBeingDefined();
1515}
1516
1517/// Parse construction of a specified type.
1518/// Can be interpreted either as function-style casting ("int(x)")
1519/// or class type construction ("ClassType(x,y,z)")
1520/// or creation of a value-initialized type ("int()").
1523 SourceLocation LParenOrBraceLoc,
1524 MultiExprArg exprs,
1525 SourceLocation RParenOrBraceLoc,
1526 bool ListInitialization) {
1527 if (!TypeRep)
1528 return ExprError();
1529
1530 TypeSourceInfo *TInfo;
1531 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1532 if (!TInfo)
1534
1535 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1536 RParenOrBraceLoc, ListInitialization);
1537 // Avoid creating a non-type-dependent expression that contains typos.
1538 // Non-type-dependent expressions are liable to be discarded without
1539 // checking for embedded typos.
1540 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1541 !Result.get()->isTypeDependent())
1543 else if (Result.isInvalid())
1545 RParenOrBraceLoc, exprs, Ty);
1546 return Result;
1547}
1548
1551 SourceLocation LParenOrBraceLoc,
1552 MultiExprArg Exprs,
1553 SourceLocation RParenOrBraceLoc,
1554 bool ListInitialization) {
1555 QualType Ty = TInfo->getType();
1556 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1557
1558 assert((!ListInitialization || Exprs.size() == 1) &&
1559 "List initialization must have exactly one expression.");
1560 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1561
1562 InitializedEntity Entity =
1564 InitializationKind Kind =
1565 Exprs.size()
1566 ? ListInitialization
1568 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1569 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1570 RParenOrBraceLoc)
1571 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1572 RParenOrBraceLoc);
1573
1574 // C++17 [expr.type.conv]p1:
1575 // If the type is a placeholder for a deduced class type, [...perform class
1576 // template argument deduction...]
1577 // C++23:
1578 // Otherwise, if the type contains a placeholder type, it is replaced by the
1579 // type determined by placeholder type deduction.
1580 DeducedType *Deduced = Ty->getContainedDeducedType();
1581 if (Deduced && !Deduced->isDeduced() &&
1582 isa<DeducedTemplateSpecializationType>(Deduced)) {
1584 Kind, Exprs);
1585 if (Ty.isNull())
1586 return ExprError();
1587 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1588 } else if (Deduced && !Deduced->isDeduced()) {
1589 MultiExprArg Inits = Exprs;
1590 if (ListInitialization) {
1591 auto *ILE = cast<InitListExpr>(Exprs[0]);
1592 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1593 }
1594
1595 if (Inits.empty())
1596 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1597 << Ty << FullRange);
1598 if (Inits.size() > 1) {
1599 Expr *FirstBad = Inits[1];
1600 return ExprError(Diag(FirstBad->getBeginLoc(),
1601 diag::err_auto_expr_init_multiple_expressions)
1602 << Ty << FullRange);
1603 }
1604 if (getLangOpts().CPlusPlus23) {
1605 if (Ty->getAs<AutoType>())
1606 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1607 }
1608 Expr *Deduce = Inits[0];
1609 if (isa<InitListExpr>(Deduce))
1610 return ExprError(
1611 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1612 << ListInitialization << Ty << FullRange);
1614 TemplateDeductionInfo Info(Deduce->getExprLoc());
1616 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1619 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1620 << Ty << Deduce->getType() << FullRange
1621 << Deduce->getSourceRange());
1622 if (DeducedType.isNull()) {
1624 return ExprError();
1625 }
1626
1627 Ty = DeducedType;
1628 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1629 }
1630
1633 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1634 RParenOrBraceLoc, ListInitialization);
1635
1636 // C++ [expr.type.conv]p1:
1637 // If the expression list is a parenthesized single expression, the type
1638 // conversion expression is equivalent (in definedness, and if defined in
1639 // meaning) to the corresponding cast expression.
1640 if (Exprs.size() == 1 && !ListInitialization &&
1641 !isa<InitListExpr>(Exprs[0])) {
1642 Expr *Arg = Exprs[0];
1643 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1644 RParenOrBraceLoc);
1645 }
1646
1647 // For an expression of the form T(), T shall not be an array type.
1648 QualType ElemTy = Ty;
1649 if (Ty->isArrayType()) {
1650 if (!ListInitialization)
1651 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1652 << FullRange);
1653 ElemTy = Context.getBaseElementType(Ty);
1654 }
1655
1656 // Only construct objects with object types.
1657 // The standard doesn't explicitly forbid function types here, but that's an
1658 // obvious oversight, as there's no way to dynamically construct a function
1659 // in general.
1660 if (Ty->isFunctionType())
1661 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1662 << Ty << FullRange);
1663
1664 // C++17 [expr.type.conv]p2:
1665 // If the type is cv void and the initializer is (), the expression is a
1666 // prvalue of the specified type that performs no initialization.
1667 if (!Ty->isVoidType() &&
1668 RequireCompleteType(TyBeginLoc, ElemTy,
1669 diag::err_invalid_incomplete_type_use, FullRange))
1670 return ExprError();
1671
1672 // Otherwise, the expression is a prvalue of the specified type whose
1673 // result object is direct-initialized (11.6) with the initializer.
1674 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1675 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1676
1677 if (Result.isInvalid())
1678 return Result;
1679
1680 Expr *Inner = Result.get();
1681 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1682 Inner = BTE->getSubExpr();
1683 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1684 CE && CE->isImmediateInvocation())
1685 Inner = CE->getSubExpr();
1686 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1687 !isa<CXXScalarValueInitExpr>(Inner)) {
1688 // If we created a CXXTemporaryObjectExpr, that node also represents the
1689 // functional cast. Otherwise, create an explicit cast to represent
1690 // the syntactic form of a functional-style cast that was used here.
1691 //
1692 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1693 // would give a more consistent AST representation than using a
1694 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1695 // is sometimes handled by initialization and sometimes not.
1696 QualType ResultType = Result.get()->getType();
1697 SourceRange Locs = ListInitialization
1698 ? SourceRange()
1699 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1701 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1702 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1703 Locs.getBegin(), Locs.getEnd());
1704 }
1705
1706 return Result;
1707}
1708
1710 // [CUDA] Ignore this function, if we can't call it.
1711 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1712 if (getLangOpts().CUDA) {
1713 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1714 // If it's not callable at all, it's not the right function.
1715 if (CallPreference < SemaCUDA::CFP_WrongSide)
1716 return false;
1717 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1718 // Maybe. We have to check if there are better alternatives.
1720 Method->getDeclContext()->lookup(Method->getDeclName());
1721 for (const auto *D : R) {
1722 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1723 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1724 return false;
1725 }
1726 }
1727 // We've found no better variants.
1728 }
1729 }
1730
1732 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1733
1734 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1735 return Result;
1736
1737 // In case of CUDA, return true if none of the 1-argument deallocator
1738 // functions are actually callable.
1739 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1740 assert(FD->getNumParams() == 1 &&
1741 "Only single-operand functions should be in PreventedBy");
1742 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1743 });
1744}
1745
1746/// Determine whether the given function is a non-placement
1747/// deallocation function.
1749 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1750 return S.isUsualDeallocationFunction(Method);
1751
1752 if (FD->getOverloadedOperator() != OO_Delete &&
1753 FD->getOverloadedOperator() != OO_Array_Delete)
1754 return false;
1755
1756 unsigned UsualParams = 1;
1757
1758 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1760 FD->getParamDecl(UsualParams)->getType(),
1761 S.Context.getSizeType()))
1762 ++UsualParams;
1763
1764 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1766 FD->getParamDecl(UsualParams)->getType(),
1768 ++UsualParams;
1769
1770 return UsualParams == FD->getNumParams();
1771}
1772
1773namespace {
1774 struct UsualDeallocFnInfo {
1775 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1776 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1777 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1778 Destroying(false), HasSizeT(false), HasAlignValT(false),
1779 CUDAPref(SemaCUDA::CFP_Native) {
1780 // A function template declaration is never a usual deallocation function.
1781 if (!FD)
1782 return;
1783 unsigned NumBaseParams = 1;
1784 if (FD->isDestroyingOperatorDelete()) {
1785 Destroying = true;
1786 ++NumBaseParams;
1787 }
1788
1789 if (NumBaseParams < FD->getNumParams() &&
1791 FD->getParamDecl(NumBaseParams)->getType(),
1792 S.Context.getSizeType())) {
1793 ++NumBaseParams;
1794 HasSizeT = true;
1795 }
1796
1797 if (NumBaseParams < FD->getNumParams() &&
1798 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1799 ++NumBaseParams;
1800 HasAlignValT = true;
1801 }
1802
1803 // In CUDA, determine how much we'd like / dislike to call this.
1804 if (S.getLangOpts().CUDA)
1805 CUDAPref = S.CUDA().IdentifyPreference(
1806 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1807 }
1808
1809 explicit operator bool() const { return FD; }
1810
1811 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1812 bool WantAlign) const {
1813 // C++ P0722:
1814 // A destroying operator delete is preferred over a non-destroying
1815 // operator delete.
1816 if (Destroying != Other.Destroying)
1817 return Destroying;
1818
1819 // C++17 [expr.delete]p10:
1820 // If the type has new-extended alignment, a function with a parameter
1821 // of type std::align_val_t is preferred; otherwise a function without
1822 // such a parameter is preferred
1823 if (HasAlignValT != Other.HasAlignValT)
1824 return HasAlignValT == WantAlign;
1825
1826 if (HasSizeT != Other.HasSizeT)
1827 return HasSizeT == WantSize;
1828
1829 // Use CUDA call preference as a tiebreaker.
1830 return CUDAPref > Other.CUDAPref;
1831 }
1832
1833 DeclAccessPair Found;
1834 FunctionDecl *FD;
1835 bool Destroying, HasSizeT, HasAlignValT;
1837 };
1838}
1839
1840/// Determine whether a type has new-extended alignment. This may be called when
1841/// the type is incomplete (for a delete-expression with an incomplete pointee
1842/// type), in which case it will conservatively return false if the alignment is
1843/// not known.
1844static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1845 return S.getLangOpts().AlignedAllocation &&
1846 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1848}
1849
1850/// Select the correct "usual" deallocation function to use from a selection of
1851/// deallocation functions (either global or class-scope).
1852static UsualDeallocFnInfo resolveDeallocationOverload(
1853 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1854 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1855 UsualDeallocFnInfo Best;
1856
1857 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1858 UsualDeallocFnInfo Info(S, I.getPair());
1859 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1860 Info.CUDAPref == SemaCUDA::CFP_Never)
1861 continue;
1862
1863 if (!Best) {
1864 Best = Info;
1865 if (BestFns)
1866 BestFns->push_back(Info);
1867 continue;
1868 }
1869
1870 if (Best.isBetterThan(Info, WantSize, WantAlign))
1871 continue;
1872
1873 // If more than one preferred function is found, all non-preferred
1874 // functions are eliminated from further consideration.
1875 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1876 BestFns->clear();
1877
1878 Best = Info;
1879 if (BestFns)
1880 BestFns->push_back(Info);
1881 }
1882
1883 return Best;
1884}
1885
1886/// Determine whether a given type is a class for which 'delete[]' would call
1887/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1888/// we need to store the array size (even if the type is
1889/// trivially-destructible).
1891 QualType allocType) {
1892 const RecordType *record =
1893 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1894 if (!record) return false;
1895
1896 // Try to find an operator delete[] in class scope.
1897
1898 DeclarationName deleteName =
1899 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1900 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1901 S.LookupQualifiedName(ops, record->getDecl());
1902
1903 // We're just doing this for information.
1904 ops.suppressDiagnostics();
1905
1906 // Very likely: there's no operator delete[].
1907 if (ops.empty()) return false;
1908
1909 // If it's ambiguous, it should be illegal to call operator delete[]
1910 // on this thing, so it doesn't matter if we allocate extra space or not.
1911 if (ops.isAmbiguous()) return false;
1912
1913 // C++17 [expr.delete]p10:
1914 // If the deallocation functions have class scope, the one without a
1915 // parameter of type std::size_t is selected.
1916 auto Best = resolveDeallocationOverload(
1917 S, ops, /*WantSize*/false,
1918 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1919 return Best && Best.HasSizeT;
1920}
1921
1922/// Parsed a C++ 'new' expression (C++ 5.3.4).
1923///
1924/// E.g.:
1925/// @code new (memory) int[size][4] @endcode
1926/// or
1927/// @code ::new Foo(23, "hello") @endcode
1928///
1929/// \param StartLoc The first location of the expression.
1930/// \param UseGlobal True if 'new' was prefixed with '::'.
1931/// \param PlacementLParen Opening paren of the placement arguments.
1932/// \param PlacementArgs Placement new arguments.
1933/// \param PlacementRParen Closing paren of the placement arguments.
1934/// \param TypeIdParens If the type is in parens, the source range.
1935/// \param D The type to be allocated, as well as array dimensions.
1936/// \param Initializer The initializing expression or initializer-list, or null
1937/// if there is none.
1939Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1940 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1941 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1943 std::optional<Expr *> ArraySize;
1944 // If the specified type is an array, unwrap it and save the expression.
1945 if (D.getNumTypeObjects() > 0 &&
1947 DeclaratorChunk &Chunk = D.getTypeObject(0);
1948 if (D.getDeclSpec().hasAutoTypeSpec())
1949 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1950 << D.getSourceRange());
1951 if (Chunk.Arr.hasStatic)
1952 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1953 << D.getSourceRange());
1954 if (!Chunk.Arr.NumElts && !Initializer)
1955 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1956 << D.getSourceRange());
1957
1958 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1960 }
1961
1962 // Every dimension shall be of constant size.
1963 if (ArraySize) {
1964 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1966 break;
1967
1969 if (Expr *NumElts = (Expr *)Array.NumElts) {
1970 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1971 // FIXME: GCC permits constant folding here. We should either do so consistently
1972 // or not do so at all, rather than changing behavior in C++14 onwards.
1973 if (getLangOpts().CPlusPlus14) {
1974 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1975 // shall be a converted constant expression (5.19) of type std::size_t
1976 // and shall evaluate to a strictly positive value.
1977 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1978 Array.NumElts
1981 .get();
1982 } else {
1983 Array.NumElts =
1985 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1986 .get();
1987 }
1988 if (!Array.NumElts)
1989 return ExprError();
1990 }
1991 }
1992 }
1993 }
1994
1996 QualType AllocType = TInfo->getType();
1997 if (D.isInvalidType())
1998 return ExprError();
1999
2000 SourceRange DirectInitRange;
2001 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
2002 DirectInitRange = List->getSourceRange();
2003
2004 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
2005 PlacementLParen, PlacementArgs, PlacementRParen,
2006 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
2007 Initializer);
2008}
2009
2011 Expr *Init, bool IsCPlusPlus20) {
2012 if (!Init)
2013 return true;
2014 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
2015 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
2016 if (isa<ImplicitValueInitExpr>(Init))
2017 return true;
2018 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
2019 return !CCE->isListInitialization() &&
2020 CCE->getConstructor()->isDefaultConstructor();
2021 else if (Style == CXXNewInitializationStyle::Braces) {
2022 assert(isa<InitListExpr>(Init) &&
2023 "Shouldn't create list CXXConstructExprs for arrays.");
2024 return true;
2025 }
2026 return false;
2027}
2028
2029bool
2031 if (!getLangOpts().AlignedAllocationUnavailable)
2032 return false;
2033 if (FD.isDefined())
2034 return false;
2035 std::optional<unsigned> AlignmentParam;
2036 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2037 AlignmentParam)
2038 return true;
2039 return false;
2040}
2041
2042// Emit a diagnostic if an aligned allocation/deallocation function that is not
2043// implemented in the standard library is selected.
2047 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2048 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2049 getASTContext().getTargetInfo().getPlatformName());
2050 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2051
2053 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
2054 Diag(Loc, diag::err_aligned_allocation_unavailable)
2055 << IsDelete << FD.getType().getAsString() << OSName
2056 << OSVersion.getAsString() << OSVersion.empty();
2057 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2058 }
2059}
2060
2062 SourceLocation PlacementLParen,
2063 MultiExprArg PlacementArgs,
2064 SourceLocation PlacementRParen,
2065 SourceRange TypeIdParens, QualType AllocType,
2066 TypeSourceInfo *AllocTypeInfo,
2067 std::optional<Expr *> ArraySize,
2068 SourceRange DirectInitRange, Expr *Initializer) {
2069 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2070 SourceLocation StartLoc = Range.getBegin();
2071
2072 CXXNewInitializationStyle InitStyle;
2073 if (DirectInitRange.isValid()) {
2074 assert(Initializer && "Have parens but no initializer.");
2076 } else if (Initializer && isa<InitListExpr>(Initializer))
2078 else {
2079 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
2080 isa<CXXConstructExpr>(Initializer)) &&
2081 "Initializer expression that cannot have been implicitly created.");
2083 }
2084
2085 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2086 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2087 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2088 "paren init for non-call init");
2089 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2090 }
2091
2092 // C++11 [expr.new]p15:
2093 // A new-expression that creates an object of type T initializes that
2094 // object as follows:
2095 InitializationKind Kind = [&] {
2096 switch (InitStyle) {
2097 // - If the new-initializer is omitted, the object is default-
2098 // initialized (8.5); if no initialization is performed,
2099 // the object has indeterminate value
2101 return InitializationKind::CreateDefault(TypeRange.getBegin());
2102 // - Otherwise, the new-initializer is interpreted according to the
2103 // initialization rules of 8.5 for direct-initialization.
2105 return InitializationKind::CreateDirect(TypeRange.getBegin(),
2106 DirectInitRange.getBegin(),
2107 DirectInitRange.getEnd());
2110 Initializer->getBeginLoc(),
2111 Initializer->getEndLoc());
2112 }
2113 llvm_unreachable("Unknown initialization kind");
2114 }();
2115
2116 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2117 auto *Deduced = AllocType->getContainedDeducedType();
2118 if (Deduced && !Deduced->isDeduced() &&
2119 isa<DeducedTemplateSpecializationType>(Deduced)) {
2120 if (ArraySize)
2121 return ExprError(
2122 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2123 diag::err_deduced_class_template_compound_type)
2124 << /*array*/ 2
2125 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2126
2127 InitializedEntity Entity
2128 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2130 AllocTypeInfo, Entity, Kind, Exprs);
2131 if (AllocType.isNull())
2132 return ExprError();
2133 } else if (Deduced && !Deduced->isDeduced()) {
2134 MultiExprArg Inits = Exprs;
2135 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2136 if (Braced) {
2137 auto *ILE = cast<InitListExpr>(Exprs[0]);
2138 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2139 }
2140
2141 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2142 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2143 << AllocType << TypeRange);
2144 if (Inits.size() > 1) {
2145 Expr *FirstBad = Inits[1];
2146 return ExprError(Diag(FirstBad->getBeginLoc(),
2147 diag::err_auto_new_ctor_multiple_expressions)
2148 << AllocType << TypeRange);
2149 }
2150 if (Braced && !getLangOpts().CPlusPlus17)
2151 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2152 << AllocType << TypeRange;
2153 Expr *Deduce = Inits[0];
2154 if (isa<InitListExpr>(Deduce))
2155 return ExprError(
2156 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2157 << Braced << AllocType << TypeRange);
2159 TemplateDeductionInfo Info(Deduce->getExprLoc());
2161 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2164 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2165 << AllocType << Deduce->getType() << TypeRange
2166 << Deduce->getSourceRange());
2167 if (DeducedType.isNull()) {
2169 return ExprError();
2170 }
2171 AllocType = DeducedType;
2172 }
2173
2174 // Per C++0x [expr.new]p5, the type being constructed may be a
2175 // typedef of an array type.
2176 if (!ArraySize) {
2177 if (const ConstantArrayType *Array
2178 = Context.getAsConstantArrayType(AllocType)) {
2179 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2181 TypeRange.getEnd());
2182 AllocType = Array->getElementType();
2183 }
2184 }
2185
2186 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2187 return ExprError();
2188
2189 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2190 return ExprError();
2191
2192 // In ARC, infer 'retaining' for the allocated
2193 if (getLangOpts().ObjCAutoRefCount &&
2194 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2195 AllocType->isObjCLifetimeType()) {
2196 AllocType = Context.getLifetimeQualifiedType(AllocType,
2197 AllocType->getObjCARCImplicitLifetime());
2198 }
2199
2200 QualType ResultType = Context.getPointerType(AllocType);
2201
2202 if (ArraySize && *ArraySize &&
2203 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2204 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2205 if (result.isInvalid()) return ExprError();
2206 ArraySize = result.get();
2207 }
2208 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2209 // integral or enumeration type with a non-negative value."
2210 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2211 // enumeration type, or a class type for which a single non-explicit
2212 // conversion function to integral or unscoped enumeration type exists.
2213 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2214 // std::size_t.
2215 std::optional<uint64_t> KnownArraySize;
2216 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2217 ExprResult ConvertedSize;
2218 if (getLangOpts().CPlusPlus14) {
2219 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2220
2221 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2223
2224 if (!ConvertedSize.isInvalid() &&
2225 (*ArraySize)->getType()->getAs<RecordType>())
2226 // Diagnose the compatibility of this conversion.
2227 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2228 << (*ArraySize)->getType() << 0 << "'size_t'";
2229 } else {
2230 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2231 protected:
2232 Expr *ArraySize;
2233
2234 public:
2235 SizeConvertDiagnoser(Expr *ArraySize)
2236 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2237 ArraySize(ArraySize) {}
2238
2239 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2240 QualType T) override {
2241 return S.Diag(Loc, diag::err_array_size_not_integral)
2242 << S.getLangOpts().CPlusPlus11 << T;
2243 }
2244
2245 SemaDiagnosticBuilder diagnoseIncomplete(
2246 Sema &S, SourceLocation Loc, QualType T) override {
2247 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2248 << T << ArraySize->getSourceRange();
2249 }
2250
2251 SemaDiagnosticBuilder diagnoseExplicitConv(
2252 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2253 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2254 }
2255
2256 SemaDiagnosticBuilder noteExplicitConv(
2257 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2258 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2259 << ConvTy->isEnumeralType() << ConvTy;
2260 }
2261
2262 SemaDiagnosticBuilder diagnoseAmbiguous(
2263 Sema &S, SourceLocation Loc, QualType T) override {
2264 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2265 }
2266
2267 SemaDiagnosticBuilder noteAmbiguous(
2268 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2269 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2270 << ConvTy->isEnumeralType() << ConvTy;
2271 }
2272
2273 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2274 QualType T,
2275 QualType ConvTy) override {
2276 return S.Diag(Loc,
2277 S.getLangOpts().CPlusPlus11
2278 ? diag::warn_cxx98_compat_array_size_conversion
2279 : diag::ext_array_size_conversion)
2280 << T << ConvTy->isEnumeralType() << ConvTy;
2281 }
2282 } SizeDiagnoser(*ArraySize);
2283
2284 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2285 SizeDiagnoser);
2286 }
2287 if (ConvertedSize.isInvalid())
2288 return ExprError();
2289
2290 ArraySize = ConvertedSize.get();
2291 QualType SizeType = (*ArraySize)->getType();
2292
2293 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2294 return ExprError();
2295
2296 // C++98 [expr.new]p7:
2297 // The expression in a direct-new-declarator shall have integral type
2298 // with a non-negative value.
2299 //
2300 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2301 // per CWG1464. Otherwise, if it's not a constant, we must have an
2302 // unparenthesized array type.
2303
2304 // We've already performed any required implicit conversion to integer or
2305 // unscoped enumeration type.
2306 // FIXME: Per CWG1464, we are required to check the value prior to
2307 // converting to size_t. This will never find a negative array size in
2308 // C++14 onwards, because Value is always unsigned here!
2309 if (std::optional<llvm::APSInt> Value =
2310 (*ArraySize)->getIntegerConstantExpr(Context)) {
2311 if (Value->isSigned() && Value->isNegative()) {
2312 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2313 diag::err_typecheck_negative_array_size)
2314 << (*ArraySize)->getSourceRange());
2315 }
2316
2317 if (!AllocType->isDependentType()) {
2318 unsigned ActiveSizeBits =
2320 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2321 return ExprError(
2322 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2323 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2324 }
2325
2326 KnownArraySize = Value->getZExtValue();
2327 } else if (TypeIdParens.isValid()) {
2328 // Can't have dynamic array size when the type-id is in parentheses.
2329 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2330 << (*ArraySize)->getSourceRange()
2331 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2332 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2333
2334 TypeIdParens = SourceRange();
2335 }
2336
2337 // Note that we do *not* convert the argument in any way. It can
2338 // be signed, larger than size_t, whatever.
2339 }
2340
2341 FunctionDecl *OperatorNew = nullptr;
2342 FunctionDecl *OperatorDelete = nullptr;
2343 unsigned Alignment =
2344 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2345 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2346 bool PassAlignment = getLangOpts().AlignedAllocation &&
2347 Alignment > NewAlignment;
2348
2349 if (CheckArgsForPlaceholders(PlacementArgs))
2350 return ExprError();
2351
2353 if (!AllocType->isDependentType() &&
2354 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2356 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2357 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2358 OperatorNew, OperatorDelete))
2359 return ExprError();
2360
2361 // If this is an array allocation, compute whether the usual array
2362 // deallocation function for the type has a size_t parameter.
2363 bool UsualArrayDeleteWantsSize = false;
2364 if (ArraySize && !AllocType->isDependentType())
2365 UsualArrayDeleteWantsSize =
2366 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2367
2368 SmallVector<Expr *, 8> AllPlaceArgs;
2369 if (OperatorNew) {
2370 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2371 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2373
2374 // We've already converted the placement args, just fill in any default
2375 // arguments. Skip the first parameter because we don't have a corresponding
2376 // argument. Skip the second parameter too if we're passing in the
2377 // alignment; we've already filled it in.
2378 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2379 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2380 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2381 CallType))
2382 return ExprError();
2383
2384 if (!AllPlaceArgs.empty())
2385 PlacementArgs = AllPlaceArgs;
2386
2387 // We would like to perform some checking on the given `operator new` call,
2388 // but the PlacementArgs does not contain the implicit arguments,
2389 // namely allocation size and maybe allocation alignment,
2390 // so we need to conjure them.
2391
2392 QualType SizeTy = Context.getSizeType();
2393 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2394
2395 llvm::APInt SingleEltSize(
2396 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2397
2398 // How many bytes do we want to allocate here?
2399 std::optional<llvm::APInt> AllocationSize;
2400 if (!ArraySize && !AllocType->isDependentType()) {
2401 // For non-array operator new, we only want to allocate one element.
2402 AllocationSize = SingleEltSize;
2403 } else if (KnownArraySize && !AllocType->isDependentType()) {
2404 // For array operator new, only deal with static array size case.
2405 bool Overflow;
2406 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2407 .umul_ov(SingleEltSize, Overflow);
2408 (void)Overflow;
2409 assert(
2410 !Overflow &&
2411 "Expected that all the overflows would have been handled already.");
2412 }
2413
2414 IntegerLiteral AllocationSizeLiteral(
2415 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2416 SizeTy, SourceLocation());
2417 // Otherwise, if we failed to constant-fold the allocation size, we'll
2418 // just give up and pass-in something opaque, that isn't a null pointer.
2419 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2420 OK_Ordinary, /*SourceExpr=*/nullptr);
2421
2422 // Let's synthesize the alignment argument in case we will need it.
2423 // Since we *really* want to allocate these on stack, this is slightly ugly
2424 // because there might not be a `std::align_val_t` type.
2426 QualType AlignValT =
2428 IntegerLiteral AlignmentLiteral(
2429 Context,
2430 llvm::APInt(Context.getTypeSize(SizeTy),
2431 Alignment / Context.getCharWidth()),
2432 SizeTy, SourceLocation());
2433 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2434 CK_IntegralCast, &AlignmentLiteral,
2436
2437 // Adjust placement args by prepending conjured size and alignment exprs.
2439 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2440 CallArgs.emplace_back(AllocationSize
2441 ? static_cast<Expr *>(&AllocationSizeLiteral)
2442 : &OpaqueAllocationSize);
2443 if (PassAlignment)
2444 CallArgs.emplace_back(&DesiredAlignment);
2445 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2446
2447 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2448
2449 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2450 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2451
2452 // Warn if the type is over-aligned and is being allocated by (unaligned)
2453 // global operator new.
2454 if (PlacementArgs.empty() && !PassAlignment &&
2455 (OperatorNew->isImplicit() ||
2456 (OperatorNew->getBeginLoc().isValid() &&
2457 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2458 if (Alignment > NewAlignment)
2459 Diag(StartLoc, diag::warn_overaligned_type)
2460 << AllocType
2461 << unsigned(Alignment / Context.getCharWidth())
2462 << unsigned(NewAlignment / Context.getCharWidth());
2463 }
2464 }
2465
2466 // Array 'new' can't have any initializers except empty parentheses.
2467 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2468 // dialect distinction.
2469 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2471 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2472 Exprs.back()->getEndLoc());
2473 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2474 return ExprError();
2475 }
2476
2477 // If we can perform the initialization, and we've not already done so,
2478 // do it now.
2479 if (!AllocType->isDependentType() &&
2481 // The type we initialize is the complete type, including the array bound.
2482 QualType InitType;
2483 if (KnownArraySize)
2484 InitType = Context.getConstantArrayType(
2485 AllocType,
2486 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2487 *KnownArraySize),
2488 *ArraySize, ArraySizeModifier::Normal, 0);
2489 else if (ArraySize)
2490 InitType = Context.getIncompleteArrayType(AllocType,
2492 else
2493 InitType = AllocType;
2494
2495 InitializedEntity Entity
2496 = InitializedEntity::InitializeNew(StartLoc, InitType);
2497 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2498 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2499 if (FullInit.isInvalid())
2500 return ExprError();
2501
2502 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2503 // we don't want the initialized object to be destructed.
2504 // FIXME: We should not create these in the first place.
2505 if (CXXBindTemporaryExpr *Binder =
2506 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2507 FullInit = Binder->getSubExpr();
2508
2509 Initializer = FullInit.get();
2510
2511 // FIXME: If we have a KnownArraySize, check that the array bound of the
2512 // initializer is no greater than that constant value.
2513
2514 if (ArraySize && !*ArraySize) {
2515 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2516 if (CAT) {
2517 // FIXME: Track that the array size was inferred rather than explicitly
2518 // specified.
2519 ArraySize = IntegerLiteral::Create(
2520 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2521 } else {
2522 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2523 << Initializer->getSourceRange();
2524 }
2525 }
2526 }
2527
2528 // Mark the new and delete operators as referenced.
2529 if (OperatorNew) {
2530 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2531 return ExprError();
2532 MarkFunctionReferenced(StartLoc, OperatorNew);
2533 }
2534 if (OperatorDelete) {
2535 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2536 return ExprError();
2537 MarkFunctionReferenced(StartLoc, OperatorDelete);
2538 }
2539
2540 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2541 PassAlignment, UsualArrayDeleteWantsSize,
2542 PlacementArgs, TypeIdParens, ArraySize, InitStyle,
2543 Initializer, ResultType, AllocTypeInfo, Range,
2544 DirectInitRange);
2545}
2546
2547/// Checks that a type is suitable as the allocated type
2548/// in a new-expression.
2550 SourceRange R) {
2551 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2552 // abstract class type or array thereof.
2553 if (AllocType->isFunctionType())
2554 return Diag(Loc, diag::err_bad_new_type)
2555 << AllocType << 0 << R;
2556 else if (AllocType->isReferenceType())
2557 return Diag(Loc, diag::err_bad_new_type)
2558 << AllocType << 1 << R;
2559 else if (!AllocType->isDependentType() &&
2561 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2562 return true;
2563 else if (RequireNonAbstractType(Loc, AllocType,
2564 diag::err_allocation_of_abstract_type))
2565 return true;
2566 else if (AllocType->isVariablyModifiedType())
2567 return Diag(Loc, diag::err_variably_modified_new_type)
2568 << AllocType;
2569 else if (AllocType.getAddressSpace() != LangAS::Default &&
2570 !getLangOpts().OpenCLCPlusPlus)
2571 return Diag(Loc, diag::err_address_space_qualified_new)
2572 << AllocType.getUnqualifiedType()
2574 else if (getLangOpts().ObjCAutoRefCount) {
2575 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2576 QualType BaseAllocType = Context.getBaseElementType(AT);
2577 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2578 BaseAllocType->isObjCLifetimeType())
2579 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2580 << BaseAllocType;
2581 }
2582 }
2583
2584 return false;
2585}
2586
2589 bool &PassAlignment, FunctionDecl *&Operator,
2590 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2591 OverloadCandidateSet Candidates(R.getNameLoc(),
2593 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2594 Alloc != AllocEnd; ++Alloc) {
2595 // Even member operator new/delete are implicitly treated as
2596 // static, so don't use AddMemberCandidate.
2597 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2598
2599 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2600 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2601 /*ExplicitTemplateArgs=*/nullptr, Args,
2602 Candidates,
2603 /*SuppressUserConversions=*/false);
2604 continue;
2605 }
2606
2607 FunctionDecl *Fn = cast<FunctionDecl>(D);
2608 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2609 /*SuppressUserConversions=*/false);
2610 }
2611
2612 // Do the resolution.
2614 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2615 case OR_Success: {
2616 // Got one!
2617 FunctionDecl *FnDecl = Best->Function;
2619 Best->FoundDecl) == Sema::AR_inaccessible)
2620 return true;
2621
2622 Operator = FnDecl;
2623 return false;
2624 }
2625
2627 // C++17 [expr.new]p13:
2628 // If no matching function is found and the allocated object type has
2629 // new-extended alignment, the alignment argument is removed from the
2630 // argument list, and overload resolution is performed again.
2631 if (PassAlignment) {
2632 PassAlignment = false;
2633 AlignArg = Args[1];
2634 Args.erase(Args.begin() + 1);
2635 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2636 Operator, &Candidates, AlignArg,
2637 Diagnose);
2638 }
2639
2640 // MSVC will fall back on trying to find a matching global operator new
2641 // if operator new[] cannot be found. Also, MSVC will leak by not
2642 // generating a call to operator delete or operator delete[], but we
2643 // will not replicate that bug.
2644 // FIXME: Find out how this interacts with the std::align_val_t fallback
2645 // once MSVC implements it.
2646 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2647 S.Context.getLangOpts().MSVCCompat) {
2648 R.clear();
2651 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2652 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2653 Operator, /*Candidates=*/nullptr,
2654 /*AlignArg=*/nullptr, Diagnose);
2655 }
2656
2657 if (Diagnose) {
2658 // If this is an allocation of the form 'new (p) X' for some object
2659 // pointer p (or an expression that will decay to such a pointer),
2660 // diagnose the missing inclusion of <new>.
2661 if (!R.isClassLookup() && Args.size() == 2 &&
2662 (Args[1]->getType()->isObjectPointerType() ||
2663 Args[1]->getType()->isArrayType())) {
2664 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2665 << R.getLookupName() << Range;
2666 // Listing the candidates is unlikely to be useful; skip it.
2667 return true;
2668 }
2669
2670 // Finish checking all candidates before we note any. This checking can
2671 // produce additional diagnostics so can't be interleaved with our
2672 // emission of notes.
2673 //
2674 // For an aligned allocation, separately check the aligned and unaligned
2675 // candidates with their respective argument lists.
2678 llvm::SmallVector<Expr*, 4> AlignedArgs;
2679 if (AlignedCandidates) {
2680 auto IsAligned = [](OverloadCandidate &C) {
2681 return C.Function->getNumParams() > 1 &&
2682 C.Function->getParamDecl(1)->getType()->isAlignValT();
2683 };
2684 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2685
2686 AlignedArgs.reserve(Args.size() + 1);
2687 AlignedArgs.push_back(Args[0]);
2688 AlignedArgs.push_back(AlignArg);
2689 AlignedArgs.append(Args.begin() + 1, Args.end());
2690 AlignedCands = AlignedCandidates->CompleteCandidates(
2691 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2692
2693 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2694 R.getNameLoc(), IsUnaligned);
2695 } else {
2696 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2697 R.getNameLoc());
2698 }
2699
2700 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2701 << R.getLookupName() << Range;
2702 if (AlignedCandidates)
2703 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2704 R.getNameLoc());
2705 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2706 }
2707 return true;
2708
2709 case OR_Ambiguous:
2710 if (Diagnose) {
2711 Candidates.NoteCandidates(
2713 S.PDiag(diag::err_ovl_ambiguous_call)
2714 << R.getLookupName() << Range),
2715 S, OCD_AmbiguousCandidates, Args);
2716 }
2717 return true;
2718
2719 case OR_Deleted: {
2720 if (Diagnose)
2722 Candidates, Best->Function, Args);
2723 return true;
2724 }
2725 }
2726 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2727}
2728
2730 AllocationFunctionScope NewScope,
2731 AllocationFunctionScope DeleteScope,
2732 QualType AllocType, bool IsArray,
2733 bool &PassAlignment, MultiExprArg PlaceArgs,
2734 FunctionDecl *&OperatorNew,
2735 FunctionDecl *&OperatorDelete,
2736 bool Diagnose) {
2737 // --- Choosing an allocation function ---
2738 // C++ 5.3.4p8 - 14 & 18
2739 // 1) If looking in AFS_Global scope for allocation functions, only look in
2740 // the global scope. Else, if AFS_Class, only look in the scope of the
2741 // allocated class. If AFS_Both, look in both.
2742 // 2) If an array size is given, look for operator new[], else look for
2743 // operator new.
2744 // 3) The first argument is always size_t. Append the arguments from the
2745 // placement form.
2746
2747 SmallVector<Expr*, 8> AllocArgs;
2748 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2749
2750 // We don't care about the actual value of these arguments.
2751 // FIXME: Should the Sema create the expression and embed it in the syntax
2752 // tree? Or should the consumer just recalculate the value?
2753 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2754 QualType SizeTy = Context.getSizeType();
2755 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2756 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
2757 SourceLocation());
2758 AllocArgs.push_back(&Size);
2759
2760 QualType AlignValT = Context.VoidTy;
2761 if (PassAlignment) {
2764 }
2765 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2766 if (PassAlignment)
2767 AllocArgs.push_back(&Align);
2768
2769 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2770
2771 // C++ [expr.new]p8:
2772 // If the allocated type is a non-array type, the allocation
2773 // function's name is operator new and the deallocation function's
2774 // name is operator delete. If the allocated type is an array
2775 // type, the allocation function's name is operator new[] and the
2776 // deallocation function's name is operator delete[].
2778 IsArray ? OO_Array_New : OO_New);
2779
2780 QualType AllocElemType = Context.getBaseElementType(AllocType);
2781
2782 // Find the allocation function.
2783 {
2784 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2785
2786 // C++1z [expr.new]p9:
2787 // If the new-expression begins with a unary :: operator, the allocation
2788 // function's name is looked up in the global scope. Otherwise, if the
2789 // allocated type is a class type T or array thereof, the allocation
2790 // function's name is looked up in the scope of T.
2791 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2792 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2793
2794 // We can see ambiguity here if the allocation function is found in
2795 // multiple base classes.
2796 if (R.isAmbiguous())
2797 return true;
2798
2799 // If this lookup fails to find the name, or if the allocated type is not
2800 // a class type, the allocation function's name is looked up in the
2801 // global scope.
2802 if (R.empty()) {
2803 if (NewScope == AFS_Class)
2804 return true;
2805
2807 }
2808
2809 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2810 if (PlaceArgs.empty()) {
2811 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2812 } else {
2813 Diag(StartLoc, diag::err_openclcxx_placement_new);
2814 }
2815 return true;
2816 }
2817
2818 assert(!R.empty() && "implicitly declared allocation functions not found");
2819 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2820
2821 // We do our own custom access checks below.
2823
2824 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2825 OperatorNew, /*Candidates=*/nullptr,
2826 /*AlignArg=*/nullptr, Diagnose))
2827 return true;
2828 }
2829
2830 // We don't need an operator delete if we're running under -fno-exceptions.
2831 if (!getLangOpts().Exceptions) {
2832 OperatorDelete = nullptr;
2833 return false;
2834 }
2835
2836 // Note, the name of OperatorNew might have been changed from array to
2837 // non-array by resolveAllocationOverload.
2839 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2840 ? OO_Array_Delete
2841 : OO_Delete);
2842
2843 // C++ [expr.new]p19:
2844 //
2845 // If the new-expression begins with a unary :: operator, the
2846 // deallocation function's name is looked up in the global
2847 // scope. Otherwise, if the allocated type is a class type T or an
2848 // array thereof, the deallocation function's name is looked up in
2849 // the scope of T. If this lookup fails to find the name, or if
2850 // the allocated type is not a class type or array thereof, the
2851 // deallocation function's name is looked up in the global scope.
2852 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2853 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2854 auto *RD =
2855 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2856 LookupQualifiedName(FoundDelete, RD);
2857 }
2858 if (FoundDelete.isAmbiguous())
2859 return true; // FIXME: clean up expressions?
2860
2861 // Filter out any destroying operator deletes. We can't possibly call such a
2862 // function in this context, because we're handling the case where the object
2863 // was not successfully constructed.
2864 // FIXME: This is not covered by the language rules yet.
2865 {
2866 LookupResult::Filter Filter = FoundDelete.makeFilter();
2867 while (Filter.hasNext()) {
2868 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2869 if (FD && FD->isDestroyingOperatorDelete())
2870 Filter.erase();
2871 }
2872 Filter.done();
2873 }
2874
2875 bool FoundGlobalDelete = FoundDelete.empty();
2876 if (FoundDelete.empty()) {
2877 FoundDelete.clear(LookupOrdinaryName);
2878
2879 if (DeleteScope == AFS_Class)
2880 return true;
2881
2884 }
2885
2886 FoundDelete.suppressDiagnostics();
2887
2889
2890 // Whether we're looking for a placement operator delete is dictated
2891 // by whether we selected a placement operator new, not by whether
2892 // we had explicit placement arguments. This matters for things like
2893 // struct A { void *operator new(size_t, int = 0); ... };
2894 // A *a = new A()
2895 //
2896 // We don't have any definition for what a "placement allocation function"
2897 // is, but we assume it's any allocation function whose
2898 // parameter-declaration-clause is anything other than (size_t).
2899 //
2900 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2901 // This affects whether an exception from the constructor of an overaligned
2902 // type uses the sized or non-sized form of aligned operator delete.
2903 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2904 OperatorNew->isVariadic();
2905
2906 if (isPlacementNew) {
2907 // C++ [expr.new]p20:
2908 // A declaration of a placement deallocation function matches the
2909 // declaration of a placement allocation function if it has the
2910 // same number of parameters and, after parameter transformations
2911 // (8.3.5), all parameter types except the first are
2912 // identical. [...]
2913 //
2914 // To perform this comparison, we compute the function type that
2915 // the deallocation function should have, and use that type both
2916 // for template argument deduction and for comparison purposes.
2917 QualType ExpectedFunctionType;
2918 {
2919 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2920
2921 SmallVector<QualType, 4> ArgTypes;
2922 ArgTypes.push_back(Context.VoidPtrTy);
2923 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2924 ArgTypes.push_back(Proto->getParamType(I));
2925
2927 // FIXME: This is not part of the standard's rule.
2928 EPI.Variadic = Proto->isVariadic();
2929
2930 ExpectedFunctionType
2931 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2932 }
2933
2934 for (LookupResult::iterator D = FoundDelete.begin(),
2935 DEnd = FoundDelete.end();
2936 D != DEnd; ++D) {
2937 FunctionDecl *Fn = nullptr;
2938 if (FunctionTemplateDecl *FnTmpl =
2939 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2940 // Perform template argument deduction to try to match the
2941 // expected function type.
2942 TemplateDeductionInfo Info(StartLoc);
2943 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2945 continue;
2946 } else
2947 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2948
2950 ExpectedFunctionType,
2951 /*AdjustExcpetionSpec*/true),
2952 ExpectedFunctionType))
2953 Matches.push_back(std::make_pair(D.getPair(), Fn));
2954 }
2955
2956 if (getLangOpts().CUDA)
2957 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2958 Matches);
2959 } else {
2960 // C++1y [expr.new]p22:
2961 // For a non-placement allocation function, the normal deallocation
2962 // function lookup is used
2963 //
2964 // Per [expr.delete]p10, this lookup prefers a member operator delete
2965 // without a size_t argument, but prefers a non-member operator delete
2966 // with a size_t where possible (which it always is in this case).
2968 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2969 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2970 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2971 &BestDeallocFns);
2972 if (Selected)
2973 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2974 else {
2975 // If we failed to select an operator, all remaining functions are viable
2976 // but ambiguous.
2977 for (auto Fn : BestDeallocFns)
2978 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2979 }
2980 }
2981
2982 // C++ [expr.new]p20:
2983 // [...] If the lookup finds a single matching deallocation
2984 // function, that function will be called; otherwise, no
2985 // deallocation function will be called.
2986 if (Matches.size() == 1) {
2987 OperatorDelete = Matches[0].second;
2988
2989 // C++1z [expr.new]p23:
2990 // If the lookup finds a usual deallocation function (3.7.4.2)
2991 // with a parameter of type std::size_t and that function, considered
2992 // as a placement deallocation function, would have been
2993 // selected as a match for the allocation function, the program
2994 // is ill-formed.
2995 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2996 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2997 UsualDeallocFnInfo Info(*this,
2998 DeclAccessPair::make(OperatorDelete, AS_public));
2999 // Core issue, per mail to core reflector, 2016-10-09:
3000 // If this is a member operator delete, and there is a corresponding
3001 // non-sized member operator delete, this isn't /really/ a sized
3002 // deallocation function, it just happens to have a size_t parameter.
3003 bool IsSizedDelete = Info.HasSizeT;
3004 if (IsSizedDelete && !FoundGlobalDelete) {
3005 auto NonSizedDelete =
3006 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
3007 /*WantAlign*/Info.HasAlignValT);
3008 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
3009 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
3010 IsSizedDelete = false;
3011 }
3012
3013 if (IsSizedDelete) {
3014 SourceRange R = PlaceArgs.empty()
3015 ? SourceRange()
3016 : SourceRange(PlaceArgs.front()->getBeginLoc(),
3017 PlaceArgs.back()->getEndLoc());
3018 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
3019 if (!OperatorDelete->isImplicit())
3020 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
3021 << DeleteName;
3022 }
3023 }
3024
3025 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
3026 Matches[0].first);
3027 } else if (!Matches.empty()) {
3028 // We found multiple suitable operators. Per [expr.new]p20, that means we
3029 // call no 'operator delete' function, but we should at least warn the user.
3030 // FIXME: Suppress this warning if the construction cannot throw.
3031 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
3032 << DeleteName << AllocElemType;
3033
3034 for (auto &Match : Matches)
3035 Diag(Match.second->getLocation(),
3036 diag::note_member_declared_here) << DeleteName;
3037 }
3038
3039 return false;
3040}
3041
3042/// DeclareGlobalNewDelete - Declare the global forms of operator new and
3043/// delete. These are:
3044/// @code
3045/// // C++03:
3046/// void* operator new(std::size_t) throw(std::bad_alloc);
3047/// void* operator new[](std::size_t) throw(std::bad_alloc);
3048/// void operator delete(void *) throw();
3049/// void operator delete[](void *) throw();
3050/// // C++11:
3051/// void* operator new(std::size_t);
3052/// void* operator new[](std::size_t);
3053/// void operator delete(void *) noexcept;
3054/// void operator delete[](void *) noexcept;
3055/// // C++1y:
3056/// void* operator new(std::size_t);
3057/// void* operator new[](std::size_t);
3058/// void operator delete(void *) noexcept;
3059/// void operator delete[](void *) noexcept;
3060/// void operator delete(void *, std::size_t) noexcept;
3061/// void operator delete[](void *, std::size_t) noexcept;
3062/// @endcode
3063/// Note that the placement and nothrow forms of new are *not* implicitly
3064/// declared. Their use requires including <new>.
3067 return;
3068
3069 // The implicitly declared new and delete operators
3070 // are not supported in OpenCL.
3071 if (getLangOpts().OpenCLCPlusPlus)
3072 return;
3073
3074 // C++ [basic.stc.dynamic.general]p2:
3075 // The library provides default definitions for the global allocation
3076 // and deallocation functions. Some global allocation and deallocation
3077 // functions are replaceable ([new.delete]); these are attached to the
3078 // global module ([module.unit]).
3079 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3080 PushGlobalModuleFragment(SourceLocation());
3081
3082 // C++ [basic.std.dynamic]p2:
3083 // [...] The following allocation and deallocation functions (18.4) are
3084 // implicitly declared in global scope in each translation unit of a
3085 // program
3086 //
3087 // C++03:
3088 // void* operator new(std::size_t) throw(std::bad_alloc);
3089 // void* operator new[](std::size_t) throw(std::bad_alloc);
3090 // void operator delete(void*) throw();
3091 // void operator delete[](void*) throw();
3092 // C++11:
3093 // void* operator new(std::size_t);
3094 // void* operator new[](std::size_t);
3095 // void operator delete(void*) noexcept;
3096 // void operator delete[](void*) noexcept;
3097 // C++1y:
3098 // void* operator new(std::size_t);
3099 // void* operator new[](std::size_t);
3100 // void operator delete(void*) noexcept;
3101 // void operator delete[](void*) noexcept;
3102 // void operator delete(void*, std::size_t) noexcept;
3103 // void operator delete[](void*, std::size_t) noexcept;
3104 //
3105 // These implicit declarations introduce only the function names operator
3106 // new, operator new[], operator delete, operator delete[].
3107 //
3108 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3109 // "std" or "bad_alloc" as necessary to form the exception specification.
3110 // However, we do not make these implicit declarations visible to name
3111 // lookup.
3112 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3113 // The "std::bad_alloc" class has not yet been declared, so build it
3114 // implicitly.
3118 &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3119 getStdBadAlloc()->setImplicit(true);
3120
3121 // The implicitly declared "std::bad_alloc" should live in global module
3122 // fragment.
3123 if (TheGlobalModuleFragment) {
3126 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3127 }
3128 }
3129 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3130 // The "std::align_val_t" enum class has not yet been declared, so build it
3131 // implicitly.
3132 auto *AlignValT = EnumDecl::Create(
3134 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3135
3136 // The implicitly declared "std::align_val_t" should live in global module
3137 // fragment.
3138 if (TheGlobalModuleFragment) {
3139 AlignValT->setModuleOwnershipKind(
3141 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3142 }
3143
3144 AlignValT->setIntegerType(Context.getSizeType());
3145 AlignValT->setPromotionType(Context.getSizeType());
3146 AlignValT->setImplicit(true);
3147
3148 StdAlignValT = AlignValT;
3149 }
3150
3152
3154 QualType SizeT = Context.getSizeType();
3155
3156 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3157 QualType Return, QualType Param) {
3159 Params.push_back(Param);
3160
3161 // Create up to four variants of the function (sized/aligned).
3162 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3163 (Kind == OO_Delete || Kind == OO_Array_Delete);
3164 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3165
3166 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3167 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3168 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3169 if (Sized)
3170 Params.push_back(SizeT);
3171
3172 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3173 if (Aligned)
3174 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3175
3177 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3178
3179 if (Aligned)
3180 Params.pop_back();
3181 }
3182 }
3183 };
3184
3185 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3186 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3187 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3188 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3189
3190 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3191 PopGlobalModuleFragment();
3192}
3193
3194/// DeclareGlobalAllocationFunction - Declares a single implicit global
3195/// allocation function if it doesn't already exist.
3197 QualType Return,
3198 ArrayRef<QualType> Params) {
3200
3201 // Check if this function is already declared.
3202 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3203 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3204 Alloc != AllocEnd; ++Alloc) {
3205 // Only look at non-template functions, as it is the predefined,
3206 // non-templated allocation function we are trying to declare here.
3207 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3208 if (Func->getNumParams() == Params.size()) {
3210 for (auto *P : Func->parameters())
3211 FuncParams.push_back(
3212 Context.getCanonicalType(P->getType().getUnqualifiedType()));
3213 if (llvm::ArrayRef(FuncParams) == Params) {
3214 // Make the function visible to name lookup, even if we found it in
3215 // an unimported module. It either is an implicitly-declared global
3216 // allocation function, or is suppressing that function.
3217 Func->setVisibleDespiteOwningModule();
3218 return;
3219 }
3220 }
3221 }
3222 }
3223
3225 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3226
3227 QualType BadAllocType;
3228 bool HasBadAllocExceptionSpec
3229 = (Name.getCXXOverloadedOperator() == OO_New ||
3230 Name.getCXXOverloadedOperator() == OO_Array_New);
3231 if (HasBadAllocExceptionSpec) {
3232 if (!getLangOpts().CPlusPlus11) {
3233 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3234 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3236 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3237 }
3238 if (getLangOpts().NewInfallible) {
3240 }
3241 } else {
3242 EPI.ExceptionSpec =
3244 }
3245
3246 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3247 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3249 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3250 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3251 true);
3252 Alloc->setImplicit();
3253 // Global allocation functions should always be visible.
3255
3256 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3257 !getLangOpts().CheckNew)
3258 Alloc->addAttr(
3259 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3260
3261 // C++ [basic.stc.dynamic.general]p2:
3262 // The library provides default definitions for the global allocation
3263 // and deallocation functions. Some global allocation and deallocation
3264 // functions are replaceable ([new.delete]); these are attached to the
3265 // global module ([module.unit]).
3266 //
3267 // In the language wording, these functions are attched to the global
3268 // module all the time. But in the implementation, the global module
3269 // is only meaningful when we're in a module unit. So here we attach
3270 // these allocation functions to global module conditionally.
3271 if (TheGlobalModuleFragment) {
3274 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3275 }
3276
3278 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3280 ? VisibilityAttr::Hidden
3282 ? VisibilityAttr::Protected
3283 : VisibilityAttr::Default));
3284
3286 for (QualType T : Params) {
3287 ParamDecls.push_back(ParmVarDecl::Create(
3288 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3289 /*TInfo=*/nullptr, SC_None, nullptr));
3290 ParamDecls.back()->setImplicit();
3291 }
3292 Alloc->setParams(ParamDecls);
3293 if (ExtraAttr)
3294 Alloc->addAttr(ExtraAttr);
3297 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3298 };
3299
3300 if (!LangOpts.CUDA)
3301 CreateAllocationFunctionDecl(nullptr);
3302 else {
3303 // Host and device get their own declaration so each can be
3304 // defined or re-declared independently.
3305 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3306 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3307 }
3308}
3309
3311 bool CanProvideSize,
3312 bool Overaligned,
3313 DeclarationName Name) {
3315
3316 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3318
3319 // FIXME: It's possible for this to result in ambiguity, through a
3320 // user-declared variadic operator delete or the enable_if attribute. We
3321 // should probably not consider those cases to be usual deallocation
3322 // functions. But for now we just make an arbitrary choice in that case.
3323 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3324 Overaligned);
3325 assert(Result.FD && "operator delete missing from global scope?");
3326 return Result.FD;
3327}
3328
3330 CXXRecordDecl *RD) {
3332
3333 FunctionDecl *OperatorDelete = nullptr;
3334 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3335 return nullptr;
3336 if (OperatorDelete)
3337 return OperatorDelete;
3338
3339 // If there's no class-specific operator delete, look up the global
3340 // non-array delete.
3343 Name);
3344}
3345
3347 DeclarationName Name,
3348 FunctionDecl *&Operator, bool Diagnose,
3349 bool WantSize, bool WantAligned) {
3350 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3351 // Try to find operator delete/operator delete[] in class scope.
3352 LookupQualifiedName(Found, RD);
3353
3354 if (Found.isAmbiguous())
3355 return true;
3356
3357 Found.suppressDiagnostics();
3358
3359 bool Overaligned =
3360 WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3361
3362 // C++17 [expr.delete]p10:
3363 // If the deallocation functions have class scope, the one without a
3364 // parameter of type std::size_t is selected.
3366 resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3367 /*WantAlign*/ Overaligned, &Matches);
3368
3369 // If we could find an overload, use it.
3370 if (Matches.size() == 1) {
3371 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3372
3373 // FIXME: DiagnoseUseOfDecl?
3374 if (Operator->isDeleted()) {
3375 if (Diagnose) {
3376 StringLiteral *Msg = Operator->getDeletedMessage();
3377 Diag(StartLoc, diag::err_deleted_function_use)
3378 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
3379 NoteDeletedFunction(Operator);
3380 }
3381 return true;
3382 }
3383
3384 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3385 Matches[0].Found, Diagnose) == AR_inaccessible)
3386 return true;
3387
3388 return false;
3389 }
3390
3391 // We found multiple suitable operators; complain about the ambiguity.
3392 // FIXME: The standard doesn't say to do this; it appears that the intent
3393 // is that this should never happen.
3394 if (!Matches.empty()) {
3395 if (Diagnose) {
3396 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3397 << Name << RD;
3398 for (auto &Match : Matches)
3399 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3400 }
3401 return true;
3402 }
3403
3404 // We did find operator delete/operator delete[] declarations, but
3405 // none of them were suitable.
3406 if (!Found.empty()) {
3407 if (Diagnose) {
3408 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3409 << Name << RD;
3410
3411 for (NamedDecl *D : Found)
3412 Diag(D->getUnderlyingDecl()->getLocation(),
3413 diag::note_member_declared_here) << Name;
3414 }
3415 return true;
3416 }
3417
3418 Operator = nullptr;
3419 return false;
3420}
3421
3422namespace {
3423/// Checks whether delete-expression, and new-expression used for
3424/// initializing deletee have the same array form.
3425class MismatchingNewDeleteDetector {
3426public:
3427 enum MismatchResult {
3428 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3429 NoMismatch,
3430 /// Indicates that variable is initialized with mismatching form of \a new.
3431 VarInitMismatches,
3432 /// Indicates that member is initialized with mismatching form of \a new.
3433 MemberInitMismatches,
3434 /// Indicates that 1 or more constructors' definitions could not been
3435 /// analyzed, and they will be checked again at the end of translation unit.
3436 AnalyzeLater
3437 };
3438
3439 /// \param EndOfTU True, if this is the final analysis at the end of
3440 /// translation unit. False, if this is the initial analysis at the point
3441 /// delete-expression was encountered.
3442 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3443 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3444 HasUndefinedConstructors(false) {}
3445
3446 /// Checks whether pointee of a delete-expression is initialized with
3447 /// matching form of new-expression.
3448 ///
3449 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3450 /// point where delete-expression is encountered, then a warning will be
3451 /// issued immediately. If return value is \c AnalyzeLater at the point where
3452 /// delete-expression is seen, then member will be analyzed at the end of
3453 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3454 /// couldn't be analyzed. If at least one constructor initializes the member
3455 /// with matching type of new, the return value is \c NoMismatch.
3456 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3457 /// Analyzes a class member.
3458 /// \param Field Class member to analyze.
3459 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3460 /// for deleting the \p Field.
3461 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3463 /// List of mismatching new-expressions used for initialization of the pointee
3465 /// Indicates whether delete-expression was in array form.
3466 bool IsArrayForm;
3467
3468private:
3469 const bool EndOfTU;
3470 /// Indicates that there is at least one constructor without body.
3471 bool HasUndefinedConstructors;
3472 /// Returns \c CXXNewExpr from given initialization expression.
3473 /// \param E Expression used for initializing pointee in delete-expression.
3474 /// E can be a single-element \c InitListExpr consisting of new-expression.
3475 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3476 /// Returns whether member is initialized with mismatching form of
3477 /// \c new either by the member initializer or in-class initialization.
3478 ///
3479 /// If bodies of all constructors are not visible at the end of translation
3480 /// unit or at least one constructor initializes member with the matching
3481 /// form of \c new, mismatch cannot be proven, and this function will return
3482 /// \c NoMismatch.
3483 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3484 /// Returns whether variable is initialized with mismatching form of
3485 /// \c new.
3486 ///
3487 /// If variable is initialized with matching form of \c new or variable is not
3488 /// initialized with a \c new expression, this function will return true.
3489 /// If variable is initialized with mismatching form of \c new, returns false.
3490 /// \param D Variable to analyze.
3491 bool hasMatchingVarInit(const DeclRefExpr *D);
3492 /// Checks whether the constructor initializes pointee with mismatching
3493 /// form of \c new.
3494 ///
3495 /// Returns true, if member is initialized with matching form of \c new in
3496 /// member initializer list. Returns false, if member is initialized with the
3497 /// matching form of \c new in this constructor's initializer or given
3498 /// constructor isn't defined at the point where delete-expression is seen, or
3499 /// member isn't initialized by the constructor.
3500 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3501 /// Checks whether member is initialized with matching form of
3502 /// \c new in member initializer list.
3503 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3504 /// Checks whether member is initialized with mismatching form of \c new by
3505 /// in-class initializer.
3506 MismatchResult analyzeInClassInitializer();
3507};
3508}
3509
3510MismatchingNewDeleteDetector::MismatchResult
3511MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3512 NewExprs.clear();
3513 assert(DE && "Expected delete-expression");
3514 IsArrayForm = DE->isArrayForm();
3515 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3516 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3517 return analyzeMemberExpr(ME);
3518 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3519 if (!hasMatchingVarInit(D))
3520 return VarInitMismatches;
3521 }
3522 return NoMismatch;
3523}
3524
3525const CXXNewExpr *
3526MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3527 assert(E != nullptr && "Expected a valid initializer expression");
3528 E = E->IgnoreParenImpCasts();
3529 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3530 if (ILE->getNumInits() == 1)
3531 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3532 }
3533
3534 return dyn_cast_or_null<const CXXNewExpr>(E);
3535}
3536
3537bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3538 const CXXCtorInitializer *CI) {
3539 const CXXNewExpr *NE = nullptr;
3540 if (Field == CI->getMember() &&
3541 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3542 if (NE->isArray() == IsArrayForm)
3543 return true;
3544 else
3545 NewExprs.push_back(NE);
3546 }
3547 return false;
3548}
3549
3550bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3551 const CXXConstructorDecl *CD) {
3552 if (CD->isImplicit())
3553 return false;
3554 const FunctionDecl *Definition = CD;
3556 HasUndefinedConstructors = true;
3557 return EndOfTU;
3558 }
3559 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3560 if (hasMatchingNewInCtorInit(CI))
3561 return true;
3562 }
3563 return false;
3564}
3565
3566MismatchingNewDeleteDetector::MismatchResult
3567MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3568 assert(Field != nullptr && "This should be called only for members");
3569 const Expr *InitExpr = Field->getInClassInitializer();
3570 if (!InitExpr)
3571 return EndOfTU ? NoMismatch : AnalyzeLater;
3572 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3573 if (NE->isArray() != IsArrayForm) {
3574 NewExprs.push_back(NE);
3575 return MemberInitMismatches;
3576 }
3577 }
3578 return NoMismatch;
3579}
3580
3581MismatchingNewDeleteDetector::MismatchResult
3582MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3583 bool DeleteWasArrayForm) {
3584 assert(Field != nullptr && "Analysis requires a valid class member.");
3585 this->Field = Field;
3586 IsArrayForm = DeleteWasArrayForm;
3587 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3588 for (const auto *CD : RD->ctors()) {
3589 if (hasMatchingNewInCtor(CD))
3590 return NoMismatch;
3591 }
3592 if (HasUndefinedConstructors)
3593 return EndOfTU ? NoMismatch : AnalyzeLater;
3594 if (!NewExprs.empty())
3595 return MemberInitMismatches;
3596 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3597 : NoMismatch;
3598}
3599
3600MismatchingNewDeleteDetector::MismatchResult
3601MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3602 assert(ME != nullptr && "Expected a member expression");
3603 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3604 return analyzeField(F, IsArrayForm);
3605 return NoMismatch;
3606}
3607
3608bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3609 const CXXNewExpr *NE = nullptr;
3610 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3611 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3612 NE->isArray() != IsArrayForm) {
3613 NewExprs.push_back(NE);
3614 }
3615 }
3616 return NewExprs.empty();
3617}
3618
3619static void
3621 const MismatchingNewDeleteDetector &Detector) {
3622 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3623 FixItHint H;
3624 if (!Detector.IsArrayForm)
3625 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3626 else {
3628 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3629 SemaRef.getLangOpts(), true);
3630 if (RSquare.isValid())
3631 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3632 }
3633 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3634 << Detector.IsArrayForm << H;
3635
3636 for (const auto *NE : Detector.NewExprs)
3637 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3638 << Detector.IsArrayForm;
3639}
3640
3641void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3642 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3643 return;
3644 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3645 switch (Detector.analyzeDeleteExpr(DE)) {
3646 case MismatchingNewDeleteDetector::VarInitMismatches:
3647 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3648 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3649 break;
3650 }
3651 case MismatchingNewDeleteDetector::AnalyzeLater: {
3652 DeleteExprs[Detector.Field].push_back(
3653 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3654 break;
3655 }
3656 case MismatchingNewDeleteDetector::NoMismatch:
3657 break;
3658 }
3659}
3660
3661void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3662 bool DeleteWasArrayForm) {
3663 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3664 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3665 case MismatchingNewDeleteDetector::VarInitMismatches:
3666 llvm_unreachable("This analysis should have been done for class members.");
3667 case MismatchingNewDeleteDetector::AnalyzeLater:
3668 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3669 "translation unit.");
3670 case MismatchingNewDeleteDetector::MemberInitMismatches:
3671 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3672 break;
3673 case MismatchingNewDeleteDetector::NoMismatch:
3674 break;
3675 }
3676}
3677
3678/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3679/// @code ::delete ptr; @endcode
3680/// or
3681/// @code delete [] ptr; @endcode
3683Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3684 bool ArrayForm, Expr *ExE) {
3685 // C++ [expr.delete]p1:
3686 // The operand shall have a pointer type, or a class type having a single
3687 // non-explicit conversion function to a pointer type. The result has type
3688 // void.
3689 //
3690 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3691
3692 ExprResult Ex = ExE;
3693 FunctionDecl *OperatorDelete = nullptr;
3694 bool ArrayFormAsWritten = ArrayForm;
3695 bool UsualArrayDeleteWantsSize = false;
3696
3697 if (!Ex.get()->isTypeDependent()) {
3698 // Perform lvalue-to-rvalue cast, if needed.
3699 Ex = DefaultLvalueConversion(Ex.get());
3700 if (Ex.isInvalid())
3701 return ExprError();
3702
3703 QualType Type = Ex.get()->getType();
3704
3705 class DeleteConverter : public ContextualImplicitConverter {
3706 public:
3707 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3708
3709 bool match(QualType ConvType) override {
3710 // FIXME: If we have an operator T* and an operator void*, we must pick
3711 // the operator T*.
3712 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3713 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3714 return true;
3715 return false;
3716 }
3717
3718 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3719 QualType T) override {
3720 return S.Diag(Loc, diag::err_delete_operand) << T;
3721 }
3722
3723 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3724 QualType T) override {
3725 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3726 }
3727
3728 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3729 QualType T,
3730 QualType ConvTy) override {
3731 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3732 }
3733
3734 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3735 QualType ConvTy) override {
3736 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3737 << ConvTy;
3738 }
3739
3740 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3741 QualType T) override {
3742 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3743 }
3744
3745 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3746 QualType ConvTy) override {
3747 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3748 << ConvTy;
3749 }
3750
3751 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3752 QualType T,
3753 QualType ConvTy) override {
3754 llvm_unreachable("conversion functions are permitted");
3755 }
3756 } Converter;
3757
3758 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3759 if (Ex.isInvalid())
3760 return ExprError();
3761 Type = Ex.get()->getType();
3762 if (!Converter.match(Type))
3763 // FIXME: PerformContextualImplicitConversion should return ExprError
3764 // itself in this case.
3765 return ExprError();
3766
3767 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3768 QualType PointeeElem = Context.getBaseElementType(Pointee);
3769
3770 if (Pointee.getAddressSpace() != LangAS::Default &&
3771 !getLangOpts().OpenCLCPlusPlus)
3772 return Diag(Ex.get()->getBeginLoc(),
3773 diag::err_address_space_qualified_delete)
3774 << Pointee.getUnqualifiedType()
3776
3777 CXXRecordDecl *PointeeRD = nullptr;
3778 if (Pointee->isVoidType() && !isSFINAEContext()) {
3779 // The C++ standard bans deleting a pointer to a non-object type, which
3780 // effectively bans deletion of "void*". However, most compilers support
3781 // this, so we treat it as a warning unless we're in a SFINAE context.
3782 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3783 << Type << Ex.get()->getSourceRange();
3784 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3785 Pointee->isSizelessType()) {
3786 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3787 << Type << Ex.get()->getSourceRange());
3788 } else if (!Pointee->isDependentType()) {
3789 // FIXME: This can result in errors if the definition was imported from a
3790 // module but is hidden.
3791 if (!RequireCompleteType(StartLoc, Pointee,
3792 diag::warn_delete_incomplete, Ex.get())) {
3793 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3794 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3795 }
3796 }
3797
3798 if (Pointee->isArrayType() && !ArrayForm) {
3799 Diag(StartLoc, diag::warn_delete_array_type)
3800 << Type << Ex.get()->getSourceRange()
3802 ArrayForm = true;
3803 }
3804
3806 ArrayForm ? OO_Array_Delete : OO_Delete);
3807
3808 if (PointeeRD) {
3809 if (!UseGlobal &&
3810 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3811 OperatorDelete))
3812 return ExprError();
3813
3814 // If we're allocating an array of records, check whether the
3815 // usual operator delete[] has a size_t parameter.
3816 if (ArrayForm) {
3817 // If the user specifically asked to use the global allocator,
3818 // we'll need to do the lookup into the class.
3819 if (UseGlobal)
3820 UsualArrayDeleteWantsSize =
3821 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3822
3823 // Otherwise, the usual operator delete[] should be the
3824 // function we just found.
3825 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3826 UsualArrayDeleteWantsSize =
3827 UsualDeallocFnInfo(*this,
3828 DeclAccessPair::make(OperatorDelete, AS_public))
3829 .HasSizeT;
3830 }
3831
3832 if (!PointeeRD->hasIrrelevantDestructor())
3833 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3834 MarkFunctionReferenced(StartLoc,
3835 const_cast<CXXDestructorDecl*>(Dtor));
3836 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3837 return ExprError();
3838 }
3839
3840 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3841 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3842 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3843 SourceLocation());
3844 }
3845
3846 if (!OperatorDelete) {
3847 if (getLangOpts().OpenCLCPlusPlus) {
3848 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3849 return ExprError();
3850 }
3851
3852 bool IsComplete = isCompleteType(StartLoc, Pointee);
3853 bool CanProvideSize =
3854 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3855 Pointee.isDestructedType());
3856 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3857
3858 // Look for a global declaration.
3859 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3860 Overaligned, DeleteName);
3861 }
3862
3863 MarkFunctionReferenced(StartLoc, OperatorDelete);
3864
3865 // Check access and ambiguity of destructor if we're going to call it.
3866 // Note that this is required even for a virtual delete.
3867 bool IsVirtualDelete = false;
3868 if (PointeeRD) {
3869 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3870 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3871 PDiag(diag::err_access_dtor) << PointeeElem);
3872 IsVirtualDelete = Dtor->isVirtual();
3873 }
3874 }
3875
3876 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3877
3878 // Convert the operand to the type of the first parameter of operator
3879 // delete. This is only necessary if we selected a destroying operator
3880 // delete that we are going to call (non-virtually); converting to void*
3881 // is trivial and left to AST consumers to handle.
3882 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3883 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3884 Qualifiers Qs = Pointee.getQualifiers();
3885 if (Qs.hasCVRQualifiers()) {
3886 // Qualifiers are irrelevant to this conversion; we're only looking
3887 // for access and ambiguity.
3891 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3892 }
3893 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3894 if (Ex.isInvalid())
3895 return ExprError();
3896 }
3897 }
3898
3900 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3901 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3902 AnalyzeDeleteExprMismatch(Result);
3903 return Result;
3904}
3905
3907 bool IsDelete,
3908 FunctionDecl *&Operator) {
3909
3911 IsDelete ? OO_Delete : OO_New);
3912
3913 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3915 assert(!R.empty() && "implicitly declared allocation functions not found");
3916 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3917
3918 // We do our own custom access checks below.
3920
3921 SmallVector<Expr *, 8> Args(TheCall->arguments());
3922 OverloadCandidateSet Candidates(R.getNameLoc(),
3924 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3925 FnOvl != FnOvlEnd; ++FnOvl) {
3926 // Even member operator new/delete are implicitly treated as
3927 // static, so don't use AddMemberCandidate.
3928 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3929
3930 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3931 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3932 /*ExplicitTemplateArgs=*/nullptr, Args,
3933 Candidates,
3934 /*SuppressUserConversions=*/false);
3935 continue;
3936 }
3937
3938 FunctionDecl *Fn = cast<FunctionDecl>(D);
3939 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3940 /*SuppressUserConversions=*/false);
3941 }
3942
3943 SourceRange Range = TheCall->getSourceRange();
3944
3945 // Do the resolution.
3947 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3948 case OR_Success: {
3949 // Got one!
3950 FunctionDecl *FnDecl = Best->Function;
3951 assert(R.getNamingClass() == nullptr &&
3952 "class members should not be considered");
3953
3955 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3956 << (IsDelete ? 1 : 0) << Range;
3957 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3958 << R.getLookupName() << FnDecl->getSourceRange();
3959 return true;
3960 }
3961
3962 Operator = FnDecl;
3963 return false;
3964 }
3965
3967 Candidates.NoteCandidates(
3969 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3970 << R.getLookupName() << Range),
3971 S, OCD_AllCandidates, Args);
3972 return true;
3973
3974 case OR_Ambiguous:
3975 Candidates.NoteCandidates(
3977 S.PDiag(diag::err_ovl_ambiguous_call)
3978 << R.getLookupName() << Range),
3979 S, OCD_AmbiguousCandidates, Args);
3980 return true;
3981
3982 case OR_Deleted:
3984 Candidates, Best->Function, Args);
3985 return true;
3986 }
3987 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3988}
3989
3990ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3991 bool IsDelete) {
3992 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3993 if (!getLangOpts().CPlusPlus) {
3994 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3995 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3996 << "C++";
3997 return ExprError();
3998 }
3999 // CodeGen assumes it can find the global new and delete to call,
4000 // so ensure that they are declared.
4002
4003 FunctionDecl *OperatorNewOrDelete = nullptr;
4004 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
4005 OperatorNewOrDelete))
4006 return ExprError();
4007 assert(OperatorNewOrDelete && "should be found");
4008
4009 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
4010 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
4011
4012 TheCall->setType(OperatorNewOrDelete->getReturnType());
4013 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4014 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
4015 InitializedEntity Entity =
4018 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
4019 if (Arg.isInvalid())
4020 return ExprError();
4021 TheCall->setArg(i, Arg.get());
4022 }
4023 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
4024 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
4025 "Callee expected to be implicit cast to a builtin function pointer");
4026 Callee->setType(OperatorNewOrDelete->getType());
4027
4028 return TheCallResult;
4029}
4030
4032 bool IsDelete, bool CallCanBeVirtual,
4033 bool WarnOnNonAbstractTypes,
4034 SourceLocation DtorLoc) {
4035 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
4036 return;
4037
4038 // C++ [expr.delete]p3:
4039 // In the first alternative (delete object), if the static type of the
4040 // object to be deleted is different from its dynamic type, the static
4041 // type shall be a base class of the dynamic type of the object to be
4042 // deleted and the static type shall have a virtual destructor or the
4043 // behavior is undefined.
4044 //
4045 const CXXRecordDecl *PointeeRD = dtor->getParent();
4046 // Note: a final class cannot be derived from, no issue there
4047 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
4048 return;
4049
4050 // If the superclass is in a system header, there's nothing that can be done.
4051 // The `delete` (where we emit the warning) can be in a system header,
4052 // what matters for this warning is where the deleted type is defined.
4053 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4054 return;
4055
4056 QualType ClassType = dtor->getFunctionObjectParameterType();
4057 if (PointeeRD->isAbstract()) {
4058 // If the class is abstract, we warn by default, because we're
4059 // sure the code has undefined behavior.
4060 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4061 << ClassType;
4062 } else if (WarnOnNonAbstractTypes) {
4063 // Otherwise, if this is not an array delete, it's a bit suspect,
4064 // but not necessarily wrong.
4065 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4066 << ClassType;
4067 }
4068 if (!IsDelete) {
4069 std::string TypeStr;
4070 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4071 Diag(DtorLoc, diag::note_delete_non_virtual)
4072 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4073 }
4074}
4075
4077 SourceLocation StmtLoc,
4078 ConditionKind CK) {
4079 ExprResult E =
4080 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4081 if (E.isInvalid())
4082 return ConditionError();
4083 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
4085}
4086
4087/// Check the use of the given variable as a C++ condition in an if,
4088/// while, do-while, or switch statement.
4090 SourceLocation StmtLoc,
4091 ConditionKind CK) {
4092 if (ConditionVar->isInvalidDecl())
4093 return ExprError();
4094
4095 QualType T = ConditionVar->getType();
4096
4097 // C++ [stmt.select]p2:
4098 // The declarator shall not specify a function or an array.
4099 if (T->isFunctionType())
4100 return ExprError(Diag(ConditionVar->getLocation(),
4101 diag::err_invalid_use_of_function_type)
4102 << ConditionVar->getSourceRange());
4103 else if (T->isArrayType())
4104 return ExprError(Diag(ConditionVar->getLocation(),
4105 diag::err_invalid_use_of_array_type)
4106 << ConditionVar->getSourceRange());
4107
4109 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4110 ConditionVar->getLocation());
4111
4112 switch (CK) {
4114 return CheckBooleanCondition(StmtLoc, Condition.get());
4115
4117 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4118
4120 return CheckSwitchCondition(StmtLoc, Condition.get());
4121 }
4122
4123 llvm_unreachable("unexpected condition kind");
4124}
4125
4126/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
4127ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4128 // C++11 6.4p4:
4129 // The value of a condition that is an initialized declaration in a statement
4130 // other than a switch statement is the value of the declared variable
4131 // implicitly converted to type bool. If that conversion is ill-formed, the
4132 // program is ill-formed.
4133 // The value of a condition that is an expression is the value of the
4134 // expression, implicitly converted to bool.
4135 //
4136 // C++23 8.5.2p2
4137 // If the if statement is of the form if constexpr, the value of the condition
4138 // is contextually converted to bool and the converted expression shall be
4139 // a constant expression.
4140 //
4141
4143 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4144 return E;
4145
4146 // FIXME: Return this value to the caller so they don't need to recompute it.
4147 llvm::APSInt Cond;
4149 E.get(), &Cond,
4150 diag::err_constexpr_if_condition_expression_is_not_constant);
4151 return E;
4152}
4153
4154/// Helper function to determine whether this is the (deprecated) C++
4155/// conversion from a string literal to a pointer to non-const char or
4156/// non-const wchar_t (for narrow and wide string literals,
4157/// respectively).
4158bool
4160 // Look inside the implicit cast, if it exists.
4161 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4162 From = Cast->getSubExpr();
4163
4164 // A string literal (2.13.4) that is not a wide string literal can
4165 // be converted to an rvalue of type "pointer to char"; a wide
4166 // string literal can be converted to an rvalue of type "pointer
4167 // to wchar_t" (C++ 4.2p2).
4168 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4169 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4170 if (const BuiltinType *ToPointeeType
4171 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4172 // This conversion is considered only when there is an
4173 // explicit appropriate pointer target type (C++ 4.2p2).
4174 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4175 switch (StrLit->getKind()) {
4179 // We don't allow UTF literals to be implicitly converted
4180 break;
4182 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4183 ToPointeeType->getKind() == BuiltinType::Char_S);
4186 QualType(ToPointeeType, 0));
4188 assert(false && "Unevaluated string literal in expression");
4189 break;
4190 }
4191 }
4192 }
4193
4194 return false;
4195}
4196
4198 SourceLocation CastLoc,
4199 QualType Ty,
4200 CastKind Kind,
4201 CXXMethodDecl *Method,
4202 DeclAccessPair FoundDecl,
4203 bool HadMultipleCandidates,
4204 Expr *From) {
4205 switch (Kind) {
4206 default: llvm_unreachable("Unhandled cast kind!");
4207 case CK_ConstructorConversion: {
4208 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4209 SmallVector<Expr*, 8> ConstructorArgs;
4210
4211 if (S.RequireNonAbstractType(CastLoc, Ty,
4212 diag::err_allocation_of_abstract_type))
4213 return ExprError();
4214
4215 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4216 ConstructorArgs))
4217 return ExprError();
4218
4219 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4221 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4222 return ExprError();
4223
4225 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4226 ConstructorArgs, HadMultipleCandidates,
4227 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4229 if (Result.isInvalid())
4230 return ExprError();
4231
4232 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4233 }
4234
4235 case CK_UserDefinedConversion: {
4236 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4237
4238 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4239 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4240 return ExprError();
4241
4242 // Create an implicit call expr that calls it.
4243 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4244 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4245 HadMultipleCandidates);
4246 if (Result.isInvalid())
4247 return ExprError();
4248 // Record usage of conversion in an implicit cast.
4249 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4250 CK_UserDefinedConversion, Result.get(),
4251 nullptr, Result.get()->getValueKind(),
4253
4254 return S.MaybeBindToTemporary(Result.get());
4255 }
4256 }
4257}
4258
4259/// PerformImplicitConversion - Perform an implicit conversion of the
4260/// expression From to the type ToType using the pre-computed implicit
4261/// conversion sequence ICS. Returns the converted
4262/// expression. Action is the kind of conversion we're performing,
4263/// used in the error message.
4266 const ImplicitConversionSequence &ICS,
4267 AssignmentAction Action,
4269 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4271 !From->getType()->isRecordType())
4272 return From;
4273
4274 switch (ICS.getKind()) {
4276 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4277 Action, CCK);
4278 if (Res.isInvalid())
4279 return ExprError();
4280 From = Res.get();
4281 break;
4282 }
4283
4285
4288 QualType BeforeToType;
4289 assert(FD && "no conversion function for user-defined conversion seq");
4290 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4291 CastKind = CK_UserDefinedConversion;
4292
4293 // If the user-defined conversion is specified by a conversion function,
4294 // the initial standard conversion sequence converts the source type to
4295 // the implicit object parameter of the conversion function.
4296 BeforeToType = Context.getTagDeclType(Conv->getParent());
4297 } else {
4298 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4299 CastKind = CK_ConstructorConversion;
4300 // Do no conversion if dealing with ... for the first conversion.
4302 // If the user-defined conversion is specified by a constructor, the
4303 // initial standard conversion sequence converts the source type to
4304 // the type required by the argument of the constructor
4305 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4306 }
4307 }
4308 // Watch out for ellipsis conversion.
4310 ExprResult Res =
4311 PerformImplicitConversion(From, BeforeToType,
4313 CCK);
4314 if (Res.isInvalid())
4315 return ExprError();
4316 From = Res.get();
4317 }
4318
4320 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4321 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4323
4324 if (CastArg.isInvalid())
4325 return ExprError();
4326
4327 From = CastArg.get();
4328
4329 // C++ [over.match.oper]p7:
4330 // [...] the second standard conversion sequence of a user-defined
4331 // conversion sequence is not applied.
4333 return From;
4334
4335 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4336 AA_Converting, CCK);
4337 }
4338
4340 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4341 PDiag(diag::err_typecheck_ambiguous_condition)
4342 << From->getSourceRange());
4343 return ExprError();
4344
4347 llvm_unreachable("bad conversion");
4348
4351 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4352 bool Diagnosed = DiagnoseAssignmentResult(
4353 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4354 ToType, From->getType(), From, Action);
4355 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4356 return ExprError();
4357 }
4358
4359 // Everything went well.
4360 return From;
4361}
4362
4363/// PerformImplicitConversion - Perform an implicit conversion of the
4364/// expression From to the type ToType by following the standard
4365/// conversion sequence SCS. Returns the converted
4366/// expression. Flavor is the context in which we're performing this
4367/// conversion, for use in error messages.
4370 const StandardConversionSequence& SCS,
4371 AssignmentAction Action,
4373 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4375
4376 // Overall FIXME: we are recomputing too many types here and doing far too
4377 // much extra work. What this means is that we need to keep track of more
4378 // information that is computed when we try the implicit conversion initially,
4379 // so that we don't need to recompute anything here.
4380 QualType FromType = From->getType();
4381
4382 if (SCS.CopyConstructor) {
4383 // FIXME: When can ToType be a reference type?
4384 assert(!ToType->isReferenceType());
4385 if (SCS.Second == ICK_Derived_To_Base) {
4386 SmallVector<Expr*, 8> ConstructorArgs;
4388 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4389 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4390 return ExprError();
4391 return BuildCXXConstructExpr(
4392 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4393 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4394 /*HadMultipleCandidates*/ false,
4395 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4397 }
4398 return BuildCXXConstructExpr(
4399 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4401 /*HadMultipleCandidates*/ false,
4402 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4404 }
4405
4406 // Resolve overloaded function references.
4407 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4408 DeclAccessPair Found;
4410 true, Found);
4411 if (!Fn)
4412 return ExprError();
4413
4414 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4415 return ExprError();
4416
4417 ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn);
4418 if (Res.isInvalid())
4419 return ExprError();
4420
4421 // We might get back another placeholder expression if we resolved to a
4422 // builtin.
4423 Res = CheckPlaceholderExpr(Res.get());
4424 if (Res.isInvalid())
4425 return ExprError();
4426
4427 From = Res.get();
4428 FromType = From->getType();
4429 }
4430
4431 // If we're converting to an atomic type, first convert to the corresponding
4432 // non-atomic type.
4433 QualType ToAtomicType;
4434 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4435 ToAtomicType = ToType;
4436 ToType = ToAtomic->getValueType();
4437 }
4438
4439 QualType InitialFromType = FromType;
4440 // Perform the first implicit conversion.
4441 switch (SCS.First) {
4442 case ICK_Identity:
4443 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4444 FromType = FromAtomic->getValueType().getUnqualifiedType();
4445 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4446 From, /*BasePath=*/nullptr, VK_PRValue,
4448 }
4449 break;
4450
4451 case ICK_Lvalue_To_Rvalue: {
4452 assert(From->getObjectKind() != OK_ObjCProperty);
4453 ExprResult FromRes = DefaultLvalueConversion(From);
4454 if (FromRes.isInvalid())
4455 return ExprError();
4456
4457 From = FromRes.get();
4458 FromType = From->getType();
4459 break;
4460 }
4461
4463 FromType = Context.getArrayDecayedType(FromType);
4464 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4465 /*BasePath=*/nullptr, CCK)
4466 .get();
4467 break;
4468
4470 FromType = Context.getArrayParameterType(FromType);
4471 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4472 /*BasePath=*/nullptr, CCK)
4473 .get();
4474 break;
4475
4477 FromType = Context.getPointerType(FromType);
4478 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4479 VK_PRValue, /*BasePath=*/nullptr, CCK)
4480 .get();
4481 break;
4482
4483 default:
4484 llvm_unreachable("Improper first standard conversion");
4485 }
4486
4487 // Perform the second implicit conversion
4488 switch (SCS.Second) {
4489 case ICK_Identity:
4490 // C++ [except.spec]p5:
4491 // [For] assignment to and initialization of pointers to functions,
4492 // pointers to member functions, and references to functions: the
4493 // target entity shall allow at least the exceptions allowed by the
4494 // source value in the assignment or initialization.
4495 switch (Action) {
4496 case AA_Assigning:
4497 case AA_Initializing:
4498 // Note, function argument passing and returning are initialization.
4499 case AA_Passing:
4500 case AA_Returning:
4501 case AA_Sending:
4503 if (CheckExceptionSpecCompatibility(From, ToType))
4504 return ExprError();
4505 break;
4506
4507 case AA_Casting:
4508 case AA_Converting:
4509 // Casts and implicit conversions are not initialization, so are not
4510 // checked for exception specification mismatches.
4511 break;
4512 }
4513 // Nothing else to do.
4514 break;
4515
4518 if (ToType->isBooleanType()) {
4519 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4521 "only enums with fixed underlying type can promote to bool");
4522 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4523 /*BasePath=*/nullptr, CCK)
4524 .get();
4525 } else {
4526 From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4527 /*BasePath=*/nullptr, CCK)
4528 .get();
4529 }
4530 break;
4531
4534 From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4535 /*BasePath=*/nullptr, CCK)
4536 .get();
4537 break;
4538
4541 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4542 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4543 CastKind CK;
4544 if (FromEl->isRealFloatingType()) {
4545 if (ToEl->isRealFloatingType())
4546 CK = CK_FloatingComplexCast;
4547 else
4548 CK = CK_FloatingComplexToIntegralComplex;
4549 } else if (ToEl->isRealFloatingType()) {
4550 CK = CK_IntegralComplexToFloatingComplex;
4551 } else {
4552 CK = CK_IntegralComplexCast;
4553 }
4554 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4555 CCK)
4556 .get();
4557 break;
4558 }
4559
4561 if (ToType->isRealFloatingType())
4562 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4563 /*BasePath=*/nullptr, CCK)
4564 .get();
4565 else
4566 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4567 /*BasePath=*/nullptr, CCK)
4568 .get();
4569 break;
4570
4572 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
4573 "Attempting implicit fixed point conversion without a fixed "
4574 "point operand");
4575 if (FromType->isFloatingType())
4576 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
4577 VK_PRValue,
4578 /*BasePath=*/nullptr, CCK).get();
4579 else if (ToType->isFloatingType())
4580 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
4581 VK_PRValue,
4582 /*BasePath=*/nullptr, CCK).get();
4583 else if (FromType->isIntegralType(Context))
4584 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
4585 VK_PRValue,
4586 /*BasePath=*/nullptr, CCK).get();
4587 else if (ToType->isIntegralType(Context))
4588 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
4589 VK_PRValue,
4590 /*BasePath=*/nullptr, CCK).get();
4591 else if (ToType->isBooleanType())
4592 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
4593 VK_PRValue,
4594 /*BasePath=*/nullptr, CCK).get();
4595 else
4596 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
4597 VK_PRValue,
4598 /*BasePath=*/nullptr, CCK).get();
4599 break;
4600
4602 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4603 /*BasePath=*/nullptr, CCK).get();
4604 break;
4605
4608 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4609 // Diagnose incompatible Objective-C conversions
4610 if (Action == AA_Initializing || Action == AA_Assigning)
4611 Diag(From->getBeginLoc(),
4612 diag::ext_typecheck_convert_incompatible_pointer)
4613 << ToType << From->getType() << Action << From->getSourceRange()
4614 << 0;
4615 else
4616 Diag(From->getBeginLoc(),
4617 diag::ext_typecheck_convert_incompatible_pointer)
4618 << From->getType() << ToType << Action << From->getSourceRange()
4619 << 0;
4620
4621 if (From->getType()->isObjCObjectPointerType() &&
4622 ToType->isObjCObjectPointerType())
4624 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4625 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
4626 From->getType())) {
4627 if (Action == AA_Initializing)
4628 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4629 else
4630 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4631 << (Action == AA_Casting) << From->getType() << ToType
4632 << From->getSourceRange();
4633 }
4634
4635 // Defer address space conversion to the third conversion.
4636 QualType FromPteeType = From->getType()->getPointeeType();
4637 QualType ToPteeType = ToType->getPointeeType();
4638 QualType NewToType = ToType;
4639 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4640 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4641 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4642 NewToType = Context.getAddrSpaceQualType(NewToType,
4643 FromPteeType.getAddressSpace());
4644 if (ToType->isObjCObjectPointerType())
4645 NewToType = Context.getObjCObjectPointerType(NewToType);
4646 else if (ToType->isBlockPointerType())
4647 NewToType = Context.getBlockPointerType(NewToType);
4648 else
4649 NewToType = Context.getPointerType(NewToType);
4650 }
4651
4652 CastKind Kind;
4653 CXXCastPath BasePath;
4654 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4655 return ExprError();
4656
4657 // Make sure we extend blocks if necessary.
4658 // FIXME: doing this here is really ugly.
4659 if (Kind == CK_BlockPointerToObjCPointerCast) {
4660 ExprResult E = From;
4662 From = E.get();
4663 }
4665 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4666 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4667 .get();
4668 break;
4669 }
4670
4671 case ICK_Pointer_Member: {
4672 CastKind Kind;
4673 CXXCastPath BasePath;
4674 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4675 return ExprError();
4676 if (CheckExceptionSpecCompatibility(From, ToType))
4677 return ExprError();
4678
4679 // We may not have been able to figure out what this member pointer resolved
4680 // to up until this exact point. Attempt to lock-in it's inheritance model.
4682 (void)isCompleteType(From->getExprLoc(), From->getType());
4683 (void)isCompleteType(From->getExprLoc(), ToType);
4684 }
4685
4686 From =
4687 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4688 break;
4689 }
4690
4692 // Perform half-to-boolean conversion via float.
4693 if (From->getType()->isHalfType()) {
4694 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4695 FromType = Context.FloatTy;
4696 }
4697
4698 From = ImpCastExprToType(From, Context.BoolTy,
4700 /*BasePath=*/nullptr, CCK)
4701 .get();
4702 break;
4703
4704 case ICK_Derived_To_Base: {
4705 CXXCastPath BasePath;
4707 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4708 From->getSourceRange(), &BasePath, CStyle))
4709 return ExprError();
4710
4711 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4712 CK_DerivedToBase, From->getValueKind(),
4713 &BasePath, CCK).get();
4714 break;
4715 }
4716
4718 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4719 /*BasePath=*/nullptr, CCK)
4720 .get();
4721 break;
4722
4725 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4726 /*BasePath=*/nullptr, CCK)
4727 .get();
4728 break;
4729
4730 case ICK_Vector_Splat: {
4731 // Vector splat from any arithmetic type to a vector.
4732 Expr *Elem = prepareVectorSplat(ToType, From).get();
4733 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4734 /*BasePath=*/nullptr, CCK)
4735 .get();
4736 break;
4737 }
4738
4739 case ICK_Complex_Real:
4740 // Case 1. x -> _Complex y
4741 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4742 QualType ElType = ToComplex->getElementType();
4743 bool isFloatingComplex = ElType->isRealFloatingType();
4744
4745 // x -> y
4746 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4747 // do nothing
4748 } else if (From->getType()->isRealFloatingType()) {
4749 From = ImpCastExprToType(From, ElType,
4750 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4751 } else {
4752 assert(From->getType()->isIntegerType());
4753 From = ImpCastExprToType(From, ElType,
4754 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4755 }
4756 // y -> _Complex y
4757 From = ImpCastExprToType(From, ToType,
4758 isFloatingComplex ? CK_FloatingRealToComplex
4759 : CK_IntegralRealToComplex).get();
4760
4761 // Case 2. _Complex x -> y
4762 } else {
4763 auto *FromComplex = From->getType()->castAs<ComplexType>();
4764 QualType ElType = FromComplex->getElementType();
4765 bool isFloatingComplex = ElType->isRealFloatingType();
4766
4767 // _Complex x -> x
4768 From = ImpCastExprToType(From, ElType,
4769 isFloatingComplex ? CK_FloatingComplexToReal
4770 : CK_IntegralComplexToReal,
4771 VK_PRValue, /*BasePath=*/nullptr, CCK)
4772 .get();
4773
4774 // x -> y
4775 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4776 // do nothing
4777 } else if (ToType->isRealFloatingType()) {
4778 From = ImpCastExprToType(From, ToType,
4779 isFloatingComplex ? CK_FloatingCast
4780 : CK_IntegralToFloating,
4781 VK_PRValue, /*BasePath=*/nullptr, CCK)
4782 .get();
4783 } else {
4784 assert(ToType->isIntegerType());
4785 From = ImpCastExprToType(From, ToType,
4786 isFloatingComplex ? CK_FloatingToIntegral
4787 : CK_IntegralCast,
4788 VK_PRValue, /*BasePath=*/nullptr, CCK)
4789 .get();
4790 }
4791 }
4792 break;
4793
4795 LangAS AddrSpaceL =
4796 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4797 LangAS AddrSpaceR =
4798 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4799 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4800 "Invalid cast");
4801 CastKind Kind =
4802 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4803 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4804 VK_PRValue, /*BasePath=*/nullptr, CCK)
4805 .get();
4806 break;
4807 }
4808
4810 ExprResult FromRes = From;
4813 if (FromRes.isInvalid())
4814 return ExprError();
4815 From = FromRes.get();
4816 assert ((ConvTy == Sema::Compatible) &&
4817 "Improper transparent union conversion");
4818 (void)ConvTy;
4819 break;
4820 }
4821
4824 From = ImpCastExprToType(From, ToType,
4825 CK_ZeroToOCLOpaqueType,
4826 From->getValueKind()).get();
4827 break;
4829 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a vector
4830 // to a smaller vector, this can only operate on arguments where the source
4831 // and destination types are ExtVectors.
4832 assert(From->getType()->isExtVectorType() && ToType->isExtVectorType() &&
4833 "HLSL vector truncation should only apply to ExtVectors");
4834 auto *FromVec = From->getType()->castAs<VectorType>();
4835 auto *ToVec = ToType->castAs<VectorType>();
4836 QualType ElType = FromVec->getElementType();
4837 QualType TruncTy =
4838 Context.getExtVectorType(ElType, ToVec->getNumElements());
4839 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
4840 From->getValueKind())
4841 .get();
4842 break;
4843 }
4844
4849 case ICK_Qualification:
4854 llvm_unreachable("Improper second standard conversion");
4855 }
4856
4857 if (SCS.Element != ICK_Identity) {
4858 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
4859 // vectors or matrices.
4860
4861 // TODO: Support HLSL matrices.
4862 assert((!From->getType()->isMatrixType() && !ToType->isMatrixType()) &&
4863 "Element conversion for matrix types is not implemented yet.");
4864 assert(From->getType()->isVectorType() && ToType->isVectorType() &&
4865 "Element conversion is only supported for vector types.");
4866 assert(From->getType()->getAs<VectorType>()->getNumElements() ==
4867 ToType->getAs<VectorType>()->getNumElements() &&
4868 "Element conversion is only supported for vectors with the same "
4869 "element counts.");
4870 QualType FromElTy = From->getType()->getAs<VectorType>()->getElementType();
4871 unsigned NumElts = ToType->getAs<VectorType>()->getNumElements();
4872 switch (SCS.Element) {
4874 // Perform half-to-boolean conversion via float.
4875 if (FromElTy->isHalfType()) {
4876 QualType FPExtType = Context.getExtVectorType(FromElTy, NumElts);
4877 From = ImpCastExprToType(From, FPExtType, CK_FloatingCast).get();
4878 FromType = FPExtType;
4879 }
4880
4881 From =
4882 ImpCastExprToType(From, ToType, ScalarTypeToBooleanCastKind(FromElTy),
4883 VK_PRValue,
4884 /*BasePath=*/nullptr, CCK)
4885 .get();
4886 break;
4889 if (ToType->isBooleanType()) {
4890 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4892 "only enums with fixed underlying type can promote to bool");
4893 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4894 /*BasePath=*/nullptr, CCK)
4895 .get();
4896 } else {
4897 From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4898 /*BasePath=*/nullptr, CCK)
4899 .get();
4900 }
4901 break;
4902
4905 From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4906 /*BasePath=*/nullptr, CCK)
4907 .get();
4908 break;
4910 if (ToType->hasFloatingRepresentation())
4911 From =
4912 ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4913 /*BasePath=*/nullptr, CCK)
4914 .get();
4915 else
4916 From =
4917 ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4918 /*BasePath=*/nullptr, CCK)
4919 .get();
4920 break;
4921 case ICK_Identity:
4922 default:
4923 llvm_unreachable("Improper element standard conversion");
4924 }
4925 }
4926
4927 switch (SCS.Third) {
4928 case ICK_Identity:
4929 // Nothing to do.
4930 break;
4931
4933 // If both sides are functions (or pointers/references to them), there could
4934 // be incompatible exception declarations.
4935 if (CheckExceptionSpecCompatibility(From, ToType))
4936 return ExprError();
4937
4938 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4939 /*BasePath=*/nullptr, CCK)
4940 .get();
4941 break;
4942
4943 case ICK_Qualification: {
4944 ExprValueKind VK = From->getValueKind();
4945 CastKind CK = CK_NoOp;
4946
4947 if (ToType->isReferenceType() &&
4948 ToType->getPointeeType().getAddressSpace() !=
4949 From->getType().getAddressSpace())
4950 CK = CK_AddressSpaceConversion;
4951
4952 if (ToType->isPointerType() &&
4953 ToType->getPointeeType().getAddressSpace() !=
4955 CK = CK_AddressSpaceConversion;
4956
4957 if (!isCast(CCK) &&
4958 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4960 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4961 << InitialFromType << ToType;
4962 }
4963
4964 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4965 /*BasePath=*/nullptr, CCK)
4966 .get();
4967
4969 !getLangOpts().WritableStrings) {
4970 Diag(From->getBeginLoc(),
4972 ? diag::ext_deprecated_string_literal_conversion
4973 : diag::warn_deprecated_string_literal_conversion)
4974 << ToType.getNonReferenceType();
4975 }
4976
4977 break;
4978 }
4979
4980 default:
4981 llvm_unreachable("Improper third standard conversion");
4982 }
4983
4984 // If this conversion sequence involved a scalar -> atomic conversion, perform
4985 // that conversion now.
4986 if (!ToAtomicType.isNull()) {
4987 assert(Context.hasSameType(
4988 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4989 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4990 VK_PRValue, nullptr, CCK)
4991 .get();
4992 }
4993
4994 // Materialize a temporary if we're implicitly converting to a reference
4995 // type. This is not required by the C++ rules but is necessary to maintain
4996 // AST invariants.
4997 if (ToType->isReferenceType() && From->isPRValue()) {
4999 if (Res.isInvalid())
5000 return ExprError();
5001 From = Res.get();
5002 }
5003
5004 // If this conversion sequence succeeded and involved implicitly converting a
5005 // _Nullable type to a _Nonnull one, complain.
5006 if (!isCast(CCK))
5007 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
5008 From->getBeginLoc());
5009
5010 return From;
5011}
5012
5013/// Checks that type T is not a VLA.
5014///
5015/// @returns @c true if @p T is VLA and a diagnostic was emitted,
5016/// @c false otherwise.
5018 clang::tok::TokenKind TypeTraitID) {
5019 if (!T->getType()->isVariableArrayType())
5020 return false;
5021
5022 S.Diag(T->getTypeLoc().getBeginLoc(), diag::err_vla_unsupported)
5023 << 1 << TypeTraitID;
5024 return true;
5025}
5026
5027/// Check the completeness of a type in a unary type trait.
5028///
5029/// If the particular type trait requires a complete type, tries to complete
5030/// it. If completing the type fails, a diagnostic is emitted and false
5031/// returned. If completing the type succeeds or no completion was required,
5032/// returns true.
5035 QualType ArgTy) {
5036 // C++0x [meta.unary.prop]p3:
5037 // For all of the class templates X declared in this Clause, instantiating
5038 // that template with a template argument that is a class template
5039 // specialization may result in the implicit instantiation of the template
5040 // argument if and only if the semantics of X require that the argument
5041 // must be a complete type.
5042 // We apply this rule to all the type trait expressions used to implement
5043 // these class templates. We also try to follow any GCC documented behavior
5044 // in these expressions to ensure portability of standard libraries.
5045 switch (UTT) {
5046 default: llvm_unreachable("not a UTT");
5047 // is_complete_type somewhat obviously cannot require a complete type.
5048 case UTT_IsCompleteType:
5049 // Fall-through
5050
5051 // These traits are modeled on the type predicates in C++0x
5052 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
5053 // requiring a complete type, as whether or not they return true cannot be
5054 // impacted by the completeness of the type.
5055 case UTT_IsVoid:
5056 case UTT_IsIntegral:
5057 case UTT_IsFloatingPoint:
5058 case UTT_IsArray:
5059 case UTT_IsBoundedArray:
5060 case UTT_IsPointer:
5061 case UTT_IsNullPointer:
5062 case UTT_IsReferenceable:
5063 case UTT_IsLvalueReference:
5064 case UTT_IsRvalueReference:
5065 case UTT_IsMemberFunctionPointer:
5066 case UTT_IsMemberObjectPointer:
5067 case UTT_IsEnum:
5068 case UTT_IsScopedEnum:
5069 case UTT_IsUnion:
5070 case UTT_IsClass:
5071 case UTT_IsFunction:
5072 case UTT_IsReference:
5073 case UTT_IsArithmetic:
5074 case UTT_IsFundamental:
5075 case UTT_IsObject:
5076 case UTT_IsScalar:
5077 case UTT_IsCompound:
5078 case UTT_IsMemberPointer:
5079 // Fall-through
5080
5081 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
5082 // which requires some of its traits to have the complete type. However,
5083 // the completeness of the type cannot impact these traits' semantics, and
5084 // so they don't require it. This matches the comments on these traits in
5085 // Table 49.
5086 case UTT_IsConst:
5087 case UTT_IsVolatile:
5088 case UTT_IsSigned:
5089 case UTT_IsUnboundedArray:
5090 case UTT_IsUnsigned:
5091
5092 // This type trait always returns false, checking the type is moot.
5093 case UTT_IsInterfaceClass:
5094 return true;
5095
5096 // C++14 [meta.unary.prop]:
5097 // If T is a non-union class type, T shall be a complete type.
5098 case UTT_IsEmpty:
5099 case UTT_IsPolymorphic:
5100 case UTT_IsAbstract:
5101 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
5102 if (!RD->isUnion())
5103 return !S.RequireCompleteType(
5104 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5105 return true;
5106
5107 // C++14 [meta.unary.prop]:
5108 // If T is a class type, T shall be a complete type.
5109 case UTT_IsFinal:
5110 case UTT_IsSealed:
5111 if (ArgTy->getAsCXXRecordDecl())
5112 return !S.RequireCompleteType(
5113 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5114 return true;
5115
5116 // LWG3823: T shall be an array type, a complete type, or cv void.
5117 case UTT_IsAggregate:
5118 if (ArgTy->isArrayType() || ArgTy->isVoidType())
5119 return true;
5120
5121 return !S.RequireCompleteType(
5122 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5123
5124 // C++1z [meta.unary.prop]:
5125 // remove_all_extents_t<T> shall be a complete type or cv void.
5126 case UTT_IsTrivial:
5127 case UTT_IsTriviallyCopyable:
5128 case UTT_IsStandardLayout:
5129 case UTT_IsPOD:
5130 case UTT_IsLiteral:
5131 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
5132 // impose the same constraints.
5133 case UTT_IsTriviallyRelocatable:
5134 case UTT_IsTriviallyEqualityComparable:
5135 case UTT_CanPassInRegs:
5136 // Per the GCC type traits documentation, T shall be a complete type, cv void,
5137 // or an array of unknown bound. But GCC actually imposes the same constraints
5138 // as above.
5139 case UTT_HasNothrowAssign:
5140 case UTT_HasNothrowMoveAssign:
5141 case UTT_HasNothrowConstructor:
5142 case UTT_HasNothrowCopy:
5143 case UTT_HasTrivialAssign:
5144 case UTT_HasTrivialMoveAssign:
5145 case UTT_HasTrivialDefaultConstructor:
5146 case UTT_HasTrivialMoveConstructor:
5147 case UTT_HasTrivialCopy:
5148 case UTT_HasTrivialDestructor:
5149 case UTT_HasVirtualDestructor:
5150 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
5151 [[fallthrough]];
5152
5153 // C++1z [meta.unary.prop]:
5154 // T shall be a complete type, cv void, or an array of unknown bound.
5155 case UTT_IsDestructible:
5156 case UTT_IsNothrowDestructible:
5157 case UTT_IsTriviallyDestructible:
5158 case UTT_HasUniqueObjectRepresentations:
5159 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
5160 return true;
5161
5162 return !S.RequireCompleteType(
5163 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
5164 }
5165}
5166
5168 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
5169 bool (CXXRecordDecl::*HasTrivial)() const,
5170 bool (CXXRecordDecl::*HasNonTrivial)() const,
5171 bool (CXXMethodDecl::*IsDesiredOp)() const)
5172{
5173 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5174 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
5175 return true;
5176
5177 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
5178 DeclarationNameInfo NameInfo(Name, KeyLoc);
5180 if (Self.LookupQualifiedName(Res, RD)) {
5181 bool FoundOperator = false;
5182 Res.suppressDiagnostics();
5183 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
5184 Op != OpEnd; ++Op) {
5185 if (isa<FunctionTemplateDecl>(*Op))
5186 continue;
5187
5188 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
5189 if((Operator->*IsDesiredOp)()) {
5190 FoundOperator = true;
5191 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
5192 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5193 if (!CPT || !CPT->isNothrow())
5194 return false;
5195 }
5196 }
5197 return FoundOperator;
5198 }
5199 return false;
5200}
5201
5203 SourceLocation KeyLoc,
5204 TypeSourceInfo *TInfo) {
5205 QualType T = TInfo->getType();
5206 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5207
5208 ASTContext &C = Self.Context;
5209 switch(UTT) {
5210 default: llvm_unreachable("not a UTT");
5211 // Type trait expressions corresponding to the primary type category
5212 // predicates in C++0x [meta.unary.cat].
5213 case UTT_IsVoid:
5214 return T->isVoidType();
5215 case UTT_IsIntegral:
5216 return T->isIntegralType(C);
5217 case UTT_IsFloatingPoint:
5218 return T->isFloatingType();
5219 case UTT_IsArray:
5220 // Zero-sized arrays aren't considered arrays in partial specializations,
5221 // so __is_array shouldn't consider them arrays either.
5222 if (const auto *CAT = C.getAsConstantArrayType(T))
5223 return CAT->getSize() != 0;
5224 return T->isArrayType();
5225 case UTT_IsBoundedArray:
5226 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_bounded_array))
5227 return false;
5228 // Zero-sized arrays aren't considered arrays in partial specializations,
5229 // so __is_bounded_array shouldn't consider them arrays either.
5230 if (const auto *CAT = C.getAsConstantArrayType(T))
5231 return CAT->getSize() != 0;
5232 return T->isArrayType() && !T->isIncompleteArrayType();
5233 case UTT_IsUnboundedArray:
5234 if (DiagnoseVLAInCXXTypeTrait(Self, TInfo, tok::kw___is_unbounded_array))
5235 return false;
5236 return T->isIncompleteArrayType();
5237 case UTT_IsPointer:
5238 return T->isAnyPointerType();
5239 case UTT_IsNullPointer:
5240 return T->isNullPtrType();
5241 case UTT_IsLvalueReference:
5242 return T->isLValueReferenceType();
5243 case UTT_IsRvalueReference:
5244 return T->isRValueReferenceType();
5245 case UTT_IsMemberFunctionPointer:
5247 case UTT_IsMemberObjectPointer:
5248 return T->isMemberDataPointerType();
5249 case UTT_IsEnum:
5250 return T->isEnumeralType();
5251 case UTT_IsScopedEnum:
5252 return T->isScopedEnumeralType();
5253 case UTT_IsUnion:
5254 return T->isUnionType();
5255 case UTT_IsClass:
5256 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
5257 case UTT_IsFunction:
5258 return T->isFunctionType();
5259
5260 // Type trait expressions which correspond to the convenient composition
5261 // predicates in C++0x [meta.unary.comp].
5262 case UTT_IsReference:
5263 return T->isReferenceType();
5264 case UTT_IsArithmetic:
5265 return T->isArithmeticType() && !T->isEnumeralType();
5266 case UTT_IsFundamental:
5267 return T->isFundamentalType();
5268 case UTT_IsObject:
5269 return T->isObjectType();
5270 case UTT_IsScalar:
5271 // Note: semantic analysis depends on Objective-C lifetime types to be
5272 // considered scalar types. However, such types do not actually behave
5273 // like scalar types at run time (since they may require retain/release
5274 // operations), so we report them as non-scalar.
5275 if (T->isObjCLifetimeType()) {
5276 switch (T.getObjCLifetime()) {
5279 return true;
5280
5284 return false;
5285 }
5286 }
5287
5288 return T->isScalarType();
5289 case UTT_IsCompound:
5290 return T->isCompoundType();
5291 case UTT_IsMemberPointer:
5292 return T->isMemberPointerType();
5293
5294 // Type trait expressions which correspond to the type property predicates
5295 // in C++0x [meta.unary.prop].
5296 case UTT_IsConst:
5297 return T.isConstQualified();
5298 case UTT_IsVolatile:
5299 return T.isVolatileQualified();
5300 case UTT_IsTrivial:
5301 return T.isTrivialType(C);
5302 case UTT_IsTriviallyCopyable:
5303 return T.isTriviallyCopyableType(C);
5304 case UTT_IsStandardLayout:
5305 return T->isStandardLayoutType();
5306 case UTT_IsPOD:
5307 return T.isPODType(C);
5308 case UTT_IsLiteral:
5309 return T->isLiteralType(C);
5310 case UTT_IsEmpty:
5311 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5312 return !RD->isUnion() && RD->isEmpty();
5313 return false;
5314 case UTT_IsPolymorphic:
5315 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5316 return !RD->isUnion() && RD->isPolymorphic();
5317 return false;
5318 case UTT_IsAbstract:
5319 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5320 return !RD->isUnion() && RD->isAbstract();
5321 return false;
5322 case UTT_IsAggregate:
5323 // Report vector extensions and complex types as aggregates because they
5324 // support aggregate initialization. GCC mirrors this behavior for vectors
5325 // but not _Complex.
5326 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5328 // __is_interface_class only returns true when CL is invoked in /CLR mode and
5329 // even then only when it is used with the 'interface struct ...' syntax
5330 // Clang doesn't support /CLR which makes this type trait moot.
5331 case UTT_IsInterfaceClass:
5332 return false;
5333 case UTT_IsFinal:
5334 case UTT_IsSealed:
5335 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5336 return RD->hasAttr<FinalAttr>();
5337 return false;
5338 case UTT_IsSigned:
5339 // Enum types should always return false.
5340 // Floating points should always return true.
5341 return T->isFloatingType() ||
5343 case UTT_IsUnsigned:
5344 // Enum types should always return false.
5345 return T->isUnsignedIntegerType() && !T->isEnumeralType();
5346
5347 // Type trait expressions which query classes regarding their construction,
5348 // destruction, and copying. Rather than being based directly on the
5349 // related type predicates in the standard, they are specified by both
5350 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5351 // specifications.
5352 //
5353 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5354 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5355 //
5356 // Note that these builtins do not behave as documented in g++: if a class
5357 // has both a trivial and a non-trivial special member of a particular kind,
5358 // they return false! For now, we emulate this behavior.
5359 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5360 // does not correctly compute triviality in the presence of multiple special
5361 // members of the same kind. Revisit this once the g++ bug is fixed.
5362 case UTT_HasTrivialDefaultConstructor:
5363 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5364 // If __is_pod (type) is true then the trait is true, else if type is
5365 // a cv class or union type (or array thereof) with a trivial default
5366 // constructor ([class.ctor]) then the trait is true, else it is false.
5367 if (T.isPODType(C))
5368 return true;
5369 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5370 return RD->hasTrivialDefaultConstructor() &&
5372 return false;
5373 case UTT_HasTrivialMoveConstructor:
5374 // This trait is implemented by MSVC 2012 and needed to parse the
5375 // standard library headers. Specifically this is used as the logic
5376 // behind std::is_trivially_move_constructible (20.9.4.3).
5377 if (T.isPODType(C))
5378 return true;
5379 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5381 return false;
5382 case UTT_HasTrivialCopy:
5383 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5384 // If __is_pod (type) is true or type is a reference type then
5385 // the trait is true, else if type is a cv class or union type
5386 // with a trivial copy constructor ([class.copy]) then the trait
5387 // is true, else it is false.
5388 if (T.isPODType(C) || T->isReferenceType())
5389 return true;
5390 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5391 return RD->hasTrivialCopyConstructor() &&
5393 return false;
5394 case UTT_HasTrivialMoveAssign:
5395 // This trait is implemented by MSVC 2012 and needed to parse the
5396 // standard library headers. Specifically it is used as the logic
5397 // behind std::is_trivially_move_assignable (20.9.4.3)
5398 if (T.isPODType(C))
5399 return true;
5400 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5402 return false;
5403 case UTT_HasTrivialAssign:
5404 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5405 // If type is const qualified or is a reference type then the
5406 // trait is false. Otherwise if __is_pod (type) is true then the
5407 // trait is true, else if type is a cv class or union type with
5408 // a trivial copy assignment ([class.copy]) then the trait is
5409 // true, else it is false.
5410 // Note: the const and reference restrictions are interesting,
5411 // given that const and reference members don't prevent a class
5412 // from having a trivial copy assignment operator (but do cause
5413 // errors if the copy assignment operator is actually used, q.v.
5414 // [class.copy]p12).
5415
5416 if (T.isConstQualified())
5417 return false;
5418 if (T.isPODType(C))
5419 return true;
5420 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5421 return RD->hasTrivialCopyAssignment() &&
5423 return false;
5424 case UTT_IsDestructible:
5425 case UTT_IsTriviallyDestructible:
5426 case UTT_IsNothrowDestructible:
5427 // C++14 [meta.unary.prop]:
5428 // For reference types, is_destructible<T>::value is true.
5429 if (T->isReferenceType())
5430 return true;
5431
5432 // Objective-C++ ARC: autorelease types don't require destruction.
5433 if (T->isObjCLifetimeType() &&
5434 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5435 return true;
5436
5437 // C++14 [meta.unary.prop]:
5438 // For incomplete types and function types, is_destructible<T>::value is
5439 // false.
5440 if (T->isIncompleteType() || T->isFunctionType())
5441 return false;
5442
5443 // A type that requires destruction (via a non-trivial destructor or ARC
5444 // lifetime semantics) is not trivially-destructible.
5445 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5446 return false;
5447
5448 // C++14 [meta.unary.prop]:
5449 // For object types and given U equal to remove_all_extents_t<T>, if the
5450 // expression std::declval<U&>().~U() is well-formed when treated as an
5451 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
5452 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5453 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5454 if (!Destructor)
5455 return false;
5456 // C++14 [dcl.fct.def.delete]p2:
5457 // A program that refers to a deleted function implicitly or
5458 // explicitly, other than to declare it, is ill-formed.
5459 if (Destructor->isDeleted())
5460 return false;
5461 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5462 return false;
5463 if (UTT == UTT_IsNothrowDestructible) {
5464 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5465 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5466 if (!CPT || !CPT->isNothrow())
5467 return false;
5468 }
5469 }
5470 return true;
5471
5472 case UTT_HasTrivialDestructor:
5473 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5474 // If __is_pod (type) is true or type is a reference type
5475 // then the trait is true, else if type is a cv class or union
5476 // type (or array thereof) with a trivial destructor
5477 // ([class.dtor]) then the trait is true, else it is
5478 // false.
5479 if (T.isPODType(C) || T->isReferenceType())
5480 return true;
5481
5482 // Objective-C++ ARC: autorelease types don't require destruction.
5483 if (T->isObjCLifetimeType() &&
5484 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5485 return true;
5486
5487 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5488 return RD->hasTrivialDestructor();
5489 return false;
5490 // TODO: Propagate nothrowness for implicitly declared special members.
5491 case UTT_HasNothrowAssign:
5492 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5493 // If type is const qualified or is a reference type then the
5494 // trait is false. Otherwise if __has_trivial_assign (type)
5495 // is true then the trait is true, else if type is a cv class
5496 // or union type with copy assignment operators that are known
5497 // not to throw an exception then the trait is true, else it is
5498 // false.
5499 if (C.getBaseElementType(T).isConstQualified())
5500 return false;
5501 if (T->isReferenceType())
5502 return false;
5503 if (T.isPODType(C) || T->isObjCLifetimeType())
5504 return true;
5505
5506 if (const RecordType *RT = T->getAs<RecordType>())
5507 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5511 return false;
5512 case UTT_HasNothrowMoveAssign:
5513 // This trait is implemented by MSVC 2012 and needed to parse the
5514 // standard library headers. Specifically this is used as the logic
5515 // behind std::is_nothrow_move_assignable (20.9.4.3).
5516 if (T.isPODType(C))
5517 return true;
5518
5519 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5520 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5524 return false;
5525 case UTT_HasNothrowCopy:
5526 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5527 // If __has_trivial_copy (type) is true then the trait is true, else
5528 // if type is a cv class or union type with copy constructors that are
5529 // known not to throw an exception then the trait is true, else it is
5530 // false.
5531 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5532 return true;
5533 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5534 if (RD->hasTrivialCopyConstructor() &&
5536 return true;
5537
5538 bool FoundConstructor = false;
5539 unsigned FoundTQs;
5540 for (const auto *ND : Self.LookupConstructors(RD)) {
5541 // A template constructor is never a copy constructor.
5542 // FIXME: However, it may actually be selected at the actual overload
5543 // resolution point.
5544 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5545 continue;
5546 // UsingDecl itself is not a constructor
5547 if (isa<UsingDecl>(ND))
5548 continue;
5549 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5550 if (Constructor->isCopyConstructor(FoundTQs)) {
5551 FoundConstructor = true;
5552 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5553 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5554 if (!CPT)
5555 return false;
5556 // TODO: check whether evaluating default arguments can throw.
5557 // For now, we'll be conservative and assume that they can throw.
5558 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5559 return false;
5560 }
5561 }
5562
5563 return FoundConstructor;
5564 }
5565 return false;
5566 case UTT_HasNothrowConstructor:
5567 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5568 // If __has_trivial_constructor (type) is true then the trait is
5569 // true, else if type is a cv class or union type (or array
5570 // thereof) with a default constructor that is known not to
5571 // throw an exception then the trait is true, else it is false.
5572 if (T.isPODType(C) || T->isObjCLifetimeType())
5573 return true;
5574 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5575 if (RD->hasTrivialDefaultConstructor() &&
5577 return true;
5578
5579 bool FoundConstructor = false;
5580 for (const auto *ND : Self.LookupConstructors(RD)) {
5581 // FIXME: In C++0x, a constructor template can be a default constructor.
5582 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5583 continue;
5584 // UsingDecl itself is not a constructor
5585 if (isa<UsingDecl>(ND))
5586 continue;
5587 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5588 if (Constructor->isDefaultConstructor()) {
5589 FoundConstructor = true;
5590 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5591 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5592 if (!CPT)
5593 return false;
5594 // FIXME: check whether evaluating default arguments can throw.
5595 // For now, we'll be conservative and assume that they can throw.
5596 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5597 return false;
5598 }
5599 }
5600 return FoundConstructor;
5601 }
5602 return false;
5603 case UTT_HasVirtualDestructor:
5604 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5605 // If type is a class type with a virtual destructor ([class.dtor])
5606 // then the trait is true, else it is false.
5607 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5608 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5609 return Destructor->isVirtual();
5610 return false;
5611
5612 // These type trait expressions are modeled on the specifications for the
5613 // Embarcadero C++0x type trait functions:
5614 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5615 case UTT_IsCompleteType:
5616 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5617 // Returns True if and only if T is a complete type at the point of the
5618 // function call.
5619 return !T->isIncompleteType();
5620 case UTT_HasUniqueObjectRepresentations:
5621 return C.hasUniqueObjectRepresentations(T);
5622 case UTT_IsTriviallyRelocatable:
5623 return T.isTriviallyRelocatableType(C);
5624 case UTT_IsReferenceable:
5625 return T.isReferenceable();
5626 case UTT_CanPassInRegs:
5627 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())
5628 return RD->canPassInRegisters();
5629 Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;
5630 return false;
5631 case UTT_IsTriviallyEqualityComparable:
5632 return T.isTriviallyEqualityComparableType(C);
5633 }
5634}
5635
5636static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, const TypeSourceInfo *Lhs,
5637 const TypeSourceInfo *Rhs, SourceLocation KeyLoc);
5638
5640 Sema &Self, const TypeSourceInfo *Lhs, const TypeSourceInfo *Rhs,
5641 SourceLocation KeyLoc, llvm::BumpPtrAllocator &OpaqueExprAllocator) {
5642
5643 QualType LhsT = Lhs->getType();
5644 QualType RhsT = Rhs->getType();
5645
5646 // C++0x [meta.rel]p4:
5647 // Given the following function prototype:
5648 //
5649 // template <class T>
5650 // typename add_rvalue_reference<T>::type create();
5651 //
5652 // the predicate condition for a template specialization
5653 // is_convertible<From, To> shall be satisfied if and only if
5654 // the return expression in the following code would be
5655 // well-formed, including any implicit conversions to the return
5656 // type of the function:
5657 //
5658 // To test() {
5659 // return create<From>();
5660 // }
5661 //
5662 // Access checking is performed as if in a context unrelated to To and
5663 // From. Only the validity of the immediate context of the expression
5664 // of the return-statement (including conversions to the return type)
5665 // is considered.
5666 //
5667 // We model the initialization as a copy-initialization of a temporary
5668 // of the appropriate type, which for this expression is identical to the
5669 // return statement (since NRVO doesn't apply).
5670
5671 // Functions aren't allowed to return function or array types.
5672 if (RhsT->isFunctionType() || RhsT->isArrayType())
5673 return ExprError();
5674
5675 // A function definition requires a complete, non-abstract return type.
5676 if (!Self.isCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT) ||
5677 Self.isAbstractType(Rhs->getTypeLoc().getBeginLoc(), RhsT))
5678 return ExprError();
5679
5680 // Compute the result of add_rvalue_reference.
5681 if (LhsT->isObjectType() || LhsT->isFunctionType())
5682 LhsT = Self.Context.getRValueReferenceType(LhsT);
5683
5684 // Build a fake source and destination for initialization.
5686 Expr *From = new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5687 OpaqueValueExpr(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5689 InitializationKind Kind =
5691
5692 // Perform the initialization in an unevaluated context within a SFINAE
5693 // trap at translation unit scope.
5696 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5697 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5698 InitializationSequence Init(Self, To, Kind, From);
5699 if (Init.Failed())
5700 return ExprError();
5701
5702 ExprResult Result = Init.Perform(Self, To, Kind, From);
5703 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5704 return ExprError();
5705
5706 return Result;
5707}
5708
5710 SourceLocation KWLoc,
5712 SourceLocation RParenLoc,
5713 bool IsDependent) {
5714 if (IsDependent)
5715 return false;
5716
5717 if (Kind <= UTT_Last)
5718 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]);
5719
5720 // Evaluate ReferenceBindsToTemporary and ReferenceConstructsFromTemporary
5721 // alongside the IsConstructible traits to avoid duplication.
5722 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary &&
5723 Kind != BTT_ReferenceConstructsFromTemporary &&
5724 Kind != BTT_ReferenceConvertsFromTemporary)
5725 return EvaluateBinaryTypeTrait(S, Kind, Args[0],
5726 Args[1], RParenLoc);
5727
5728 switch (Kind) {
5729 case clang::BTT_ReferenceBindsToTemporary:
5730 case clang::BTT_ReferenceConstructsFromTemporary:
5731 case clang::BTT_ReferenceConvertsFromTemporary:
5732 case clang::TT_IsConstructible:
5733 case clang::TT_IsNothrowConstructible:
5734 case clang::TT_IsTriviallyConstructible: {
5735 // C++11 [meta.unary.prop]:
5736 // is_trivially_constructible is defined as:
5737 //
5738 // is_constructible<T, Args...>::value is true and the variable
5739 // definition for is_constructible, as defined below, is known to call
5740 // no operation that is not trivial.
5741 //
5742 // The predicate condition for a template specialization
5743 // is_constructible<T, Args...> shall be satisfied if and only if the
5744 // following variable definition would be well-formed for some invented
5745 // variable t:
5746 //
5747 // T t(create<Args>()...);
5748 assert(!Args.empty());
5749
5750 // Precondition: T and all types in the parameter pack Args shall be
5751 // complete types, (possibly cv-qualified) void, or arrays of
5752 // unknown bound.
5753 for (const auto *TSI : Args) {
5754 QualType ArgTy = TSI->getType();
5755 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5756 continue;
5757
5758 if (S.RequireCompleteType(KWLoc, ArgTy,
5759 diag::err_incomplete_type_used_in_type_trait_expr))
5760 return false;
5761 }
5762
5763 // Make sure the first argument is not incomplete nor a function type.
5764 QualType T = Args[0]->getType();
5765 if (T->isIncompleteType() || T->isFunctionType())
5766 return false;
5767
5768 // Make sure the first argument is not an abstract type.
5770 if (RD && RD->isAbstract())
5771 return false;
5772
5773 llvm::BumpPtrAllocator OpaqueExprAllocator;
5774 SmallVector<Expr *, 2> ArgExprs;
5775 ArgExprs.reserve(Args.size() - 1);
5776 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5777 QualType ArgTy = Args[I]->getType();
5778 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5779 ArgTy = S.Context.getRValueReferenceType(ArgTy);
5780 ArgExprs.push_back(
5781 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5782 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5785 }
5786
5787 // Perform the initialization in an unevaluated context within a SFINAE
5788 // trap at translation unit scope.
5791 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5795 InitializationKind InitKind(
5796 Kind == clang::BTT_ReferenceConvertsFromTemporary
5797 ? InitializationKind::CreateCopy(KWLoc, KWLoc)
5798 : InitializationKind::CreateDirect(KWLoc, KWLoc, RParenLoc));
5799 InitializationSequence Init(S, To, InitKind, ArgExprs);
5800 if (Init.Failed())
5801 return false;
5802
5803 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5804 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5805 return false;
5806
5807 if (Kind == clang::TT_IsConstructible)
5808 return true;
5809
5810 if (Kind == clang::BTT_ReferenceBindsToTemporary ||
5811 Kind == clang::BTT_ReferenceConstructsFromTemporary ||
5812 Kind == clang::BTT_ReferenceConvertsFromTemporary) {
5813 if (!T->isReferenceType())
5814 return false;
5815
5816 if (!Init.isDirectReferenceBinding())
5817 return true;
5818
5819 if (Kind == clang::BTT_ReferenceBindsToTemporary)
5820 return false;
5821
5822 QualType U = Args[1]->getType();
5823 if (U->isReferenceType())
5824 return false;
5825
5827 S.Context.getPointerType(T.getNonReferenceType()));
5829 S.Context.getPointerType(U.getNonReferenceType()));
5830 return !CheckConvertibilityForTypeTraits(S, UPtr, TPtr, RParenLoc,
5831 OpaqueExprAllocator)
5832 .isInvalid();
5833 }
5834
5835 if (Kind == clang::TT_IsNothrowConstructible)
5836 return S.canThrow(Result.get()) == CT_Cannot;
5837
5838 if (Kind == clang::TT_IsTriviallyConstructible) {
5839 // Under Objective-C ARC and Weak, if the destination has non-trivial
5840 // Objective-C lifetime, this is a non-trivial construction.
5841 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5842 return false;
5843
5844 // The initialization succeeded; now make sure there are no non-trivial
5845 // calls.
5846 return !Result.get()->hasNonTrivialCall(S.Context);
5847 }
5848
5849 llvm_unreachable("unhandled type trait");
5850 return false;
5851 }
5852 default: llvm_unreachable("not a TT");
5853 }
5854
5855 return false;
5856}
5857
5858namespace {
5859void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5860 SourceLocation KWLoc) {
5861 TypeTrait Replacement;
5862 switch (Kind) {
5863 case UTT_HasNothrowAssign:
5864 case UTT_HasNothrowMoveAssign:
5865 Replacement = BTT_IsNothrowAssignable;
5866 break;
5867 case UTT_HasNothrowCopy:
5868 case UTT_HasNothrowConstructor:
5869 Replacement = TT_IsNothrowConstructible;
5870 break;
5871 case UTT_HasTrivialAssign:
5872 case UTT_HasTrivialMoveAssign:
5873 Replacement = BTT_IsTriviallyAssignable;
5874 break;
5875 case UTT_HasTrivialCopy:
5876 Replacement = UTT_IsTriviallyCopyable;
5877 break;
5878 case UTT_HasTrivialDefaultConstructor:
5879 case UTT_HasTrivialMoveConstructor:
5880 Replacement = TT_IsTriviallyConstructible;
5881 break;
5882 case UTT_HasTrivialDestructor:
5883 Replacement = UTT_IsTriviallyDestructible;
5884 break;
5885 default:
5886 return;
5887 }
5888 S.Diag(KWLoc, diag::warn_deprecated_builtin)
5889 << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5890}
5891}
5892
5893bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
5894 if (Arity && N != Arity) {
5895 Diag(Loc, diag::err_type_trait_arity)
5896 << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
5897 return false;
5898 }
5899
5900 if (!Arity && N == 0) {
5901 Diag(Loc, diag::err_type_trait_arity)
5902 << 1 << 1 << 1 << (int)N << SourceRange(Loc);
5903 return false;
5904 }
5905 return true;
5906}
5907
5909 Bool,
5910};
5911
5913 return TypeTraitReturnType::Bool;
5914}
5915
5918 SourceLocation RParenLoc) {
5919 if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
5920 return ExprError();
5921
5923 *this, Kind, KWLoc, Args[0]->getType()))
5924 return ExprError();
5925
5926 DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5927
5928 bool Dependent = false;
5929 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5930 if (Args[I]->getType()->isDependentType()) {
5931 Dependent = true;
5932 break;
5933 }
5934 }
5935
5936 switch (GetReturnType(Kind)) {
5937 case TypeTraitReturnType::Bool: {
5938 bool Result = EvaluateBooleanTypeTrait(*this, Kind, KWLoc, Args, RParenLoc,
5939 Dependent);
5941 KWLoc, Kind, Args, RParenLoc, Result);
5942 }
5943 }
5944 llvm_unreachable("unhandled type trait return type");
5945}
5946
5949 SourceLocation RParenLoc) {
5951 ConvertedArgs.reserve(Args.size());
5952
5953 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5954 TypeSourceInfo *TInfo;
5955 QualType T = GetTypeFromParser(Args[I], &TInfo);
5956 if (!TInfo)
5957 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5958
5959 ConvertedArgs.push_back(TInfo);
5960 }
5961
5962 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5963}
5964
5966 const TypeSourceInfo *Rhs, SourceLocation KeyLoc) {
5967 QualType LhsT = Lhs->getType();
5968 QualType RhsT = Rhs->getType();
5969
5970 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5971 "Cannot evaluate traits of dependent types");
5972
5973 switch(BTT) {
5974 case BTT_IsBaseOf: {
5975 // C++0x [meta.rel]p2
5976 // Base is a base class of Derived without regard to cv-qualifiers or
5977 // Base and Derived are not unions and name the same class type without
5978 // regard to cv-qualifiers.
5979
5980 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5981 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5982 if (!rhsRecord || !lhsRecord) {
5983 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5984 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5985 if (!LHSObjTy || !RHSObjTy)
5986 return false;
5987
5988 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5989 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5990 if (!BaseInterface || !DerivedInterface)
5991 return false;
5992
5993 if (Self.RequireCompleteType(
5994 Rhs->getTypeLoc().getBeginLoc(), RhsT,
5995 diag::err_incomplete_type_used_in_type_trait_expr))
5996 return false;
5997
5998 return BaseInterface->isSuperClassOf(DerivedInterface);
5999 }
6000
6001 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
6002 == (lhsRecord == rhsRecord));
6003
6004 // Unions are never base classes, and never have base classes.
6005 // It doesn't matter if they are complete or not. See PR#41843
6006 if (lhsRecord && lhsRecord->getDecl()->isUnion())
6007 return false;
6008 if (rhsRecord && rhsRecord->getDecl()->isUnion())
6009 return false;
6010
6011 if (lhsRecord == rhsRecord)
6012 return true;
6013
6014 // C++0x [meta.rel]p2:
6015 // If Base and Derived are class types and are different types
6016 // (ignoring possible cv-qualifiers) then Derived shall be a
6017 // complete type.
6018 if (Self.RequireCompleteType(
6019 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6020 diag::err_incomplete_type_used_in_type_trait_expr))
6021 return false;
6022
6023 return cast<CXXRecordDecl>(rhsRecord->getDecl())
6024 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
6025 }
6026 case BTT_IsSame:
6027 return Self.Context.hasSameType(LhsT, RhsT);
6028 case BTT_TypeCompatible: {
6029 // GCC ignores cv-qualifiers on arrays for this builtin.
6030 Qualifiers LhsQuals, RhsQuals;
6031 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
6032 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
6033 return Self.Context.typesAreCompatible(Lhs, Rhs);
6034 }
6035 case BTT_IsConvertible:
6036 case BTT_IsConvertibleTo:
6037 case BTT_IsNothrowConvertible: {
6038 if (RhsT->isVoidType())
6039 return LhsT->isVoidType();
6040 llvm::BumpPtrAllocator OpaqueExprAllocator;
6042 OpaqueExprAllocator);
6043 if (Result.isInvalid())
6044 return false;
6045
6046 if (BTT != BTT_IsNothrowConvertible)
6047 return true;
6048
6049 return Self.canThrow(Result.get()) == CT_Cannot;
6050 }
6051
6052 case BTT_IsAssignable:
6053 case BTT_IsNothrowAssignable:
6054 case BTT_IsTriviallyAssignable: {
6055 // C++11 [meta.unary.prop]p3:
6056 // is_trivially_assignable is defined as:
6057 // is_assignable<T, U>::value is true and the assignment, as defined by
6058 // is_assignable, is known to call no operation that is not trivial
6059 //
6060 // is_assignable is defined as:
6061 // The expression declval<T>() = declval<U>() is well-formed when
6062 // treated as an unevaluated operand (Clause 5).
6063 //
6064 // For both, T and U shall be complete types, (possibly cv-qualified)
6065 // void, or arrays of unknown bound.
6066 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
6067 Self.RequireCompleteType(
6068 Lhs->getTypeLoc().getBeginLoc(), LhsT,
6069 diag::err_incomplete_type_used_in_type_trait_expr))
6070 return false;
6071 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
6072 Self.RequireCompleteType(
6073 Rhs->getTypeLoc().getBeginLoc(), RhsT,
6074 diag::err_incomplete_type_used_in_type_trait_expr))
6075 return false;
6076
6077 // cv void is never assignable.
6078 if (LhsT->isVoidType() || RhsT->isVoidType())
6079 return false;
6080
6081 // Build expressions that emulate the effect of declval<T>() and
6082 // declval<U>().
6083 if (LhsT->isObjectType() || LhsT->isFunctionType())
6084 LhsT = Self.Context.getRValueReferenceType(LhsT);
6085 if (RhsT->isObjectType() || RhsT->isFunctionType())
6086 RhsT = Self.Context.getRValueReferenceType(RhsT);
6087 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
6089 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
6091
6092 // Attempt the assignment in an unevaluated context within a SFINAE
6093 // trap at translation unit scope.
6096 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
6097 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
6098 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
6099 &Rhs);
6100 if (Result.isInvalid())
6101 return false;
6102
6103 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
6104 Self.CheckUnusedVolatileAssignment(Result.get());
6105
6106 if (SFINAE.hasErrorOccurred())
6107 return false;
6108
6109 if (BTT == BTT_IsAssignable)
6110 return true;
6111
6112 if (BTT == BTT_IsNothrowAssignable)
6113 return Self.canThrow(Result.get()) == CT_Cannot;
6114
6115 if (BTT == BTT_IsTriviallyAssignable) {
6116 // Under Objective-C ARC and Weak, if the destination has non-trivial
6117 // Objective-C lifetime, this is a non-trivial assignment.
6119 return false;
6120
6121 return !Result.get()->hasNonTrivialCall(Self.Context);
6122 }
6123
6124 llvm_unreachable("unhandled type trait");
6125 return false;
6126 }
6127 case BTT_IsLayoutCompatible: {
6128 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType())
6129 Self.RequireCompleteType(Lhs->getTypeLoc().getBeginLoc(), LhsT,
6130 diag::err_incomplete_type);
6131 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType())
6132 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6133 diag::err_incomplete_type);
6134
6135 DiagnoseVLAInCXXTypeTrait(Self, Lhs, tok::kw___is_layout_compatible);
6136 DiagnoseVLAInCXXTypeTrait(Self, Rhs, tok::kw___is_layout_compatible);
6137
6138 return Self.IsLayoutCompatible(LhsT, RhsT);
6139 }
6140 case BTT_IsPointerInterconvertibleBaseOf: {
6141 if (LhsT->isStructureOrClassType() && RhsT->isStructureOrClassType() &&
6142 !Self.getASTContext().hasSameUnqualifiedType(LhsT, RhsT)) {
6143 Self.RequireCompleteType(Rhs->getTypeLoc().getBeginLoc(), RhsT,
6144 diag::err_incomplete_type);
6145 }
6146
6148 tok::kw___is_pointer_interconvertible_base_of);
6150 tok::kw___is_pointer_interconvertible_base_of);
6151
6152 return Self.IsPointerInterconvertibleBaseOf(Lhs, Rhs);
6153 }
6154 case BTT_IsDeducible: {
6155 const auto *TSTToBeDeduced = cast<DeducedTemplateSpecializationType>(LhsT);
6156 sema::TemplateDeductionInfo Info(KeyLoc);
6157 return Self.DeduceTemplateArgumentsFromType(
6158 TSTToBeDeduced->getTemplateName().getAsTemplateDecl(), RhsT,
6160 }
6161 default:
6162 llvm_unreachable("not a BTT");
6163 }
6164 llvm_unreachable("Unknown type trait or not implemented");
6165}
6166
6168 SourceLocation KWLoc,
6169 ParsedType Ty,
6170 Expr* DimExpr,
6171 SourceLocation RParen) {
6172 TypeSourceInfo *TSInfo;
6173 QualType T = GetTypeFromParser(Ty, &TSInfo);
6174 if (!TSInfo)
6176
6177 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
6178}
6179
6181 QualType T, Expr *DimExpr,
6182 SourceLocation KeyLoc) {
6183 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
6184
6185 switch(ATT) {
6186 case ATT_ArrayRank:
6187 if (T->isArrayType()) {
6188 unsigned Dim = 0;
6189 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6190 ++Dim;
6191 T = AT->getElementType();
6192 }
6193 return Dim;
6194 }
6195 return 0;
6196
6197 case ATT_ArrayExtent: {
6198 llvm::APSInt Value;
6199 uint64_t Dim;
6200 if (Self.VerifyIntegerConstantExpression(
6201 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
6202 .isInvalid())
6203 return 0;
6204 if (Value.isSigned() && Value.isNegative()) {
6205 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
6206 << DimExpr->getSourceRange();
6207 return 0;
6208 }
6209 Dim = Value.getLimitedValue();
6210
6211 if (T->isArrayType()) {
6212 unsigned D = 0;
6213 bool Matched = false;
6214 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
6215 if (Dim == D) {
6216 Matched = true;
6217 break;
6218 }
6219 ++D;
6220 T = AT->getElementType();
6221 }
6222
6223 if (Matched && T->isArrayType()) {
6224 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
6225 return CAT->getLimitedSize();
6226 }
6227 }
6228 return 0;
6229 }
6230 }
6231 llvm_unreachable("Unknown type trait or not implemented");
6232}
6233
6235 SourceLocation KWLoc,
6236 TypeSourceInfo *TSInfo,
6237 Expr* DimExpr,
6238 SourceLocation RParen) {
6239 QualType T = TSInfo->getType();
6240
6241 // FIXME: This should likely be tracked as an APInt to remove any host
6242 // assumptions about the width of size_t on the target.
6243 uint64_t Value = 0;
6244 if (!T->isDependentType())
6245 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
6246
6247 // While the specification for these traits from the Embarcadero C++
6248 // compiler's documentation says the return type is 'unsigned int', Clang
6249 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
6250 // compiler, there is no difference. On several other platforms this is an
6251 // important distinction.
6252 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
6253 RParen, Context.getSizeType());
6254}
6255
6257 SourceLocation KWLoc,
6258 Expr *Queried,
6259 SourceLocation RParen) {
6260 // If error parsing the expression, ignore.
6261 if (!Queried)
6262 return ExprError();
6263
6264 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
6265
6266 return Result;
6267}
6268
6270 switch (ET) {
6271 case ET_IsLValueExpr: return E->isLValue();
6272 case ET_IsRValueExpr:
6273 return E->isPRValue();
6274 }
6275 llvm_unreachable("Expression trait not covered by switch");
6276}
6277
6279 SourceLocation KWLoc,
6280 Expr *Queried,
6281 SourceLocation RParen) {
6282 if (Queried->isTypeDependent()) {
6283 // Delay type-checking for type-dependent expressions.
6284 } else if (Queried->hasPlaceholderType()) {
6285 ExprResult PE = CheckPlaceholderExpr(Queried);
6286 if (PE.isInvalid()) return ExprError();
6287 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
6288 }
6289
6290 bool Value = EvaluateExpressionTrait(ET, Queried);
6291
6292 return new (Context)
6293 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
6294}
6295
6297 ExprValueKind &VK,
6299 bool isIndirect) {
6300 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
6301 "placeholders should have been weeded out by now");
6302
6303 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
6304 // temporary materialization conversion otherwise.
6305 if (isIndirect)
6306 LHS = DefaultLvalueConversion(LHS.get());
6307 else if (LHS.get()->isPRValue())
6309 if (LHS.isInvalid())
6310 return QualType();
6311
6312 // The RHS always undergoes lvalue conversions.
6313 RHS = DefaultLvalueConversion(RHS.get());
6314 if (RHS.isInvalid()) return QualType();
6315
6316 const char *OpSpelling = isIndirect ? "->*" : ".*";
6317 // C++ 5.5p2
6318 // The binary operator .* [p3: ->*] binds its second operand, which shall
6319 // be of type "pointer to member of T" (where T is a completely-defined
6320 // class type) [...]
6321 QualType RHSType = RHS.get()->getType();
6322 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
6323 if (!MemPtr) {
6324 Diag(Loc, diag::err_bad_memptr_rhs)
6325 << OpSpelling << RHSType << RHS.get()->getSourceRange();
6326 return QualType();
6327 }
6328
6329 QualType Class(MemPtr->getClass(), 0);
6330
6331 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
6332 // member pointer points must be completely-defined. However, there is no
6333 // reason for this semantic distinction, and the rule is not enforced by
6334 // other compilers. Therefore, we do not check this property, as it is
6335 // likely to be considered a defect.
6336
6337 // C++ 5.5p2
6338 // [...] to its first operand, which shall be of class T or of a class of
6339 // which T is an unambiguous and accessible base class. [p3: a pointer to
6340 // such a class]
6341 QualType LHSType = LHS.get()->getType();
6342 if (isIndirect) {
6343 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
6344 LHSType = Ptr->getPointeeType();
6345 else {
6346 Diag(Loc, diag::err_bad_memptr_lhs)
6347 << OpSpelling << 1 << LHSType
6349 return QualType();
6350 }
6351 }
6352
6353 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
6354 // If we want to check the hierarchy, we need a complete type.
6355 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
6356 OpSpelling, (int)isIndirect)) {
6357 return QualType();
6358 }
6359
6360 if (!IsDerivedFrom(Loc, LHSType, Class)) {
6361 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6362 << (int)isIndirect << LHS.get()->getType();
6363 return QualType();
6364 }
6365
6366 CXXCastPath BasePath;
6368 LHSType, Class, Loc,
6369 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6370 &BasePath))
6371 return QualType();
6372
6373 // Cast LHS to type of use.
6374 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6375 if (isIndirect)
6376 UseType = Context.getPointerType(UseType);
6377 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6378 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6379 &BasePath);
6380 }
6381
6382 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6383 // Diagnose use of pointer-to-member type which when used as
6384 // the functional cast in a pointer-to-member expression.
6385 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6386 return QualType();
6387 }
6388
6389 // C++ 5.5p2
6390 // The result is an object or a function of the type specified by the
6391 // second operand.
6392 // The cv qualifiers are the union of those in the pointer and the left side,
6393 // in accordance with 5.5p5 and 5.2.5.
6394 QualType Result = MemPtr->getPointeeType();
6396
6397 // C++0x [expr.mptr.oper]p6:
6398 // In a .* expression whose object expression is an rvalue, the program is
6399 // ill-formed if the second operand is a pointer to member function with
6400 // ref-qualifier &. In a ->* expression or in a .* expression whose object
6401 // expression is an lvalue, the program is ill-formed if the second operand
6402 // is a pointer to member function with ref-qualifier &&.
6403 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6404 switch (Proto->getRefQualifier()) {
6405 case RQ_None:
6406 // Do nothing
6407 break;
6408
6409 case RQ_LValue:
6410 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6411 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6412 // is (exactly) 'const'.
6413 if (Proto->isConst() && !Proto->isVolatile())
6415 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6416 : diag::ext_pointer_to_const_ref_member_on_rvalue);
6417 else
6418 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6419 << RHSType << 1 << LHS.get()->getSourceRange();
6420 }
6421 break;
6422
6423 case RQ_RValue:
6424 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6425 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6426 << RHSType << 0 << LHS.get()->getSourceRange();
6427 break;
6428 }
6429 }
6430
6431 // C++ [expr.mptr.oper]p6:
6432 // The result of a .* expression whose second operand is a pointer
6433 // to a data member is of the same value category as its
6434 // first operand. The result of a .* expression whose second
6435 // operand is a pointer to a member function is a prvalue. The
6436 // result of an ->* expression is an lvalue if its second operand
6437 // is a pointer to data member and a prvalue otherwise.
6438 if (Result->isFunctionType()) {
6439 VK = VK_PRValue;
6440 return Context.BoundMemberTy;
6441 } else if (isIndirect) {
6442 VK = VK_LValue;
6443 } else {
6444 VK = LHS.get()->getValueKind();
6445 }
6446
6447 return Result;
6448}
6449
6450/// Try to convert a type to another according to C++11 5.16p3.
6451///
6452/// This is part of the parameter validation for the ? operator. If either
6453/// value operand is a class type, the two operands are attempted to be
6454/// converted to each other. This function does the conversion in one direction.
6455/// It returns true if the program is ill-formed and has already been diagnosed
6456/// as such.
6457static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6458 SourceLocation QuestionLoc,
6459 bool &HaveConversion,
6460 QualType &ToType) {
6461 HaveConversion = false;
6462 ToType = To->getType();
6463
6464 InitializationKind Kind =
6466 // C++11 5.16p3
6467 // The process for determining whether an operand expression E1 of type T1
6468 // can be converted to match an operand expression E2 of type T2 is defined
6469 // as follows:
6470 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6471 // implicitly converted to type "lvalue reference to T2", subject to the
6472 // constraint that in the conversion the reference must bind directly to
6473 // an lvalue.
6474 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6475 // implicitly converted to the type "rvalue reference to R2", subject to
6476 // the constraint that the reference must bind directly.
6477 if (To->isGLValue()) {
6478 QualType T = Self.Context.getReferenceQualifiedType(To);
6480
6481 InitializationSequence InitSeq(Self, Entity, Kind, From);
6482 if (InitSeq.isDirectReferenceBinding()) {
6483 ToType = T;
6484 HaveConversion = true;
6485 return false;
6486 }
6487
6488 if (InitSeq.isAmbiguous())
6489 return InitSeq.Diagnose(Self, Entity, Kind, From);
6490 }
6491
6492 // -- If E2 is an rvalue, or if the conversion above cannot be done:
6493 // -- if E1 and E2 have class type, and the underlying class types are
6494 // the same or one is a base class of the other:
6495 QualType FTy = From->getType();
6496 QualType TTy = To->getType();
6497 const RecordType *FRec = FTy->getAs<RecordType>();
6498 const RecordType *TRec = TTy->getAs<RecordType>();
6499 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6500 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6501 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6502 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6503 // E1 can be converted to match E2 if the class of T2 is the
6504 // same type as, or a base class of, the class of T1, and
6505 // [cv2 > cv1].
6506 if (FRec == TRec || FDerivedFromT) {
6507 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6509 InitializationSequence InitSeq(Self, Entity, Kind, From);
6510 if (InitSeq) {
6511 HaveConversion = true;
6512 return false;
6513 }
6514
6515 if (InitSeq.isAmbiguous())
6516 return InitSeq.Diagnose(Self, Entity, Kind, From);
6517 }
6518 }
6519
6520 return false;
6521 }
6522
6523 // -- Otherwise: E1 can be converted to match E2 if E1 can be
6524 // implicitly converted to the type that expression E2 would have
6525 // if E2 were converted to an rvalue (or the type it has, if E2 is
6526 // an rvalue).
6527 //
6528 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6529 // to the array-to-pointer or function-to-pointer conversions.
6530 TTy = TTy.getNonLValueExprType(Self.Context);
6531
6533 InitializationSequence InitSeq(Self, Entity, Kind, From);
6534 HaveConversion = !InitSeq.Failed();
6535 ToType = TTy;
6536 if (InitSeq.isAmbiguous())
6537 return InitSeq.Diagnose(Self, Entity, Kind, From);
6538
6539 return false;
6540}
6541
6542/// Try to find a common type for two according to C++0x 5.16p5.
6543///
6544/// This is part of the parameter validation for the ? operator. If either
6545/// value operand is a class type, overload resolution is used to find a
6546/// conversion to a common type.
6548 SourceLocation QuestionLoc) {
6549 Expr *Args[2] = { LHS.get(), RHS.get() };
6550 OverloadCandidateSet CandidateSet(QuestionLoc,
6552 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6553 CandidateSet);
6554
6556 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6557 case OR_Success: {
6558 // We found a match. Perform the conversions on the arguments and move on.
6559 ExprResult LHSRes = Self.PerformImplicitConversion(
6560 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6562 if (LHSRes.isInvalid())
6563 break;
6564 LHS = LHSRes;
6565
6566 ExprResult RHSRes = Self.PerformImplicitConversion(
6567 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6569 if (RHSRes.isInvalid())
6570 break;
6571 RHS = RHSRes;
6572 if (Best->Function)
6573 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6574 return false;
6575 }
6576
6578
6579 // Emit a better diagnostic if one of the expressions is a null pointer
6580 // constant and the other is a pointer type. In this case, the user most
6581 // likely forgot to take the address of the other expression.
6582 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6583 return true;
6584
6585 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6586 << LHS.get()->getType() << RHS.get()->getType()
6587 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6588 return true;
6589
6590 case OR_Ambiguous:
6591 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6592 << LHS.get()->getType() << RHS.get()->getType()
6593 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6594 // FIXME: Print the possible common types by printing the return types of
6595 // the viable candidates.
6596 break;
6597
6598 case OR_Deleted:
6599 llvm_unreachable("Conditional operator has only built-in overloads");
6600 }
6601 return true;
6602}
6603
6604/// Perform an "extended" implicit conversion as returned by
6605/// TryClassUnification.
6608 InitializationKind Kind =
6610 Expr *Arg = E.get();
6611 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6612 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6613 if (Result.isInvalid())
6614 return true;
6615
6616 E = Result;
6617 return false;
6618}
6619
6620// Check the condition operand of ?: to see if it is valid for the GCC
6621// extension.
6623 QualType CondTy) {
6624 if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6625 return false;
6626 const QualType EltTy =
6627 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6628 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6629 return EltTy->isIntegralType(Ctx);
6630}
6631
6633 QualType CondTy) {
6634 if (!CondTy->isSveVLSBuiltinType())
6635 return false;
6636 const QualType EltTy =
6637 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6638 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
6639 return EltTy->isIntegralType(Ctx);
6640}
6641
6643 ExprResult &RHS,
6644 SourceLocation QuestionLoc) {
6647
6648 QualType CondType = Cond.get()->getType();
6649 const auto *CondVT = CondType->castAs<VectorType>();
6650 QualType CondElementTy = CondVT->getElementType();
6651 unsigned CondElementCount = CondVT->getNumElements();
6652 QualType LHSType = LHS.get()->getType();
6653 const auto *LHSVT = LHSType->getAs<VectorType>();
6654 QualType RHSType = RHS.get()->getType();
6655 const auto *RHSVT = RHSType->getAs<VectorType>();
6656
6657 QualType ResultType;
6658
6659
6660 if (LHSVT && RHSVT) {
6661 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6662 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6663 << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6664 return {};
6665 }
6666
6667 // If both are vector types, they must be the same type.
6668 if (!Context.hasSameType(LHSType, RHSType)) {
6669 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6670 << LHSType << RHSType;
6671 return {};
6672 }
6673 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6674 } else if (LHSVT || RHSVT) {
6675 ResultType = CheckVectorOperands(
6676 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6677 /*AllowBoolConversions*/ false,
6678 /*AllowBoolOperation*/ true,
6679 /*ReportInvalid*/ true);
6680 if (ResultType.isNull())
6681 return {};
6682 } else {
6683 // Both are scalar.
6684 LHSType = LHSType.getUnqualifiedType();
6685 RHSType = RHSType.getUnqualifiedType();
6686 QualType ResultElementTy =
6687 Context.hasSameType(LHSType, RHSType)
6688 ? Context.getCommonSugaredType(LHSType, RHSType)
6689 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6691
6692 if (ResultElementTy->isEnumeralType()) {
6693 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6694 << ResultElementTy;
6695 return {};
6696 }
6697 if (CondType->isExtVectorType())
6698 ResultType =
6699 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6700 else
6701 ResultType = Context.getVectorType(
6702 ResultElementTy, CondVT->getNumElements(), VectorKind::Generic);
6703
6704 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6705 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6706 }
6707
6708 assert(!ResultType.isNull() && ResultType->isVectorType() &&
6709 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
6710 "Result should have been a vector type");
6711 auto *ResultVectorTy = ResultType->castAs<VectorType>();
6712 QualType ResultElementTy = ResultVectorTy->getElementType();
6713 unsigned ResultElementCount = ResultVectorTy->getNumElements();
6714
6715 if (ResultElementCount != CondElementCount) {
6716 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6717 << ResultType;
6718 return {};
6719 }
6720
6721 if (Context.getTypeSize(ResultElementTy) !=
6722 Context.getTypeSize(CondElementTy)) {
6723 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6724 << ResultType;
6725 return {};
6726 }
6727
6728 return ResultType;
6729}
6730
6732 ExprResult &LHS,
6733 ExprResult &RHS,
6734 SourceLocation QuestionLoc) {
6737
6738 QualType CondType = Cond.get()->getType();
6739 const auto *CondBT = CondType->castAs<BuiltinType>();
6740 QualType CondElementTy = CondBT->getSveEltType(Context);
6741 llvm::ElementCount CondElementCount =
6743
6744 QualType LHSType = LHS.get()->getType();
6745 const auto *LHSBT =
6746 LHSType->isSveVLSBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6747 QualType RHSType = RHS.get()->getType();
6748 const auto *RHSBT =
6749 RHSType->isSveVLSBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6750
6751 QualType ResultType;
6752
6753 if (LHSBT && RHSBT) {
6754 // If both are sizeless vector types, they must be the same type.
6755 if (!Context.hasSameType(LHSType, RHSType)) {
6756 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6757 << LHSType << RHSType;
6758 return QualType();
6759 }
6760 ResultType = LHSType;
6761 } else if (LHSBT || RHSBT) {
6762 ResultType = CheckSizelessVectorOperands(
6763 LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6764 if (ResultType.isNull())
6765 return QualType();
6766 } else {
6767 // Both are scalar so splat
6768 QualType ResultElementTy;
6769 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6770 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6771
6772 if (Context.hasSameType(LHSType, RHSType))
6773 ResultElementTy = LHSType;
6774 else
6775 ResultElementTy =
6776 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6777
6778 if (ResultElementTy->isEnumeralType()) {
6779 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6780 << ResultElementTy;
6781 return QualType();
6782 }
6783
6784 ResultType = Context.getScalableVectorType(
6785 ResultElementTy, CondElementCount.getKnownMinValue());
6786
6787 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6788 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6789 }
6790
6791 assert(!ResultType.isNull() && ResultType->isSveVLSBuiltinType() &&
6792 "Result should have been a vector type");
6793 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6794 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6795 llvm::ElementCount ResultElementCount =
6796 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6797
6798 if (ResultElementCount != CondElementCount) {
6799 Diag(QuestionLoc, diag::err_conditional_vector_size)
6800 << CondType << ResultType;
6801 return QualType();
6802 }
6803
6804 if (Context.getTypeSize(ResultElementTy) !=
6805 Context.getTypeSize(CondElementTy)) {
6806 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6807 << CondType << ResultType;
6808 return QualType();
6809 }
6810
6811 return ResultType;
6812}
6813
6814/// Check the operands of ?: under C++ semantics.
6815///
6816/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6817/// extension. In this case, LHS == Cond. (But they're not aliases.)
6818///
6819/// This function also implements GCC's vector extension and the
6820/// OpenCL/ext_vector_type extension for conditionals. The vector extensions
6821/// permit the use of a?b:c where the type of a is that of a integer vector with
6822/// the same number of elements and size as the vectors of b and c. If one of
6823/// either b or c is a scalar it is implicitly converted to match the type of
6824/// the vector. Otherwise the expression is ill-formed. If both b and c are
6825/// scalars, then b and c are checked and converted to the type of a if
6826/// possible.
6827///
6828/// The expressions are evaluated differently for GCC's and OpenCL's extensions.
6829/// For the GCC extension, the ?: operator is evaluated as
6830/// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
6831/// For the OpenCL extensions, the ?: operator is evaluated as
6832/// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
6833/// most-significant-bit-set(a[n]) ? b[n] : c[n]).
6835 ExprResult &RHS, ExprValueKind &VK,
6836 ExprObjectKind &OK,
6837 SourceLocation QuestionLoc) {
6838 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6839 // pointers.
6840
6841 // Assume r-value.
6842 VK = VK_PRValue;
6843 OK = OK_Ordinary;
6844 bool IsVectorConditional =
6846
6847 bool IsSizelessVectorConditional =
6849 Cond.get()->getType());
6850
6851 // C++11 [expr.cond]p1
6852 // The first expression is contextually converted to bool.
6853 if (!Cond.get()->isTypeDependent()) {
6854 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6856 : CheckCXXBooleanCondition(Cond.get());
6857 if (CondRes.isInvalid())
6858 return QualType();
6859 Cond = CondRes;
6860 } else {
6861 // To implement C++, the first expression typically doesn't alter the result
6862 // type of the conditional, however the GCC compatible vector extension
6863 // changes the result type to be that of the conditional. Since we cannot
6864 // know if this is a vector extension here, delay the conversion of the
6865 // LHS/RHS below until later.
6866 return Context.DependentTy;
6867 }
6868
6869
6870 // Either of the arguments dependent?
6871 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6872 return Context.DependentTy;
6873
6874 // C++11 [expr.cond]p2
6875 // If either the second or the third operand has type (cv) void, ...
6876 QualType LTy = LHS.get()->getType();
6877 QualType RTy = RHS.get()->getType();
6878 bool LVoid = LTy->isVoidType();
6879 bool RVoid = RTy->isVoidType();
6880 if (LVoid || RVoid) {
6881 // ... one of the following shall hold:
6882 // -- The second or the third operand (but not both) is a (possibly
6883 // parenthesized) throw-expression; the result is of the type
6884 // and value category of the other.
6885 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6886 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6887
6888 // Void expressions aren't legal in the vector-conditional expressions.
6889 if (IsVectorConditional) {
6890 SourceRange DiagLoc =
6891 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6892 bool IsThrow = LVoid ? LThrow : RThrow;
6893 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6894 << DiagLoc << IsThrow;
6895 return QualType();
6896 }
6897
6898 if (LThrow != RThrow) {
6899 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6900 VK = NonThrow->getValueKind();
6901 // DR (no number yet): the result is a bit-field if the
6902 // non-throw-expression operand is a bit-field.
6903 OK = NonThrow->getObjectKind();
6904 return NonThrow->getType();
6905 }
6906
6907 // -- Both the second and third operands have type void; the result is of
6908 // type void and is a prvalue.
6909 if (LVoid && RVoid)
6910 return Context.getCommonSugaredType(LTy, RTy);
6911
6912 // Neither holds, error.
6913 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6914 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6915 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6916 return QualType();
6917 }
6918
6919 // Neither is void.
6920 if (IsVectorConditional)
6921 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6922
6923 if (IsSizelessVectorConditional)
6924 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6925
6926 // WebAssembly tables are not allowed as conditional LHS or RHS.
6927 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
6928 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
6929 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6930 return QualType();
6931 }
6932
6933 // C++11 [expr.cond]p3
6934 // Otherwise, if the second and third operand have different types, and
6935 // either has (cv) class type [...] an attempt is made to convert each of
6936 // those operands to the type of the other.
6937 if (!Context.hasSameType(LTy, RTy) &&
6938 (LTy->isRecordType() || RTy->isRecordType())) {
6939 // These return true if a single direction is already ambiguous.
6940 QualType L2RType, R2LType;
6941 bool HaveL2R, HaveR2L;
6942 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6943 return QualType();
6944 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6945 return QualType();
6946
6947 // If both can be converted, [...] the program is ill-formed.
6948 if (HaveL2R && HaveR2L) {
6949 Diag(QuestionLoc, diag::err_conditional_ambiguous)
6950 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6951 return QualType();
6952 }
6953
6954 // If exactly one conversion is possible, that conversion is applied to
6955 // the chosen operand and the converted operands are used in place of the
6956 // original operands for the remainder of this section.
6957 if (HaveL2R) {
6958 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6959 return QualType();
6960 LTy = LHS.get()->getType();
6961 } else if (HaveR2L) {
6962 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6963 return QualType();
6964 RTy = RHS.get()->getType();
6965 }
6966 }
6967
6968 // C++11 [expr.cond]p3
6969 // if both are glvalues of the same value category and the same type except
6970 // for cv-qualification, an attempt is made to convert each of those
6971 // operands to the type of the other.
6972 // FIXME:
6973 // Resolving a defect in P0012R1: we extend this to cover all cases where
6974 // one of the operands is reference-compatible with the other, in order
6975 // to support conditionals between functions differing in noexcept. This
6976 // will similarly cover difference in array bounds after P0388R4.
6977 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6978 // that instead?
6979 ExprValueKind LVK = LHS.get()->getValueKind();
6980 ExprValueKind RVK = RHS.get()->getValueKind();
6981 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6982 // DerivedToBase was already handled by the class-specific case above.
6983 // FIXME: Should we allow ObjC conversions here?
6984 const ReferenceConversions AllowedConversions =
6985 ReferenceConversions::Qualification |
6986 ReferenceConversions::NestedQualification |
6987 ReferenceConversions::Function;
6988
6989 ReferenceConversions RefConv;
6990 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6992 !(RefConv & ~AllowedConversions) &&
6993 // [...] subject to the constraint that the reference must bind
6994 // directly [...]
6995 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6996 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6997 RTy = RHS.get()->getType();
6998 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
7000 !(RefConv & ~AllowedConversions) &&
7001 !LHS.get()->refersToBitField() &&
7002 !LHS.get()->refersToVectorElement()) {
7003 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
7004 LTy = LHS.get()->getType();
7005 }
7006 }
7007
7008 // C++11 [expr.cond]p4
7009 // If the second and third operands are glvalues of the same value
7010 // category and have the same type, the result is of that type and
7011 // value category and it is a bit-field if the second or the third
7012 // operand is a bit-field, or if both are bit-fields.
7013 // We only extend this to bitfields, not to the crazy other kinds of
7014 // l-values.
7015 bool Same = Context.hasSameType(LTy, RTy);
7016 if (Same && LVK == RVK && LVK != VK_PRValue &&
7019 VK = LHS.get()->getValueKind();
7020 if (LHS.get()->getObjectKind() == OK_BitField ||
7021 RHS.get()->getObjectKind() == OK_BitField)
7022 OK = OK_BitField;
7023 return Context.getCommonSugaredType(LTy, RTy);
7024 }
7025
7026 // C++11 [expr.cond]p5
7027 // Otherwise, the result is a prvalue. If the second and third operands
7028 // do not have the same type, and either has (cv) class type, ...
7029 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
7030 // ... overload resolution is used to determine the conversions (if any)
7031 // to be applied to the operands. If the overload resolution fails, the
7032 // program is ill-formed.
7033 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
7034 return QualType();
7035 }
7036
7037 // C++11 [expr.cond]p6
7038 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
7039 // conversions are performed on the second and third operands.
7042 if (LHS.isInvalid() || RHS.isInvalid())
7043 return QualType();
7044 LTy = LHS.get()->getType();
7045 RTy = RHS.get()->getType();
7046
7047 // After those conversions, one of the following shall hold:
7048 // -- The second and third operands have the same type; the result
7049 // is of that type. If the operands have class type, the result
7050 // is a prvalue temporary of the result type, which is
7051 // copy-initialized from either the second operand or the third
7052 // operand depending on the value of the first operand.
7053 if (Context.hasSameType(LTy, RTy)) {
7054 if (LTy->isRecordType()) {
7055 // The operands have class type. Make a temporary copy.
7058 if (LHSCopy.isInvalid())
7059 return QualType();
7060
7063 if (RHSCopy.isInvalid())
7064 return QualType();
7065
7066 LHS = LHSCopy;
7067 RHS = RHSCopy;
7068 }
7069 return Context.getCommonSugaredType(LTy, RTy);
7070 }
7071
7072 // Extension: conditional operator involving vector types.
7073 if (LTy->isVectorType() || RTy->isVectorType())
7074 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
7075 /*AllowBothBool*/ true,
7076 /*AllowBoolConversions*/ false,
7077 /*AllowBoolOperation*/ false,
7078 /*ReportInvalid*/ true);
7079
7080 // -- The second and third operands have arithmetic or enumeration type;
7081 // the usual arithmetic conversions are performed to bring them to a
7082 // common type, and the result is of that type.
7083 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
7084 QualType ResTy =
7085 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
7086 if (LHS.isInvalid() || RHS.isInvalid())
7087 return QualType();
7088 if (ResTy.isNull()) {
7089 Diag(QuestionLoc,
7090 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
7091 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7092 return QualType();
7093 }
7094
7095 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7096 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7097
7098 return ResTy;
7099 }
7100
7101 // -- The second and third operands have pointer type, or one has pointer
7102 // type and the other is a null pointer constant, or both are null
7103 // pointer constants, at least one of which is non-integral; pointer
7104 // conversions and qualification conversions are performed to bring them
7105 // to their composite pointer type. The result is of the composite
7106 // pointer type.
7107 // -- The second and third operands have pointer to member type, or one has
7108 // pointer to member type and the other is a null pointer constant;
7109 // pointer to member conversions and qualification conversions are
7110 // performed to bring them to a common type, whose cv-qualification
7111 // shall match the cv-qualification of either the second or the third
7112 // operand. The result is of the common type.
7113 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
7114 if (!Composite.isNull())
7115 return Composite;
7116
7117 // Similarly, attempt to find composite type of two objective-c pointers.
7118 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
7119 if (LHS.isInvalid() || RHS.isInvalid())
7120 return QualType();
7121 if (!Composite.isNull())
7122 return Composite;
7123
7124 // Check if we are using a null with a non-pointer type.
7125 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7126 return QualType();
7127
7128 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7129 << LHS.get()->getType() << RHS.get()->getType()
7130 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7131 return QualType();
7132}
7133
7134/// Find a merged pointer type and convert the two expressions to it.
7135///
7136/// This finds the composite pointer type for \p E1 and \p E2 according to
7137/// C++2a [expr.type]p3. It converts both expressions to this type and returns
7138/// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
7139/// is \c true).
7140///
7141/// \param Loc The location of the operator requiring these two expressions to
7142/// be converted to the composite pointer type.
7143///
7144/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
7146 Expr *&E1, Expr *&E2,
7147 bool ConvertArgs) {
7148 assert(getLangOpts().CPlusPlus && "This function assumes C++");
7149
7150 // C++1z [expr]p14:
7151 // The composite pointer type of two operands p1 and p2 having types T1
7152 // and T2
7153 QualType T1 = E1->getType(), T2 = E2->getType();
7154
7155 // where at least one is a pointer or pointer to member type or
7156 // std::nullptr_t is:
7157 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
7158 T1->isNullPtrType();
7159 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
7160 T2->isNullPtrType();
7161 if (!T1IsPointerLike && !T2IsPointerLike)
7162 return QualType();
7163
7164 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
7165 // This can't actually happen, following the standard, but we also use this
7166 // to implement the end of [expr.conv], which hits this case.
7167 //
7168 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
7169 if (T1IsPointerLike &&
7171 if (ConvertArgs)
7172 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
7173 ? CK_NullToMemberPointer
7174 : CK_NullToPointer).get();
7175 return T1;
7176 }
7177 if (T2IsPointerLike &&
7179 if (ConvertArgs)
7180 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
7181 ? CK_NullToMemberPointer
7182 : CK_NullToPointer).get();
7183 return T2;
7184 }
7185
7186 // Now both have to be pointers or member pointers.
7187 if (!T1IsPointerLike || !T2IsPointerLike)
7188 return QualType();
7189 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
7190 "nullptr_t should be a null pointer constant");
7191
7192 struct Step {
7193 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
7194 // Qualifiers to apply under the step kind.
7195 Qualifiers Quals;
7196 /// The class for a pointer-to-member; a constant array type with a bound
7197 /// (if any) for an array.
7198 const Type *ClassOrBound;
7199
7200 Step(Kind K, const Type *ClassOrBound = nullptr)
7201 : K(K), ClassOrBound(ClassOrBound) {}
7202 QualType rebuild(ASTContext &Ctx, QualType T) const {
7203 T = Ctx.getQualifiedType(T, Quals);
7204 switch (K) {
7205 case Pointer:
7206 return Ctx.getPointerType(T);
7207 case MemberPointer:
7208 return Ctx.getMemberPointerType(T, ClassOrBound);
7209 case ObjCPointer:
7210 return Ctx.getObjCObjectPointerType(T);
7211 case Array:
7212 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
7213 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
7214 ArraySizeModifier::Normal, 0);
7215 else
7216 return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0);
7217 }
7218 llvm_unreachable("unknown step kind");
7219 }
7220 };
7221
7223
7224 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7225 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7226 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
7227 // respectively;
7228 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
7229 // to member of C2 of type cv2 U2" for some non-function type U, where
7230 // C1 is reference-related to C2 or C2 is reference-related to C1, the
7231 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
7232 // respectively;
7233 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
7234 // T2;
7235 //
7236 // Dismantle T1 and T2 to simultaneously determine whether they are similar
7237 // and to prepare to form the cv-combined type if so.
7238 QualType Composite1 = T1;
7239 QualType Composite2 = T2;
7240 unsigned NeedConstBefore = 0;
7241 while (true) {
7242 assert(!Composite1.isNull() && !Composite2.isNull());
7243
7244 Qualifiers Q1, Q2;
7245 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
7246 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
7247
7248 // Top-level qualifiers are ignored. Merge at all lower levels.
7249 if (!Steps.empty()) {
7250 // Find the qualifier union: (approximately) the unique minimal set of
7251 // qualifiers that is compatible with both types.
7253 Q2.getCVRUQualifiers());
7254
7255 // Under one level of pointer or pointer-to-member, we can change to an
7256 // unambiguous compatible address space.
7257 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
7258 Quals.setAddressSpace(Q1.getAddressSpace());
7259 } else if (Steps.size() == 1) {
7260 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
7261 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
7262 if (MaybeQ1 == MaybeQ2) {
7263 // Exception for ptr size address spaces. Should be able to choose
7264 // either address space during comparison.
7267 MaybeQ1 = true;
7268 else
7269 return QualType(); // No unique best address space.
7270 }
7271 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
7272 : Q2.getAddressSpace());
7273 } else {
7274 return QualType();
7275 }
7276
7277 // FIXME: In C, we merge __strong and none to __strong at the top level.
7278 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
7279 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
7280 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7281 assert(Steps.size() == 1);
7282 else
7283 return QualType();
7284
7285 // Mismatched lifetime qualifiers never compatibly include each other.
7286 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
7287 Quals.setObjCLifetime(Q1.getObjCLifetime());
7288 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
7289 assert(Steps.size() == 1);
7290 else
7291 return QualType();
7292
7293 Steps.back().Quals = Quals;
7294 if (Q1 != Quals || Q2 != Quals)
7295 NeedConstBefore = Steps.size() - 1;
7296 }
7297
7298 // FIXME: Can we unify the following with UnwrapSimilarTypes?
7299
7300 const ArrayType *Arr1, *Arr2;
7301 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
7302 (Arr2 = Context.getAsArrayType(Composite2))) {
7303 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
7304 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
7305 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
7306 Composite1 = Arr1->getElementType();
7307 Composite2 = Arr2->getElementType();
7308 Steps.emplace_back(Step::Array, CAT1);
7309 continue;
7310 }
7311 bool IAT1 = isa<IncompleteArrayType>(Arr1);
7312 bool IAT2 = isa<IncompleteArrayType>(Arr2);
7313 if ((IAT1 && IAT2) ||
7314 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
7315 ((bool)CAT1 != (bool)CAT2) &&
7316 (Steps.empty() || Steps.back().K != Step::Array))) {
7317 // In C++20 onwards, we can unify an array of N T with an array of
7318 // a different or unknown bound. But we can't form an array whose
7319 // element type is an array of unknown bound by doing so.
7320 Composite1 = Arr1->getElementType();
7321 Composite2 = Arr2->getElementType();
7322 Steps.emplace_back(Step::Array);
7323 if (CAT1 || CAT2)
7324 NeedConstBefore = Steps.size();
7325 continue;
7326 }
7327 }
7328
7329 const PointerType *Ptr1, *Ptr2;
7330 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
7331 (Ptr2 = Composite2->getAs<PointerType>())) {
7332 Composite1 = Ptr1->getPointeeType();
7333 Composite2 = Ptr2->getPointeeType();
7334 Steps.emplace_back(Step::Pointer);
7335 continue;
7336 }
7337
7338 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
7339 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
7340 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
7341 Composite1 = ObjPtr1->getPointeeType();
7342 Composite2 = ObjPtr2->getPointeeType();
7343 Steps.emplace_back(Step::ObjCPointer);
7344 continue;
7345 }
7346
7347 const MemberPointerType *MemPtr1, *MemPtr2;
7348 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
7349 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
7350 Composite1 = MemPtr1->getPointeeType();
7351 Composite2 = MemPtr2->getPointeeType();
7352
7353 // At the top level, we can perform a base-to-derived pointer-to-member
7354 // conversion:
7355 //
7356 // - [...] where C1 is reference-related to C2 or C2 is
7357 // reference-related to C1
7358 //
7359 // (Note that the only kinds of reference-relatedness in scope here are
7360 // "same type or derived from".) At any other level, the class must
7361 // exactly match.
7362 const Type *Class = nullptr;
7363 QualType Cls1(MemPtr1->getClass(), 0);
7364 QualType Cls2(MemPtr2->getClass(), 0);
7365 if (Context.hasSameType(Cls1, Cls2))
7366 Class = MemPtr1->getClass();
7367 else if (Steps.empty())
7368 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7369 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7370 if (!Class)
7371 return QualType();
7372
7373 Steps.emplace_back(Step::MemberPointer, Class);
7374 continue;
7375 }
7376
7377 // Special case: at the top level, we can decompose an Objective-C pointer
7378 // and a 'cv void *'. Unify the qualifiers.
7379 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7380 Composite2->isObjCObjectPointerType()) ||
7381 (Composite1->isObjCObjectPointerType() &&
7382 Composite2->isVoidPointerType()))) {
7383 Composite1 = Composite1->getPointeeType();
7384 Composite2 = Composite2->getPointeeType();
7385 Steps.emplace_back(Step::Pointer);
7386 continue;
7387 }
7388
7389 // FIXME: block pointer types?
7390
7391 // Cannot unwrap any more types.
7392 break;
7393 }
7394
7395 // - if T1 or T2 is "pointer to noexcept function" and the other type is
7396 // "pointer to function", where the function types are otherwise the same,
7397 // "pointer to function";
7398 // - if T1 or T2 is "pointer to member of C1 of type function", the other
7399 // type is "pointer to member of C2 of type noexcept function", and C1
7400 // is reference-related to C2 or C2 is reference-related to C1, where
7401 // the function types are otherwise the same, "pointer to member of C2 of
7402 // type function" or "pointer to member of C1 of type function",
7403 // respectively;
7404 //
7405 // We also support 'noreturn' here, so as a Clang extension we generalize the
7406 // above to:
7407 //
7408 // - [Clang] If T1 and T2 are both of type "pointer to function" or
7409 // "pointer to member function" and the pointee types can be unified
7410 // by a function pointer conversion, that conversion is applied
7411 // before checking the following rules.
7412 //
7413 // We've already unwrapped down to the function types, and we want to merge
7414 // rather than just convert, so do this ourselves rather than calling
7415 // IsFunctionConversion.
7416 //
7417 // FIXME: In order to match the standard wording as closely as possible, we
7418 // currently only do this under a single level of pointers. Ideally, we would
7419 // allow this in general, and set NeedConstBefore to the relevant depth on
7420 // the side(s) where we changed anything. If we permit that, we should also
7421 // consider this conversion when determining type similarity and model it as
7422 // a qualification conversion.
7423 if (Steps.size() == 1) {
7424 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7425 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7426 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7427 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7428
7429 // The result is noreturn if both operands are.
7430 bool Noreturn =
7431 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7432 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7433 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7434
7435 // The result is nothrow if both operands are.
7436 SmallVector<QualType, 8> ExceptionTypeStorage;
7438 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7440
7441 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7442 FPT1->getParamTypes(), EPI1);
7443 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7444 FPT2->getParamTypes(), EPI2);
7445 }
7446 }
7447 }
7448
7449 // There are some more conversions we can perform under exactly one pointer.
7450 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7451 !Context.hasSameType(Composite1, Composite2)) {
7452 // - if T1 or T2 is "pointer to cv1 void" and the other type is
7453 // "pointer to cv2 T", where T is an object type or void,
7454 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7455 if (Composite1->isVoidType() && Composite2->isObjectType())
7456 Composite2 = Composite1;
7457 else if (Composite2->isVoidType() && Composite1->isObjectType())
7458 Composite1 = Composite2;
7459 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7460 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7461 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7462 // T1, respectively;
7463 //
7464 // The "similar type" handling covers all of this except for the "T1 is a
7465 // base class of T2" case in the definition of reference-related.
7466 else if (IsDerivedFrom(Loc, Composite1, Composite2))
7467 Composite1 = Composite2;
7468 else if (IsDerivedFrom(Loc, Composite2, Composite1))
7469 Composite2 = Composite1;
7470 }
7471
7472 // At this point, either the inner types are the same or we have failed to
7473 // find a composite pointer type.
7474 if (!Context.hasSameType(Composite1, Composite2))
7475 return QualType();
7476
7477 // Per C++ [conv.qual]p3, add 'const' to every level before the last
7478 // differing qualifier.
7479 for (unsigned I = 0; I != NeedConstBefore; ++I)
7480 Steps[I].Quals.addConst();
7481
7482 // Rebuild the composite type.
7483 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7484 for (auto &S : llvm::reverse(Steps))
7485 Composite = S.rebuild(Context, Composite);
7486
7487 if (ConvertArgs) {
7488 // Convert the expressions to the composite pointer type.
7489 InitializedEntity Entity =
7491 InitializationKind Kind =
7493
7494 InitializationSequence E1ToC(*this, Entity, Kind, E1);
7495 if (!E1ToC)
7496 return QualType();
7497
7498 InitializationSequence E2ToC(*this, Entity, Kind, E2);
7499 if (!E2ToC)
7500 return QualType();
7501
7502 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7503 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7504 if (E1Result.isInvalid())
7505 return QualType();
7506 E1 = E1Result.get();
7507
7508 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7509 if (E2Result.isInvalid())
7510 return QualType();
7511 E2 = E2Result.get();
7512 }
7513
7514 return Composite;
7515}
7516
7518 if (!E)
7519 return ExprError();
7520
7521 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
7522
7523 // If the result is a glvalue, we shouldn't bind it.
7524 if (E->isGLValue())
7525 return E;
7526
7527 // In ARC, calls that return a retainable type can return retained,
7528 // in which case we have to insert a consuming cast.
7529 if (getLangOpts().ObjCAutoRefCount &&
7530 E->getType()->isObjCRetainableType()) {
7531
7532 bool ReturnsRetained;
7533
7534 // For actual calls, we compute this by examining the type of the
7535 // called value.
7536 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7537 Expr *Callee = Call->getCallee()->IgnoreParens();
7538 QualType T = Callee->getType();
7539
7540 if (T == Context.BoundMemberTy) {
7541 // Handle pointer-to-members.
7542 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7543 T = BinOp->getRHS()->getType();
7544 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7545 T = Mem->getMemberDecl()->getType();
7546 }
7547
7548 if (const PointerType *Ptr = T->getAs<PointerType>())
7549 T = Ptr->getPointeeType();
7550 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7551 T = Ptr->getPointeeType();
7552 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7553 T = MemPtr->getPointeeType();
7554
7555 auto *FTy = T->castAs<FunctionType>();
7556 ReturnsRetained = FTy->getExtInfo().getProducesResult();
7557
7558 // ActOnStmtExpr arranges things so that StmtExprs of retainable
7559 // type always produce a +1 object.
7560 } else if (isa<StmtExpr>(E)) {
7561 ReturnsRetained = true;
7562
7563 // We hit this case with the lambda conversion-to-block optimization;
7564 // we don't want any extra casts here.
7565 } else if (isa<CastExpr>(E) &&
7566 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7567 return E;
7568
7569 // For message sends and property references, we try to find an
7570 // actual method. FIXME: we should infer retention by selector in
7571 // cases where we don't have an actual method.
7572 } else {
7573 ObjCMethodDecl *D = nullptr;
7574 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7575 D = Send->getMethodDecl();
7576 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7577 D = BoxedExpr->getBoxingMethod();
7578 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7579 // Don't do reclaims if we're using the zero-element array
7580 // constant.
7581 if (ArrayLit->getNumElements() == 0 &&
7583 return E;
7584
7585 D = ArrayLit->getArrayWithObjectsMethod();
7586 } else if (ObjCDictionaryLiteral *DictLit
7587 = dyn_cast<ObjCDictionaryLiteral>(E)) {
7588 // Don't do reclaims if we're using the zero-element dictionary
7589 // constant.
7590 if (DictLit->getNumElements() == 0 &&
7592 return E;
7593
7594 D = DictLit->getDictWithObjectsMethod();
7595 }
7596
7597 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7598
7599 // Don't do reclaims on performSelector calls; despite their
7600 // return type, the invoked method doesn't necessarily actually
7601 // return an object.
7602 if (!ReturnsRetained &&
7604 return E;
7605 }
7606
7607 // Don't reclaim an object of Class type.
7608 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7609 return E;
7610
7612
7613 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7614 : CK_ARCReclaimReturnedObject);
7615 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7617 }
7618
7621
7622 if (!getLangOpts().CPlusPlus)
7623 return E;
7624
7625 // Search for the base element type (cf. ASTContext::getBaseElementType) with
7626 // a fast path for the common case that the type is directly a RecordType.
7628 const RecordType *RT = nullptr;
7629 while (!RT) {
7630 switch (T->getTypeClass()) {
7631 case Type::Record:
7632 RT = cast<RecordType>(T);
7633 break;
7634 case Type::ConstantArray:
7635 case Type::IncompleteArray:
7636 case Type::VariableArray:
7637 case Type::DependentSizedArray:
7638 T = cast<ArrayType>(T)->getElementType().getTypePtr();
7639 break;
7640 default:
7641 return E;
7642 }
7643 }
7644
7645 // That should be enough to guarantee that this type is complete, if we're
7646 // not processing a decltype expression.
7647 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7648 if (RD->isInvalidDecl() || RD->isDependentContext())
7649 return E;
7650
7651 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7653 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7654
7655 if (Destructor) {
7658 PDiag(diag::err_access_dtor_temp)
7659 << E->getType());
7661 return ExprError();
7662
7663 // If destructor is trivial, we can avoid the extra copy.
7664 if (Destructor->isTrivial())
7665 return E;
7666
7667 // We need a cleanup, but we don't need to remember the temporary.
7669 }
7670
7673
7674 if (IsDecltype)
7675 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7676
7677 return Bind;
7678}
7679
7682 if (SubExpr.isInvalid())
7683 return ExprError();
7684
7685 return MaybeCreateExprWithCleanups(SubExpr.get());
7686}
7687
7689 assert(SubExpr && "subexpression can't be null!");
7690
7692
7693 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7694 assert(ExprCleanupObjects.size() >= FirstCleanup);
7695 assert(Cleanup.exprNeedsCleanups() ||
7696 ExprCleanupObjects.size() == FirstCleanup);
7698 return SubExpr;
7699
7700 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7701 ExprCleanupObjects.size() - FirstCleanup);
7702
7703 auto *E = ExprWithCleanups::Create(
7704 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7706
7707 return E;
7708}
7709
7711 assert(SubStmt && "sub-statement can't be null!");
7712
7714
7716 return SubStmt;
7717
7718 // FIXME: In order to attach the temporaries, wrap the statement into
7719 // a StmtExpr; currently this is only used for asm statements.
7720 // This is hacky, either create a new CXXStmtWithTemporaries statement or
7721 // a new AsmStmtWithTemporaries.
7722 CompoundStmt *CompStmt =
7725 Expr *E = new (Context)
7727 /*FIXME TemplateDepth=*/0);
7729}
7730
7731/// Process the expression contained within a decltype. For such expressions,
7732/// certain semantic checks on temporaries are delayed until this point, and
7733/// are omitted for the 'topmost' call in the decltype expression. If the
7734/// topmost call bound a temporary, strip that temporary off the expression.
7736 assert(ExprEvalContexts.back().ExprContext ==
7738 "not in a decltype expression");
7739
7741 if (Result.isInvalid())
7742 return ExprError();
7743 E = Result.get();
7744
7745 // C++11 [expr.call]p11:
7746 // If a function call is a prvalue of object type,
7747 // -- if the function call is either
7748 // -- the operand of a decltype-specifier, or
7749 // -- the right operand of a comma operator that is the operand of a
7750 // decltype-specifier,
7751 // a temporary object is not introduced for the prvalue.
7752
7753 // Recursively rebuild ParenExprs and comma expressions to strip out the
7754 // outermost CXXBindTemporaryExpr, if any.
7755 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7756 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7757 if (SubExpr.isInvalid())
7758 return ExprError();
7759 if (SubExpr.get() == PE->getSubExpr())
7760 return E;
7761 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7762 }
7763 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7764 if (BO->getOpcode() == BO_Comma) {
7765 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7766 if (RHS.isInvalid())
7767 return ExprError();
7768 if (RHS.get() == BO->getRHS())
7769 return E;
7770 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7771 BO->getType(), BO->getValueKind(),
7772 BO->getObjectKind(), BO->getOperatorLoc(),
7773 BO->getFPFeatures());
7774 }
7775 }
7776
7777 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7778 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7779 : nullptr;
7780 if (TopCall)
7781 E = TopCall;
7782 else
7783 TopBind = nullptr;
7784
7785 // Disable the special decltype handling now.
7786 ExprEvalContexts.back().ExprContext =
7788
7790 if (Result.isInvalid())
7791 return ExprError();
7792 E = Result.get();
7793
7794 // In MS mode, don't perform any extra checking of call return types within a
7795 // decltype expression.
7796 if (getLangOpts().MSVCCompat)
7797 return E;
7798
7799 // Perform the semantic checks we delayed until this point.
7800 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7801 I != N; ++I) {
7802 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7803 if (Call == TopCall)
7804 continue;
7805
7806 if (CheckCallReturnType(Call->getCallReturnType(Context),
7807 Call->getBeginLoc(), Call, Call->getDirectCallee()))
7808 return ExprError();
7809 }
7810
7811 // Now all relevant types are complete, check the destructors are accessible
7812 // and non-deleted, and annotate them on the temporaries.
7813 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7814 I != N; ++I) {
7816 ExprEvalContexts.back().DelayedDecltypeBinds[I];
7817 if (Bind == TopBind)
7818 continue;
7819
7820 CXXTemporary *Temp = Bind->getTemporary();
7821
7822 CXXRecordDecl *RD =
7823 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7826
7827 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7828 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7829 PDiag(diag::err_access_dtor_temp)
7830 << Bind->getType());
7831 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7832 return ExprError();
7833
7834 // We need a cleanup, but we don't need to remember the temporary.
7836 }
7837
7838 // Possibly strip off the top CXXBindTemporaryExpr.
7839 return E;
7840}
7841
7842/// Note a set of 'operator->' functions that were used for a member access.
7844 ArrayRef<FunctionDecl *> OperatorArrows) {
7845 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7846 // FIXME: Make this configurable?
7847 unsigned Limit = 9;
7848 if (OperatorArrows.size() > Limit) {
7849 // Produce Limit-1 normal notes and one 'skipping' note.
7850 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7851 SkipCount = OperatorArrows.size() - (Limit - 1);
7852 }
7853
7854 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7855 if (I == SkipStart) {
7856 S.Diag(OperatorArrows[I]->getLocation(),
7857 diag::note_operator_arrows_suppressed)
7858 << SkipCount;
7859 I += SkipCount;
7860 } else {
7861 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7862 << OperatorArrows[I]->getCallResultType();
7863 ++I;
7864 }
7865 }
7866}
7867
7869 SourceLocation OpLoc,
7870 tok::TokenKind OpKind,
7871 ParsedType &ObjectType,
7872 bool &MayBePseudoDestructor) {
7873 // Since this might be a postfix expression, get rid of ParenListExprs.
7875 if (Result.isInvalid()) return ExprError();
7876 Base = Result.get();
7877
7879 if (Result.isInvalid()) return ExprError();
7880 Base = Result.get();
7881
7882 QualType BaseType = Base->getType();
7883 MayBePseudoDestructor = false;
7884 if (BaseType->isDependentType()) {
7885 // If we have a pointer to a dependent type and are using the -> operator,
7886 // the object type is the type that the pointer points to. We might still
7887 // have enough information about that type to do something useful.
7888 if (OpKind == tok::arrow)
7889 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7890 BaseType = Ptr->getPointeeType();
7891
7892 ObjectType = ParsedType::make(BaseType);
7893 MayBePseudoDestructor = true;
7894 return Base;
7895 }
7896
7897 // C++ [over.match.oper]p8:
7898 // [...] When operator->returns, the operator-> is applied to the value
7899 // returned, with the original second operand.
7900 if (OpKind == tok::arrow) {
7901 QualType StartingType = BaseType;
7902 bool NoArrowOperatorFound = false;
7903 bool FirstIteration = true;
7904 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7905 // The set of types we've considered so far.
7907 SmallVector<FunctionDecl*, 8> OperatorArrows;
7908 CTypes.insert(Context.getCanonicalType(BaseType));
7909
7910 while (BaseType->isRecordType()) {
7911 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7912 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7913 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7914 noteOperatorArrows(*this, OperatorArrows);
7915 Diag(OpLoc, diag::note_operator_arrow_depth)
7916 << getLangOpts().ArrowDepth;
7917 return ExprError();
7918 }
7919
7921 S, Base, OpLoc,
7922 // When in a template specialization and on the first loop iteration,
7923 // potentially give the default diagnostic (with the fixit in a
7924 // separate note) instead of having the error reported back to here
7925 // and giving a diagnostic with a fixit attached to the error itself.
7926 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7927 ? nullptr
7928 : &NoArrowOperatorFound);
7929 if (Result.isInvalid()) {
7930 if (NoArrowOperatorFound) {
7931 if (FirstIteration) {
7932 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7933 << BaseType << 1 << Base->getSourceRange()
7934 << FixItHint::CreateReplacement(OpLoc, ".");
7935 OpKind = tok::period;
7936 break;
7937 }
7938 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7939 << BaseType << Base->getSourceRange();
7940 CallExpr *CE = dyn_cast<CallExpr>(Base);
7941 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7942 Diag(CD->getBeginLoc(),
7943 diag::note_member_reference_arrow_from_operator_arrow);
7944 }
7945 }
7946 return ExprError();
7947 }
7948 Base = Result.get();
7949 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7950 OperatorArrows.push_back(OpCall->getDirectCallee());
7951 BaseType = Base->getType();
7952 CanQualType CBaseType = Context.getCanonicalType(BaseType);
7953 if (!CTypes.insert(CBaseType).second) {
7954 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7955 noteOperatorArrows(*this, OperatorArrows);
7956 return ExprError();
7957 }
7958 FirstIteration = false;
7959 }
7960
7961 if (OpKind == tok::arrow) {
7962 if (BaseType->isPointerType())
7963 BaseType = BaseType->getPointeeType();
7964 else if (auto *AT = Context.getAsArrayType(BaseType))
7965 BaseType = AT->getElementType();
7966 }
7967 }
7968
7969 // Objective-C properties allow "." access on Objective-C pointer types,
7970 // so adjust the base type to the object type itself.
7971 if (BaseType->isObjCObjectPointerType())
7972 BaseType = BaseType->getPointeeType();
7973
7974 // C++ [basic.lookup.classref]p2:
7975 // [...] If the type of the object expression is of pointer to scalar
7976 // type, the unqualified-id is looked up in the context of the complete
7977 // postfix-expression.
7978 //
7979 // This also indicates that we could be parsing a pseudo-destructor-name.
7980 // Note that Objective-C class and object types can be pseudo-destructor
7981 // expressions or normal member (ivar or property) access expressions, and
7982 // it's legal for the type to be incomplete if this is a pseudo-destructor
7983 // call. We'll do more incomplete-type checks later in the lookup process,
7984 // so just skip this check for ObjC types.
7985 if (!BaseType->isRecordType()) {
7986 ObjectType = ParsedType::make(BaseType);
7987 MayBePseudoDestructor = true;
7988 return Base;
7989 }
7990
7991 // The object type must be complete (or dependent), or
7992 // C++11 [expr.prim.general]p3:
7993 // Unlike the object expression in other contexts, *this is not required to
7994 // be of complete type for purposes of class member access (5.2.5) outside
7995 // the member function body.
7996 if (!BaseType->isDependentType() &&
7998 RequireCompleteType(OpLoc, BaseType,
7999 diag::err_incomplete_member_access)) {
8000 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
8001 }
8002
8003 // C++ [basic.lookup.classref]p2:
8004 // If the id-expression in a class member access (5.2.5) is an
8005 // unqualified-id, and the type of the object expression is of a class
8006 // type C (or of pointer to a class type C), the unqualified-id is looked
8007 // up in the scope of class C. [...]
8008 ObjectType = ParsedType::make(BaseType);
8009 return Base;
8010}
8011
8012static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
8013 tok::TokenKind &OpKind, SourceLocation OpLoc) {
8014 if (Base->hasPlaceholderType()) {
8016 if (result.isInvalid()) return true;
8017 Base = result.get();
8018 }
8019 ObjectType = Base->getType();
8020
8021 // C++ [expr.pseudo]p2:
8022 // The left-hand side of the dot operator shall be of scalar type. The
8023 // left-hand side of the arrow operator shall be of pointer to scalar type.
8024 // This scalar type is the object type.
8025 // Note that this is rather different from the normal handling for the
8026 // arrow operator.
8027 if (OpKind == tok::arrow) {
8028 // The operator requires a prvalue, so perform lvalue conversions.
8029 // Only do this if we might plausibly end with a pointer, as otherwise
8030 // this was likely to be intended to be a '.'.
8031 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
8032 ObjectType->isFunctionType()) {
8034 if (BaseResult.isInvalid())
8035 return true;
8036 Base = BaseResult.get();
8037 ObjectType = Base->getType();
8038 }
8039
8040 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
8041 ObjectType = Ptr->getPointeeType();
8042 } else if (!Base->isTypeDependent()) {
8043 // The user wrote "p->" when they probably meant "p."; fix it.
8044 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8045 << ObjectType << true
8046 << FixItHint::CreateReplacement(OpLoc, ".");
8047 if (S.isSFINAEContext())
8048 return true;
8049
8050 OpKind = tok::period;
8051 }
8052 }
8053
8054 return false;
8055}
8056
8057/// Check if it's ok to try and recover dot pseudo destructor calls on
8058/// pointer objects.
8059static bool
8061 QualType DestructedType) {
8062 // If this is a record type, check if its destructor is callable.
8063 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
8064 if (RD->hasDefinition())
8066 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
8067 return false;
8068 }
8069
8070 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
8071 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
8072 DestructedType->isVectorType();
8073}
8074
8076 SourceLocation OpLoc,
8077 tok::TokenKind OpKind,
8078 const CXXScopeSpec &SS,
8079 TypeSourceInfo *ScopeTypeInfo,
8080 SourceLocation CCLoc,
8081 SourceLocation TildeLoc,
8082 PseudoDestructorTypeStorage Destructed) {
8083 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
8084
8085 QualType ObjectType;
8086 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8087 return ExprError();
8088
8089 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
8090 !ObjectType->isVectorType()) {
8091 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
8092 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
8093 else {
8094 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
8095 << ObjectType << Base->getSourceRange();
8096 return ExprError();
8097 }
8098 }
8099
8100 // C++ [expr.pseudo]p2:
8101 // [...] The cv-unqualified versions of the object type and of the type
8102 // designated by the pseudo-destructor-name shall be the same type.
8103 if (DestructedTypeInfo) {
8104 QualType DestructedType = DestructedTypeInfo->getType();
8105 SourceLocation DestructedTypeStart =
8106 DestructedTypeInfo->getTypeLoc().getBeginLoc();
8107 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
8108 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
8109 // Detect dot pseudo destructor calls on pointer objects, e.g.:
8110 // Foo *foo;
8111 // foo.~Foo();
8112 if (OpKind == tok::period && ObjectType->isPointerType() &&
8113 Context.hasSameUnqualifiedType(DestructedType,
8114 ObjectType->getPointeeType())) {
8115 auto Diagnostic =
8116 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
8117 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
8118
8119 // Issue a fixit only when the destructor is valid.
8121 *this, DestructedType))
8123
8124 // Recover by setting the object type to the destructed type and the
8125 // operator to '->'.
8126 ObjectType = DestructedType;
8127 OpKind = tok::arrow;
8128 } else {
8129 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
8130 << ObjectType << DestructedType << Base->getSourceRange()
8131 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8132
8133 // Recover by setting the destructed type to the object type.
8134 DestructedType = ObjectType;
8135 DestructedTypeInfo =
8136 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
8137 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8138 }
8139 } else if (DestructedType.getObjCLifetime() !=
8140 ObjectType.getObjCLifetime()) {
8141
8142 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
8143 // Okay: just pretend that the user provided the correctly-qualified
8144 // type.
8145 } else {
8146 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
8147 << ObjectType << DestructedType << Base->getSourceRange()
8148 << DestructedTypeInfo->getTypeLoc().getSourceRange();
8149 }
8150
8151 // Recover by setting the destructed type to the object type.
8152 DestructedType = ObjectType;
8153 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
8154 DestructedTypeStart);
8155 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8156 }
8157 }
8158 }
8159
8160 // C++ [expr.pseudo]p2:
8161 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
8162 // form
8163 //
8164 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
8165 //
8166 // shall designate the same scalar type.
8167 if (ScopeTypeInfo) {
8168 QualType ScopeType = ScopeTypeInfo->getType();
8169 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
8170 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
8171
8172 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
8173 diag::err_pseudo_dtor_type_mismatch)
8174 << ObjectType << ScopeType << Base->getSourceRange()
8175 << ScopeTypeInfo->getTypeLoc().getSourceRange();
8176
8177 ScopeType = QualType();
8178 ScopeTypeInfo = nullptr;
8179 }
8180 }
8181
8182 Expr *Result
8184 OpKind == tok::arrow, OpLoc,
8186 ScopeTypeInfo,
8187 CCLoc,
8188 TildeLoc,
8189 Destructed);
8190
8191 return Result;
8192}
8193
8195 SourceLocation OpLoc,
8196 tok::TokenKind OpKind,
8197 CXXScopeSpec &SS,
8198 UnqualifiedId &FirstTypeName,
8199 SourceLocation CCLoc,
8200 SourceLocation TildeLoc,
8201 UnqualifiedId &SecondTypeName) {
8202 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8203 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8204 "Invalid first type name in pseudo-destructor");
8205 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8206 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
8207 "Invalid second type name in pseudo-destructor");
8208
8209 QualType ObjectType;
8210 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8211 return ExprError();
8212
8213 // Compute the object type that we should use for name lookup purposes. Only
8214 // record types and dependent types matter.
8215 ParsedType ObjectTypePtrForLookup;
8216 if (!SS.isSet()) {
8217 if (ObjectType->isRecordType())
8218 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
8219 else if (ObjectType->isDependentType())
8220 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
8221 }
8222
8223 // Convert the name of the type being destructed (following the ~) into a
8224 // type (with source-location information).
8225 QualType DestructedType;
8226 TypeSourceInfo *DestructedTypeInfo = nullptr;
8227 PseudoDestructorTypeStorage Destructed;
8228 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8229 ParsedType T = getTypeName(*SecondTypeName.Identifier,
8230 SecondTypeName.StartLocation,
8231 S, &SS, true, false, ObjectTypePtrForLookup,
8232 /*IsCtorOrDtorName*/true);
8233 if (!T &&
8234 ((SS.isSet() && !computeDeclContext(SS, false)) ||
8235 (!SS.isSet() && ObjectType->isDependentType()))) {
8236 // The name of the type being destroyed is a dependent name, and we
8237 // couldn't find anything useful in scope. Just store the identifier and
8238 // it's location, and we'll perform (qualified) name lookup again at
8239 // template instantiation time.
8240 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
8241 SecondTypeName.StartLocation);
8242 } else if (!T) {
8243 Diag(SecondTypeName.StartLocation,
8244 diag::err_pseudo_dtor_destructor_non_type)
8245 << SecondTypeName.Identifier << ObjectType;
8246 if (isSFINAEContext())
8247 return ExprError();
8248
8249 // Recover by assuming we had the right type all along.
8250 DestructedType = ObjectType;
8251 } else
8252 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
8253 } else {
8254 // Resolve the template-id to a type.
8255 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
8256 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8257 TemplateId->NumArgs);
8259 SS,
8260 TemplateId->TemplateKWLoc,
8261 TemplateId->Template,
8262 TemplateId->Name,
8263 TemplateId->TemplateNameLoc,
8264 TemplateId->LAngleLoc,
8265 TemplateArgsPtr,
8266 TemplateId->RAngleLoc,
8267 /*IsCtorOrDtorName*/true);
8268 if (T.isInvalid() || !T.get()) {
8269 // Recover by assuming we had the right type all along.
8270 DestructedType = ObjectType;
8271 } else
8272 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
8273 }
8274
8275 // If we've performed some kind of recovery, (re-)build the type source
8276 // information.
8277 if (!DestructedType.isNull()) {
8278 if (!DestructedTypeInfo)
8279 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
8280 SecondTypeName.StartLocation);
8281 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
8282 }
8283
8284 // Convert the name of the scope type (the type prior to '::') into a type.
8285 TypeSourceInfo *ScopeTypeInfo = nullptr;
8286 QualType ScopeType;
8287 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
8288 FirstTypeName.Identifier) {
8289 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
8290 ParsedType T = getTypeName(*FirstTypeName.Identifier,
8291 FirstTypeName.StartLocation,
8292 S, &SS, true, false, ObjectTypePtrForLookup,
8293 /*IsCtorOrDtorName*/true);
8294 if (!T) {
8295 Diag(FirstTypeName.StartLocation,
8296 diag::err_pseudo_dtor_destructor_non_type)
8297 << FirstTypeName.Identifier << ObjectType;
8298
8299 if (isSFINAEContext())
8300 return ExprError();
8301
8302 // Just drop this type. It's unnecessary anyway.
8303 ScopeType = QualType();
8304 } else
8305 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
8306 } else {
8307 // Resolve the template-id to a type.
8308 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
8309 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8310 TemplateId->NumArgs);
8312 SS,
8313 TemplateId->TemplateKWLoc,
8314 TemplateId->Template,
8315 TemplateId->Name,
8316 TemplateId->TemplateNameLoc,
8317 TemplateId->LAngleLoc,
8318 TemplateArgsPtr,
8319 TemplateId->RAngleLoc,
8320 /*IsCtorOrDtorName*/true);
8321 if (T.isInvalid() || !T.get()) {
8322 // Recover by dropping this type.
8323 ScopeType = QualType();
8324 } else
8325 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
8326 }
8327 }
8328
8329 if (!ScopeType.isNull() && !ScopeTypeInfo)
8330 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
8331 FirstTypeName.StartLocation);
8332
8333
8334 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
8335 ScopeTypeInfo, CCLoc, TildeLoc,
8336 Destructed);
8337}
8338
8340 SourceLocation OpLoc,
8341 tok::TokenKind OpKind,
8342 SourceLocation TildeLoc,
8343 const DeclSpec& DS) {
8344 QualType ObjectType;
8345 QualType T;
8346 TypeLocBuilder TLB;
8347 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
8348 return ExprError();
8349
8350 switch (DS.getTypeSpecType()) {
8352 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
8353 return true;
8354 }
8356 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
8357 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
8358 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
8359 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
8360 break;
8361 }
8364 DS.getBeginLoc(), DS.getEllipsisLoc());
8366 cast<PackIndexingType>(T.getTypePtr())->getPattern(),
8367 DS.getBeginLoc());
8369 PITL.setEllipsisLoc(DS.getEllipsisLoc());
8370 break;
8371 }
8372 default:
8373 llvm_unreachable("Unsupported type in pseudo destructor");
8374 }
8375 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
8376 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
8377
8378 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
8379 nullptr, SourceLocation(), TildeLoc,
8380 Destructed);
8381}
8382
8384 SourceLocation RParen) {
8385 // If the operand is an unresolved lookup expression, the expression is ill-
8386 // formed per [over.over]p1, because overloaded function names cannot be used
8387 // without arguments except in explicit contexts.
8388 ExprResult R = CheckPlaceholderExpr(Operand);
8389 if (R.isInvalid())
8390 return R;
8391
8393 if (R.isInvalid())
8394 return ExprError();
8395
8396 Operand = R.get();
8397
8398 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8399 Operand->HasSideEffects(Context, false)) {
8400 // The expression operand for noexcept is in an unevaluated expression
8401 // context, so side effects could result in unintended consequences.
8402 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8403 }
8404
8405 CanThrowResult CanThrow = canThrow(Operand);
8406 return new (Context)
8407 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8408}
8409
8411 Expr *Operand, SourceLocation RParen) {
8412 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8413}
8414
8416 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8417 DeclRefExpr *LHS = nullptr;
8418 bool IsCompoundAssign = false;
8419 bool isIncrementDecrementUnaryOp = false;
8420 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8421 if (BO->getLHS()->getType()->isDependentType() ||
8422 BO->getRHS()->getType()->isDependentType()) {
8423 if (BO->getOpcode() != BO_Assign)
8424 return;
8425 } else if (!BO->isAssignmentOp())
8426 return;
8427 else
8428 IsCompoundAssign = BO->isCompoundAssignmentOp();
8429 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8430 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8431 if (COCE->getOperator() != OO_Equal)
8432 return;
8433 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8434 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8435 if (!UO->isIncrementDecrementOp())
8436 return;
8437 isIncrementDecrementUnaryOp = true;
8438 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8439 }
8440 if (!LHS)
8441 return;
8442 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8443 if (!VD)
8444 return;
8445 // Don't decrement RefsMinusAssignments if volatile variable with compound
8446 // assignment (+=, ...) or increment/decrement unary operator to avoid
8447 // potential unused-but-set-variable warning.
8448 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8450 return;
8451 auto iter = RefsMinusAssignments.find(VD);
8452 if (iter == RefsMinusAssignments.end())
8453 return;
8454 iter->getSecond()--;
8455}
8456
8457/// Perform the conversions required for an expression used in a
8458/// context that ignores the result.
8461
8462 if (E->hasPlaceholderType()) {
8463 ExprResult result = CheckPlaceholderExpr(E);
8464 if (result.isInvalid()) return E;
8465 E = result.get();
8466 }
8467
8468 if (getLangOpts().CPlusPlus) {
8469 // The C++11 standard defines the notion of a discarded-value expression;
8470 // normally, we don't need to do anything to handle it, but if it is a
8471 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8472 // conversion.
8475 if (Res.isInvalid())
8476 return E;
8477 E = Res.get();
8478 } else {
8479 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8480 // it occurs as a discarded-value expression.
8482 }
8483
8484 // C++1z:
8485 // If the expression is a prvalue after this optional conversion, the
8486 // temporary materialization conversion is applied.
8487 //
8488 // We do not materialize temporaries by default in order to avoid creating
8489 // unnecessary temporary objects. If we skip this step, IR generation is
8490 // able to synthesize the storage for itself in the aggregate case, and
8491 // adding the extra node to the AST is just clutter.
8493 E->isPRValue() && !E->getType()->isVoidType()) {
8495 if (Res.isInvalid())
8496 return E;
8497 E = Res.get();
8498 }
8499 return E;
8500 }
8501
8502 // C99 6.3.2.1:
8503 // [Except in specific positions,] an lvalue that does not have
8504 // array type is converted to the value stored in the
8505 // designated object (and is no longer an lvalue).
8506 if (E->isPRValue()) {
8507 // In C, function designators (i.e. expressions of function type)
8508 // are r-values, but we still want to do function-to-pointer decay
8509 // on them. This is both technically correct and convenient for
8510 // some clients.
8511 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
8513
8514 return E;
8515 }
8516
8517 // GCC seems to also exclude expressions of incomplete enum type.
8518 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8519 if (!T->getDecl()->isComplete()) {
8520 // FIXME: stupid workaround for a codegen bug!
8521 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8522 return E;
8523 }
8524 }
8525
8527 if (Res.isInvalid())
8528 return E;
8529 E = Res.get();
8530
8531 if (!E->getType()->isVoidType())
8533 diag::err_incomplete_type);
8534 return E;
8535}
8536
8538 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8539 // it occurs as an unevaluated operand.
8541
8542 return E;
8543}
8544
8545// If we can unambiguously determine whether Var can never be used
8546// in a constant expression, return true.
8547// - if the variable and its initializer are non-dependent, then
8548// we can unambiguously check if the variable is a constant expression.
8549// - if the initializer is not value dependent - we can determine whether
8550// it can be used to initialize a constant expression. If Init can not
8551// be used to initialize a constant expression we conclude that Var can
8552// never be a constant expression.
8553// - FXIME: if the initializer is dependent, we can still do some analysis and
8554// identify certain cases unambiguously as non-const by using a Visitor:
8555// - such as those that involve odr-use of a ParmVarDecl, involve a new
8556// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8559 if (isa<ParmVarDecl>(Var)) return true;
8560 const VarDecl *DefVD = nullptr;
8561
8562 // If there is no initializer - this can not be a constant expression.
8563 const Expr *Init = Var->getAnyInitializer(DefVD);
8564 if (!Init)
8565 return true;
8566 assert(DefVD);
8567 if (DefVD->isWeak())
8568 return false;
8569
8570 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8571 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8572 // of value-dependent expressions, and use it here to determine whether the
8573 // initializer is a potential constant expression.
8574 return false;
8575 }
8576
8578}
8579
8580/// Check if the current lambda has any potential captures
8581/// that must be captured by any of its enclosing lambdas that are ready to
8582/// capture. If there is a lambda that can capture a nested
8583/// potential-capture, go ahead and do so. Also, check to see if any
8584/// variables are uncaptureable or do not involve an odr-use so do not
8585/// need to be captured.
8586
8588 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8589
8590 assert(!S.isUnevaluatedContext());
8591 assert(S.CurContext->isDependentContext());
8592#ifndef NDEBUG
8593 DeclContext *DC = S.CurContext;
8594 while (DC && isa<CapturedDecl>(DC))
8595 DC = DC->getParent();
8596 assert(
8597 CurrentLSI->CallOperator == DC &&
8598 "The current call operator must be synchronized with Sema's CurContext");
8599#endif // NDEBUG
8600
8601 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8602
8603 // All the potentially captureable variables in the current nested
8604 // lambda (within a generic outer lambda), must be captured by an
8605 // outer lambda that is enclosed within a non-dependent context.
8606 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8607 // If the variable is clearly identified as non-odr-used and the full
8608 // expression is not instantiation dependent, only then do we not
8609 // need to check enclosing lambda's for speculative captures.
8610 // For e.g.:
8611 // Even though 'x' is not odr-used, it should be captured.
8612 // int test() {
8613 // const int x = 10;
8614 // auto L = [=](auto a) {
8615 // (void) +x + a;
8616 // };
8617 // }
8618 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8619 !IsFullExprInstantiationDependent)
8620 return;
8621
8622 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8623 if (!UnderlyingVar)
8624 return;
8625
8626 // If we have a capture-capable lambda for the variable, go ahead and
8627 // capture the variable in that lambda (and all its enclosing lambdas).
8628 if (const std::optional<unsigned> Index =
8630 S.FunctionScopes, Var, S))
8631 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8632 const bool IsVarNeverAConstantExpression =
8634 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8635 // This full expression is not instantiation dependent or the variable
8636 // can not be used in a constant expression - which means
8637 // this variable must be odr-used here, so diagnose a
8638 // capture violation early, if the variable is un-captureable.
8639 // This is purely for diagnosing errors early. Otherwise, this
8640 // error would get diagnosed when the lambda becomes capture ready.
8641 QualType CaptureType, DeclRefType;
8642 SourceLocation ExprLoc = VarExpr->getExprLoc();
8643 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8644 /*EllipsisLoc*/ SourceLocation(),
8645 /*BuildAndDiagnose*/false, CaptureType,
8646 DeclRefType, nullptr)) {
8647 // We will never be able to capture this variable, and we need
8648 // to be able to in any and all instantiations, so diagnose it.
8649 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8650 /*EllipsisLoc*/ SourceLocation(),
8651 /*BuildAndDiagnose*/true, CaptureType,
8652 DeclRefType, nullptr);
8653 }
8654 }
8655 });
8656
8657 // Check if 'this' needs to be captured.
8658 if (CurrentLSI->hasPotentialThisCapture()) {
8659 // If we have a capture-capable lambda for 'this', go ahead and capture
8660 // 'this' in that lambda (and all its enclosing lambdas).
8661 if (const std::optional<unsigned> Index =
8663 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8664 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8666 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8667 &FunctionScopeIndexOfCapturableLambda);
8668 }
8669 }
8670
8671 // Reset all the potential captures at the end of each full-expression.
8672 CurrentLSI->clearPotentialCaptures();
8673}
8674
8677 const TypoCorrection &TC) {
8678 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8679 Consumer.getLookupResult().getLookupKind());
8680 const CXXScopeSpec *SS = Consumer.getSS();
8681 CXXScopeSpec NewSS;
8682
8683 // Use an approprate CXXScopeSpec for building the expr.
8684 if (auto *NNS = TC.getCorrectionSpecifier())
8686 else if (SS && !TC.WillReplaceSpecifier())
8687 NewSS = *SS;
8688
8689 if (auto *ND = TC.getFoundDecl()) {
8690 R.setLookupName(ND->getDeclName());
8691 R.addDecl(ND);
8692 if (ND->isCXXClassMember()) {
8693 // Figure out the correct naming class to add to the LookupResult.
8694 CXXRecordDecl *Record = nullptr;
8695 if (auto *NNS = TC.getCorrectionSpecifier())
8696 Record = NNS->getAsType()->getAsCXXRecordDecl();
8697 if (!Record)
8698 Record =
8699 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8700 if (Record)
8702
8703 // Detect and handle the case where the decl might be an implicit
8704 // member.
8706 NewSS, R, Consumer.isAddressOfOperand()))
8708 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8709 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8710 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8711 return SemaRef.ObjC().LookupInObjCMethod(R, Consumer.getScope(),
8712 Ivar->getIdentifier());
8713 }
8714 }
8715
8716 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8717 /*AcceptInvalidDecl*/ true);
8718}
8719
8720namespace {
8721class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8723
8724public:
8725 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8726 : TypoExprs(TypoExprs) {}
8727 bool VisitTypoExpr(TypoExpr *TE) {
8728 TypoExprs.insert(TE);
8729 return true;
8730 }
8731};
8732
8733class TransformTypos : public TreeTransform<TransformTypos> {
8734 typedef TreeTransform<TransformTypos> BaseTransform;
8735
8736 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8737 // process of being initialized.
8738 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8739 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8740 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8741 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8742
8743 /// Emit diagnostics for all of the TypoExprs encountered.
8744 ///
8745 /// If the TypoExprs were successfully corrected, then the diagnostics should
8746 /// suggest the corrections. Otherwise the diagnostics will not suggest
8747 /// anything (having been passed an empty TypoCorrection).
8748 ///
8749 /// If we've failed to correct due to ambiguous corrections, we need to
8750 /// be sure to pass empty corrections and replacements. Otherwise it's
8751 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8752 /// and we don't want to report those diagnostics.
8753 void EmitAllDiagnostics(bool IsAmbiguous) {
8754 for (TypoExpr *TE : TypoExprs) {
8755 auto &State = SemaRef.getTypoExprState(TE);
8756 if (State.DiagHandler) {
8757 TypoCorrection TC = IsAmbiguous
8758 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8759 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8760
8761 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8762 // TypoCorrection, replacing the existing decls. This ensures the right
8763 // NamedDecl is used in diagnostics e.g. in the case where overload
8764 // resolution was used to select one from several possible decls that
8765 // had been stored in the TypoCorrection.
8766 if (auto *ND = getDeclFromExpr(
8767 Replacement.isInvalid() ? nullptr : Replacement.get()))
8768 TC.setCorrectionDecl(ND);
8769
8770 State.DiagHandler(TC);
8771 }
8772 SemaRef.clearDelayedTypo(TE);
8773 }
8774 }
8775
8776 /// Try to advance the typo correction state of the first unfinished TypoExpr.
8777 /// We allow advancement of the correction stream by removing it from the
8778 /// TransformCache which allows `TransformTypoExpr` to advance during the
8779 /// next transformation attempt.
8780 ///
8781 /// Any substitution attempts for the previous TypoExprs (which must have been
8782 /// finished) will need to be retried since it's possible that they will now
8783 /// be invalid given the latest advancement.
8784 ///
8785 /// We need to be sure that we're making progress - it's possible that the
8786 /// tree is so malformed that the transform never makes it to the
8787 /// `TransformTypoExpr`.
8788 ///
8789 /// Returns true if there are any untried correction combinations.
8790 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8791 for (auto *TE : TypoExprs) {
8792 auto &State = SemaRef.getTypoExprState(TE);
8793 TransformCache.erase(TE);
8794 if (!State.Consumer->hasMadeAnyCorrectionProgress())
8795 return false;
8796 if (!State.Consumer->finished())
8797 return true;
8798 State.Consumer->resetCorrectionStream();
8799 }
8800 return false;
8801 }
8802
8804 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8805 E = OverloadResolution[OE];
8806
8807 if (!E)
8808 return nullptr;
8809 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8810 return DRE->getFoundDecl();
8811 if (auto *ME = dyn_cast<MemberExpr>(E))
8812 return ME->getFoundDecl();
8813 // FIXME: Add any other expr types that could be seen by the delayed typo
8814 // correction TreeTransform for which the corresponding TypoCorrection could
8815 // contain multiple decls.
8816 return nullptr;
8817 }
8818
8819 ExprResult TryTransform(Expr *E) {
8820 Sema::SFINAETrap Trap(SemaRef);
8821 ExprResult Res = TransformExpr(E);
8822 if (Trap.hasErrorOccurred() || Res.isInvalid())
8823 return ExprError();
8824
8825 return ExprFilter(Res.get());
8826 }
8827
8828 // Since correcting typos may intoduce new TypoExprs, this function
8829 // checks for new TypoExprs and recurses if it finds any. Note that it will
8830 // only succeed if it is able to correct all typos in the given expression.
8831 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8832 if (Res.isInvalid()) {
8833 return Res;
8834 }
8835 // Check to see if any new TypoExprs were created. If so, we need to recurse
8836 // to check their validity.
8837 Expr *FixedExpr = Res.get();
8838
8839 auto SavedTypoExprs = std::move(TypoExprs);
8840 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8841 TypoExprs.clear();
8842 AmbiguousTypoExprs.clear();
8843
8844 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8845 if (!TypoExprs.empty()) {
8846 // Recurse to handle newly created TypoExprs. If we're not able to
8847 // handle them, discard these TypoExprs.
8848 ExprResult RecurResult =
8849 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8850 if (RecurResult.isInvalid()) {
8851 Res = ExprError();
8852 // Recursive corrections didn't work, wipe them away and don't add
8853 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8854 // since we don't want to clear them twice. Note: it's possible the
8855 // TypoExprs were created recursively and thus won't be in our
8856 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8857 auto &SemaTypoExprs = SemaRef.TypoExprs;
8858 for (auto *TE : TypoExprs) {
8859 TransformCache.erase(TE);
8860 SemaRef.clearDelayedTypo(TE);
8861
8862 auto SI = find(SemaTypoExprs, TE);
8863 if (SI != SemaTypoExprs.end()) {
8864 SemaTypoExprs.erase(SI);
8865 }
8866 }
8867 } else {
8868 // TypoExpr is valid: add newly created TypoExprs since we were
8869 // able to correct them.
8870 Res = RecurResult;
8871 SavedTypoExprs.set_union(TypoExprs);
8872 }
8873 }
8874
8875 TypoExprs = std::move(SavedTypoExprs);
8876 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8877
8878 return Res;
8879 }
8880
8881 // Try to transform the given expression, looping through the correction
8882 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8883 //
8884 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8885 // true and this method immediately will return an `ExprError`.
8886 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8887 ExprResult Res;
8888 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8889 SemaRef.TypoExprs.clear();
8890
8891 while (true) {
8892 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8893
8894 // Recursion encountered an ambiguous correction. This means that our
8895 // correction itself is ambiguous, so stop now.
8896 if (IsAmbiguous)
8897 break;
8898
8899 // If the transform is still valid after checking for any new typos,
8900 // it's good to go.
8901 if (!Res.isInvalid())
8902 break;
8903
8904 // The transform was invalid, see if we have any TypoExprs with untried
8905 // correction candidates.
8906 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8907 break;
8908 }
8909
8910 // If we found a valid result, double check to make sure it's not ambiguous.
8911 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8912 auto SavedTransformCache =
8913 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8914
8915 // Ensure none of the TypoExprs have multiple typo correction candidates
8916 // with the same edit length that pass all the checks and filters.
8917 while (!AmbiguousTypoExprs.empty()) {
8918 auto TE = AmbiguousTypoExprs.back();
8919
8920 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8921 // and invalidating our TypoExprState, so always fetch it instead of storing.
8922 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8923
8924 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8925 TypoCorrection Next;
8926 do {
8927 // Fetch the next correction by erasing the typo from the cache and calling
8928 // `TryTransform` which will iterate through corrections in
8929 // `TransformTypoExpr`.
8930 TransformCache.erase(TE);
8931 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8932
8933 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8934 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8935 SavedTransformCache.erase(TE);
8936 Res = ExprError();
8937 IsAmbiguous = true;
8938 break;
8939 }
8940 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8941 Next.getEditDistance(false) == TC.getEditDistance(false));
8942
8943 if (IsAmbiguous)
8944 break;
8945
8946 AmbiguousTypoExprs.remove(TE);
8947 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8948 TransformCache[TE] = SavedTransformCache[TE];
8949 }
8950 TransformCache = std::move(SavedTransformCache);
8951 }
8952
8953 // Wipe away any newly created TypoExprs that we don't know about. Since we
8954 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8955 // possible if a `TypoExpr` is created during a transformation but then
8956 // fails before we can discover it.
8957 auto &SemaTypoExprs = SemaRef.TypoExprs;
8958 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8959 auto TE = *Iterator;
8960 auto FI = find(TypoExprs, TE);
8961 if (FI != TypoExprs.end()) {
8962 Iterator++;
8963 continue;
8964 }
8965 SemaRef.clearDelayedTypo(TE);
8966 Iterator = SemaTypoExprs.erase(Iterator);
8967 }
8968 SemaRef.TypoExprs = std::move(SavedTypoExprs);
8969
8970 return Res;
8971 }
8972
8973public:
8974 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8975 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8976
8977 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8978 MultiExprArg Args,
8979 SourceLocation RParenLoc,
8980 Expr *ExecConfig = nullptr) {
8981 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8982 RParenLoc, ExecConfig);
8983 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8984 if (Result.isUsable()) {
8985 Expr *ResultCall = Result.get();
8986 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8987 ResultCall = BE->getSubExpr();
8988 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8989 OverloadResolution[OE] = CE->getCallee();
8990 }
8991 }
8992 return Result;
8993 }
8994
8995 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8996
8997 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8998
8999 ExprResult Transform(Expr *E) {
9000 bool IsAmbiguous = false;
9001 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
9002
9003 if (!Res.isUsable())
9004 FindTypoExprs(TypoExprs).TraverseStmt(E);
9005
9006 EmitAllDiagnostics(IsAmbiguous);
9007
9008 return Res;
9009 }
9010
9011 ExprResult TransformTypoExpr(TypoExpr *E) {
9012 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
9013 // cached transformation result if there is one and the TypoExpr isn't the
9014 // first one that was encountered.
9015 auto &CacheEntry = TransformCache[E];
9016 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
9017 return CacheEntry;
9018 }
9019
9020 auto &State = SemaRef.getTypoExprState(E);
9021 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
9022
9023 // For the first TypoExpr and an uncached TypoExpr, find the next likely
9024 // typo correction and return it.
9025 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
9026 if (InitDecl && TC.getFoundDecl() == InitDecl)
9027 continue;
9028 // FIXME: If we would typo-correct to an invalid declaration, it's
9029 // probably best to just suppress all errors from this typo correction.
9030 ExprResult NE = State.RecoveryHandler ?
9031 State.RecoveryHandler(SemaRef, E, TC) :
9032 attemptRecovery(SemaRef, *State.Consumer, TC);
9033 if (!NE.isInvalid()) {
9034 // Check whether there may be a second viable correction with the same
9035 // edit distance; if so, remember this TypoExpr may have an ambiguous
9036 // correction so it can be more thoroughly vetted later.
9037 TypoCorrection Next;
9038 if ((Next = State.Consumer->peekNextCorrection()) &&
9039 Next.getEditDistance(false) == TC.getEditDistance(false)) {
9040 AmbiguousTypoExprs.insert(E);
9041 } else {
9042 AmbiguousTypoExprs.remove(E);
9043 }
9044 assert(!NE.isUnset() &&
9045 "Typo was transformed into a valid-but-null ExprResult");
9046 return CacheEntry = NE;
9047 }
9048 }
9049 return CacheEntry = ExprError();
9050 }
9051};
9052}
9053
9056 bool RecoverUncorrectedTypos,
9057 llvm::function_ref<ExprResult(Expr *)> Filter) {
9058 // If the current evaluation context indicates there are uncorrected typos
9059 // and the current expression isn't guaranteed to not have typos, try to
9060 // resolve any TypoExpr nodes that might be in the expression.
9061 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
9062 (E->isTypeDependent() || E->isValueDependent() ||
9064 auto TyposResolved = DelayedTypos.size();
9065 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
9066 TyposResolved -= DelayedTypos.size();
9067 if (Result.isInvalid() || Result.get() != E) {
9068 ExprEvalContexts.back().NumTypos -= TyposResolved;
9069 if (Result.isInvalid() && RecoverUncorrectedTypos) {
9070 struct TyposReplace : TreeTransform<TyposReplace> {
9071 TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
9072 ExprResult TransformTypoExpr(clang::TypoExpr *E) {
9073 return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
9074 E->getEndLoc(), {});
9075 }
9076 } TT(*this);
9077 return TT.TransformExpr(E);
9078 }
9079 return Result;
9080 }
9081 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
9082 }
9083 return E;
9084}
9085
9087 bool DiscardedValue, bool IsConstexpr,
9088 bool IsTemplateArgument) {
9089 ExprResult FullExpr = FE;
9090
9091 if (!FullExpr.get())
9092 return ExprError();
9093
9094 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
9095 return ExprError();
9096
9097 if (DiscardedValue) {
9098 // Top-level expressions default to 'id' when we're in a debugger.
9099 if (getLangOpts().DebuggerCastResultToId &&
9100 FullExpr.get()->getType() == Context.UnknownAnyTy) {
9102 if (FullExpr.isInvalid())
9103 return ExprError();
9104 }
9105
9107 if (FullExpr.isInvalid())
9108 return ExprError();
9109
9111 if (FullExpr.isInvalid())
9112 return ExprError();
9113
9114 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
9115 }
9116
9117 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
9118 /*RecoverUncorrectedTypos=*/true);
9119 if (FullExpr.isInvalid())
9120 return ExprError();
9121
9122 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
9123
9124 // At the end of this full expression (which could be a deeply nested
9125 // lambda), if there is a potential capture within the nested lambda,
9126 // have the outer capture-able lambda try and capture it.
9127 // Consider the following code:
9128 // void f(int, int);
9129 // void f(const int&, double);
9130 // void foo() {
9131 // const int x = 10, y = 20;
9132 // auto L = [=](auto a) {
9133 // auto M = [=](auto b) {
9134 // f(x, b); <-- requires x to be captured by L and M
9135 // f(y, a); <-- requires y to be captured by L, but not all Ms
9136 // };
9137 // };
9138 // }
9139
9140 // FIXME: Also consider what happens for something like this that involves
9141 // the gnu-extension statement-expressions or even lambda-init-captures:
9142 // void f() {
9143 // const int n = 0;
9144 // auto L = [&](auto a) {
9145 // +n + ({ 0; a; });
9146 // };
9147 // }
9148 //
9149 // Here, we see +n, and then the full-expression 0; ends, so we don't
9150 // capture n (and instead remove it from our list of potential captures),
9151 // and then the full-expression +n + ({ 0; }); ends, but it's too late
9152 // for us to see that we need to capture n after all.
9153
9154 LambdaScopeInfo *const CurrentLSI =
9155 getCurLambda(/*IgnoreCapturedRegions=*/true);
9156 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
9157 // even if CurContext is not a lambda call operator. Refer to that Bug Report
9158 // for an example of the code that might cause this asynchrony.
9159 // By ensuring we are in the context of a lambda's call operator
9160 // we can fix the bug (we only need to check whether we need to capture
9161 // if we are within a lambda's body); but per the comments in that
9162 // PR, a proper fix would entail :
9163 // "Alternative suggestion:
9164 // - Add to Sema an integer holding the smallest (outermost) scope
9165 // index that we are *lexically* within, and save/restore/set to
9166 // FunctionScopes.size() in InstantiatingTemplate's
9167 // constructor/destructor.
9168 // - Teach the handful of places that iterate over FunctionScopes to
9169 // stop at the outermost enclosing lexical scope."
9170 DeclContext *DC = CurContext;
9171 while (DC && isa<CapturedDecl>(DC))
9172 DC = DC->getParent();
9173 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
9174 if (IsInLambdaDeclContext && CurrentLSI &&
9175 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
9177 *this);
9179}
9180
9182 if (!FullStmt) return StmtError();
9183
9184 return MaybeCreateStmtWithCleanups(FullStmt);
9185}
9186
9189 CXXScopeSpec &SS,
9190 const DeclarationNameInfo &TargetNameInfo) {
9191 DeclarationName TargetName = TargetNameInfo.getName();
9192 if (!TargetName)
9193 return IER_DoesNotExist;
9194
9195 // If the name itself is dependent, then the result is dependent.
9196 if (TargetName.isDependentName())
9197 return IER_Dependent;
9198
9199 // Do the redeclaration lookup in the current scope.
9200 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
9201 RedeclarationKind::NotForRedeclaration);
9202 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
9204
9205 switch (R.getResultKind()) {
9210 return IER_Exists;
9211
9213 return IER_DoesNotExist;
9214
9216 return IER_Dependent;
9217 }
9218
9219 llvm_unreachable("Invalid LookupResult Kind!");
9220}
9221
9224 bool IsIfExists, CXXScopeSpec &SS,
9225 UnqualifiedId &Name) {
9226 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9227
9228 // Check for an unexpanded parameter pack.
9229 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
9230 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
9231 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
9232 return IER_Error;
9233
9234 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
9235}
9236
9238 return BuildExprRequirement(E, /*IsSimple=*/true,
9239 /*NoexceptLoc=*/SourceLocation(),
9240 /*ReturnTypeRequirement=*/{});
9241}
9242
9244 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
9245 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
9246 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
9247 "Exactly one of TypeName and TemplateId must be specified.");
9248 TypeSourceInfo *TSI = nullptr;
9249 if (TypeName) {
9250 QualType T =
9252 SS.getWithLocInContext(Context), *TypeName, NameLoc,
9253 &TSI, /*DeducedTSTContext=*/false);
9254 if (T.isNull())
9255 return nullptr;
9256 } else {
9257 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
9258 TemplateId->NumArgs);
9259 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
9260 TemplateId->TemplateKWLoc,
9261 TemplateId->Template, TemplateId->Name,
9262 TemplateId->TemplateNameLoc,
9263 TemplateId->LAngleLoc, ArgsPtr,
9264 TemplateId->RAngleLoc);
9265 if (T.isInvalid())
9266 return nullptr;
9267 if (GetTypeFromParser(T.get(), &TSI).isNull())
9268 return nullptr;
9269 }
9270 return BuildTypeRequirement(TSI);
9271}
9272
9275 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
9276 /*ReturnTypeRequirement=*/{});
9277}
9278
9281 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
9282 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
9283 // C++2a [expr.prim.req.compound] p1.3.3
9284 // [..] the expression is deduced against an invented function template
9285 // F [...] F is a void function template with a single type template
9286 // parameter T declared with the constrained-parameter. Form a new
9287 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
9288 // around the constrained-parameter. F has a single parameter whose
9289 // type-specifier is cv T followed by the abstract-declarator. [...]
9290 //
9291 // The cv part is done in the calling function - we get the concept with
9292 // arguments and the abstract declarator with the correct CV qualification and
9293 // have to synthesize T and the single parameter of F.
9294 auto &II = Context.Idents.get("expr-type");
9297 SourceLocation(), Depth,
9298 /*Index=*/0, &II,
9299 /*Typename=*/true,
9300 /*ParameterPack=*/false,
9301 /*HasTypeConstraint=*/true);
9302
9303 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
9304 /*EllipsisLoc=*/SourceLocation(),
9305 /*AllowUnexpandedPack=*/true))
9306 // Just produce a requirement with no type requirements.
9307 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
9308
9311 ArrayRef<NamedDecl *>(TParam),
9313 /*RequiresClause=*/nullptr);
9314 return BuildExprRequirement(
9315 E, /*IsSimple=*/false, NoexceptLoc,
9317}
9318
9321 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9324 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9326 ReturnTypeRequirement.isDependent())
9328 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9330 else if (ReturnTypeRequirement.isSubstitutionFailure())
9332 else if (ReturnTypeRequirement.isTypeConstraint()) {
9333 // C++2a [expr.prim.req]p1.3.3
9334 // The immediately-declared constraint ([temp]) of decltype((E)) shall
9335 // be satisfied.
9337 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9338 QualType MatchedType =
9341 Args.push_back(TemplateArgument(MatchedType));
9342
9343 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9344
9345 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/false);
9346 MLTAL.addOuterRetainedLevels(TPL->getDepth());
9347 const TypeConstraint *TC = Param->getTypeConstraint();
9348 assert(TC && "Type Constraint cannot be null here");
9349 auto *IDC = TC->getImmediatelyDeclaredConstraint();
9350 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
9351 ExprResult Constraint = SubstExpr(IDC, MLTAL);
9352 if (Constraint.isInvalid()) {
9354 concepts::createSubstDiagAt(*this, IDC->getExprLoc(),
9355 [&](llvm::raw_ostream &OS) {
9356 IDC->printPretty(OS, /*Helper=*/nullptr,
9357 getPrintingPolicy());
9358 }),
9359 IsSimple, NoexceptLoc, ReturnTypeRequirement);
9360 }
9361 SubstitutedConstraintExpr =
9362 cast<ConceptSpecializationExpr>(Constraint.get());
9363 if (!SubstitutedConstraintExpr->isSatisfied())
9365 }
9366 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9367 ReturnTypeRequirement, Status,
9368 SubstitutedConstraintExpr);
9369}
9370
9373 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9374 bool IsSimple, SourceLocation NoexceptLoc,
9376 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9377 IsSimple, NoexceptLoc,
9378 ReturnTypeRequirement);
9379}
9380
9384}
9385
9389 return new (Context) concepts::TypeRequirement(SubstDiag);
9390}
9391
9393 return BuildNestedRequirement(Constraint);
9394}
9395
9398 ConstraintSatisfaction Satisfaction;
9399 if (!Constraint->isInstantiationDependent() &&
9400 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9401 Constraint->getSourceRange(), Satisfaction))
9402 return nullptr;
9403 return new (Context) concepts::NestedRequirement(Context, Constraint,
9404 Satisfaction);
9405}
9406
9408Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9409 const ASTConstraintSatisfaction &Satisfaction) {
9411 InvalidConstraintEntity,
9413}
9414
9417 ArrayRef<ParmVarDecl *> LocalParameters,
9418 Scope *BodyScope) {
9419 assert(BodyScope);
9420
9422 RequiresKWLoc);
9423
9424 PushDeclContext(BodyScope, Body);
9425
9426 for (ParmVarDecl *Param : LocalParameters) {
9427 if (Param->hasDefaultArg())
9428 // C++2a [expr.prim.req] p4
9429 // [...] A local parameter of a requires-expression shall not have a
9430 // default argument. [...]
9431 Diag(Param->getDefaultArgRange().getBegin(),
9432 diag::err_requires_expr_local_parameter_default_argument);
9433 // Ignore default argument and move on
9434
9435 Param->setDeclContext(Body);
9436 // If this has an identifier, add it to the scope stack.
9437 if (Param->getIdentifier()) {
9438 CheckShadow(BodyScope, Param);
9439 PushOnScopeChains(Param, BodyScope);
9440 }
9441 }
9442 return Body;
9443}
9444
9446 assert(CurContext && "DeclContext imbalance!");
9448 assert(CurContext && "Popped translation unit!");
9449}
9450
9452 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
9453 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
9454 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
9455 SourceLocation ClosingBraceLoc) {
9456 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
9457 LocalParameters, RParenLoc, Requirements,
9458 ClosingBraceLoc);
9460 return ExprError();
9461 return RE;
9462}
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
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition: Darwin.cpp:3174
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 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 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 isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD)
Determine whether the given function is a non-placement deallocation function.
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14598
This file provides some common utility functions for processing Lambdas.
SourceRange Range
Definition: SemaObjC.cpp:754
SourceLocation Loc
Definition: SemaObjC.cpp:755
This file declares semantic analysis for Objective-C.
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:182
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:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2768
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:648
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:1103
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:2575
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2591
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:2141
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
CanQualType DependentTy
Definition: ASTContext.h:1119
CanQualType NullPtrTy
Definition: ASTContext.h:1118
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:1591
IdentifierTable & Idents
Definition: ASTContext.h:644
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:775
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
CanQualType BoolTy
Definition: ASTContext.h:1092
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:1119
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:2157
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:1119
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2064
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2618
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:2341
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1091
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getExceptionObjectType(QualType T) const
CanQualType UnknownAnyTy
Definition: ASTContext.h:1120
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:1569
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:2152
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:757
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2180
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:1794
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2000
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:2372
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2345
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:2848
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3518
QualType getElementType() const
Definition: Type.h:3530
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition: Type.h:7189
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:5981
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
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:4786
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Pointer to a block type.
Definition: Type.h:3349
This class is used for builtin types like 'int'.
Definition: Type.h:2981
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1487
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition: ExprCXX.cpp:1048
const Expr * getSubExpr() const
Definition: ExprCXX.h:1509
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1542
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:2493
bool isArrayForm() const
Definition: ExprCXX.h:2519
SourceLocation getBeginLoc() const
Definition: ExprCXX.h:2543
Expr * getArgument()
Definition: ExprCXX.h:2534
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:852
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:2378
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:2488
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:2466
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2236
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:245
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4119
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:2612
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:1975
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:1594
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2177
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:1453
void setDestructor(const CXXDestructorDecl *Dtor)
Definition: ExprCXX.h:1466
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1043
Represents the this expression in C++.
Definition: ExprCXX.h:1148
static CXXThisExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType Ty, bool IsImplicit)
Definition: ExprCXX.cpp:1519
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1202
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:1422
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1062
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3024
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1638
Expr * getCallee()
Definition: Expr.h:2970
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2998
arg_range arguments()
Definition: Expr.h:3059
Decl * getCalleeDecl()
Definition: Expr.h:2984
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:3086
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:3556
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:178
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:218
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2066
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2082
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1716
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:592
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
void addAttr(Attr *A)
Definition: DeclBase.cpp:991
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:132
bool isInvalidDecl() const
Definition: DeclBase.h:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:820
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:871
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
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:822
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2398
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2047
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:2084
void DropFirstTypeObject()
Definition: DeclSpec.h:2415
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2394
bool isInvalidType() const
Definition: DeclSpec.h:2714
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2082
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:5947
bool isDeduced() const
Definition: Type.h:5969
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:3867
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4852
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4081
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5575
EnumDecl * getDecl() const
Definition: Type.h:5582
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1397
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:2523
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:4138
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:3059
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3055
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:3279
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
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:3556
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:3923
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:2919
Represents difference between two FPOptions values.
Definition: LangOptions.h:915
Represents a member of a struct/union/class.
Definition: Decl.h:3057
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:1039
Represents a function declaration or definition.
Definition: Decl.h:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2706
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.cpp:4054
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2283
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition: Decl.h:2667
QualType getReturnType() const
Definition: Decl.h:2754
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2339
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3089
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2502
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:3366
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:2160
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4395
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3692
size_t param_size() const
Definition: Decl.h:2699
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:3203
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
unsigned getNumParams() const
Definition: Type.h:4889
QualType getParamType(unsigned i) const
Definition: Type.h:4891
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5012
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
Definition: Type.h:5007
Declaration of a template function.
Definition: DeclTemplate.h:957
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4441
bool getNoReturn() const
Definition: Type.h:4415
bool getProducesResult() const
Definition: Type.h:4416
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
ExtInfo getExtInfo() const
Definition: Type.h:4585
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:3655
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:543
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition: Overload.h:594
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition: Overload.h:598
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition: Expr.h:4847
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:8601
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
Definition: SemaInit.cpp:3701
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
Definition: SemaInit.cpp:9638
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:3690
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:1950
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
bool hasGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:725
bool allowsNonTrivialObjCLifetimeQualifiers() const
True if any ObjC types may have non-trivial lifetime qualifiers.
Definition: LangOptions.h:638
bool hasHiddenGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:740
bool hasProtectedGlobalAllocationFunctionVisibility() const
Definition: LangOptions.h:735
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:3172
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition: Expr.h:3259
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
QualType getPointeeType() const
Definition: Type.h:3476
const Type * getClass() const
Definition: Type.h:3490
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
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
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
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:1053
Represents a pointer to an Objective C object.
Definition: Type.h:7008
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7020
Represents a class type in Objective C.
Definition: Type.h:6754
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6987
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:1168
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition: Overload.h:991
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
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 parethesized expression, e.g.
Definition: Expr.h:2130
Represents a parameter to a function.
Definition: Decl.h:1761
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:2915
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
QualType getPointeeType() const
Definition: Type.h:3149
SourceManager & getSourceManager() const
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
Stores the type being destroyed by a pseudo-destructor expression.
Definition: ExprCXX.h:2561
TypeSourceInfo * getTypeSourceInfo() const
Definition: ExprCXX.h:2577
A (possibly-)qualified type.
Definition: Type.h:940
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7443
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3477
@ DK_nontrivial_c_struct
Definition: Type.h:1523
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
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:7541
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7359
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7485
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7399
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1432
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:7560
QualType getCanonicalType() const
Definition: Type.h:7411
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7453
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2849
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1530
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:7405
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1436
The collection of all-type qualifiers we support.
Definition: Type.h:318
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:481
GC getObjCGCAttr() const
Definition: Type.h:505
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:336
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
bool hasCVRQualifiers() const
Definition: Type.h:473
bool hasUnaligned() const
Definition: Type.h:497
unsigned getAddressSpaceAttributePrintValue() const
Get the address space attribute value to be printed by diagnostics.
Definition: Type.h:564
void setAddressSpace(LangAS space)
Definition: Type.h:577
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:694
unsigned getCVRUQualifiers() const
Definition: Type.h:475
void setObjCGCAttr(GC type)
Definition: Type.h:506
ObjCLifetime getObjCLifetime() const
Definition: Type.h:531
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition: Type.h:427
LangAS getAddressSpace() const
Definition: Type.h:557
void setObjCLifetime(ObjCLifetime type)
Definition: Type.h:534
Represents a struct/union/class.
Definition: Decl.h:4168
bool canPassInRegisters() const
Determine whether this class can be passed in registers.
Definition: Decl.h:4297
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
RecordDecl * getDecl() const
Definition: Type.h:5559
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:2174
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:56
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.
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:2531
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition: Sema.h:7976
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9409
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9439
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
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:6350
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:688
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
Definition: SemaType.cpp:2054
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:6289
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7287
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition: Sema.h:7302
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:7290
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:7332
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:424
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
VariadicCallType
Definition: Sema.h:2004
@ VariadicDoesNotApply
Definition: Sema.h:2009
@ VariadicFunction
Definition: Sema.h:2005
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:6789
@ IER_DoesNotExist
The symbol does not exist.
Definition: Sema.h:6794
@ IER_Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
Definition: Sema.h:6798
@ IER_Error
An error occurred.
Definition: Sema.h:6801
@ IER_Exists
The symbol exists.
Definition: Sema.h:6791
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:1563
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:993
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:20218
ConditionKind
Definition: Sema.h:5828
@ 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:797
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition: Sema.h:8068
@ AR_inaccessible
Definition: Sema.h:1076
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:18283
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:17038
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:10192
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1422
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:1499
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.
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1058
ASTContext & Context
Definition: Sema.h:848
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:582
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:514
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:7940
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
SemaObjC & ObjC()
Definition: Sema.h:1003
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:5722
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1523
ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19482
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:764
ASTContext & getASTContext() const
Definition: Sema.h:517
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:18774
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9630
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
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:645
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:6193
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:765
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
ActOnCXXThrow - Parse throw expressions.
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2208
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:6400
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:3279
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:512
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:65
@ UPPC_IfExists
Microsoft __if_exists.
Definition: Sema.h:10759
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition: Sema.h:10762
const LangOptions & getLangOpts() const
Definition: Sema.h:510
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:7298
SemaOpenACC & OpenACC()
Definition: Sema.h:1008
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:847
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:11163
const LangOptions & LangOpts
Definition: Sema.h:846
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:2366
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:8564
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:17339
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:19890
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:5149
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:727
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:10442
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:5146
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:10754
void MarkThisReferenced(CXXThisExpr *This)
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:652
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3232
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:6219
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:7661
static bool isCast(CheckedConversionKind CCK)
Definition: Sema.h:1794
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7714
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
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:5870
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:7965
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:6211
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1479
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6018
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6020
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:6099
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer)
ActOnCXXNew - Parsed a C++ 'new' expression.
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:5869
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:6411
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4151
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20806
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17232
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:10401
SourceManager & getSourceManager() const
Definition: Sema.h:515
@ TryCapture_Implicit
Definition: Sema.h:5237
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition: Sema.h:6472
AssignmentAction
Definition: Sema.h:5157
@ AA_Returning
Definition: Sema.h:5160
@ AA_Passing_CFAudited
Definition: Sema.h:5165
@ AA_Initializing
Definition: Sema.h:5162
@ AA_Converting
Definition: Sema.h:5161
@ AA_Assigning
Definition: Sema.h:5158
@ AA_Passing
Definition: Sema.h:5159
@ AA_Casting
Definition: Sema.h:5164
@ AA_Sending
Definition: Sema.h:5163
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:3437
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:228
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:8301
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:61
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:11583
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:6407
@ CCEK_ArrayBound
Array bound in array declarator or new-expression.
Definition: Sema.h:7950
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:291
ASTConsumer & Consumer
Definition: Sema.h:849
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:5153
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:16600
@ 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:9436
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5678
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20090
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8831
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...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20734
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:6418
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17757
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6362
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1330
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:850
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:528
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10684
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:1757
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:9450
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:16705
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:17940
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:5950
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1899
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:20999
ParsedType getConstructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
Definition: SemaExprCXX.cpp:95
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition: Sema.h:6404
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9208
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:2805
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:5815
IdentifierResolver IdResolver
Definition: Sema.h:2524
const TypoExprState & getTypoExprState(TypoExpr *TE) const
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:5771
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:6572
@ AFS_Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition: Sema.h:6580
@ AFS_Class
Only look for allocation functions in the scope of the allocated class.
Definition: Sema.h:6577
@ AFS_Global
Only look for allocation functions in the global scope.
Definition: Sema.h:6574
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:5396
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:6650
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:267
DeclAccessPair FoundCopyConstructor
Definition: Overload.h:355
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition: Overload.h:272
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition: Overload.h:294
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition: Overload.h:354
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition: Overload.h:304
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition: Overload.h:288
ImplicitConversionKind Element
Element - Between the second and third conversion a vector or matrix element conversion may occur.
Definition: Overload.h:284
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4383
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:1773
StringRef getString() const
Definition: Expr.h:1850
bool isUnion() const
Definition: Decl.h:3790
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:231
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:246
Represents a declaration of a type.
Definition: Decl.h:3390
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:7330
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:7341
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:1828
The base class of the type hierarchy.
Definition: Type.h:1813
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:2463
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:1871
bool isBlockPointerType() const
Definition: Type.h:7620
bool isVoidType() const
Definition: Type.h:7905
bool isBooleanType() const
Definition: Type.h:8033
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2901
bool isIncompleteArrayType() const
Definition: Type.h:7686
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:7881
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition: Type.cpp:2135
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2060
bool isRValueReferenceType() const
Definition: Type.h:7632
bool isFundamentalType() const
Tests whether the type is categorized as a fundamental type.
Definition: Type.h:7575
bool isVoidPointerType() const
Definition: Type.cpp:655
bool isArrayType() const
Definition: Type.h:7678
bool isArithmeticType() const
Definition: Type.cpp:2270
bool isPointerType() const
Definition: Type.h:7612
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7945
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8193
bool isReferenceType() const
Definition: Type.h:7624
bool isEnumeralType() const
Definition: Type.h:7710
bool isScalarType() const
Definition: Type.h:8004
bool isInterfaceType() const
Definition: Type.cpp:641
bool isVariableArrayType() const
Definition: Type.h:7690
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2496
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2047
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isExtVectorType() const
Definition: Type.h:7722
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2534
bool isMemberDataPointerType() const
Definition: Type.h:7671
bool isLValueReferenceType() const
Definition: Type.h:7628
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2327
bool isAnyComplexType() const
Definition: Type.h:7714
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7958
bool isHalfType() const
Definition: Type.h:7909
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:2000
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2453
bool isCompoundType() const
Tests whether the type is categorized as a compound type.
Definition: Type.h:7586
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8076
bool isMemberPointerType() const
Definition: Type.h:7660
bool isMatrixType() const
Definition: Type.h:7732
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2982
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2671
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4906
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:2405
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4849
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2351
bool isFunctionType() const
Definition: Type.h:7608
bool isObjCObjectPointerType() const
Definition: Type.h:7744
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2247
bool isStructureOrClassType() const
Definition: Type.cpp:647
bool isMemberFunctionPointerType() const
Definition: Type.h:7664
bool isVectorType() const
Definition: Type.h:7718
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2255
bool isFloatingType() const
Definition: Type.cpp:2238
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:2185
bool isAnyPointerType() const
Definition: Type.h:7616
bool isClassType() const
Definition: Type.cpp:623
TypeClass getTypeClass() const
Definition: Type.h:2300
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:4855
bool isNullPtrType() const
Definition: Type.h:7938
bool isRecordType() const
Definition: Type.h:7706
bool isObjCRetainableType() const
Definition: Type.cpp:4886
bool isUnionType() const
Definition: Type.cpp:661
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:1879
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition: Type.cpp:678
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:6585
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:6605
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:6604
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
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
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5365
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3324
Represents a variable declaration or definition.
Definition: Decl.h:918
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2187
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:2505
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1345
Represents a GCC generic vector type.
Definition: Type.h:3969
unsigned getNumElements() const
Definition: Type.h:3984
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:251
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:235
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:868
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:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
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:178
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:1762
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1765
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1768
@ 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_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:205
@ 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:367
@ 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:2221
@ 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:436
@ 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:93
static ASTConstraintSatisfaction * Rebuild(const ASTContext &C, const ASTConstraintSatisfaction &Satisfaction)
Definition: ASTConcept.cpp:76
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
enum clang::DeclaratorChunk::@221 Kind
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:4709
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:4712
Extra information about a function prototype.
Definition: Type.h:4735
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4742
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4736
Parts of a decomposed MSGuidDecl.
Definition: DeclCXX.h:4264
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition: Overload.h:848
ReferenceConversions
The conversions that would be performed on an lvalue of type T2 when binding a reference of type T1 t...
Definition: Sema.h:8076
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:410
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition: Overload.h:432
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition: Overload.h:423
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition: Overload.h:427
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition: Overload.h:418
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition: Overload.h:437