clang 23.0.0git
SemaExprCXX.cpp
Go to the documentation of this file.
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Implements semantic analysis for C++ expressions.
11///
12//===----------------------------------------------------------------------===//
13
14#include "TreeTransform.h"
15#include "TypeLocBuilder.h"
17#include "clang/AST/ASTLambda.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/Type.h"
27#include "clang/AST/TypeLoc.h"
34#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/Lookup.h"
39#include "clang/Sema/Scope.h"
41#include "clang/Sema/SemaCUDA.h"
42#include "clang/Sema/SemaHLSL.h"
44#include "clang/Sema/SemaObjC.h"
45#include "clang/Sema/SemaPPC.h"
46#include "clang/Sema/Template.h"
48#include "llvm/ADT/APInt.h"
49#include "llvm/ADT/STLExtras.h"
50#include "llvm/ADT/StringExtras.h"
51#include "llvm/Support/ErrorHandling.h"
52#include "llvm/Support/TypeSize.h"
53#include <optional>
54using namespace clang;
55using namespace sema;
56
58 SourceLocation NameLoc,
59 const IdentifierInfo &Name) {
61 QualType Type(NNS.getAsType(), 0);
62 if ([[maybe_unused]] const auto *DNT = dyn_cast<DependentNameType>(Type))
63 assert(DNT->getIdentifier() == &Name && "not a constructor name");
64
65 // This reference to the type is located entirely at the location of the
66 // final identifier in the qualified-id.
68 Context.getTrivialTypeSourceInfo(Type, NameLoc));
69}
70
72 SourceLocation NameLoc, Scope *S,
73 CXXScopeSpec &SS, bool EnteringContext) {
74 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
75 assert(CurClass && &II == CurClass->getIdentifier() &&
76 "not a constructor name");
77
78 // When naming a constructor as a member of a dependent context (eg, in a
79 // friend declaration or an inherited constructor declaration), form an
80 // unresolved "typename" type.
81 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
82 QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None,
83 SS.getScopeRep(), &II);
84 return ParsedType::make(T);
85 }
86
87 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
88 return ParsedType();
89
90 // Find the injected-class-name declaration. Note that we make no attempt to
91 // diagnose cases where the injected-class-name is shadowed: the only
92 // declaration that can validly shadow the injected-class-name is a
93 // non-static data member, and if the class contains both a non-static data
94 // member and a constructor then it is ill-formed (we check that in
95 // CheckCompletedCXXClass).
96 CXXRecordDecl *InjectedClassName = nullptr;
97 for (NamedDecl *ND : CurClass->lookup(&II)) {
98 auto *RD = dyn_cast<CXXRecordDecl>(ND);
99 if (RD && RD->isInjectedClassName()) {
100 InjectedClassName = RD;
101 break;
102 }
103 }
104 if (!InjectedClassName) {
105 if (!CurClass->isInvalidDecl()) {
106 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
107 // properly. Work around it here for now.
109 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
110 }
111 return ParsedType();
112 }
113
115 InjectedClassName, /*OwnsTag=*/false);
116 return ParsedType::make(T);
117}
118
120 SourceLocation NameLoc, Scope *S,
121 CXXScopeSpec &SS, ParsedType ObjectTypePtr,
122 bool EnteringContext) {
123 // Determine where to perform name lookup.
124
125 // FIXME: This area of the standard is very messy, and the current
126 // wording is rather unclear about which scopes we search for the
127 // destructor name; see core issues 399 and 555. Issue 399 in
128 // particular shows where the current description of destructor name
129 // lookup is completely out of line with existing practice, e.g.,
130 // this appears to be ill-formed:
131 //
132 // namespace N {
133 // template <typename T> struct S {
134 // ~S();
135 // };
136 // }
137 //
138 // void f(N::S<int>* s) {
139 // s->N::S<int>::~S();
140 // }
141 //
142 // See also PR6358 and PR6359.
143 //
144 // For now, we accept all the cases in which the name given could plausibly
145 // be interpreted as a correct destructor name, issuing off-by-default
146 // extension diagnostics on the cases that don't strictly conform to the
147 // C++20 rules. This basically means we always consider looking in the
148 // nested-name-specifier prefix, the complete nested-name-specifier, and
149 // the scope, and accept if we find the expected type in any of the three
150 // places.
151
152 if (SS.isInvalid())
153 return nullptr;
154
155 // Whether we've failed with a diagnostic already.
156 bool Failed = false;
157
160
161 // If we have an object type, it's because we are in a
162 // pseudo-destructor-expression or a member access expression, and
163 // we know what type we're looking for.
164 QualType SearchType =
165 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
166
167 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
168 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
169 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
170 if (!Type)
171 return false;
172
173 if (SearchType.isNull() || SearchType->isDependentType())
174 return true;
175
176 CanQualType T = Context.getCanonicalTypeDeclType(Type);
177 return Context.hasSameUnqualifiedType(T, SearchType);
178 };
179
180 unsigned NumAcceptableResults = 0;
181 for (NamedDecl *D : Found) {
182 if (IsAcceptableResult(D))
183 ++NumAcceptableResults;
184
185 // Don't list a class twice in the lookup failure diagnostic if it's
186 // found by both its injected-class-name and by the name in the enclosing
187 // scope.
188 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
189 if (RD->isInjectedClassName())
190 D = cast<NamedDecl>(RD->getParent());
191
192 if (FoundDeclSet.insert(D).second)
193 FoundDecls.push_back(D);
194 }
195
196 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
197 // results, and all non-matching results if we have a search type. It's not
198 // clear what the right behavior is if destructor lookup hits an ambiguity,
199 // but other compilers do generally accept at least some kinds of
200 // ambiguity.
201 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
202 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
203 LookupResult::Filter F = Found.makeFilter();
204 while (F.hasNext()) {
205 NamedDecl *D = F.next();
206 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
207 Diag(D->getLocation(), diag::note_destructor_type_here)
208 << Context.getTypeDeclType(ElaboratedTypeKeyword::None,
209 /*Qualifier=*/std::nullopt, TD);
210 else
211 Diag(D->getLocation(), diag::note_destructor_nontype_here);
212
213 if (!IsAcceptableResult(D))
214 F.erase();
215 }
216 F.done();
217 }
218
219 if (Found.isAmbiguous())
220 Failed = true;
221
222 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
223 if (IsAcceptableResult(Type)) {
224 QualType T = Context.getTypeDeclType(ElaboratedTypeKeyword::None,
225 /*Qualifier=*/std::nullopt, Type);
226 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
227 return CreateParsedType(T,
228 Context.getTrivialTypeSourceInfo(T, NameLoc));
229 }
230 }
231
232 return nullptr;
233 };
234
235 bool IsDependent = false;
236
237 auto LookupInObjectType = [&]() -> ParsedType {
238 if (Failed || SearchType.isNull())
239 return nullptr;
240
241 IsDependent |= SearchType->isDependentType();
242
243 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
244 DeclContext *LookupCtx = computeDeclContext(SearchType);
245 if (!LookupCtx)
246 return nullptr;
247 LookupQualifiedName(Found, LookupCtx);
248 return CheckLookupResult(Found);
249 };
250
251 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
252 if (Failed)
253 return nullptr;
254
255 IsDependent |= isDependentScopeSpecifier(LookupSS);
256 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
257 if (!LookupCtx)
258 return nullptr;
259
260 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
261 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
262 Failed = true;
263 return nullptr;
264 }
265 LookupQualifiedName(Found, LookupCtx);
266 return CheckLookupResult(Found);
267 };
268
269 auto LookupInScope = [&]() -> ParsedType {
270 if (Failed || !S)
271 return nullptr;
272
273 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
274 LookupName(Found, S);
275 return CheckLookupResult(Found);
276 };
277
278 // C++2a [basic.lookup.qual]p6:
279 // In a qualified-id of the form
280 //
281 // nested-name-specifier[opt] type-name :: ~ type-name
282 //
283 // the second type-name is looked up in the same scope as the first.
284 //
285 // We interpret this as meaning that if you do a dual-scope lookup for the
286 // first name, you also do a dual-scope lookup for the second name, per
287 // C++ [basic.lookup.classref]p4:
288 //
289 // If the id-expression in a class member access is a qualified-id of the
290 // form
291 //
292 // class-name-or-namespace-name :: ...
293 //
294 // the class-name-or-namespace-name following the . or -> is first looked
295 // up in the class of the object expression and the name, if found, is used.
296 // Otherwise, it is looked up in the context of the entire
297 // postfix-expression.
298 //
299 // This looks in the same scopes as for an unqualified destructor name:
300 //
301 // C++ [basic.lookup.classref]p3:
302 // If the unqualified-id is ~ type-name, the type-name is looked up
303 // in the context of the entire postfix-expression. If the type T
304 // of the object expression is of a class type C, the type-name is
305 // also looked up in the scope of class C. At least one of the
306 // lookups shall find a name that refers to cv T.
307 //
308 // FIXME: The intent is unclear here. Should type-name::~type-name look in
309 // the scope anyway if it finds a non-matching name declared in the class?
310 // If both lookups succeed and find a dependent result, which result should
311 // we retain? (Same question for p->~type-name().)
312
313 auto Prefix = [&]() -> NestedNameSpecifierLoc {
315 if (!NNS)
316 return NestedNameSpecifierLoc();
317 if (auto TL = NNS.getAsTypeLoc())
318 return TL.getPrefix();
319 return NNS.getAsNamespaceAndPrefix().Prefix;
320 }();
321
322 if (Prefix) {
323 // This is
324 //
325 // nested-name-specifier type-name :: ~ type-name
326 //
327 // Look for the second type-name in the nested-name-specifier.
328 CXXScopeSpec PrefixSS;
329 PrefixSS.Adopt(Prefix);
330 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
331 return T;
332 } else {
333 // This is one of
334 //
335 // type-name :: ~ type-name
336 // ~ type-name
337 //
338 // Look in the scope and (if any) the object type.
339 if (ParsedType T = LookupInScope())
340 return T;
341 if (ParsedType T = LookupInObjectType())
342 return T;
343 }
344
345 if (Failed)
346 return nullptr;
347
348 if (IsDependent) {
349 // We didn't find our type, but that's OK: it's dependent anyway.
350
351 // FIXME: What if we have no nested-name-specifier?
352 TypeSourceInfo *TSI = nullptr;
353 QualType T =
355 SS.getWithLocInContext(Context), II, NameLoc, &TSI,
356 /*DeducedTSTContext=*/true);
357 if (T.isNull())
358 return ParsedType();
359 return CreateParsedType(T, TSI);
360 }
361
362 // The remaining cases are all non-standard extensions imitating the behavior
363 // of various other compilers.
364 unsigned NumNonExtensionDecls = FoundDecls.size();
365
366 if (SS.isSet()) {
367 // For compatibility with older broken C++ rules and existing code,
368 //
369 // nested-name-specifier :: ~ type-name
370 //
371 // also looks for type-name within the nested-name-specifier.
372 if (ParsedType T = LookupInNestedNameSpec(SS)) {
373 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
374 << SS.getRange()
376 ("::" + II.getName()).str());
377 return T;
378 }
379
380 // For compatibility with other compilers and older versions of Clang,
381 //
382 // nested-name-specifier type-name :: ~ type-name
383 //
384 // also looks for type-name in the scope. Unfortunately, we can't
385 // reasonably apply this fallback for dependent nested-name-specifiers.
386 if (Prefix) {
387 if (ParsedType T = LookupInScope()) {
388 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
390 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
391 << GetTypeFromParser(T);
392 return T;
393 }
394 }
395 }
396
397 // We didn't find anything matching; tell the user what we did find (if
398 // anything).
399
400 // Don't tell the user about declarations we shouldn't have found.
401 FoundDecls.resize(NumNonExtensionDecls);
402
403 // List types before non-types.
404 llvm::stable_sort(FoundDecls, [](NamedDecl *A, NamedDecl *B) {
405 return isa<TypeDecl>(A->getUnderlyingDecl()) >
407 });
408
409 // Suggest a fixit to properly name the destroyed type.
410 auto MakeFixItHint = [&]{
411 const CXXRecordDecl *Destroyed = nullptr;
412 // FIXME: If we have a scope specifier, suggest its last component?
413 if (!SearchType.isNull())
414 Destroyed = SearchType->getAsCXXRecordDecl();
415 else if (S)
416 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
417 if (Destroyed)
419 Destroyed->getNameAsString());
420 return FixItHint();
421 };
422
423 if (FoundDecls.empty()) {
424 // FIXME: Attempt typo-correction?
425 Diag(NameLoc, diag::err_undeclared_destructor_name)
426 << &II << MakeFixItHint();
427 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
428 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
429 assert(!SearchType.isNull() &&
430 "should only reject a type result if we have a search type");
431 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
432 << Context.getTypeDeclType(ElaboratedTypeKeyword::None,
433 /*Qualifier=*/std::nullopt, TD)
434 << SearchType << MakeFixItHint();
435 } else {
436 Diag(NameLoc, diag::err_destructor_expr_nontype)
437 << &II << MakeFixItHint();
438 }
439 } else {
440 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
441 : diag::err_destructor_expr_mismatch)
442 << &II << SearchType << MakeFixItHint();
443 }
444
445 for (NamedDecl *FoundD : FoundDecls) {
446 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
447 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
448 << Context.getTypeDeclType(ElaboratedTypeKeyword::None,
449 /*Qualifier=*/std::nullopt, TD);
450 else
451 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
452 << FoundD;
453 }
454
455 return nullptr;
456}
457
459 ParsedType ObjectType) {
461 return nullptr;
462
464 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
465 return nullptr;
466 }
467
469 "unexpected type in getDestructorType");
471
472 // If we know the type of the object, check that the correct destructor
473 // type was named now; we can give better diagnostics this way.
474 QualType SearchType = GetTypeFromParser(ObjectType);
475 if (!SearchType.isNull() && !SearchType->isDependentType() &&
476 !Context.hasSameUnqualifiedType(T, SearchType)) {
477 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
478 << T << SearchType;
479 return nullptr;
480 }
481
482 TypeLocBuilder TLB;
483 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
484 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
485 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
486 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
487}
488
490 const UnqualifiedId &Name, bool IsUDSuffix) {
492 if (!IsUDSuffix) {
493 // [over.literal] p8
494 //
495 // double operator""_Bq(long double); // OK: not a reserved identifier
496 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
497 const IdentifierInfo *II = Name.Identifier;
498 ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());
499 SourceLocation Loc = Name.getEndLoc();
500
502 Name.getSourceRange(),
503 (StringRef("operator\"\"") + II->getName()).str());
504
505 // Only emit this diagnostic if we start with an underscore, else the
506 // diagnostic for C++11 requiring a space between the quotes and the
507 // identifier conflicts with this and gets confusing. The diagnostic stating
508 // this is a reserved name should force the underscore, which gets this
509 // back.
510 if (II->isReservedLiteralSuffixId() !=
512 Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint;
513
514 if (isReservedInAllContexts(Status))
515 Diag(Loc, diag::warn_reserved_extern_symbol)
516 << II << static_cast<int>(Status) << Hint;
517 }
518
519 switch (SS.getScopeRep().getKind()) {
521 // Per C++11 [over.literal]p2, literal operators can only be declared at
522 // namespace scope. Therefore, this unqualified-id cannot name anything.
523 // Reject it early, because we have no AST representation for this in the
524 // case where the scope is dependent.
525 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
526 << SS.getScopeRep();
527 return true;
528
533 return false;
534 }
535
536 llvm_unreachable("unknown nested name specifier kind");
537}
538
540 SourceLocation TypeidLoc,
541 TypeSourceInfo *Operand,
542 SourceLocation RParenLoc) {
543 // C++ [expr.typeid]p4:
544 // The top-level cv-qualifiers of the lvalue expression or the type-id
545 // that is the operand of typeid are always ignored.
546 // If the type of the type-id is a class type or a reference to a class
547 // type, the class shall be completely-defined.
548 Qualifiers Quals;
549 QualType T
550 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
551 Quals);
552 if (T->isRecordType() &&
553 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
554 return ExprError();
555
556 if (T->isVariablyModifiedType())
557 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
558
559 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
560 return ExprError();
561
562 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
563 SourceRange(TypeidLoc, RParenLoc));
564}
565
567 SourceLocation TypeidLoc,
568 Expr *E,
569 SourceLocation RParenLoc) {
570 bool WasEvaluated = false;
571 if (E && !E->isTypeDependent()) {
572 if (E->hasPlaceholderType()) {
574 if (result.isInvalid()) return ExprError();
575 E = result.get();
576 }
577
578 QualType T = E->getType();
579 if (auto *RecordD = T->getAsCXXRecordDecl()) {
580 // C++ [expr.typeid]p3:
581 // [...] If the type of the expression is a class type, the class
582 // shall be completely-defined.
583 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
584 return ExprError();
585
586 // C++ [expr.typeid]p3:
587 // When typeid is applied to an expression other than an glvalue of a
588 // polymorphic class type [...] [the] expression is an unevaluated
589 // operand. [...]
590 if (RecordD->isPolymorphic() && E->isGLValue()) {
591 if (isUnevaluatedContext()) {
592 // The operand was processed in unevaluated context, switch the
593 // context and recheck the subexpression.
595 if (Result.isInvalid())
596 return ExprError();
597 E = Result.get();
598 }
599
600 // We require a vtable to query the type at run time.
601 MarkVTableUsed(TypeidLoc, RecordD);
602 WasEvaluated = true;
603 }
604 }
605
607 if (Result.isInvalid())
608 return ExprError();
609 E = Result.get();
610
611 // C++ [expr.typeid]p4:
612 // [...] If the type of the type-id is a reference to a possibly
613 // cv-qualified type, the result of the typeid expression refers to a
614 // std::type_info object representing the cv-unqualified referenced
615 // type.
616 Qualifiers Quals;
617 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
618 if (!Context.hasSameType(T, UnqualT)) {
619 T = UnqualT;
620 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
621 }
622 }
623
625 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
626 << E->getType());
627 else if (!inTemplateInstantiation() &&
628 E->HasSideEffects(Context, WasEvaluated)) {
629 // The expression operand for typeid is in an unevaluated expression
630 // context, so side effects could result in unintended consequences.
631 Diag(E->getExprLoc(), WasEvaluated
632 ? diag::warn_side_effects_typeid
633 : diag::warn_side_effects_unevaluated_context);
634 }
635
636 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
637 SourceRange(TypeidLoc, RParenLoc));
638}
639
640/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
643 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
644 // typeid is not supported in OpenCL.
645 if (getLangOpts().OpenCLCPlusPlus) {
646 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
647 << "typeid");
648 }
649
650 // Find the std::type_info type.
651 if (!getStdNamespace()) {
652 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)
653 << (getLangOpts().CPlusPlus20 ? 1 : 0));
654 }
655
656 if (!CXXTypeInfoDecl) {
657 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
658 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
660 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
661 // Microsoft's typeinfo doesn't have type_info in std but in the global
662 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
663 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
664 LookupQualifiedName(R, Context.getTranslationUnitDecl());
665 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
666 }
667 if (!CXXTypeInfoDecl)
668 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)
669 << (getLangOpts().CPlusPlus20 ? 1 : 0));
670 }
671
672 if (!getLangOpts().RTTI) {
673 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
674 }
675
676 CanQualType TypeInfoType = Context.getCanonicalTagType(CXXTypeInfoDecl);
677
678 if (isType) {
679 // The operand is a type; handle it as such.
680 TypeSourceInfo *TInfo = nullptr;
682 &TInfo);
683 if (T.isNull())
684 return ExprError();
685
686 if (!TInfo)
687 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
688
689 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
690 }
691
692 // The operand is an expression.
694 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
695
696 if (!getLangOpts().RTTIData && !Result.isInvalid())
697 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
698 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
699 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
700 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
702 return Result;
703}
704
705/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
706/// a single GUID.
707static void
710 // Optionally remove one level of pointer, reference or array indirection.
711 const Type *Ty = QT.getTypePtr();
712 if (QT->isPointerOrReferenceType())
713 Ty = QT->getPointeeType().getTypePtr();
714 else if (QT->isArrayType())
715 Ty = Ty->getBaseElementTypeUnsafe();
716
717 const auto *TD = Ty->getAsTagDecl();
718 if (!TD)
719 return;
720
721 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
722 UuidAttrs.insert(Uuid);
723 return;
724 }
725
726 // __uuidof can grab UUIDs from template arguments.
727 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
728 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
729 for (const TemplateArgument &TA : TAL.asArray()) {
730 const UuidAttr *UuidForTA = nullptr;
731 if (TA.getKind() == TemplateArgument::Type)
732 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
733 else if (TA.getKind() == TemplateArgument::Declaration)
734 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
735
736 if (UuidForTA)
737 UuidAttrs.insert(UuidForTA);
738 }
739 }
740}
741
743 SourceLocation TypeidLoc,
744 TypeSourceInfo *Operand,
745 SourceLocation RParenLoc) {
746 MSGuidDecl *Guid = nullptr;
747 if (!Operand->getType()->isDependentType()) {
749 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
750 if (UuidAttrs.empty())
751 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
752 if (UuidAttrs.size() > 1)
753 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
754 Guid = UuidAttrs.back()->getGuidDecl();
755 }
756
757 return new (Context)
758 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
759}
760
762 Expr *E, SourceLocation RParenLoc) {
763 MSGuidDecl *Guid = nullptr;
764 if (!E->getType()->isDependentType()) {
766 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
767 Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
768 } else {
770 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
771 if (UuidAttrs.empty())
772 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
773 if (UuidAttrs.size() > 1)
774 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
775 Guid = UuidAttrs.back()->getGuidDecl();
776 }
777 }
778
779 return new (Context)
780 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
781}
782
783/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
786 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
787 QualType GuidType = Context.getMSGuidType();
788 GuidType.addConst();
789
790 if (isType) {
791 // The operand is a type; handle it as such.
792 TypeSourceInfo *TInfo = nullptr;
794 &TInfo);
795 if (T.isNull())
796 return ExprError();
797
798 if (!TInfo)
799 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
800
801 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
802 }
803
804 // The operand is an expression.
805 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
806}
807
810 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
811 "Unknown C++ Boolean value!");
812 return new (Context)
813 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
814}
815
820
823 bool IsThrownVarInScope = false;
824 if (Ex) {
825 // C++0x [class.copymove]p31:
826 // When certain criteria are met, an implementation is allowed to omit the
827 // copy/move construction of a class object [...]
828 //
829 // - in a throw-expression, when the operand is the name of a
830 // non-volatile automatic object (other than a function or catch-
831 // clause parameter) whose scope does not extend beyond the end of the
832 // innermost enclosing try-block (if there is one), the copy/move
833 // operation from the operand to the exception object (15.1) can be
834 // omitted by constructing the automatic object directly into the
835 // exception object
836 if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
837 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl());
838 Var && Var->hasLocalStorage() &&
839 !Var->getType().isVolatileQualified()) {
840 for (; S; S = S->getParent()) {
841 if (S->isDeclScope(Var)) {
842 IsThrownVarInScope = true;
843 break;
844 }
845
846 // FIXME: Many of the scope checks here seem incorrect.
847 if (S->getFlags() &
850 break;
851 }
852 }
853 }
854
855 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
856}
857
859 bool IsThrownVarInScope) {
860 const llvm::Triple &T = Context.getTargetInfo().getTriple();
861 const bool IsOpenMPGPUTarget =
862 getLangOpts().OpenMPIsTargetDevice && T.isGPU();
863
864 DiagnoseExceptionUse(OpLoc, /* IsTry= */ false);
865
866 // In OpenMP target regions, we replace 'throw' with a trap on GPU targets.
867 if (IsOpenMPGPUTarget)
868 targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str();
869
870 // Exceptions aren't allowed in CUDA device code.
871 if (getLangOpts().CUDA)
872 CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
873 << "throw" << CUDA().CurrentTarget();
874
875 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
876 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
877
878 // Exceptions that escape a compute construct are ill-formed.
879 if (getLangOpts().OpenACC && getCurScope() &&
880 getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope))
881 Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct)
882 << /*throw*/ 2 << /*out of*/ 0;
883
884 if (Ex && !Ex->isTypeDependent()) {
885 // Initialize the exception result. This implicitly weeds out
886 // abstract types or types with inaccessible copy constructors.
887
888 // C++0x [class.copymove]p31:
889 // When certain criteria are met, an implementation is allowed to omit the
890 // copy/move construction of a class object [...]
891 //
892 // - in a throw-expression, when the operand is the name of a
893 // non-volatile automatic object (other than a function or
894 // catch-clause
895 // parameter) whose scope does not extend beyond the end of the
896 // innermost enclosing try-block (if there is one), the copy/move
897 // operation from the operand to the exception object (15.1) can be
898 // omitted by constructing the automatic object directly into the
899 // exception object
900 NamedReturnInfo NRInfo =
901 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
902
903 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
904 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
905 return ExprError();
906
907 InitializedEntity Entity =
908 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
909 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
910 if (Res.isInvalid())
911 return ExprError();
912 Ex = Res.get();
913 }
914
915 // PPC MMA non-pointer types are not allowed as throw expr types.
916 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
917 PPC().CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
918
919 return new (Context)
920 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
921}
922
923static void
925 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
926 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
927 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
928 bool ParentIsPublic) {
929 for (const CXXBaseSpecifier &BS : RD->bases()) {
930 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
931 bool NewSubobject;
932 // Virtual bases constitute the same subobject. Non-virtual bases are
933 // always distinct subobjects.
934 if (BS.isVirtual())
935 NewSubobject = VBases.insert(BaseDecl).second;
936 else
937 NewSubobject = true;
938
939 if (NewSubobject)
940 ++SubobjectsSeen[BaseDecl];
941
942 // Only add subobjects which have public access throughout the entire chain.
943 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
944 if (PublicPath)
945 PublicSubobjectsSeen.insert(BaseDecl);
946
947 // Recurse on to each base subobject.
948 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
949 PublicPath);
950 }
951}
952
955 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
957 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
958 SubobjectsSeen[RD] = 1;
959 PublicSubobjectsSeen.insert(RD);
960 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
961 /*ParentIsPublic=*/true);
962
963 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
964 // Skip ambiguous objects.
965 if (SubobjectsSeen[PublicSubobject] > 1)
966 continue;
967
968 Objects.push_back(PublicSubobject);
969 }
970}
971
973 QualType ExceptionObjectTy, Expr *E) {
974 // If the type of the exception would be an incomplete type or a pointer
975 // to an incomplete type other than (cv) void the program is ill-formed.
976 QualType Ty = ExceptionObjectTy;
977 bool isPointer = false;
978 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
979 Ty = Ptr->getPointeeType();
980 isPointer = true;
981 }
982
983 // Cannot throw WebAssembly reference type.
985 Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange();
986 return true;
987 }
988
989 // Cannot throw WebAssembly table.
990 if (isPointer && Ty.isWebAssemblyReferenceType()) {
991 Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange();
992 return true;
993 }
994
995 if (!isPointer || !Ty->isVoidType()) {
996 if (RequireCompleteType(ThrowLoc, Ty,
997 isPointer ? diag::err_throw_incomplete_ptr
998 : diag::err_throw_incomplete,
999 E->getSourceRange()))
1000 return true;
1001
1002 if (!isPointer && Ty->isSizelessType()) {
1003 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
1004 return true;
1005 }
1006
1007 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
1008 diag::err_throw_abstract_type, E))
1009 return true;
1010 }
1011
1012 // If the exception has class type, we need additional handling.
1014 if (!RD)
1015 return false;
1016
1017 // If we are throwing a polymorphic class type or pointer thereof,
1018 // exception handling will make use of the vtable.
1019 MarkVTableUsed(ThrowLoc, RD);
1020
1021 // If a pointer is thrown, the referenced object will not be destroyed.
1022 if (isPointer)
1023 return false;
1024
1025 // If the class has a destructor, we must be able to call it.
1026 if (!RD->hasIrrelevantDestructor()) {
1030 PDiag(diag::err_access_dtor_exception) << Ty);
1032 return true;
1033 }
1034 }
1035
1036 // The MSVC ABI creates a list of all types which can catch the exception
1037 // object. This list also references the appropriate copy constructor to call
1038 // if the object is caught by value and has a non-trivial copy constructor.
1039 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1040 // We are only interested in the public, unambiguous bases contained within
1041 // the exception object. Bases which are ambiguous or otherwise
1042 // inaccessible are not catchable types.
1043 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1044 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1045
1046 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1047 // Attempt to lookup the copy constructor. Various pieces of machinery
1048 // will spring into action, like template instantiation, which means this
1049 // cannot be a simple walk of the class's decls. Instead, we must perform
1050 // lookup and overload resolution.
1051 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1052 if (!CD || CD->isDeleted())
1053 continue;
1054
1055 // Mark the constructor referenced as it is used by this throw expression.
1057
1058 // Skip this copy constructor if it is trivial, we don't need to record it
1059 // in the catchable type data.
1060 if (CD->isTrivial())
1061 continue;
1062
1063 // The copy constructor is non-trivial, create a mapping from this class
1064 // type to this constructor.
1065 // N.B. The selection of copy constructor is not sensitive to this
1066 // particular throw-site. Lookup will be performed at the catch-site to
1067 // ensure that the copy constructor is, in fact, accessible (via
1068 // friendship or any other means).
1069 Context.addCopyConstructorForExceptionObject(Subobject, CD);
1070
1071 // We don't keep the instantiated default argument expressions around so
1072 // we must rebuild them here.
1073 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1074 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1075 return true;
1076 }
1077 }
1078 }
1079
1080 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1081 // the runtime with no ability for the compiler to request additional
1082 // alignment. Warn if the exception type requires alignment beyond the minimum
1083 // guaranteed by the target C++ runtime.
1084 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1085 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1086 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1087 if (ExnObjAlign < TypeAlign) {
1088 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1089 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1090 << Ty << (unsigned)TypeAlign.getQuantity()
1091 << (unsigned)ExnObjAlign.getQuantity();
1092 }
1093 }
1094 if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) {
1095 if (CXXDestructorDecl *Dtor = RD->getDestructor()) {
1096 auto Ty = Dtor->getType();
1097 if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) {
1098 if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) &&
1099 !FT->isNothrow())
1100 Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD;
1101 }
1102 }
1103 }
1104
1105 return false;
1106}
1107
1109 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1110 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1111
1112 QualType ClassType = ThisTy->getPointeeType();
1113 LambdaScopeInfo *CurLSI = nullptr;
1114 DeclContext *CurDC = CurSemaContext;
1115
1116 // Iterate through the stack of lambdas starting from the innermost lambda to
1117 // the outermost lambda, checking if '*this' is ever captured by copy - since
1118 // that could change the cv-qualifiers of the '*this' object.
1119 // The object referred to by '*this' starts out with the cv-qualifiers of its
1120 // member function. We then start with the innermost lambda and iterate
1121 // outward checking to see if any lambda performs a by-copy capture of '*this'
1122 // - and if so, any nested lambda must respect the 'constness' of that
1123 // capturing lamdbda's call operator.
1124 //
1125
1126 // Since the FunctionScopeInfo stack is representative of the lexical
1127 // nesting of the lambda expressions during initial parsing (and is the best
1128 // place for querying information about captures about lambdas that are
1129 // partially processed) and perhaps during instantiation of function templates
1130 // that contain lambda expressions that need to be transformed BUT not
1131 // necessarily during instantiation of a nested generic lambda's function call
1132 // operator (which might even be instantiated at the end of the TU) - at which
1133 // time the DeclContext tree is mature enough to query capture information
1134 // reliably - we use a two pronged approach to walk through all the lexically
1135 // enclosing lambda expressions:
1136 //
1137 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1138 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1139 // enclosed by the call-operator of the LSI below it on the stack (while
1140 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1141 // the stack represents the innermost lambda.
1142 //
1143 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1144 // represents a lambda's call operator. If it does, we must be instantiating
1145 // a generic lambda's call operator (represented by the Current LSI, and
1146 // should be the only scenario where an inconsistency between the LSI and the
1147 // DeclContext should occur), so climb out the DeclContexts if they
1148 // represent lambdas, while querying the corresponding closure types
1149 // regarding capture information.
1150
1151 // 1) Climb down the function scope info stack.
1152 for (int I = FunctionScopes.size();
1153 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1154 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1155 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1156 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1157 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1158
1159 if (!CurLSI->isCXXThisCaptured())
1160 continue;
1161
1162 auto C = CurLSI->getCXXThisCapture();
1163
1164 if (C.isCopyCapture()) {
1165 if (CurLSI->lambdaCaptureShouldBeConst())
1166 ClassType.addConst();
1167 return ASTCtx.getPointerType(ClassType);
1168 }
1169 }
1170
1171 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1172 // can happen during instantiation of its nested generic lambda call
1173 // operator); 2. if we're in a lambda scope (lambda body).
1174 if (CurLSI && isLambdaCallOperator(CurDC)) {
1176 "While computing 'this' capture-type for a generic lambda, when we "
1177 "run out of enclosing LSI's, yet the enclosing DC is a "
1178 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1179 "lambda call oeprator");
1180 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1181
1182 auto IsThisCaptured =
1183 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1184 IsConst = false;
1185 IsByCopy = false;
1186 for (auto &&C : Closure->captures()) {
1187 if (C.capturesThis()) {
1188 if (C.getCaptureKind() == LCK_StarThis)
1189 IsByCopy = true;
1190 if (Closure->getLambdaCallOperator()->isConst())
1191 IsConst = true;
1192 return true;
1193 }
1194 }
1195 return false;
1196 };
1197
1198 bool IsByCopyCapture = false;
1199 bool IsConstCapture = false;
1200 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1201 while (Closure &&
1202 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1203 if (IsByCopyCapture) {
1204 if (IsConstCapture)
1205 ClassType.addConst();
1206 return ASTCtx.getPointerType(ClassType);
1207 }
1208 Closure = isLambdaCallOperator(Closure->getParent())
1209 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1210 : nullptr;
1211 }
1212 }
1213 return ThisTy;
1214}
1215
1219
1220 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1221 if (method && method->isImplicitObjectMemberFunction())
1222 ThisTy = method->getThisType().getNonReferenceType();
1223 }
1224
1227
1228 // This is a lambda call operator that is being instantiated as a default
1229 // initializer. DC must point to the enclosing class type, so we can recover
1230 // the 'this' type from it.
1231 CanQualType ClassTy = Context.getCanonicalTagType(cast<CXXRecordDecl>(DC));
1232 // There are no cv-qualifiers for 'this' within default initializers,
1233 // per [expr.prim.general]p4.
1234 ThisTy = Context.getPointerType(ClassTy);
1235 }
1236
1237 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1238 // might need to be adjusted if the lambda or any of its enclosing lambda's
1239 // captures '*this' by copy.
1240 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1243 return ThisTy;
1244}
1245
1247 Decl *ContextDecl,
1248 Qualifiers CXXThisTypeQuals,
1249 bool Enabled)
1250 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1251{
1252 if (!Enabled || !ContextDecl)
1253 return;
1254
1255 CXXRecordDecl *Record = nullptr;
1256 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1257 Record = Template->getTemplatedDecl();
1258 else
1259 Record = cast<CXXRecordDecl>(ContextDecl);
1260
1261 // 'this' never refers to the lambda class itself.
1262 if (Record->isLambda())
1263 return;
1264
1265 QualType T = S.Context.getCanonicalTagType(Record);
1266 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1267
1268 S.CXXThisTypeOverride =
1269 S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T);
1270
1271 this->Enabled = true;
1272}
1273
1274
1276 if (Enabled) {
1277 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1278 }
1279}
1280
1282 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1283 assert(!LSI->isCXXThisCaptured());
1284 // [=, this] {}; // until C++20: Error: this when = is the default
1286 !Sema.getLangOpts().CPlusPlus20)
1287 return;
1288 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1290 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1291}
1292
1294 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1295 const bool ByCopy) {
1296 // We don't need to capture this in an unevaluated context.
1298 return true;
1299
1300 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1301
1302 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1303 ? *FunctionScopeIndexToStopAt
1304 : FunctionScopes.size() - 1;
1305
1306 // Check that we can capture the *enclosing object* (referred to by '*this')
1307 // by the capturing-entity/closure (lambda/block/etc) at
1308 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1309
1310 // Note: The *enclosing object* can only be captured by-value by a
1311 // closure that is a lambda, using the explicit notation:
1312 // [*this] { ... }.
1313 // Every other capture of the *enclosing object* results in its by-reference
1314 // capture.
1315
1316 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1317 // stack), we can capture the *enclosing object* only if:
1318 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1319 // - or, 'L' has an implicit capture.
1320 // AND
1321 // -- there is no enclosing closure
1322 // -- or, there is some enclosing closure 'E' that has already captured the
1323 // *enclosing object*, and every intervening closure (if any) between 'E'
1324 // and 'L' can implicitly capture the *enclosing object*.
1325 // -- or, every enclosing closure can implicitly capture the
1326 // *enclosing object*
1327
1328
1329 unsigned NumCapturingClosures = 0;
1330 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1331 if (CapturingScopeInfo *CSI =
1332 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1333 if (CSI->CXXThisCaptureIndex != 0) {
1334 // 'this' is already being captured; there isn't anything more to do.
1335 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1336 break;
1337 }
1338 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1340 // This context can't implicitly capture 'this'; fail out.
1341 if (BuildAndDiagnose) {
1343 Diag(Loc, diag::err_this_capture)
1344 << (Explicit && idx == MaxFunctionScopesIndex);
1345 if (!Explicit)
1346 buildLambdaThisCaptureFixit(*this, LSI);
1347 }
1348 return true;
1349 }
1350 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1351 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1352 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1353 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1354 (Explicit && idx == MaxFunctionScopesIndex)) {
1355 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1356 // iteration through can be an explicit capture, all enclosing closures,
1357 // if any, must perform implicit captures.
1358
1359 // This closure can capture 'this'; continue looking upwards.
1360 NumCapturingClosures++;
1361 continue;
1362 }
1363 // This context can't implicitly capture 'this'; fail out.
1364 if (BuildAndDiagnose) {
1366 Diag(Loc, diag::err_this_capture)
1367 << (Explicit && idx == MaxFunctionScopesIndex);
1368 }
1369 if (!Explicit)
1370 buildLambdaThisCaptureFixit(*this, LSI);
1371 return true;
1372 }
1373 break;
1374 }
1375 if (!BuildAndDiagnose) return false;
1376
1377 // If we got here, then the closure at MaxFunctionScopesIndex on the
1378 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1379 // (including implicit by-reference captures in any enclosing closures).
1380
1381 // In the loop below, respect the ByCopy flag only for the closure requesting
1382 // the capture (i.e. first iteration through the loop below). Ignore it for
1383 // all enclosing closure's up to NumCapturingClosures (since they must be
1384 // implicitly capturing the *enclosing object* by reference (see loop
1385 // above)).
1386 assert((!ByCopy ||
1387 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1388 "Only a lambda can capture the enclosing object (referred to by "
1389 "*this) by copy");
1390 QualType ThisTy = getCurrentThisType();
1391 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1392 --idx, --NumCapturingClosures) {
1394
1395 // The type of the corresponding data member (not a 'this' pointer if 'by
1396 // copy').
1397 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1398
1399 bool isNested = NumCapturingClosures > 1;
1400 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1401 }
1402 return false;
1403}
1404
1406 // C++20 [expr.prim.this]p1:
1407 // The keyword this names a pointer to the object for which an
1408 // implicit object member function is invoked or a non-static
1409 // data member's initializer is evaluated.
1410 QualType ThisTy = getCurrentThisType();
1411
1412 if (CheckCXXThisType(Loc, ThisTy))
1413 return ExprError();
1414
1415 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1416}
1417
1419 if (!Type.isNull())
1420 return false;
1421
1422 // C++20 [expr.prim.this]p3:
1423 // If a declaration declares a member function or member function template
1424 // of a class X, the expression this is a prvalue of type
1425 // "pointer to cv-qualifier-seq X" wherever X is the current class between
1426 // the optional cv-qualifier-seq and the end of the function-definition,
1427 // member-declarator, or declarator. It shall not appear within the
1428 // declaration of either a static member function or an explicit object
1429 // member function of the current class (although its type and value
1430 // category are defined within such member functions as they are within
1431 // an implicit object member function).
1433 const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1434 if (Method && Method->isExplicitObjectMemberFunction()) {
1435 Diag(Loc, diag::err_invalid_this_use) << 1;
1437 Diag(Loc, diag::err_invalid_this_use) << 1;
1438 } else {
1439 Diag(Loc, diag::err_invalid_this_use) << 0;
1440 }
1441 return true;
1442}
1443
1445 bool IsImplicit) {
1446 auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit);
1448 return This;
1449}
1450
1452 CheckCXXThisCapture(This->getExprLoc());
1453 if (This->isTypeDependent())
1454 return;
1455
1456 // Check if 'this' is captured by value in a lambda with a dependent explicit
1457 // object parameter, and mark it as type-dependent as well if so.
1458 auto IsDependent = [&]() {
1459 for (auto *Scope : llvm::reverse(FunctionScopes)) {
1460 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
1461 if (!LSI)
1462 continue;
1463
1464 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
1465 LSI->AfterParameterList)
1466 return false;
1467
1468 // If this lambda captures 'this' by value, then 'this' is dependent iff
1469 // this lambda has a dependent explicit object parameter. If we can't
1470 // determine whether it does (e.g. because the CXXMethodDecl's type is
1471 // null), assume it doesn't.
1472 if (LSI->isCXXThisCaptured()) {
1473 if (!LSI->getCXXThisCapture().isCopyCapture())
1474 continue;
1475
1476 const auto *MD = LSI->CallOperator;
1477 if (MD->getType().isNull())
1478 return false;
1479
1480 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
1481 return Ty && MD->isExplicitObjectMemberFunction() &&
1482 Ty->getParamType(0)->isDependentType();
1483 }
1484 }
1485 return false;
1486 }();
1487
1488 This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent);
1489}
1490
1492 // Determine whether we're looking into a class that's currently being
1493 // defined.
1494 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1495 return Class && Class->isBeingDefined();
1496}
1497
1500 SourceLocation LParenOrBraceLoc,
1501 MultiExprArg exprs,
1502 SourceLocation RParenOrBraceLoc,
1503 bool ListInitialization) {
1504 if (!TypeRep)
1505 return ExprError();
1506
1507 TypeSourceInfo *TInfo;
1508 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1509 if (!TInfo)
1510 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1511
1512 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1513 RParenOrBraceLoc, ListInitialization);
1514 if (Result.isInvalid())
1516 RParenOrBraceLoc, exprs, Ty);
1517 return Result;
1518}
1519
1522 SourceLocation LParenOrBraceLoc,
1523 MultiExprArg Exprs,
1524 SourceLocation RParenOrBraceLoc,
1525 bool ListInitialization) {
1526 QualType Ty = TInfo->getType();
1527 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1528 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1529
1530 InitializedEntity Entity =
1532 InitializationKind Kind =
1533 Exprs.size()
1534 ? ListInitialization
1536 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1537 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1538 RParenOrBraceLoc)
1539 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1540 RParenOrBraceLoc);
1541
1542 // C++17 [expr.type.conv]p1:
1543 // If the type is a placeholder for a deduced class type, [...perform class
1544 // template argument deduction...]
1545 // C++23:
1546 // Otherwise, if the type contains a placeholder type, it is replaced by the
1547 // type determined by placeholder type deduction.
1548 DeducedType *Deduced = Ty->getContainedDeducedType();
1549 if (Deduced && !Deduced->isDeduced() &&
1552 Kind, Exprs);
1553 if (Ty.isNull())
1554 return ExprError();
1555 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1556 } else if (Deduced && !Deduced->isDeduced()) {
1557 MultiExprArg Inits = Exprs;
1558 if (ListInitialization) {
1559 auto *ILE = cast<InitListExpr>(Exprs[0]);
1560 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1561 }
1562
1563 if (Inits.empty())
1564 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1565 << Ty << FullRange);
1566 if (Inits.size() > 1) {
1567 Expr *FirstBad = Inits[1];
1568 return ExprError(Diag(FirstBad->getBeginLoc(),
1569 diag::err_auto_expr_init_multiple_expressions)
1570 << Ty << FullRange);
1571 }
1572 if (getLangOpts().CPlusPlus23) {
1573 if (Ty->getAs<AutoType>())
1574 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1575 }
1576 Expr *Deduce = Inits[0];
1577 if (isa<InitListExpr>(Deduce))
1578 return ExprError(
1579 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1580 << ListInitialization << Ty << FullRange);
1581 QualType DeducedType;
1582 TemplateDeductionInfo Info(Deduce->getExprLoc());
1584 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1587 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1588 << Ty << Deduce->getType() << FullRange
1589 << Deduce->getSourceRange());
1590 if (DeducedType.isNull()) {
1592 return ExprError();
1593 }
1594
1595 Ty = DeducedType;
1596 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1597 }
1598
1601 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1602 RParenOrBraceLoc, ListInitialization);
1603
1604 // C++ [expr.type.conv]p1:
1605 // If the expression list is a parenthesized single expression, the type
1606 // conversion expression is equivalent (in definedness, and if defined in
1607 // meaning) to the corresponding cast expression.
1608 if (Exprs.size() == 1 && !ListInitialization &&
1609 !isa<InitListExpr>(Exprs[0])) {
1610 Expr *Arg = Exprs[0];
1611 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1612 RParenOrBraceLoc);
1613 }
1614
1615 // For an expression of the form T(), T shall not be an array type.
1616 QualType ElemTy = Ty;
1617 if (Ty->isArrayType()) {
1618 if (!ListInitialization)
1619 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1620 << FullRange);
1621 ElemTy = Context.getBaseElementType(Ty);
1622 }
1623
1624 // Only construct objects with object types.
1625 // The standard doesn't explicitly forbid function types here, but that's an
1626 // obvious oversight, as there's no way to dynamically construct a function
1627 // in general.
1628 if (Ty->isFunctionType())
1629 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1630 << Ty << FullRange);
1631
1632 // C++17 [expr.type.conv]p2, per DR2351:
1633 // If the type is cv void and the initializer is () or {}, the expression is
1634 // a prvalue of the specified type that performs no initialization.
1635 if (Ty->isVoidType()) {
1636 if (Exprs.empty())
1637 return new (Context) CXXScalarValueInitExpr(
1638 Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd());
1639 if (ListInitialization &&
1640 cast<InitListExpr>(Exprs[0])->getNumInits() == 0) {
1642 Context, Ty.getUnqualifiedType(), VK_PRValue, TInfo, CK_ToVoid,
1643 Exprs[0], /*Path=*/nullptr, CurFPFeatureOverrides(),
1644 Exprs[0]->getBeginLoc(), Exprs[0]->getEndLoc());
1645 }
1646 } else if (RequireCompleteType(TyBeginLoc, ElemTy,
1647 diag::err_invalid_incomplete_type_use,
1648 FullRange))
1649 return ExprError();
1650
1651 // Otherwise, the expression is a prvalue of the specified type whose
1652 // result object is direct-initialized (11.6) with the initializer.
1653 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1654 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1655
1656 if (Result.isInvalid())
1657 return Result;
1658
1659 Expr *Inner = Result.get();
1660 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1661 Inner = BTE->getSubExpr();
1662 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1663 CE && CE->isImmediateInvocation())
1664 Inner = CE->getSubExpr();
1665 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1667 // If we created a CXXTemporaryObjectExpr, that node also represents the
1668 // functional cast. Otherwise, create an explicit cast to represent
1669 // the syntactic form of a functional-style cast that was used here.
1670 //
1671 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1672 // would give a more consistent AST representation than using a
1673 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1674 // is sometimes handled by initialization and sometimes not.
1675 QualType ResultType = Result.get()->getType();
1676 // In HLSL, vector/matrix constructors have their arguments wrapped into an
1677 // InitListExpr during initialization sequencing. Mark the resulting
1678 // CXXFunctionalCastExpr as list-initialization so that during template
1679 // re-instantiation, TreeTransform correctly passes the InitListExpr back
1680 // through BuildCXXTypeConstructExpr with ListInitialization=true as opposed
1681 // to false.
1682 bool IsListInit = ListInitialization ||
1683 (getLangOpts().HLSL && isa<InitListExpr>(Result.get()));
1684 SourceRange Locs = IsListInit
1685 ? SourceRange()
1686 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1688 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1689 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1690 Locs.getBegin(), Locs.getEnd());
1691 }
1692
1693 return Result;
1694}
1695
1697 // [CUDA] Ignore this function, if we can't call it.
1698 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1699 if (getLangOpts().CUDA) {
1700 auto CallPreference = CUDA().IdentifyPreference(Caller, Method);
1701 // If it's not callable at all, it's not the right function.
1702 if (CallPreference < SemaCUDA::CFP_WrongSide)
1703 return false;
1704 if (CallPreference == SemaCUDA::CFP_WrongSide) {
1705 // Maybe. We have to check if there are better alternatives.
1707 Method->getDeclContext()->lookup(Method->getDeclName());
1708 for (const auto *D : R) {
1709 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1710 if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide)
1711 return false;
1712 }
1713 }
1714 // We've found no better variants.
1715 }
1716 }
1717
1719 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1720
1721 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1722 return Result;
1723
1724 // In case of CUDA, return true if none of the 1-argument deallocator
1725 // functions are actually callable.
1726 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1727 assert(FD->getNumParams() == 1 &&
1728 "Only single-operand functions should be in PreventedBy");
1729 return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice;
1730 });
1731}
1732
1733/// Determine whether the given function is a non-placement
1734/// deallocation function.
1736 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1737 return S.isUsualDeallocationFunction(Method);
1738
1739 if (!FD->getDeclName().isAnyOperatorDelete())
1740 return false;
1741
1744 FD->getNumParams();
1745
1746 unsigned UsualParams = 1;
1747 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1749 FD->getParamDecl(UsualParams)->getType(),
1750 S.Context.getSizeType()))
1751 ++UsualParams;
1752
1753 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1755 FD->getParamDecl(UsualParams)->getType(),
1757 ++UsualParams;
1758
1759 return UsualParams == FD->getNumParams();
1760}
1761
1762namespace {
1763 struct UsualDeallocFnInfo {
1764 UsualDeallocFnInfo()
1765 : Found(), FD(nullptr),
1767 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found, QualType AllocType,
1768 SourceLocation Loc)
1769 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1770 Destroying(false),
1771 IDP({AllocType, TypeAwareAllocationMode::No,
1772 AlignedAllocationMode::No, SizedDeallocationMode::No}),
1773 CUDAPref(SemaCUDA::CFP_Native) {
1774 // A function template declaration is only a usual deallocation function
1775 // if it is a typed delete.
1776 if (!FD) {
1777 if (AllocType.isNull())
1778 return;
1779 auto *FTD = dyn_cast<FunctionTemplateDecl>(Found->getUnderlyingDecl());
1780 if (!FTD)
1781 return;
1782 FunctionDecl *InstantiatedDecl =
1783 S.BuildTypeAwareUsualDelete(FTD, AllocType, Loc);
1784 if (!InstantiatedDecl)
1785 return;
1786 FD = InstantiatedDecl;
1787 }
1788 unsigned NumBaseParams = 1;
1789 if (FD->isTypeAwareOperatorNewOrDelete()) {
1790 // If this is a type aware operator delete we instantiate an appropriate
1791 // specialization of std::type_identity<>. If we do not know the
1792 // type being deallocated, or if the type-identity parameter of the
1793 // deallocation function does not match the constructed type_identity
1794 // specialization we reject the declaration.
1795 if (AllocType.isNull()) {
1796 FD = nullptr;
1797 return;
1798 }
1799 QualType TypeIdentityTag = FD->getParamDecl(0)->getType();
1800 QualType ExpectedTypeIdentityTag =
1801 S.tryBuildStdTypeIdentity(AllocType, Loc);
1802 if (ExpectedTypeIdentityTag.isNull()) {
1803 FD = nullptr;
1804 return;
1805 }
1806 if (!S.Context.hasSameType(TypeIdentityTag, ExpectedTypeIdentityTag)) {
1807 FD = nullptr;
1808 return;
1809 }
1810 IDP.PassTypeIdentity = TypeAwareAllocationMode::Yes;
1811 ++NumBaseParams;
1812 }
1813
1814 if (FD->isDestroyingOperatorDelete()) {
1815 Destroying = true;
1816 ++NumBaseParams;
1817 }
1818
1819 if (NumBaseParams < FD->getNumParams() &&
1820 S.Context.hasSameUnqualifiedType(
1821 FD->getParamDecl(NumBaseParams)->getType(),
1822 S.Context.getSizeType())) {
1823 ++NumBaseParams;
1824 IDP.PassSize = SizedDeallocationMode::Yes;
1825 }
1826
1827 if (NumBaseParams < FD->getNumParams() &&
1828 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1829 ++NumBaseParams;
1830 IDP.PassAlignment = AlignedAllocationMode::Yes;
1831 }
1832
1833 // In CUDA, determine how much we'd like / dislike to call this.
1834 if (S.getLangOpts().CUDA)
1835 CUDAPref = S.CUDA().IdentifyPreference(
1836 S.getCurFunctionDecl(/*AllowLambda=*/true), FD);
1837 }
1838
1839 explicit operator bool() const { return FD; }
1840
1841 int Compare(Sema &S, const UsualDeallocFnInfo &Other,
1842 ImplicitDeallocationParameters TargetIDP) const {
1843 assert(!TargetIDP.Type.isNull() ||
1844 !isTypeAwareAllocation(Other.IDP.PassTypeIdentity));
1845
1846 // C++ P0722:
1847 // A destroying operator delete is preferred over a non-destroying
1848 // operator delete.
1849 if (Destroying != Other.Destroying)
1850 return Destroying ? 1 : -1;
1851
1852 const ImplicitDeallocationParameters &OtherIDP = Other.IDP;
1853 // Selection for type awareness has priority over alignment and size
1854 if (IDP.PassTypeIdentity != OtherIDP.PassTypeIdentity)
1855 return IDP.PassTypeIdentity == TargetIDP.PassTypeIdentity ? 1 : -1;
1856
1857 // C++17 [expr.delete]p10:
1858 // If the type has new-extended alignment, a function with a parameter
1859 // of type std::align_val_t is preferred; otherwise a function without
1860 // such a parameter is preferred
1861 if (IDP.PassAlignment != OtherIDP.PassAlignment)
1862 return IDP.PassAlignment == TargetIDP.PassAlignment ? 1 : -1;
1863
1864 if (IDP.PassSize != OtherIDP.PassSize)
1865 return IDP.PassSize == TargetIDP.PassSize ? 1 : -1;
1866
1867 if (isTypeAwareAllocation(IDP.PassTypeIdentity)) {
1868 // Type aware allocation involves templates so we need to choose
1869 // the best type
1870 FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
1871 FunctionTemplateDecl *OtherPrimaryTemplate =
1872 Other.FD->getPrimaryTemplate();
1873 if ((!PrimaryTemplate) != (!OtherPrimaryTemplate))
1874 return OtherPrimaryTemplate ? 1 : -1;
1875
1876 if (PrimaryTemplate && OtherPrimaryTemplate) {
1877 const auto *DC = dyn_cast<CXXRecordDecl>(Found->getDeclContext());
1878 const auto *OtherDC =
1879 dyn_cast<CXXRecordDecl>(Other.Found->getDeclContext());
1880 unsigned ImplicitArgCount = Destroying + IDP.getNumImplicitArgs();
1881 if (FunctionTemplateDecl *Best = S.getMoreSpecializedTemplate(
1882 PrimaryTemplate, OtherPrimaryTemplate, SourceLocation(),
1883 TPOC_Call, ImplicitArgCount,
1884 DC ? S.Context.getCanonicalTagType(DC) : QualType{},
1885 OtherDC ? S.Context.getCanonicalTagType(OtherDC) : QualType{},
1886 false)) {
1887 return Best == PrimaryTemplate ? 1 : -1;
1888 }
1889 }
1890 }
1891
1892 // Use CUDA call preference as a tiebreaker.
1893 if (CUDAPref > Other.CUDAPref)
1894 return 1;
1895 if (CUDAPref == Other.CUDAPref)
1896 return 0;
1897 return -1;
1898 }
1899
1900 DeclAccessPair Found;
1901 FunctionDecl *FD;
1902 bool Destroying;
1903 ImplicitDeallocationParameters IDP;
1905 };
1906}
1907
1908/// Determine whether a type has new-extended alignment. This may be called when
1909/// the type is incomplete (for a delete-expression with an incomplete pointee
1910/// type), in which case it will conservatively return false if the alignment is
1911/// not known.
1912static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1913 return S.getLangOpts().AlignedAllocation &&
1914 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1916}
1917
1918static bool CheckDeleteOperator(Sema &S, SourceLocation StartLoc,
1919 SourceRange Range, bool Diagnose,
1920 CXXRecordDecl *NamingClass, DeclAccessPair Decl,
1921 FunctionDecl *Operator) {
1922 if (Operator->isTypeAwareOperatorNewOrDelete()) {
1923 QualType SelectedTypeIdentityParameter =
1924 Operator->getParamDecl(0)->getType();
1925 if (S.RequireCompleteType(StartLoc, SelectedTypeIdentityParameter,
1926 diag::err_incomplete_type))
1927 return true;
1928 }
1929
1930 // FIXME: DiagnoseUseOfDecl?
1931 if (Operator->isDeleted()) {
1932 if (Diagnose) {
1933 StringLiteral *Msg = Operator->getDeletedMessage();
1934 S.Diag(StartLoc, diag::err_deleted_function_use)
1935 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
1936 S.NoteDeletedFunction(Operator);
1937 }
1938 return true;
1939 }
1940 Sema::AccessResult Accessible =
1941 S.CheckAllocationAccess(StartLoc, Range, NamingClass, Decl, Diagnose);
1942 return Accessible == Sema::AR_inaccessible;
1943}
1944
1945/// Select the correct "usual" deallocation function to use from a selection of
1946/// deallocation functions (either global or class-scope).
1947static UsualDeallocFnInfo resolveDeallocationOverload(
1949 SourceLocation Loc,
1950 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1951
1952 UsualDeallocFnInfo Best;
1953 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1954 UsualDeallocFnInfo Info(S, I.getPair(), IDP.Type, Loc);
1955 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1956 Info.CUDAPref == SemaCUDA::CFP_Never)
1957 continue;
1958
1961 continue;
1962 if (!Best) {
1963 Best = Info;
1964 if (BestFns)
1965 BestFns->push_back(Info);
1966 continue;
1967 }
1968 int ComparisonResult = Best.Compare(S, Info, IDP);
1969 if (ComparisonResult > 0)
1970 continue;
1971
1972 // If more than one preferred function is found, all non-preferred
1973 // functions are eliminated from further consideration.
1974 if (BestFns && ComparisonResult < 0)
1975 BestFns->clear();
1976
1977 Best = Info;
1978 if (BestFns)
1979 BestFns->push_back(Info);
1980 }
1981
1982 return Best;
1983}
1984
1985/// Determine whether a given type is a class for which 'delete[]' would call
1986/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1987/// we need to store the array size (even if the type is
1988/// trivially-destructible).
1990 TypeAwareAllocationMode PassType,
1991 QualType allocType) {
1992 const auto *record =
1993 allocType->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>();
1994 if (!record) return false;
1995
1996 // Try to find an operator delete[] in class scope.
1997
1998 DeclarationName deleteName =
1999 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
2000 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
2001 S.LookupQualifiedName(ops, record->getDecl()->getDefinitionOrSelf());
2002
2003 // We're just doing this for information.
2004 ops.suppressDiagnostics();
2005
2006 // Very likely: there's no operator delete[].
2007 if (ops.empty()) return false;
2008
2009 // If it's ambiguous, it should be illegal to call operator delete[]
2010 // on this thing, so it doesn't matter if we allocate extra space or not.
2011 if (ops.isAmbiguous()) return false;
2012
2013 // C++17 [expr.delete]p10:
2014 // If the deallocation functions have class scope, the one without a
2015 // parameter of type std::size_t is selected.
2017 allocType, PassType,
2020 auto Best = resolveDeallocationOverload(S, ops, IDP, loc);
2021 return Best && isSizedDeallocation(Best.IDP.PassSize);
2022}
2023
2025Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
2026 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
2027 SourceLocation PlacementRParen, SourceRange TypeIdParens,
2029 std::optional<Expr *> ArraySize;
2030 // If the specified type is an array, unwrap it and save the expression.
2031 if (D.getNumTypeObjects() > 0 &&
2033 DeclaratorChunk &Chunk = D.getTypeObject(0);
2034 if (D.getDeclSpec().hasAutoTypeSpec())
2035 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
2036 << D.getSourceRange());
2037 if (Chunk.Arr.hasStatic)
2038 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
2039 << D.getSourceRange());
2040 if (!Chunk.Arr.NumElts && !Initializer)
2041 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
2042 << D.getSourceRange());
2043
2044 ArraySize = Chunk.Arr.NumElts;
2046 }
2047
2048 // Every dimension shall be of constant size.
2049 if (ArraySize) {
2050 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
2052 break;
2053
2055 if (Expr *NumElts = Array.NumElts) {
2056 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
2057 // FIXME: GCC permits constant folding here. We should either do so consistently
2058 // or not do so at all, rather than changing behavior in C++14 onwards.
2059 if (getLangOpts().CPlusPlus14) {
2060 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
2061 // shall be a converted constant expression (5.19) of type std::size_t
2062 // and shall evaluate to a strictly positive value.
2063 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
2064 Array.NumElts =
2065 CheckConvertedConstantExpression(NumElts, Context.getSizeType(),
2067 .get();
2068 } else {
2069 Array.NumElts = VerifyIntegerConstantExpression(
2070 NumElts, nullptr, diag::err_new_array_nonconst,
2072 .get();
2073 }
2074 if (!Array.NumElts)
2075 return ExprError();
2076 }
2077 }
2078 }
2079 }
2080
2082 QualType AllocType = TInfo->getType();
2083 if (D.isInvalidType())
2084 return ExprError();
2085
2086 SourceRange DirectInitRange;
2087 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
2088 DirectInitRange = List->getSourceRange();
2089
2090 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
2091 PlacementLParen, PlacementArgs, PlacementRParen,
2092 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
2093 Initializer);
2094}
2095
2097 Expr *Init, bool IsCPlusPlus20) {
2098 if (!Init)
2099 return true;
2100 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
2101 return IsCPlusPlus20 || PLE->getNumExprs() == 0;
2103 return true;
2104 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
2105 return !CCE->isListInitialization() &&
2106 CCE->getConstructor()->isDefaultConstructor();
2107 else if (Style == CXXNewInitializationStyle::Braces) {
2108 assert(isa<InitListExpr>(Init) &&
2109 "Shouldn't create list CXXConstructExprs for arrays.");
2110 return true;
2111 }
2112 return false;
2113}
2114
2115bool
2117 if (!getLangOpts().AlignedAllocationUnavailable)
2118 return false;
2119 if (FD.isDefined())
2120 return false;
2121 UnsignedOrNone AlignmentParam = std::nullopt;
2122 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
2123 AlignmentParam)
2124 return true;
2125 return false;
2126}
2127
2128// Emit a diagnostic if an aligned allocation/deallocation function that is not
2129// implemented in the standard library is selected.
2131 SourceLocation Loc) {
2133 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
2134 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
2135 getASTContext().getTargetInfo().getPlatformName());
2136 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
2137
2138 bool IsDelete = FD.getDeclName().isAnyOperatorDelete();
2139 Diag(Loc, diag::err_aligned_allocation_unavailable)
2140 << IsDelete << FD.getType().getAsString() << OSName
2141 << OSVersion.getAsString() << OSVersion.empty();
2142 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
2143 }
2144}
2145
2147 SourceLocation PlacementLParen,
2148 MultiExprArg PlacementArgs,
2149 SourceLocation PlacementRParen,
2150 SourceRange TypeIdParens, QualType AllocType,
2151 TypeSourceInfo *AllocTypeInfo,
2152 std::optional<Expr *> ArraySize,
2153 SourceRange DirectInitRange, Expr *Initializer) {
2154 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
2155 SourceLocation StartLoc = Range.getBegin();
2156
2157 CXXNewInitializationStyle InitStyle;
2158 if (DirectInitRange.isValid()) {
2159 assert(Initializer && "Have parens but no initializer.");
2161 } else if (isa_and_nonnull<InitListExpr>(Initializer))
2163 else {
2166 "Initializer expression that cannot have been implicitly created.");
2168 }
2169
2170 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
2171 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
2172 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2173 "paren init for non-call init");
2174 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
2175 } else if (auto *List = dyn_cast_or_null<CXXParenListInitExpr>(Initializer)) {
2176 assert(InitStyle == CXXNewInitializationStyle::Parens &&
2177 "paren init for non-call init");
2178 Exprs = List->getInitExprs();
2179 }
2180
2181 // C++11 [expr.new]p15:
2182 // A new-expression that creates an object of type T initializes that
2183 // object as follows:
2184 InitializationKind Kind = [&] {
2185 switch (InitStyle) {
2186 // - If the new-initializer is omitted, the object is default-
2187 // initialized (8.5); if no initialization is performed,
2188 // the object has indeterminate value
2190 return InitializationKind::CreateDefault(TypeRange.getBegin());
2191 // - Otherwise, the new-initializer is interpreted according to the
2192 // initialization rules of 8.5 for direct-initialization.
2194 return InitializationKind::CreateDirect(TypeRange.getBegin(),
2195 DirectInitRange.getBegin(),
2196 DirectInitRange.getEnd());
2199 Initializer->getBeginLoc(),
2200 Initializer->getEndLoc());
2201 }
2202 llvm_unreachable("Unknown initialization kind");
2203 }();
2204
2205 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2206 auto *Deduced = AllocType->getContainedDeducedType();
2207 if (Deduced && !Deduced->isDeduced() &&
2209 if (ArraySize)
2210 return ExprError(
2211 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2212 diag::err_deduced_class_template_compound_type)
2213 << /*array*/ 2
2214 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2215
2219 AllocTypeInfo, Entity, Kind, Exprs);
2220 if (AllocType.isNull())
2221 return ExprError();
2222 } else if (Deduced && !Deduced->isDeduced()) {
2223 MultiExprArg Inits = Exprs;
2224 bool Braced = (InitStyle == CXXNewInitializationStyle::Braces);
2225 if (Braced) {
2226 auto *ILE = cast<InitListExpr>(Exprs[0]);
2227 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2228 }
2229
2230 if (InitStyle == CXXNewInitializationStyle::None || Inits.empty())
2231 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2232 << AllocType << TypeRange);
2233 if (Inits.size() > 1) {
2234 Expr *FirstBad = Inits[1];
2235 return ExprError(Diag(FirstBad->getBeginLoc(),
2236 diag::err_auto_new_ctor_multiple_expressions)
2237 << AllocType << TypeRange);
2238 }
2239 if (Braced && !getLangOpts().CPlusPlus17)
2240 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2241 << AllocType << TypeRange;
2242 Expr *Deduce = Inits[0];
2243 if (isa<InitListExpr>(Deduce))
2244 return ExprError(
2245 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2246 << Braced << AllocType << TypeRange);
2247 QualType DeducedType;
2248 TemplateDeductionInfo Info(Deduce->getExprLoc());
2250 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2253 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2254 << AllocType << Deduce->getType() << TypeRange
2255 << Deduce->getSourceRange());
2256 if (DeducedType.isNull()) {
2258 return ExprError();
2259 }
2260 AllocType = DeducedType;
2261 }
2262
2263 // Per C++0x [expr.new]p5, the type being constructed may be a
2264 // typedef of an array type.
2265 // Dependent case will be handled separately.
2266 if (!ArraySize && !AllocType->isDependentType()) {
2267 if (const ConstantArrayType *Array
2268 = Context.getAsConstantArrayType(AllocType)) {
2269 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2270 Context.getSizeType(),
2271 TypeRange.getEnd());
2272 AllocType = Array->getElementType();
2273 }
2274 }
2275
2276 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2277 return ExprError();
2278
2279 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2280 return ExprError();
2281
2282 // In ARC, infer 'retaining' for the allocated
2283 if (getLangOpts().ObjCAutoRefCount &&
2284 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2285 AllocType->isObjCLifetimeType()) {
2286 AllocType = Context.getLifetimeQualifiedType(AllocType,
2287 AllocType->getObjCARCImplicitLifetime());
2288 }
2289
2290 QualType ResultType = Context.getPointerType(AllocType);
2291
2292 if (ArraySize && *ArraySize &&
2293 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2294 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2295 if (result.isInvalid()) return ExprError();
2296 ArraySize = result.get();
2297 }
2298 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2299 // integral or enumeration type with a non-negative value."
2300 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2301 // enumeration type, or a class type for which a single non-explicit
2302 // conversion function to integral or unscoped enumeration type exists.
2303 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2304 // std::size_t.
2305 std::optional<uint64_t> KnownArraySize;
2306 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2307 ExprResult ConvertedSize;
2308 if (getLangOpts().CPlusPlus14) {
2309 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
2310
2311 ConvertedSize = PerformImplicitConversion(
2312 *ArraySize, Context.getSizeType(), AssignmentAction::Converting);
2313
2314 if (!ConvertedSize.isInvalid() && (*ArraySize)->getType()->isRecordType())
2315 // Diagnose the compatibility of this conversion.
2316 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2317 << (*ArraySize)->getType() << 0 << "'size_t'";
2318 } else {
2319 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2320 protected:
2321 Expr *ArraySize;
2322
2323 public:
2324 SizeConvertDiagnoser(Expr *ArraySize)
2325 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2326 ArraySize(ArraySize) {}
2327
2328 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2329 QualType T) override {
2330 return S.Diag(Loc, diag::err_array_size_not_integral)
2331 << S.getLangOpts().CPlusPlus11 << T;
2332 }
2333
2334 SemaDiagnosticBuilder diagnoseIncomplete(
2335 Sema &S, SourceLocation Loc, QualType T) override {
2336 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2337 << T << ArraySize->getSourceRange();
2338 }
2339
2340 SemaDiagnosticBuilder diagnoseExplicitConv(
2341 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2342 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2343 }
2344
2345 SemaDiagnosticBuilder noteExplicitConv(
2346 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2347 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2348 << ConvTy->isEnumeralType() << ConvTy;
2349 }
2350
2351 SemaDiagnosticBuilder diagnoseAmbiguous(
2352 Sema &S, SourceLocation Loc, QualType T) override {
2353 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2354 }
2355
2356 SemaDiagnosticBuilder noteAmbiguous(
2357 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2358 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2359 << ConvTy->isEnumeralType() << ConvTy;
2360 }
2361
2362 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2363 QualType T,
2364 QualType ConvTy) override {
2365 return S.Diag(Loc,
2366 S.getLangOpts().CPlusPlus11
2367 ? diag::warn_cxx98_compat_array_size_conversion
2368 : diag::ext_array_size_conversion)
2369 << T << ConvTy->isEnumeralType() << ConvTy;
2370 }
2371 } SizeDiagnoser(*ArraySize);
2372
2373 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2374 SizeDiagnoser);
2375 }
2376 if (ConvertedSize.isInvalid())
2377 return ExprError();
2378
2379 ArraySize = ConvertedSize.get();
2380 QualType SizeType = (*ArraySize)->getType();
2381
2382 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2383 return ExprError();
2384
2385 // C++98 [expr.new]p7:
2386 // The expression in a direct-new-declarator shall have integral type
2387 // with a non-negative value.
2388 //
2389 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2390 // per CWG1464. Otherwise, if it's not a constant, we must have an
2391 // unparenthesized array type.
2392
2393 // We've already performed any required implicit conversion to integer or
2394 // unscoped enumeration type.
2395 // FIXME: Per CWG1464, we are required to check the value prior to
2396 // converting to size_t. This will never find a negative array size in
2397 // C++14 onwards, because Value is always unsigned here!
2398 if (std::optional<llvm::APSInt> Value =
2399 (*ArraySize)->getIntegerConstantExpr(Context)) {
2400 if (Value->isSigned() && Value->isNegative()) {
2401 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2402 diag::err_typecheck_negative_array_size)
2403 << (*ArraySize)->getSourceRange());
2404 }
2405
2406 if (!AllocType->isDependentType()) {
2407 unsigned ActiveSizeBits =
2409 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2410 return ExprError(
2411 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2412 << toString(*Value, 10, Value->isSigned(),
2413 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2414 /*InsertSeparators=*/true)
2415 << (*ArraySize)->getSourceRange());
2416 }
2417
2418 KnownArraySize = Value->getZExtValue();
2419 } else if (TypeIdParens.isValid()) {
2420 // Can't have dynamic array size when the type-id is in parentheses.
2421 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2422 << (*ArraySize)->getSourceRange()
2423 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2424 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2425
2426 TypeIdParens = SourceRange();
2427 }
2428
2429 // Note that we do *not* convert the argument in any way. It can
2430 // be signed, larger than size_t, whatever.
2431 }
2432
2433 FunctionDecl *OperatorNew = nullptr;
2434 FunctionDecl *OperatorDelete = nullptr;
2435 unsigned Alignment =
2436 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2437 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2440 alignedAllocationModeFromBool(getLangOpts().AlignedAllocation &&
2441 Alignment > NewAlignment)};
2442
2443 if (CheckArgsForPlaceholders(PlacementArgs))
2444 return ExprError();
2445
2448 SourceRange AllocationParameterRange = Range;
2449 if (PlacementLParen.isValid() && PlacementRParen.isValid())
2450 AllocationParameterRange = SourceRange(PlacementLParen, PlacementRParen);
2451 if (!AllocType->isDependentType() &&
2452 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2453 FindAllocationFunctions(StartLoc, AllocationParameterRange, Scope, Scope,
2454 AllocType, ArraySize.has_value(), IAP,
2455 PlacementArgs, OperatorNew, OperatorDelete))
2456 return ExprError();
2457
2458 // If this is an array allocation, compute whether the usual array
2459 // deallocation function for the type has a size_t parameter.
2460 bool UsualArrayDeleteWantsSize = false;
2461 if (ArraySize && !AllocType->isDependentType())
2462 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(
2463 *this, StartLoc, IAP.PassTypeIdentity, AllocType);
2464
2465 SmallVector<Expr *, 8> AllPlaceArgs;
2466 if (OperatorNew) {
2467 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2468 VariadicCallType CallType = Proto->isVariadic()
2471
2472 // We've already converted the placement args, just fill in any default
2473 // arguments. Skip the first parameter because we don't have a corresponding
2474 // argument. Skip the second parameter too if we're passing in the
2475 // alignment; we've already filled it in.
2476 unsigned NumImplicitArgs = 1;
2478 assert(OperatorNew->isTypeAwareOperatorNewOrDelete());
2479 NumImplicitArgs++;
2480 }
2482 NumImplicitArgs++;
2483 if (GatherArgumentsForCall(AllocationParameterRange.getBegin(), OperatorNew,
2484 Proto, NumImplicitArgs, PlacementArgs,
2485 AllPlaceArgs, CallType))
2486 return ExprError();
2487
2488 if (!AllPlaceArgs.empty())
2489 PlacementArgs = AllPlaceArgs;
2490
2491 // We would like to perform some checking on the given `operator new` call,
2492 // but the PlacementArgs does not contain the implicit arguments,
2493 // namely allocation size and maybe allocation alignment,
2494 // so we need to conjure them.
2495
2496 QualType SizeTy = Context.getSizeType();
2497 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2498
2499 llvm::APInt SingleEltSize(
2500 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2501
2502 // How many bytes do we want to allocate here?
2503 std::optional<llvm::APInt> AllocationSize;
2504 if (!ArraySize && !AllocType->isDependentType()) {
2505 // For non-array operator new, we only want to allocate one element.
2506 AllocationSize = SingleEltSize;
2507 } else if (KnownArraySize && !AllocType->isDependentType()) {
2508 // For array operator new, only deal with static array size case.
2509 bool Overflow;
2510 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2511 .umul_ov(SingleEltSize, Overflow);
2512 (void)Overflow;
2513 assert(
2514 !Overflow &&
2515 "Expected that all the overflows would have been handled already.");
2516 }
2517
2518 IntegerLiteral AllocationSizeLiteral(
2519 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2520 SizeTy, StartLoc);
2521 // Otherwise, if we failed to constant-fold the allocation size, we'll
2522 // just give up and pass-in something opaque, that isn't a null pointer.
2523 OpaqueValueExpr OpaqueAllocationSize(StartLoc, SizeTy, VK_PRValue,
2524 OK_Ordinary, /*SourceExpr=*/nullptr);
2525
2526 // Let's synthesize the alignment argument in case we will need it.
2527 // Since we *really* want to allocate these on stack, this is slightly ugly
2528 // because there might not be a `std::align_val_t` type.
2530 QualType AlignValT =
2531 StdAlignValT ? Context.getCanonicalTagType(StdAlignValT) : SizeTy;
2532 IntegerLiteral AlignmentLiteral(
2533 Context,
2534 llvm::APInt(Context.getTypeSize(SizeTy),
2535 Alignment / Context.getCharWidth()),
2536 SizeTy, StartLoc);
2537 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2538 CK_IntegralCast, &AlignmentLiteral,
2540
2541 // Adjust placement args by prepending conjured size and alignment exprs.
2543 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2544 CallArgs.emplace_back(AllocationSize
2545 ? static_cast<Expr *>(&AllocationSizeLiteral)
2546 : &OpaqueAllocationSize);
2548 CallArgs.emplace_back(&DesiredAlignment);
2549 llvm::append_range(CallArgs, PlacementArgs);
2550
2551 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2552
2553 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2554 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2555
2556 // Warn if the type is over-aligned and is being allocated by (unaligned)
2557 // global operator new.
2558 if (PlacementArgs.empty() && !isAlignedAllocation(IAP.PassAlignment) &&
2559 (OperatorNew->isImplicit() ||
2560 (OperatorNew->getBeginLoc().isValid() &&
2561 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2562 if (Alignment > NewAlignment)
2563 Diag(StartLoc, diag::warn_overaligned_type)
2564 << AllocType
2565 << unsigned(Alignment / Context.getCharWidth())
2566 << unsigned(NewAlignment / Context.getCharWidth());
2567 }
2568 }
2569
2570 // Array 'new' can't have any initializers except empty parentheses.
2571 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2572 // dialect distinction.
2573 if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer,
2575 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2576 Exprs.back()->getEndLoc());
2577 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2578 return ExprError();
2579 }
2580
2581 // If we can perform the initialization, and we've not already done so,
2582 // do it now.
2583 if (!AllocType->isDependentType() &&
2585 // The type we initialize is the complete type, including the array bound.
2586 QualType InitType;
2587 if (KnownArraySize)
2588 InitType = Context.getConstantArrayType(
2589 AllocType,
2590 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2591 *KnownArraySize),
2592 *ArraySize, ArraySizeModifier::Normal, 0);
2593 else if (ArraySize)
2594 InitType = Context.getIncompleteArrayType(AllocType,
2596 else
2597 InitType = AllocType;
2598
2599 bool VariableLengthArrayNew = ArraySize && *ArraySize && !KnownArraySize;
2601 StartLoc, InitType,
2602 VariableLengthArrayNew ? InitializedEntity::NewArrayKind::UnknownLength
2604 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2605 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2606 if (FullInit.isInvalid())
2607 return ExprError();
2608
2609 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2610 // we don't want the initialized object to be destructed.
2611 // FIXME: We should not create these in the first place.
2612 if (CXXBindTemporaryExpr *Binder =
2613 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2614 FullInit = Binder->getSubExpr();
2615
2616 Initializer = FullInit.get();
2617
2618 // FIXME: If we have a KnownArraySize, check that the array bound of the
2619 // initializer is no greater than that constant value.
2620
2621 if (ArraySize && !*ArraySize) {
2622 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2623 if (CAT) {
2624 // FIXME: Track that the array size was inferred rather than explicitly
2625 // specified.
2626 ArraySize = IntegerLiteral::Create(
2627 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2628 } else {
2629 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2630 << Initializer->getSourceRange();
2631 }
2632 }
2633 }
2634
2635 // Mark the new and delete operators as referenced.
2636 if (OperatorNew) {
2637 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2638 return ExprError();
2639 MarkFunctionReferenced(StartLoc, OperatorNew);
2640 }
2641 if (OperatorDelete) {
2642 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2643 return ExprError();
2644 MarkFunctionReferenced(StartLoc, OperatorDelete);
2645 }
2646
2647 // new[] will trigger vector deleting destructor emission if the class has
2648 // virtual destructor for MSVC compatibility. Perform necessary checks.
2649 if (Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts())) {
2650 if (const CXXConstructExpr *CCE =
2651 dyn_cast_or_null<CXXConstructExpr>(Initializer);
2652 CCE && ArraySize) {
2653 CXXRecordDecl *ClassDecl = CCE->getConstructor()->getParent();
2654 // We probably already did this for another new[] with this class so don't
2655 // do it twice.
2656 if (!Context.classMaybeNeedsVectorDeletingDestructor(ClassDecl)) {
2657 auto *Dtor = ClassDecl->getDestructor();
2658 if (Dtor && Dtor->isVirtual() && !Dtor->isDeleted()) {
2659 Context.setClassMaybeNeedsVectorDeletingDestructor(ClassDecl);
2660 if (!Dtor->isDefined() && !Dtor->isInvalidDecl()) {
2661 // Call CheckDestructor if destructor is not defined. This is
2662 // needed to find operators delete and delete[] for vector deleting
2663 // destructor body because new[] will trigger emission of vector
2664 // deleting destructor body even if destructor is defined in another
2665 // translation unit.
2666 ContextRAII SavedContext(*this, Dtor);
2667 CheckDestructor(Dtor);
2668 }
2669 }
2670 }
2671 }
2672 }
2673
2674 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2675 IAP, UsualArrayDeleteWantsSize, PlacementArgs,
2676 TypeIdParens, ArraySize, InitStyle, Initializer,
2677 ResultType, AllocTypeInfo, Range, DirectInitRange);
2678}
2679
2681 SourceRange R) {
2682 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2683 // abstract class type or array thereof.
2684 if (AllocType->isFunctionType())
2685 return Diag(Loc, diag::err_bad_new_type)
2686 << AllocType << 0 << R;
2687 else if (AllocType->isReferenceType())
2688 return Diag(Loc, diag::err_bad_new_type)
2689 << AllocType << 1 << R;
2690 else if (!AllocType->isDependentType() &&
2692 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2693 return true;
2694 else if (RequireNonAbstractType(Loc, AllocType,
2695 diag::err_allocation_of_abstract_type))
2696 return true;
2697 else if (AllocType->isVariablyModifiedType())
2698 return Diag(Loc, diag::err_variably_modified_new_type)
2699 << AllocType;
2700 else if (AllocType.getAddressSpace() != LangAS::Default &&
2701 !getLangOpts().OpenCLCPlusPlus)
2702 return Diag(Loc, diag::err_address_space_qualified_new)
2703 << AllocType.getUnqualifiedType()
2705
2706 else if (getLangOpts().ObjCAutoRefCount) {
2707 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2708 QualType BaseAllocType = Context.getBaseElementType(AT);
2709 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2710 BaseAllocType->isObjCLifetimeType())
2711 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2712 << BaseAllocType;
2713 }
2714 }
2715
2716 return false;
2717}
2718
2719enum class ResolveMode { Typed, Untyped };
2721 Sema &S, LookupResult &R, SourceRange Range, ResolveMode Mode,
2722 SmallVectorImpl<Expr *> &Args, AlignedAllocationMode &PassAlignment,
2723 FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates,
2724 Expr *AlignArg, bool Diagnose) {
2725 unsigned NonTypeArgumentOffset = 0;
2726 if (Mode == ResolveMode::Typed) {
2727 ++NonTypeArgumentOffset;
2728 }
2729
2730 OverloadCandidateSet Candidates(R.getNameLoc(),
2732 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2733 Alloc != AllocEnd; ++Alloc) {
2734 // Even member operator new/delete are implicitly treated as
2735 // static, so don't use AddMemberCandidate.
2736 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2737 bool IsTypeAware = D->getAsFunction()->isTypeAwareOperatorNewOrDelete();
2738 if (IsTypeAware == (Mode != ResolveMode::Typed))
2739 continue;
2740
2741 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2742 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2743 /*ExplicitTemplateArgs=*/nullptr, Args,
2744 Candidates,
2745 /*SuppressUserConversions=*/false);
2746 continue;
2747 }
2748
2750 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2751 /*SuppressUserConversions=*/false);
2752 }
2753
2754 // Do the resolution.
2756 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2757 case OR_Success: {
2758 // Got one!
2759 FunctionDecl *FnDecl = Best->Function;
2760 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2761 Best->FoundDecl) == Sema::AR_inaccessible)
2762 return true;
2763
2764 Operator = FnDecl;
2765 return false;
2766 }
2767
2769 // C++17 [expr.new]p13:
2770 // If no matching function is found and the allocated object type has
2771 // new-extended alignment, the alignment argument is removed from the
2772 // argument list, and overload resolution is performed again.
2773 if (isAlignedAllocation(PassAlignment)) {
2774 PassAlignment = AlignedAllocationMode::No;
2775 AlignArg = Args[NonTypeArgumentOffset + 1];
2776 Args.erase(Args.begin() + NonTypeArgumentOffset + 1);
2777 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,
2778 PassAlignment, Operator,
2779 &Candidates, AlignArg, Diagnose);
2780 }
2781
2782 // MSVC will fall back on trying to find a matching global operator new
2783 // if operator new[] cannot be found. Also, MSVC will leak by not
2784 // generating a call to operator delete or operator delete[], but we
2785 // will not replicate that bug.
2786 // FIXME: Find out how this interacts with the std::align_val_t fallback
2787 // once MSVC implements it.
2788 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2789 S.Context.getLangOpts().MSVCCompat && Mode != ResolveMode::Typed) {
2790 R.clear();
2791 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2793 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2794 return resolveAllocationOverloadInterior(S, R, Range, Mode, Args,
2795 PassAlignment, Operator,
2796 /*Candidates=*/nullptr,
2797 /*AlignArg=*/nullptr, Diagnose);
2798 }
2799 if (Mode == ResolveMode::Typed) {
2800 // If we can't find a matching type aware operator we don't consider this
2801 // a failure.
2802 Operator = nullptr;
2803 return false;
2804 }
2805 if (Diagnose) {
2806 // If this is an allocation of the form 'new (p) X' for some object
2807 // pointer p (or an expression that will decay to such a pointer),
2808 // diagnose the reason for the error.
2809 if (!R.isClassLookup() && Args.size() == 2 &&
2810 (Args[1]->getType()->isObjectPointerType() ||
2811 Args[1]->getType()->isArrayType())) {
2812 const QualType Arg1Type = Args[1]->getType();
2813 QualType UnderlyingType = S.Context.getBaseElementType(Arg1Type);
2814 if (UnderlyingType->isPointerType())
2815 UnderlyingType = UnderlyingType->getPointeeType();
2816 if (UnderlyingType.isConstQualified()) {
2817 S.Diag(Args[1]->getExprLoc(),
2818 diag::err_placement_new_into_const_qualified_storage)
2819 << Arg1Type << Args[1]->getSourceRange();
2820 return true;
2821 }
2822 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2823 << R.getLookupName() << Range;
2824 // Listing the candidates is unlikely to be useful; skip it.
2825 return true;
2826 }
2827
2828 // Finish checking all candidates before we note any. This checking can
2829 // produce additional diagnostics so can't be interleaved with our
2830 // emission of notes.
2831 //
2832 // For an aligned allocation, separately check the aligned and unaligned
2833 // candidates with their respective argument lists.
2836 llvm::SmallVector<Expr*, 4> AlignedArgs;
2837 if (AlignedCandidates) {
2838 auto IsAligned = [NonTypeArgumentOffset](OverloadCandidate &C) {
2839 auto AlignArgOffset = NonTypeArgumentOffset + 1;
2840 return C.Function->getNumParams() > AlignArgOffset &&
2841 C.Function->getParamDecl(AlignArgOffset)
2842 ->getType()
2843 ->isAlignValT();
2844 };
2845 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2846
2847 AlignedArgs.reserve(Args.size() + NonTypeArgumentOffset + 1);
2848 for (unsigned Idx = 0; Idx < NonTypeArgumentOffset + 1; ++Idx)
2849 AlignedArgs.push_back(Args[Idx]);
2850 AlignedArgs.push_back(AlignArg);
2851 AlignedArgs.append(Args.begin() + NonTypeArgumentOffset + 1,
2852 Args.end());
2853 AlignedCands = AlignedCandidates->CompleteCandidates(
2854 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2855
2856 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2857 R.getNameLoc(), IsUnaligned);
2858 } else {
2859 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2860 R.getNameLoc());
2861 }
2862
2863 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2864 << R.getLookupName() << Range;
2865 if (AlignedCandidates)
2866 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2867 R.getNameLoc());
2868 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2869 }
2870 return true;
2871
2872 case OR_Ambiguous:
2873 if (Diagnose) {
2874 Candidates.NoteCandidates(
2875 PartialDiagnosticAt(R.getNameLoc(),
2876 S.PDiag(diag::err_ovl_ambiguous_call)
2877 << R.getLookupName() << Range),
2878 S, OCD_AmbiguousCandidates, Args);
2879 }
2880 return true;
2881
2882 case OR_Deleted: {
2883 if (Diagnose)
2884 S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),
2885 Candidates, Best->Function, Args);
2886 return true;
2887 }
2888 }
2889 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2890}
2891
2893
2895 LookupResult &FoundDelete,
2896 DeallocLookupMode Mode,
2897 DeclarationName Name) {
2900 // We're going to remove either the typed or the non-typed
2901 bool RemoveTypedDecl = Mode == DeallocLookupMode::Untyped;
2902 LookupResult::Filter Filter = FoundDelete.makeFilter();
2903 while (Filter.hasNext()) {
2904 FunctionDecl *FD = Filter.next()->getUnderlyingDecl()->getAsFunction();
2905 if (FD->isTypeAwareOperatorNewOrDelete() == RemoveTypedDecl)
2906 Filter.erase();
2907 }
2908 Filter.done();
2909 }
2910}
2911
2915 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2916 Operator = nullptr;
2918 assert(S.isStdTypeIdentity(Args[0]->getType(), nullptr));
2919 // The internal overload resolution work mutates the argument list
2920 // in accordance with the spec. We may want to change that in future,
2921 // but for now we deal with this by making a copy of the non-type-identity
2922 // arguments.
2923 SmallVector<Expr *> UntypedParameters;
2924 UntypedParameters.reserve(Args.size() - 1);
2925 UntypedParameters.push_back(Args[1]);
2926 // Type aware allocation implicitly includes the alignment parameter so
2927 // only include it in the untyped parameter list if alignment was explicitly
2928 // requested
2930 UntypedParameters.push_back(Args[2]);
2931 UntypedParameters.append(Args.begin() + 3, Args.end());
2932
2933 AlignedAllocationMode InitialAlignmentMode = IAP.PassAlignment;
2936 S, R, Range, ResolveMode::Typed, Args, IAP.PassAlignment, Operator,
2937 AlignedCandidates, AlignArg, Diagnose))
2938 return true;
2939 if (Operator)
2940 return false;
2941
2942 // If we got to this point we could not find a matching typed operator
2943 // so we update the IAP flags, and revert to our stored copy of the
2944 // type-identity-less argument list.
2946 IAP.PassAlignment = InitialAlignmentMode;
2947 Args = std::move(UntypedParameters);
2948 }
2949 assert(!S.isStdTypeIdentity(Args[0]->getType(), nullptr));
2951 S, R, Range, ResolveMode::Untyped, Args, IAP.PassAlignment, Operator,
2952 AlignedCandidates, AlignArg, Diagnose);
2953}
2954
2956 SourceLocation StartLoc, SourceRange Range,
2958 QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP,
2959 MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew,
2960 FunctionDecl *&OperatorDelete, bool Diagnose) {
2961 // --- Choosing an allocation function ---
2962 // C++ 5.3.4p8 - 14 & 18
2963 // 1) If looking in AllocationFunctionScope::Global scope for allocation
2964 // functions, only look in
2965 // the global scope. Else, if AllocationFunctionScope::Class, only look in
2966 // the scope of the allocated class. If AllocationFunctionScope::Both, look
2967 // in both.
2968 // 2) If an array size is given, look for operator new[], else look for
2969 // operator new.
2970 // 3) The first argument is always size_t. Append the arguments from the
2971 // placement form.
2972
2973 SmallVector<Expr*, 8> AllocArgs;
2974 AllocArgs.reserve(IAP.getNumImplicitArgs() + PlaceArgs.size());
2975
2976 // C++ [expr.new]p8:
2977 // If the allocated type is a non-array type, the allocation
2978 // function's name is operator new and the deallocation function's
2979 // name is operator delete. If the allocated type is an array
2980 // type, the allocation function's name is operator new[] and the
2981 // deallocation function's name is operator delete[].
2982 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2983 IsArray ? OO_Array_New : OO_New);
2984
2985 QualType AllocElemType = Context.getBaseElementType(AllocType);
2986
2987 // We don't care about the actual value of these arguments.
2988 // FIXME: Should the Sema create the expression and embed it in the syntax
2989 // tree? Or should the consumer just recalculate the value?
2990 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2991
2992 // We use size_t as a stand in so that we can construct the init
2993 // expr on the stack
2994 QualType TypeIdentity = Context.getSizeType();
2996 QualType SpecializedTypeIdentity =
2997 tryBuildStdTypeIdentity(IAP.Type, StartLoc);
2998 if (!SpecializedTypeIdentity.isNull()) {
2999 TypeIdentity = SpecializedTypeIdentity;
3000 if (RequireCompleteType(StartLoc, TypeIdentity,
3001 diag::err_incomplete_type))
3002 return true;
3003 } else
3005 }
3006 TypeAwareAllocationMode OriginalTypeAwareState = IAP.PassTypeIdentity;
3007
3008 CXXScalarValueInitExpr TypeIdentityParam(TypeIdentity, nullptr, StartLoc);
3010 AllocArgs.push_back(&TypeIdentityParam);
3011
3012 QualType SizeTy = Context.getSizeType();
3013 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
3014 IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy,
3015 SourceLocation());
3016 AllocArgs.push_back(&Size);
3017
3018 QualType AlignValT = Context.VoidTy;
3019 bool IncludeAlignParam = isAlignedAllocation(IAP.PassAlignment) ||
3021 if (IncludeAlignParam) {
3023 AlignValT = Context.getCanonicalTagType(getStdAlignValT());
3024 }
3025 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
3026 if (IncludeAlignParam)
3027 AllocArgs.push_back(&Align);
3028
3029 llvm::append_range(AllocArgs, PlaceArgs);
3030
3031 // Find the allocation function.
3032 {
3033 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
3034
3035 // C++1z [expr.new]p9:
3036 // If the new-expression begins with a unary :: operator, the allocation
3037 // function's name is looked up in the global scope. Otherwise, if the
3038 // allocated type is a class type T or array thereof, the allocation
3039 // function's name is looked up in the scope of T.
3040 if (AllocElemType->isRecordType() &&
3042 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
3043
3044 // We can see ambiguity here if the allocation function is found in
3045 // multiple base classes.
3046 if (R.isAmbiguous())
3047 return true;
3048
3049 // If this lookup fails to find the name, or if the allocated type is not
3050 // a class type, the allocation function's name is looked up in the
3051 // global scope.
3052 if (R.empty()) {
3053 if (NewScope == AllocationFunctionScope::Class)
3054 return true;
3055
3056 LookupQualifiedName(R, Context.getTranslationUnitDecl());
3057 }
3058
3059 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
3060 if (PlaceArgs.empty()) {
3061 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
3062 } else {
3063 Diag(StartLoc, diag::err_openclcxx_placement_new);
3064 }
3065 return true;
3066 }
3067
3068 assert(!R.empty() && "implicitly declared allocation functions not found");
3069 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3070
3071 // We do our own custom access checks below.
3072 R.suppressDiagnostics();
3073
3074 if (resolveAllocationOverload(*this, R, Range, AllocArgs, IAP, OperatorNew,
3075 /*Candidates=*/nullptr,
3076 /*AlignArg=*/nullptr, Diagnose))
3077 return true;
3078 }
3079
3080 // We don't need an operator delete if we're running under -fno-exceptions.
3081 if (!getLangOpts().Exceptions) {
3082 OperatorDelete = nullptr;
3083 return false;
3084 }
3085
3086 // Note, the name of OperatorNew might have been changed from array to
3087 // non-array by resolveAllocationOverload.
3088 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3089 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
3090 ? OO_Array_Delete
3091 : OO_Delete);
3092
3093 // C++ [expr.new]p19:
3094 //
3095 // If the new-expression begins with a unary :: operator, the
3096 // deallocation function's name is looked up in the global
3097 // scope. Otherwise, if the allocated type is a class type T or an
3098 // array thereof, the deallocation function's name is looked up in
3099 // the scope of T. If this lookup fails to find the name, or if
3100 // the allocated type is not a class type or array thereof, the
3101 // deallocation function's name is looked up in the global scope.
3102 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
3103 if (AllocElemType->isRecordType() &&
3104 DeleteScope != AllocationFunctionScope::Global) {
3105 auto *RD = AllocElemType->castAsCXXRecordDecl();
3106 LookupQualifiedName(FoundDelete, RD);
3107 }
3108 if (FoundDelete.isAmbiguous())
3109 return true; // FIXME: clean up expressions?
3110
3111 // Filter out any destroying operator deletes. We can't possibly call such a
3112 // function in this context, because we're handling the case where the object
3113 // was not successfully constructed.
3114 // FIXME: This is not covered by the language rules yet.
3115 {
3116 LookupResult::Filter Filter = FoundDelete.makeFilter();
3117 while (Filter.hasNext()) {
3118 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
3119 if (FD && FD->isDestroyingOperatorDelete())
3120 Filter.erase();
3121 }
3122 Filter.done();
3123 }
3124
3125 auto GetRedeclContext = [](Decl *D) {
3126 return D->getDeclContext()->getRedeclContext();
3127 };
3128
3129 DeclContext *OperatorNewContext = GetRedeclContext(OperatorNew);
3130
3131 bool FoundGlobalDelete = FoundDelete.empty();
3132 bool IsClassScopedTypeAwareNew =
3134 OperatorNewContext->isRecord();
3135 auto DiagnoseMissingTypeAwareCleanupOperator = [&](bool IsPlacementOperator) {
3137 if (Diagnose) {
3138 Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator)
3139 << OperatorNew->getDeclName() << IsPlacementOperator << DeleteName;
3140 Diag(OperatorNew->getLocation(), diag::note_type_aware_operator_declared)
3141 << OperatorNew->isTypeAwareOperatorNewOrDelete()
3142 << OperatorNew->getDeclName() << OperatorNewContext;
3143 }
3144 };
3145 if (IsClassScopedTypeAwareNew && FoundDelete.empty()) {
3146 DiagnoseMissingTypeAwareCleanupOperator(/*isPlacementNew=*/false);
3147 return true;
3148 }
3149 if (FoundDelete.empty()) {
3150 FoundDelete.clear(LookupOrdinaryName);
3151
3152 if (DeleteScope == AllocationFunctionScope::Class)
3153 return true;
3154
3156 DeallocLookupMode LookupMode = isTypeAwareAllocation(OriginalTypeAwareState)
3159 LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete, LookupMode,
3160 DeleteName);
3161 }
3162
3163 FoundDelete.suppressDiagnostics();
3164
3166
3167 // Whether we're looking for a placement operator delete is dictated
3168 // by whether we selected a placement operator new, not by whether
3169 // we had explicit placement arguments. This matters for things like
3170 // struct A { void *operator new(size_t, int = 0); ... };
3171 // A *a = new A()
3172 //
3173 // We don't have any definition for what a "placement allocation function"
3174 // is, but we assume it's any allocation function whose
3175 // parameter-declaration-clause is anything other than (size_t).
3176 //
3177 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
3178 // This affects whether an exception from the constructor of an overaligned
3179 // type uses the sized or non-sized form of aligned operator delete.
3180
3181 unsigned NonPlacementNewArgCount = 1; // size parameter
3183 NonPlacementNewArgCount =
3184 /* type-identity */ 1 + /* size */ 1 + /* alignment */ 1;
3185 bool isPlacementNew = !PlaceArgs.empty() ||
3186 OperatorNew->param_size() != NonPlacementNewArgCount ||
3187 OperatorNew->isVariadic();
3188
3189 if (isPlacementNew) {
3190 // C++ [expr.new]p20:
3191 // A declaration of a placement deallocation function matches the
3192 // declaration of a placement allocation function if it has the
3193 // same number of parameters and, after parameter transformations
3194 // (8.3.5), all parameter types except the first are
3195 // identical. [...]
3196 //
3197 // To perform this comparison, we compute the function type that
3198 // the deallocation function should have, and use that type both
3199 // for template argument deduction and for comparison purposes.
3200 QualType ExpectedFunctionType;
3201 {
3202 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
3203
3204 SmallVector<QualType, 6> ArgTypes;
3205 int InitialParamOffset = 0;
3207 ArgTypes.push_back(TypeIdentity);
3208 InitialParamOffset = 1;
3209 }
3210 ArgTypes.push_back(Context.VoidPtrTy);
3211 for (unsigned I = ArgTypes.size() - InitialParamOffset,
3212 N = Proto->getNumParams();
3213 I < N; ++I)
3214 ArgTypes.push_back(Proto->getParamType(I));
3215
3217 // FIXME: This is not part of the standard's rule.
3218 EPI.Variadic = Proto->isVariadic();
3219
3220 ExpectedFunctionType
3221 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
3222 }
3223
3224 for (LookupResult::iterator D = FoundDelete.begin(),
3225 DEnd = FoundDelete.end();
3226 D != DEnd; ++D) {
3227 FunctionDecl *Fn = nullptr;
3228 if (FunctionTemplateDecl *FnTmpl =
3229 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
3230 // Perform template argument deduction to try to match the
3231 // expected function type.
3232 TemplateDeductionInfo Info(StartLoc);
3233 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
3235 continue;
3236 } else
3237 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
3238
3239 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
3240 ExpectedFunctionType,
3241 /*AdjustExcpetionSpec*/true),
3242 ExpectedFunctionType))
3243 Matches.push_back(std::make_pair(D.getPair(), Fn));
3244 }
3245
3246 if (getLangOpts().CUDA)
3247 CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true),
3248 Matches);
3249 if (Matches.empty() && isTypeAwareAllocation(IAP.PassTypeIdentity)) {
3250 DiagnoseMissingTypeAwareCleanupOperator(isPlacementNew);
3251 return true;
3252 }
3253 } else {
3254 // C++1y [expr.new]p22:
3255 // For a non-placement allocation function, the normal deallocation
3256 // function lookup is used
3257 //
3258 // Per [expr.delete]p10, this lookup prefers a member operator delete
3259 // without a size_t argument, but prefers a non-member operator delete
3260 // with a size_t where possible (which it always is in this case).
3263 AllocElemType, OriginalTypeAwareState,
3265 hasNewExtendedAlignment(*this, AllocElemType)),
3266 sizedDeallocationModeFromBool(FoundGlobalDelete)};
3267 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
3268 *this, FoundDelete, IDP, StartLoc, &BestDeallocFns);
3269 if (Selected && BestDeallocFns.empty())
3270 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
3271 else {
3272 // If we failed to select an operator, all remaining functions are viable
3273 // but ambiguous.
3274 for (auto Fn : BestDeallocFns)
3275 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
3276 }
3277 }
3278
3279 // C++ [expr.new]p20:
3280 // [...] If the lookup finds a single matching deallocation
3281 // function, that function will be called; otherwise, no
3282 // deallocation function will be called.
3283 if (Matches.size() == 1) {
3284 OperatorDelete = Matches[0].second;
3285 DeclContext *OperatorDeleteContext = GetRedeclContext(OperatorDelete);
3286 bool FoundTypeAwareOperator =
3287 OperatorDelete->isTypeAwareOperatorNewOrDelete() ||
3288 OperatorNew->isTypeAwareOperatorNewOrDelete();
3289 if (Diagnose && FoundTypeAwareOperator) {
3290 bool MismatchedTypeAwareness =
3291 OperatorDelete->isTypeAwareOperatorNewOrDelete() !=
3292 OperatorNew->isTypeAwareOperatorNewOrDelete();
3293 bool MismatchedContext = OperatorDeleteContext != OperatorNewContext;
3294 if (MismatchedTypeAwareness || MismatchedContext) {
3295 FunctionDecl *Operators[] = {OperatorDelete, OperatorNew};
3296 bool TypeAwareOperatorIndex =
3297 OperatorNew->isTypeAwareOperatorNewOrDelete();
3298 Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator)
3299 << Operators[TypeAwareOperatorIndex]->getDeclName()
3300 << isPlacementNew
3301 << Operators[!TypeAwareOperatorIndex]->getDeclName()
3302 << GetRedeclContext(Operators[TypeAwareOperatorIndex]);
3303 Diag(OperatorNew->getLocation(),
3304 diag::note_type_aware_operator_declared)
3305 << OperatorNew->isTypeAwareOperatorNewOrDelete()
3306 << OperatorNew->getDeclName() << OperatorNewContext;
3307 Diag(OperatorDelete->getLocation(),
3308 diag::note_type_aware_operator_declared)
3309 << OperatorDelete->isTypeAwareOperatorNewOrDelete()
3310 << OperatorDelete->getDeclName() << OperatorDeleteContext;
3311 }
3312 }
3313
3314 // C++1z [expr.new]p23:
3315 // If the lookup finds a usual deallocation function (3.7.4.2)
3316 // with a parameter of type std::size_t and that function, considered
3317 // as a placement deallocation function, would have been
3318 // selected as a match for the allocation function, the program
3319 // is ill-formed.
3320 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
3321 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
3322 UsualDeallocFnInfo Info(*this,
3323 DeclAccessPair::make(OperatorDelete, AS_public),
3324 AllocElemType, StartLoc);
3325 // Core issue, per mail to core reflector, 2016-10-09:
3326 // If this is a member operator delete, and there is a corresponding
3327 // non-sized member operator delete, this isn't /really/ a sized
3328 // deallocation function, it just happens to have a size_t parameter.
3329 bool IsSizedDelete = isSizedDeallocation(Info.IDP.PassSize);
3330 if (IsSizedDelete && !FoundGlobalDelete) {
3331 ImplicitDeallocationParameters SizeTestingIDP = {
3332 AllocElemType, Info.IDP.PassTypeIdentity, Info.IDP.PassAlignment,
3334 auto NonSizedDelete = resolveDeallocationOverload(
3335 *this, FoundDelete, SizeTestingIDP, StartLoc);
3336 if (NonSizedDelete &&
3337 !isSizedDeallocation(NonSizedDelete.IDP.PassSize) &&
3338 NonSizedDelete.IDP.PassAlignment == Info.IDP.PassAlignment)
3339 IsSizedDelete = false;
3340 }
3341
3342 if (IsSizedDelete && !isTypeAwareAllocation(IAP.PassTypeIdentity)) {
3343 SourceRange R = PlaceArgs.empty()
3344 ? SourceRange()
3345 : SourceRange(PlaceArgs.front()->getBeginLoc(),
3346 PlaceArgs.back()->getEndLoc());
3347 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
3348 if (!OperatorDelete->isImplicit())
3349 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
3350 << DeleteName;
3351 }
3352 }
3353 if (CheckDeleteOperator(*this, StartLoc, Range, Diagnose,
3354 FoundDelete.getNamingClass(), Matches[0].first,
3355 Matches[0].second))
3356 return true;
3357
3358 } else if (!Matches.empty()) {
3359 // We found multiple suitable operators. Per [expr.new]p20, that means we
3360 // call no 'operator delete' function, but we should at least warn the user.
3361 // FIXME: Suppress this warning if the construction cannot throw.
3362 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
3363 << DeleteName << AllocElemType;
3364
3365 for (auto &Match : Matches)
3366 Diag(Match.second->getLocation(),
3367 diag::note_member_declared_here) << DeleteName;
3368 }
3369
3370 return false;
3371}
3372
3375 return;
3376
3377 // The implicitly declared new and delete operators
3378 // are not supported in OpenCL.
3379 if (getLangOpts().OpenCLCPlusPlus)
3380 return;
3381
3382 // C++ [basic.stc.dynamic.general]p2:
3383 // The library provides default definitions for the global allocation
3384 // and deallocation functions. Some global allocation and deallocation
3385 // functions are replaceable ([new.delete]); these are attached to the
3386 // global module ([module.unit]).
3387 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3388 PushGlobalModuleFragment(SourceLocation());
3389
3390 // C++ [basic.std.dynamic]p2:
3391 // [...] The following allocation and deallocation functions (18.4) are
3392 // implicitly declared in global scope in each translation unit of a
3393 // program
3394 //
3395 // C++03:
3396 // void* operator new(std::size_t) throw(std::bad_alloc);
3397 // void* operator new[](std::size_t) throw(std::bad_alloc);
3398 // void operator delete(void*) throw();
3399 // void operator delete[](void*) throw();
3400 // C++11:
3401 // void* operator new(std::size_t);
3402 // void* operator new[](std::size_t);
3403 // void operator delete(void*) noexcept;
3404 // void operator delete[](void*) noexcept;
3405 // C++1y:
3406 // void* operator new(std::size_t);
3407 // void* operator new[](std::size_t);
3408 // void operator delete(void*) noexcept;
3409 // void operator delete[](void*) noexcept;
3410 // void operator delete(void*, std::size_t) noexcept;
3411 // void operator delete[](void*, std::size_t) noexcept;
3412 //
3413 // These implicit declarations introduce only the function names operator
3414 // new, operator new[], operator delete, operator delete[].
3415 //
3416 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
3417 // "std" or "bad_alloc" as necessary to form the exception specification.
3418 // However, we do not make these implicit declarations visible to name
3419 // lookup.
3420 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3421 // The "std::bad_alloc" class has not yet been declared, so build it
3422 // implicitly.
3426 &PP.getIdentifierTable().get("bad_alloc"), nullptr);
3427 getStdBadAlloc()->setImplicit(true);
3428
3429 // The implicitly declared "std::bad_alloc" should live in global module
3430 // fragment.
3431 if (TheGlobalModuleFragment) {
3434 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3435 }
3436 }
3437 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3438 // The "std::align_val_t" enum class has not yet been declared, so build it
3439 // implicitly.
3440 auto *AlignValT = EnumDecl::Create(
3442 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3443
3444 // The implicitly declared "std::align_val_t" should live in global module
3445 // fragment.
3446 if (TheGlobalModuleFragment) {
3447 AlignValT->setModuleOwnershipKind(
3449 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3450 }
3451
3452 AlignValT->setIntegerType(Context.getSizeType());
3453 AlignValT->setPromotionType(Context.getSizeType());
3454 AlignValT->setImplicit(true);
3455
3456 // Add to the std namespace so that the module merger can find it via
3457 // noload_lookup and merge it with the module's explicit definition.
3458 // We want the created EnumDecl to be available for redeclaration lookups,
3459 // but not for regular name lookups (same pattern as
3460 // getOrCreateStdNamespace).
3461 getOrCreateStdNamespace()->addDecl(AlignValT);
3462
3463 StdAlignValT = AlignValT;
3464 }
3465
3467
3468 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
3469 QualType SizeT = Context.getSizeType();
3470
3471 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3472 QualType Return, QualType Param) {
3474 Params.push_back(Param);
3475
3476 // Create up to four variants of the function (sized/aligned).
3477 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3478 (Kind == OO_Delete || Kind == OO_Array_Delete);
3479 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3480
3481 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3482 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3483 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3484 if (Sized)
3485 Params.push_back(SizeT);
3486
3487 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3488 if (Aligned)
3489 Params.push_back(Context.getCanonicalTagType(getStdAlignValT()));
3490
3492 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3493
3494 if (Aligned)
3495 Params.pop_back();
3496 }
3497 }
3498 };
3499
3500 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3501 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3502 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3503 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3504
3505 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3506 PopGlobalModuleFragment();
3507}
3508
3509/// DeclareGlobalAllocationFunction - Declares a single implicit global
3510/// allocation function if it doesn't already exist.
3512 QualType Return,
3513 ArrayRef<QualType> Params) {
3514 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3515
3516 // Check if this function is already declared.
3517 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3518 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3519 Alloc != AllocEnd; ++Alloc) {
3520 // Only look at non-template functions, as it is the predefined,
3521 // non-templated allocation function we are trying to declare here.
3522 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3523 if (Func->getNumParams() == Params.size()) {
3524 if (std::equal(Func->param_begin(), Func->param_end(), Params.begin(),
3525 Params.end(), [&](ParmVarDecl *D, QualType RT) {
3526 return Context.hasSameUnqualifiedType(D->getType(),
3527 RT);
3528 })) {
3529 // Make the function visible to name lookup, even if we found it in
3530 // an unimported module. It either is an implicitly-declared global
3531 // allocation function, or is suppressing that function.
3532 Func->setVisibleDespiteOwningModule();
3533 return;
3534 }
3535 }
3536 }
3537 }
3538
3540 Context.getTargetInfo().getDefaultCallingConv());
3541
3542 QualType BadAllocType;
3543 bool HasBadAllocExceptionSpec = Name.isAnyOperatorNew();
3544 if (HasBadAllocExceptionSpec) {
3545 if (!getLangOpts().CPlusPlus11) {
3546 BadAllocType = Context.getCanonicalTagType(getStdBadAlloc());
3547 assert(StdBadAlloc && "Must have std::bad_alloc declared");
3549 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3550 }
3551 if (getLangOpts().NewInfallible) {
3553 }
3554 } else {
3555 EPI.ExceptionSpec =
3557 }
3558
3559 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3560 // The MSVC STL has explicit cdecl on its (host-side) allocation function
3561 // specializations for the allocation, so in order to prevent a CC clash
3562 // we use the host's CC, if available, or CC_C as a fallback, for the
3563 // host-side implicit decls, knowing these do not get emitted when compiling
3564 // for device.
3565 if (getLangOpts().CUDAIsDevice && ExtraAttr &&
3566 isa<CUDAHostAttr>(ExtraAttr) &&
3567 Context.getTargetInfo().getTriple().isSPIRV()) {
3568 if (auto *ATI = Context.getAuxTargetInfo())
3569 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(ATI->getDefaultCallingConv());
3570 else
3572 }
3573 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3575 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3576 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3577 true);
3578 Alloc->setImplicit();
3579 // Global allocation functions should always be visible.
3580 Alloc->setVisibleDespiteOwningModule();
3581
3582 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible &&
3583 !getLangOpts().CheckNew)
3584 Alloc->addAttr(
3585 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3586
3587 // C++ [basic.stc.dynamic.general]p2:
3588 // The library provides default definitions for the global allocation
3589 // and deallocation functions. Some global allocation and deallocation
3590 // functions are replaceable ([new.delete]); these are attached to the
3591 // global module ([module.unit]).
3592 //
3593 // In the language wording, these functions are attched to the global
3594 // module all the time. But in the implementation, the global module
3595 // is only meaningful when we're in a module unit. So here we attach
3596 // these allocation functions to global module conditionally.
3597 if (TheGlobalModuleFragment) {
3598 Alloc->setModuleOwnershipKind(
3600 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3601 }
3602
3603 if (LangOpts.hasGlobalAllocationFunctionVisibility())
3604 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3605 Context, LangOpts.hasHiddenGlobalAllocationFunctionVisibility()
3606 ? VisibilityAttr::Hidden
3607 : LangOpts.hasProtectedGlobalAllocationFunctionVisibility()
3608 ? VisibilityAttr::Protected
3609 : VisibilityAttr::Default));
3610
3612 for (QualType T : Params) {
3613 ParamDecls.push_back(ParmVarDecl::Create(
3614 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3615 /*TInfo=*/nullptr, SC_None, nullptr));
3616 ParamDecls.back()->setImplicit();
3617 }
3618 Alloc->setParams(ParamDecls);
3619 if (ExtraAttr)
3620 Alloc->addAttr(ExtraAttr);
3622 Context.getTranslationUnitDecl()->addDecl(Alloc);
3623 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3624 };
3625
3626 if (!LangOpts.CUDA)
3627 CreateAllocationFunctionDecl(nullptr);
3628 else {
3629 // Host and device get their own declaration so each can be
3630 // defined or re-declared independently.
3631 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3632 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3633 }
3634}
3635
3639 DeclarationName Name, bool Diagnose) {
3641
3642 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3643 LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete,
3645
3646 // FIXME: It's possible for this to result in ambiguity, through a
3647 // user-declared variadic operator delete or the enable_if attribute. We
3648 // should probably not consider those cases to be usual deallocation
3649 // functions. But for now we just make an arbitrary choice in that case.
3650 auto Result = resolveDeallocationOverload(*this, FoundDelete, IDP, StartLoc);
3651 if (!Result)
3652 return nullptr;
3653
3654 if (CheckDeleteOperator(*this, StartLoc, StartLoc, Diagnose,
3655 FoundDelete.getNamingClass(), Result.Found,
3656 Result.FD))
3657 return nullptr;
3658
3659 assert(Result.FD && "operator delete missing from global scope?");
3660 return Result.FD;
3661}
3662
3664 SourceLocation Loc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal,
3665 DeclarationName Name) {
3666
3667 FunctionDecl *OperatorDelete = nullptr;
3668 CanQualType DeallocType = Context.getCanonicalTagType(RD);
3672
3673 if (!LookForGlobal) {
3674 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, IDP, Diagnose))
3675 return nullptr;
3676
3677 if (OperatorDelete)
3678 return OperatorDelete;
3679 }
3680
3681 // If there's no class-specific operator delete, look up the global
3682 // non-array delete.
3684 hasNewExtendedAlignment(*this, DeallocType));
3686 return FindUsualDeallocationFunction(Loc, IDP, Name, Diagnose);
3687}
3688
3690 DeclarationName Name,
3691 FunctionDecl *&Operator,
3693 bool Diagnose) {
3694 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3695 // Try to find operator delete/operator delete[] in class scope.
3697
3698 if (Found.isAmbiguous()) {
3699 if (!Diagnose)
3700 Found.suppressDiagnostics();
3701 return true;
3702 }
3703
3704 Found.suppressDiagnostics();
3705
3707 hasNewExtendedAlignment(*this, Context.getCanonicalTagType(RD)))
3709
3710 // C++17 [expr.delete]p10:
3711 // If the deallocation functions have class scope, the one without a
3712 // parameter of type std::size_t is selected.
3714 resolveDeallocationOverload(*this, Found, IDP, StartLoc, &Matches);
3715
3716 // If we could find an overload, use it.
3717 if (Matches.size() == 1) {
3718 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3719 return CheckDeleteOperator(*this, StartLoc, StartLoc, Diagnose,
3720 Found.getNamingClass(), Matches[0].Found,
3721 Operator);
3722 }
3723
3724 // We found multiple suitable operators; complain about the ambiguity.
3725 // FIXME: The standard doesn't say to do this; it appears that the intent
3726 // is that this should never happen.
3727 if (!Matches.empty()) {
3728 if (Diagnose) {
3729 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3730 << Name << RD;
3731 for (auto &Match : Matches)
3732 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3733 }
3734 return true;
3735 }
3736
3737 // We did find operator delete/operator delete[] declarations, but
3738 // none of them were suitable.
3739 if (!Found.empty()) {
3740 if (Diagnose) {
3741 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3742 << Name << RD;
3743
3744 for (NamedDecl *D : Found)
3745 Diag(D->getUnderlyingDecl()->getLocation(),
3746 diag::note_member_declared_here) << Name;
3747 }
3748 return true;
3749 }
3750
3751 Operator = nullptr;
3752 return false;
3753}
3754
3755namespace {
3756/// Checks whether delete-expression, and new-expression used for
3757/// initializing deletee have the same array form.
3758class MismatchingNewDeleteDetector {
3759public:
3760 enum MismatchResult {
3761 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3762 NoMismatch,
3763 /// Indicates that variable is initialized with mismatching form of \a new.
3764 VarInitMismatches,
3765 /// Indicates that member is initialized with mismatching form of \a new.
3766 MemberInitMismatches,
3767 /// Indicates that 1 or more constructors' definitions could not been
3768 /// analyzed, and they will be checked again at the end of translation unit.
3769 AnalyzeLater
3770 };
3771
3772 /// \param EndOfTU True, if this is the final analysis at the end of
3773 /// translation unit. False, if this is the initial analysis at the point
3774 /// delete-expression was encountered.
3775 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3776 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3777 HasUndefinedConstructors(false) {}
3778
3779 /// Checks whether pointee of a delete-expression is initialized with
3780 /// matching form of new-expression.
3781 ///
3782 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3783 /// point where delete-expression is encountered, then a warning will be
3784 /// issued immediately. If return value is \c AnalyzeLater at the point where
3785 /// delete-expression is seen, then member will be analyzed at the end of
3786 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3787 /// couldn't be analyzed. If at least one constructor initializes the member
3788 /// with matching type of new, the return value is \c NoMismatch.
3789 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3790 /// Analyzes a class member.
3791 /// \param Field Class member to analyze.
3792 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3793 /// for deleting the \p Field.
3794 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3795 FieldDecl *Field;
3796 /// List of mismatching new-expressions used for initialization of the pointee
3797 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3798 /// Indicates whether delete-expression was in array form.
3799 bool IsArrayForm;
3800
3801private:
3802 const bool EndOfTU;
3803 /// Indicates that there is at least one constructor without body.
3804 bool HasUndefinedConstructors;
3805 /// Returns \c CXXNewExpr from given initialization expression.
3806 /// \param E Expression used for initializing pointee in delete-expression.
3807 /// E can be a single-element \c InitListExpr consisting of new-expression.
3808 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3809 /// Returns whether member is initialized with mismatching form of
3810 /// \c new either by the member initializer or in-class initialization.
3811 ///
3812 /// If bodies of all constructors are not visible at the end of translation
3813 /// unit or at least one constructor initializes member with the matching
3814 /// form of \c new, mismatch cannot be proven, and this function will return
3815 /// \c NoMismatch.
3816 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3817 /// Returns whether variable is initialized with mismatching form of
3818 /// \c new.
3819 ///
3820 /// If variable is initialized with matching form of \c new or variable is not
3821 /// initialized with a \c new expression, this function will return true.
3822 /// If variable is initialized with mismatching form of \c new, returns false.
3823 /// \param D Variable to analyze.
3824 bool hasMatchingVarInit(const DeclRefExpr *D);
3825 /// Checks whether the constructor initializes pointee with mismatching
3826 /// form of \c new.
3827 ///
3828 /// Returns true, if member is initialized with matching form of \c new in
3829 /// member initializer list. Returns false, if member is initialized with the
3830 /// matching form of \c new in this constructor's initializer or given
3831 /// constructor isn't defined at the point where delete-expression is seen, or
3832 /// member isn't initialized by the constructor.
3833 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3834 /// Checks whether member is initialized with matching form of
3835 /// \c new in member initializer list.
3836 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3837 /// Checks whether member is initialized with mismatching form of \c new by
3838 /// in-class initializer.
3839 MismatchResult analyzeInClassInitializer();
3840};
3841}
3842
3843MismatchingNewDeleteDetector::MismatchResult
3844MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3845 NewExprs.clear();
3846 assert(DE && "Expected delete-expression");
3847 IsArrayForm = DE->isArrayForm();
3848 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3849 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3850 return analyzeMemberExpr(ME);
3851 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3852 if (!hasMatchingVarInit(D))
3853 return VarInitMismatches;
3854 }
3855 return NoMismatch;
3856}
3857
3858const CXXNewExpr *
3859MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3860 assert(E != nullptr && "Expected a valid initializer expression");
3861 E = E->IgnoreParenImpCasts();
3862 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3863 if (ILE->getNumInits() == 1)
3864 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3865 }
3866
3867 return dyn_cast_or_null<const CXXNewExpr>(E);
3868}
3869
3870bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3871 const CXXCtorInitializer *CI) {
3872 const CXXNewExpr *NE = nullptr;
3873 if (Field == CI->getMember() &&
3874 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3875 if (NE->isArray() == IsArrayForm)
3876 return true;
3877 else
3878 NewExprs.push_back(NE);
3879 }
3880 return false;
3881}
3882
3883bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3884 const CXXConstructorDecl *CD) {
3885 if (CD->isImplicit())
3886 return false;
3887 const FunctionDecl *Definition = CD;
3889 HasUndefinedConstructors = true;
3890 return EndOfTU;
3891 }
3892 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3893 if (hasMatchingNewInCtorInit(CI))
3894 return true;
3895 }
3896 return false;
3897}
3898
3899MismatchingNewDeleteDetector::MismatchResult
3900MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3901 assert(Field != nullptr && "This should be called only for members");
3902 const Expr *InitExpr = Field->getInClassInitializer();
3903 if (!InitExpr)
3904 return EndOfTU ? NoMismatch : AnalyzeLater;
3905 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3906 if (NE->isArray() != IsArrayForm) {
3907 NewExprs.push_back(NE);
3908 return MemberInitMismatches;
3909 }
3910 }
3911 return NoMismatch;
3912}
3913
3914MismatchingNewDeleteDetector::MismatchResult
3915MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3916 bool DeleteWasArrayForm) {
3917 assert(Field != nullptr && "Analysis requires a valid class member.");
3918 this->Field = Field;
3919 IsArrayForm = DeleteWasArrayForm;
3920 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3921 for (const auto *CD : RD->ctors()) {
3922 if (hasMatchingNewInCtor(CD))
3923 return NoMismatch;
3924 }
3925 if (HasUndefinedConstructors)
3926 return EndOfTU ? NoMismatch : AnalyzeLater;
3927 if (!NewExprs.empty())
3928 return MemberInitMismatches;
3929 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3930 : NoMismatch;
3931}
3932
3933MismatchingNewDeleteDetector::MismatchResult
3934MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3935 assert(ME != nullptr && "Expected a member expression");
3936 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3937 return analyzeField(F, IsArrayForm);
3938 return NoMismatch;
3939}
3940
3941bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3942 const CXXNewExpr *NE = nullptr;
3943 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3944 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3945 NE->isArray() != IsArrayForm) {
3946 NewExprs.push_back(NE);
3947 }
3948 }
3949 return NewExprs.empty();
3950}
3951
3952static void
3954 const MismatchingNewDeleteDetector &Detector) {
3955 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3956 FixItHint H;
3957 if (!Detector.IsArrayForm)
3958 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3959 else {
3961 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3962 SemaRef.getLangOpts(), true);
3963 if (RSquare.isValid())
3964 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3965 }
3966 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3967 << Detector.IsArrayForm << H;
3968
3969 for (const auto *NE : Detector.NewExprs)
3970 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3971 << Detector.IsArrayForm;
3972}
3973
3974void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3975 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3976 return;
3977 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3978 switch (Detector.analyzeDeleteExpr(DE)) {
3979 case MismatchingNewDeleteDetector::VarInitMismatches:
3980 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3981 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3982 break;
3983 }
3984 case MismatchingNewDeleteDetector::AnalyzeLater: {
3985 DeleteExprs[Detector.Field].push_back(
3986 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3987 break;
3988 }
3989 case MismatchingNewDeleteDetector::NoMismatch:
3990 break;
3991 }
3992}
3993
3994void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3995 bool DeleteWasArrayForm) {
3996 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3997 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3998 case MismatchingNewDeleteDetector::VarInitMismatches:
3999 llvm_unreachable("This analysis should have been done for class members.");
4000 case MismatchingNewDeleteDetector::AnalyzeLater:
4001 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
4002 "translation unit.");
4003 case MismatchingNewDeleteDetector::MemberInitMismatches:
4004 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
4005 break;
4006 case MismatchingNewDeleteDetector::NoMismatch:
4007 break;
4008 }
4009}
4010
4012Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
4013 bool ArrayForm, Expr *ExE) {
4014 // C++ [expr.delete]p1:
4015 // The operand shall have a pointer type, or a class type having a single
4016 // non-explicit conversion function to a pointer type. The result has type
4017 // void.
4018 //
4019 // DR599 amends "pointer type" to "pointer to object type" in both cases.
4020
4021 ExprResult Ex = ExE;
4022 FunctionDecl *OperatorDelete = nullptr;
4023 bool ArrayFormAsWritten = ArrayForm;
4024 bool UsualArrayDeleteWantsSize = false;
4025
4026 if (!Ex.get()->isTypeDependent()) {
4027 // Perform lvalue-to-rvalue cast, if needed.
4028 Ex = DefaultLvalueConversion(Ex.get());
4029 if (Ex.isInvalid())
4030 return ExprError();
4031
4032 QualType Type = Ex.get()->getType();
4033
4034 class DeleteConverter : public ContextualImplicitConverter {
4035 public:
4036 DeleteConverter() : ContextualImplicitConverter(false, true) {}
4037
4038 bool match(QualType ConvType) override {
4039 // FIXME: If we have an operator T* and an operator void*, we must pick
4040 // the operator T*.
4041 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4042 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
4043 return true;
4044 return false;
4045 }
4046
4047 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
4048 QualType T) override {
4049 return S.Diag(Loc, diag::err_delete_operand) << T;
4050 }
4051
4052 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
4053 QualType T) override {
4054 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
4055 }
4056
4057 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
4058 QualType T,
4059 QualType ConvTy) override {
4060 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
4061 }
4062
4063 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
4064 QualType ConvTy) override {
4065 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
4066 << ConvTy;
4067 }
4068
4069 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
4070 QualType T) override {
4071 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
4072 }
4073
4074 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
4075 QualType ConvTy) override {
4076 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
4077 << ConvTy;
4078 }
4079
4080 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
4081 QualType T,
4082 QualType ConvTy) override {
4083 llvm_unreachable("conversion functions are permitted");
4084 }
4085 } Converter;
4086
4087 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
4088 if (Ex.isInvalid())
4089 return ExprError();
4090 Type = Ex.get()->getType();
4091 if (!Converter.match(Type))
4092 // FIXME: PerformContextualImplicitConversion should return ExprError
4093 // itself in this case.
4094 return ExprError();
4095
4097 QualType PointeeElem = Context.getBaseElementType(Pointee);
4098
4099 if (Pointee.getAddressSpace() != LangAS::Default &&
4100 !getLangOpts().OpenCLCPlusPlus)
4101 return Diag(Ex.get()->getBeginLoc(),
4102 diag::err_address_space_qualified_delete)
4103 << Pointee.getUnqualifiedType()
4105
4106 CXXRecordDecl *PointeeRD = nullptr;
4107 if (Pointee->isVoidType() && !isSFINAEContext()) {
4108 // The C++ standard bans deleting a pointer to a non-object type, which
4109 // effectively bans deletion of "void*". However, most compilers support
4110 // this, so we treat it as a warning unless we're in a SFINAE context.
4111 // But we still prohibit this since C++26.
4112 Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete
4113 : diag::ext_delete_void_ptr_operand)
4114 << (LangOpts.CPlusPlus26 ? Pointee : Type)
4115 << Ex.get()->getSourceRange();
4116 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
4117 Pointee->isSizelessType()) {
4118 return ExprError(Diag(StartLoc, diag::err_delete_operand)
4119 << Type << Ex.get()->getSourceRange());
4120 } else if (!Pointee->isDependentType()) {
4121 // FIXME: This can result in errors if the definition was imported from a
4122 // module but is hidden.
4123 if (Pointee->isEnumeralType() ||
4124 !RequireCompleteType(StartLoc, Pointee,
4125 LangOpts.CPlusPlus26
4126 ? diag::err_delete_incomplete
4127 : diag::warn_delete_incomplete,
4128 Ex.get())) {
4129 PointeeRD = PointeeElem->getAsCXXRecordDecl();
4130 }
4131 }
4132
4133 if (Pointee->isArrayType() && !ArrayForm) {
4134 Diag(StartLoc, diag::warn_delete_array_type)
4135 << Type << Ex.get()->getSourceRange()
4137 ArrayForm = true;
4138 }
4139
4140 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
4141 ArrayForm ? OO_Array_Delete : OO_Delete);
4142
4143 if (PointeeRD) {
4147 if (!UseGlobal &&
4148 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
4149 OperatorDelete, IDP))
4150 return ExprError();
4151
4152 // If we're allocating an array of records, check whether the
4153 // usual operator delete[] has a size_t parameter.
4154 if (ArrayForm) {
4155 // If the user specifically asked to use the global allocator,
4156 // we'll need to do the lookup into the class.
4157 if (UseGlobal)
4158 UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize(
4159 *this, StartLoc, IDP.PassTypeIdentity, PointeeElem);
4160
4161 // Otherwise, the usual operator delete[] should be the
4162 // function we just found.
4163 else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete)) {
4164 UsualDeallocFnInfo UDFI(
4165 *this, DeclAccessPair::make(OperatorDelete, AS_public), Pointee,
4166 StartLoc);
4167 UsualArrayDeleteWantsSize = isSizedDeallocation(UDFI.IDP.PassSize);
4168 }
4169 }
4170
4171 if (!PointeeRD->hasIrrelevantDestructor()) {
4172 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
4173 if (Dtor->isCalledByDelete(OperatorDelete)) {
4174 MarkFunctionReferenced(StartLoc, Dtor);
4175 if (DiagnoseUseOfDecl(Dtor, StartLoc))
4176 return ExprError();
4177 }
4178 }
4179 }
4180
4181 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
4182 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
4183 /*WarnOnNonAbstractTypes=*/!ArrayForm,
4184 SourceLocation());
4185 }
4186
4187 if (!OperatorDelete) {
4188 if (getLangOpts().OpenCLCPlusPlus) {
4189 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
4190 return ExprError();
4191 }
4192
4193 bool IsComplete = isCompleteType(StartLoc, Pointee);
4194 bool CanProvideSize =
4195 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
4196 Pointee.isDestructedType());
4197 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
4198
4199 // Look for a global declaration.
4202 alignedAllocationModeFromBool(Overaligned),
4203 sizedDeallocationModeFromBool(CanProvideSize)};
4204 OperatorDelete = FindUsualDeallocationFunction(StartLoc, IDP, DeleteName);
4205 if (!OperatorDelete)
4206 return ExprError();
4207 }
4208
4209 if (OperatorDelete->isInvalidDecl())
4210 return ExprError();
4211
4212 MarkFunctionReferenced(StartLoc, OperatorDelete);
4213
4214 // Check access and ambiguity of destructor if we're going to call it.
4215 // Note that this is required even for a virtual delete.
4216 bool IsVirtualDelete = false;
4217 if (PointeeRD) {
4218 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
4219 if (Dtor->isCalledByDelete(OperatorDelete))
4220 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
4221 PDiag(diag::err_access_dtor) << PointeeElem);
4222 IsVirtualDelete = Dtor->isVirtual();
4223 }
4224 }
4225
4226 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
4227
4228 unsigned AddressParamIdx = 0;
4229 if (OperatorDelete->isTypeAwareOperatorNewOrDelete()) {
4230 QualType TypeIdentity = OperatorDelete->getParamDecl(0)->getType();
4231 if (RequireCompleteType(StartLoc, TypeIdentity,
4232 diag::err_incomplete_type))
4233 return ExprError();
4234 AddressParamIdx = 1;
4235 }
4236
4237 // Convert the operand to the type of the first parameter of operator
4238 // delete. This is only necessary if we selected a destroying operator
4239 // delete that we are going to call (non-virtually); converting to void*
4240 // is trivial and left to AST consumers to handle.
4241 QualType ParamType =
4242 OperatorDelete->getParamDecl(AddressParamIdx)->getType();
4243 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
4244 Qualifiers Qs = Pointee.getQualifiers();
4245 if (Qs.hasCVRQualifiers()) {
4246 // Qualifiers are irrelevant to this conversion; we're only looking
4247 // for access and ambiguity.
4249 QualType Unqual = Context.getPointerType(
4250 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
4251 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
4252 }
4253 Ex = PerformImplicitConversion(Ex.get(), ParamType,
4255 if (Ex.isInvalid())
4256 return ExprError();
4257 }
4258 }
4259
4261 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
4262 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
4263 AnalyzeDeleteExprMismatch(Result);
4264 return Result;
4265}
4266
4268 bool IsDelete,
4269 FunctionDecl *&Operator) {
4270
4272 IsDelete ? OO_Delete : OO_New);
4273
4274 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
4276 assert(!R.empty() && "implicitly declared allocation functions not found");
4277 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
4278
4279 // We do our own custom access checks below.
4280 R.suppressDiagnostics();
4281
4282 SmallVector<Expr *, 8> Args(TheCall->arguments());
4283 OverloadCandidateSet Candidates(R.getNameLoc(),
4285 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
4286 FnOvl != FnOvlEnd; ++FnOvl) {
4287 // Even member operator new/delete are implicitly treated as
4288 // static, so don't use AddMemberCandidate.
4289 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
4290
4291 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
4292 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
4293 /*ExplicitTemplateArgs=*/nullptr, Args,
4294 Candidates,
4295 /*SuppressUserConversions=*/false);
4296 continue;
4297 }
4298
4300 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
4301 /*SuppressUserConversions=*/false);
4302 }
4303
4304 SourceRange Range = TheCall->getSourceRange();
4305
4306 // Do the resolution.
4308 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
4309 case OR_Success: {
4310 // Got one!
4311 FunctionDecl *FnDecl = Best->Function;
4312 assert(R.getNamingClass() == nullptr &&
4313 "class members should not be considered");
4314
4316 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
4317 << (IsDelete ? 1 : 0) << Range;
4318 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
4319 << R.getLookupName() << FnDecl->getSourceRange();
4320 return true;
4321 }
4322
4323 Operator = FnDecl;
4324 return false;
4325 }
4326
4328 Candidates.NoteCandidates(
4329 PartialDiagnosticAt(R.getNameLoc(),
4330 S.PDiag(diag::err_ovl_no_viable_function_in_call)
4331 << R.getLookupName() << Range),
4332 S, OCD_AllCandidates, Args);
4333 return true;
4334
4335 case OR_Ambiguous:
4336 Candidates.NoteCandidates(
4337 PartialDiagnosticAt(R.getNameLoc(),
4338 S.PDiag(diag::err_ovl_ambiguous_call)
4339 << R.getLookupName() << Range),
4340 S, OCD_AmbiguousCandidates, Args);
4341 return true;
4342
4343 case OR_Deleted:
4344 S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(),
4345 Candidates, Best->Function, Args);
4346 return true;
4347 }
4348 llvm_unreachable("Unreachable, bad result from BestViableFunction");
4349}
4350
4351ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
4352 bool IsDelete) {
4353 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4354 if (!getLangOpts().CPlusPlus) {
4355 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
4356 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
4357 << "C++";
4358 return ExprError();
4359 }
4360 // CodeGen assumes it can find the global new and delete to call,
4361 // so ensure that they are declared.
4363
4364 FunctionDecl *OperatorNewOrDelete = nullptr;
4365 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
4366 OperatorNewOrDelete))
4367 return ExprError();
4368 assert(OperatorNewOrDelete && "should be found");
4369
4370 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
4371 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
4372
4373 TheCall->setType(OperatorNewOrDelete->getReturnType());
4374 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4375 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
4376 InitializedEntity Entity =
4379 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
4380 if (Arg.isInvalid())
4381 return ExprError();
4382 TheCall->setArg(i, Arg.get());
4383 }
4384 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
4385 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
4386 "Callee expected to be implicit cast to a builtin function pointer");
4387 Callee->setType(OperatorNewOrDelete->getType());
4388
4389 return TheCallResult;
4390}
4391
4393 bool IsDelete, bool CallCanBeVirtual,
4394 bool WarnOnNonAbstractTypes,
4395 SourceLocation DtorLoc) {
4396 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
4397 return;
4398
4399 // C++ [expr.delete]p3:
4400 // In the first alternative (delete object), if the static type of the
4401 // object to be deleted is different from its dynamic type, the static
4402 // type shall be a base class of the dynamic type of the object to be
4403 // deleted and the static type shall have a virtual destructor or the
4404 // behavior is undefined.
4405 //
4406 const CXXRecordDecl *PointeeRD = dtor->getParent();
4407 // Note: a final class cannot be derived from, no issue there
4408 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
4409 return;
4410
4411 // If the superclass is in a system header, there's nothing that can be done.
4412 // The `delete` (where we emit the warning) can be in a system header,
4413 // what matters for this warning is where the deleted type is defined.
4414 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
4415 return;
4416
4417 QualType ClassType = dtor->getFunctionObjectParameterType();
4418 if (PointeeRD->isAbstract()) {
4419 // If the class is abstract, we warn by default, because we're
4420 // sure the code has undefined behavior.
4421 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
4422 << ClassType;
4423 } else if (WarnOnNonAbstractTypes) {
4424 // Otherwise, if this is not an array delete, it's a bit suspect,
4425 // but not necessarily wrong.
4426 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
4427 << ClassType;
4428 }
4429 if (!IsDelete) {
4430 std::string TypeStr;
4431 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
4432 Diag(DtorLoc, diag::note_delete_non_virtual)
4433 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
4434 }
4435}
4436
4438 SourceLocation StmtLoc,
4439 ConditionKind CK) {
4440 ExprResult E =
4441 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
4442 if (E.isInvalid())
4443 return ConditionError();
4444 E = ActOnFinishFullExpr(E.get(), /*DiscardedValue*/ false);
4445 return ConditionResult(*this, ConditionVar, E,
4447}
4448
4450 SourceLocation StmtLoc,
4451 ConditionKind CK) {
4452 if (ConditionVar->isInvalidDecl())
4453 return ExprError();
4454
4455 QualType T = ConditionVar->getType();
4456
4457 // C++ [stmt.select]p2:
4458 // The declarator shall not specify a function or an array.
4459 if (T->isFunctionType())
4460 return ExprError(Diag(ConditionVar->getLocation(),
4461 diag::err_invalid_use_of_function_type)
4462 << ConditionVar->getSourceRange());
4463 else if (T->isArrayType())
4464 return ExprError(Diag(ConditionVar->getLocation(),
4465 diag::err_invalid_use_of_array_type)
4466 << ConditionVar->getSourceRange());
4467
4469 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
4470 ConditionVar->getLocation());
4471
4472 switch (CK) {
4474 return CheckBooleanCondition(StmtLoc, Condition.get());
4475
4477 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4478
4480 return CheckSwitchCondition(StmtLoc, Condition.get());
4481 }
4482
4483 llvm_unreachable("unexpected condition kind");
4484}
4485
4486ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4487 // C++11 6.4p4:
4488 // The value of a condition that is an initialized declaration in a statement
4489 // other than a switch statement is the value of the declared variable
4490 // implicitly converted to type bool. If that conversion is ill-formed, the
4491 // program is ill-formed.
4492 // The value of a condition that is an expression is the value of the
4493 // expression, implicitly converted to bool.
4494 //
4495 // C++23 8.5.2p2
4496 // If the if statement is of the form if constexpr, the value of the condition
4497 // is contextually converted to bool and the converted expression shall be
4498 // a constant expression.
4499 //
4500
4502 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4503 return E;
4504
4505 E = ActOnFinishFullExpr(E.get(), E.get()->getExprLoc(),
4506 /*DiscardedValue*/ false,
4507 /*IsConstexpr*/ true);
4508 if (E.isInvalid())
4509 return E;
4510
4511 // FIXME: Return this value to the caller so they don't need to recompute it.
4512 llvm::APSInt Cond;
4514 E.get(), &Cond,
4515 diag::err_constexpr_if_condition_expression_is_not_constant);
4516 return E;
4517}
4518
4519bool
4521 // Look inside the implicit cast, if it exists.
4522 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4523 From = Cast->getSubExpr();
4524
4525 // A string literal (2.13.4) that is not a wide string literal can
4526 // be converted to an rvalue of type "pointer to char"; a wide
4527 // string literal can be converted to an rvalue of type "pointer
4528 // to wchar_t" (C++ 4.2p2).
4529 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4530 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4531 if (const BuiltinType *ToPointeeType
4532 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4533 // This conversion is considered only when there is an
4534 // explicit appropriate pointer target type (C++ 4.2p2).
4535 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4536 switch (StrLit->getKind()) {
4540 // We don't allow UTF literals to be implicitly converted
4541 break;
4544 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4545 ToPointeeType->getKind() == BuiltinType::Char_S);
4547 return Context.typesAreCompatible(Context.getWideCharType(),
4548 QualType(ToPointeeType, 0));
4550 assert(false && "Unevaluated string literal in expression");
4551 break;
4552 }
4553 }
4554 }
4555
4556 return false;
4557}
4558
4560 SourceLocation CastLoc,
4561 QualType Ty,
4562 CastKind Kind,
4563 CXXMethodDecl *Method,
4564 DeclAccessPair FoundDecl,
4565 bool HadMultipleCandidates,
4566 Expr *From) {
4567 switch (Kind) {
4568 default: llvm_unreachable("Unhandled cast kind!");
4569 case CK_ConstructorConversion: {
4571 SmallVector<Expr*, 8> ConstructorArgs;
4572
4573 if (S.RequireNonAbstractType(CastLoc, Ty,
4574 diag::err_allocation_of_abstract_type))
4575 return ExprError();
4576
4577 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4578 ConstructorArgs))
4579 return ExprError();
4580
4581 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4583 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4584 return ExprError();
4585
4587 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4588 ConstructorArgs, HadMultipleCandidates,
4589 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4591 if (Result.isInvalid())
4592 return ExprError();
4593
4594 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4595 }
4596
4597 case CK_UserDefinedConversion: {
4598 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
4599
4600 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4601 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4602 return ExprError();
4603
4604 // Create an implicit call expr that calls it.
4606 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4607 HadMultipleCandidates);
4608 if (Result.isInvalid())
4609 return ExprError();
4610 // Record usage of conversion in an implicit cast.
4611 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4612 CK_UserDefinedConversion, Result.get(),
4613 nullptr, Result.get()->getValueKind(),
4615
4616 return S.MaybeBindToTemporary(Result.get());
4617 }
4618 }
4619}
4620
4623 const ImplicitConversionSequence &ICS,
4624 AssignmentAction Action,
4626 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4628 !From->getType()->isRecordType())
4629 return From;
4630
4631 switch (ICS.getKind()) {
4633 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4634 Action, CCK);
4635 if (Res.isInvalid())
4636 return ExprError();
4637 From = Res.get();
4638 break;
4639 }
4640
4642
4645 QualType BeforeToType;
4646 assert(FD && "no conversion function for user-defined conversion seq");
4647 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4648 CastKind = CK_UserDefinedConversion;
4649
4650 // If the user-defined conversion is specified by a conversion function,
4651 // the initial standard conversion sequence converts the source type to
4652 // the implicit object parameter of the conversion function.
4653 BeforeToType = Context.getCanonicalTagType(Conv->getParent());
4654 } else {
4656 CastKind = CK_ConstructorConversion;
4657 // Do no conversion if dealing with ... for the first conversion.
4659 // If the user-defined conversion is specified by a constructor, the
4660 // initial standard conversion sequence converts the source type to
4661 // the type required by the argument of the constructor
4662 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4663 }
4664 }
4665 // Watch out for ellipsis conversion.
4668 From, BeforeToType, ICS.UserDefined.Before,
4670 if (Res.isInvalid())
4671 return ExprError();
4672 From = Res.get();
4673 }
4674
4676 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4679
4680 if (CastArg.isInvalid())
4681 return ExprError();
4682
4683 From = CastArg.get();
4684
4685 // C++ [over.match.oper]p7:
4686 // [...] the second standard conversion sequence of a user-defined
4687 // conversion sequence is not applied.
4689 return From;
4690
4691 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4693 }
4694
4696 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4697 PDiag(diag::err_typecheck_ambiguous_condition)
4698 << From->getSourceRange());
4699 return ExprError();
4700
4703 llvm_unreachable("bad conversion");
4704
4706 AssignConvertType ConvTy =
4707 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4708 bool Diagnosed = DiagnoseAssignmentResult(
4711 : ConvTy,
4712 From->getExprLoc(), ToType, From->getType(), From, Action);
4713 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
4714 return ExprError();
4715 }
4716
4717 // Everything went well.
4718 return From;
4719}
4720
4721// adjustVectorOrConstantMatrixType - Compute the intermediate cast type casting
4722// elements of the from type to the elements of the to type without resizing the
4723// vector or matrix.
4725 QualType FromTy,
4726 QualType ToType,
4727 QualType *ElTy = nullptr) {
4728 QualType ElType = ToType;
4729 if (auto *ToVec = ToType->getAs<VectorType>())
4730 ElType = ToVec->getElementType();
4731 else if (auto *ToMat = ToType->getAs<ConstantMatrixType>())
4732 ElType = ToMat->getElementType();
4733
4734 if (ElTy)
4735 *ElTy = ElType;
4736 if (FromTy->isVectorType()) {
4737 auto *FromVec = FromTy->castAs<VectorType>();
4738 return Context.getExtVectorType(ElType, FromVec->getNumElements());
4739 }
4740 if (FromTy->isConstantMatrixType()) {
4741 auto *FromMat = FromTy->castAs<ConstantMatrixType>();
4742 return Context.getConstantMatrixType(ElType, FromMat->getNumRows(),
4743 FromMat->getNumColumns());
4744 }
4745 return ElType;
4746}
4747
4748/// Check if an integral conversion involves incompatible overflow behavior
4749/// types. Returns true if the conversion is invalid.
4751 QualType ToType, Expr *From) {
4752 const auto *FromOBT = FromType->getAs<OverflowBehaviorType>();
4753 const auto *ToOBT = ToType->getAs<OverflowBehaviorType>();
4754
4755 if (FromOBT && ToOBT &&
4756 FromOBT->getBehaviorKind() != ToOBT->getBehaviorKind()) {
4757 S.Diag(From->getExprLoc(), diag::err_incompatible_obt_kinds_assignment)
4758 << ToType << FromType
4759 << (ToOBT->getBehaviorKind() ==
4760 OverflowBehaviorType::OverflowBehaviorKind::Trap
4761 ? "__ob_trap"
4762 : "__ob_wrap")
4763 << (FromOBT->getBehaviorKind() ==
4764 OverflowBehaviorType::OverflowBehaviorKind::Trap
4765 ? "__ob_trap"
4766 : "__ob_wrap");
4767 return true;
4768 }
4769 return false;
4770}
4771
4774 const StandardConversionSequence& SCS,
4775 AssignmentAction Action,
4777 bool CStyle = (CCK == CheckedConversionKind::CStyleCast ||
4779
4780 // Overall FIXME: we are recomputing too many types here and doing far too
4781 // much extra work. What this means is that we need to keep track of more
4782 // information that is computed when we try the implicit conversion initially,
4783 // so that we don't need to recompute anything here.
4784 QualType FromType = From->getType();
4785
4786 if (SCS.CopyConstructor) {
4787 // FIXME: When can ToType be a reference type?
4788 assert(!ToType->isReferenceType());
4789 if (SCS.Second == ICK_Derived_To_Base) {
4790 SmallVector<Expr*, 8> ConstructorArgs;
4792 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4793 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4794 return ExprError();
4795 return BuildCXXConstructExpr(
4796 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4797 SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs,
4798 /*HadMultipleCandidates*/ false,
4799 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4801 }
4802 return BuildCXXConstructExpr(
4803 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4805 /*HadMultipleCandidates*/ false,
4806 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4808 }
4809
4810 // Resolve overloaded function references.
4811 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4814 true, Found);
4815 if (!Fn)
4816 return ExprError();
4817
4818 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4819 return ExprError();
4820
4822 if (Res.isInvalid())
4823 return ExprError();
4824
4825 // We might get back another placeholder expression if we resolved to a
4826 // builtin.
4827 Res = CheckPlaceholderExpr(Res.get());
4828 if (Res.isInvalid())
4829 return ExprError();
4830
4831 From = Res.get();
4832 FromType = From->getType();
4833 }
4834
4835 // If we're converting to an atomic type, first convert to the corresponding
4836 // non-atomic type.
4837 QualType ToAtomicType;
4838 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4839 ToAtomicType = ToType;
4840 ToType = ToAtomic->getValueType();
4841 }
4842
4843 QualType InitialFromType = FromType;
4844 // Perform the first implicit conversion.
4845 switch (SCS.First) {
4846 case ICK_Identity:
4847 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4848 FromType = FromAtomic->getValueType().getUnqualifiedType();
4849 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4850 From, /*BasePath=*/nullptr, VK_PRValue,
4852 }
4853 break;
4854
4855 case ICK_Lvalue_To_Rvalue: {
4856 assert(From->getObjectKind() != OK_ObjCProperty);
4857 ExprResult FromRes = DefaultLvalueConversion(From);
4858 if (FromRes.isInvalid())
4859 return ExprError();
4860
4861 From = FromRes.get();
4862 FromType = From->getType();
4863 break;
4864 }
4865
4867 FromType = Context.getArrayDecayedType(FromType);
4868 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4869 /*BasePath=*/nullptr, CCK)
4870 .get();
4871 break;
4872
4874 if (ToType->isArrayParameterType()) {
4875 FromType = Context.getArrayParameterType(FromType);
4876 } else if (FromType->isArrayParameterType()) {
4877 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
4878 FromType = APT->getConstantArrayType(Context);
4879 }
4880 From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue,
4881 /*BasePath=*/nullptr, CCK)
4882 .get();
4883 break;
4884
4886 FromType = Context.getPointerType(FromType);
4887 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4888 VK_PRValue, /*BasePath=*/nullptr, CCK)
4889 .get();
4890 break;
4891
4892 default:
4893 llvm_unreachable("Improper first standard conversion");
4894 }
4895
4896 // Perform the second implicit conversion
4897 switch (SCS.Second) {
4898 case ICK_Identity:
4899 // C++ [except.spec]p5:
4900 // [For] assignment to and initialization of pointers to functions,
4901 // pointers to member functions, and references to functions: the
4902 // target entity shall allow at least the exceptions allowed by the
4903 // source value in the assignment or initialization.
4904 switch (Action) {
4907 // Note, function argument passing and returning are initialization.
4912 if (CheckExceptionSpecCompatibility(From, ToType))
4913 return ExprError();
4914 break;
4915
4918 // Casts and implicit conversions are not initialization, so are not
4919 // checked for exception specification mismatches.
4920 break;
4921 }
4922 // Nothing else to do.
4923 break;
4924
4927 QualType ElTy = ToType;
4928 QualType StepTy = ToType;
4929 if (FromType->isVectorType() || ToType->isVectorType() ||
4930 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
4931 StepTy =
4932 adjustVectorOrConstantMatrixType(Context, FromType, ToType, &ElTy);
4933
4934 // Check for incompatible OBT kinds before converting
4935 if (checkIncompatibleOBTConversion(*this, FromType, StepTy, From))
4936 return ExprError();
4937
4938 if (ElTy->isBooleanType()) {
4939 assert(FromType->castAsEnumDecl()->isFixed() &&
4941 "only enums with fixed underlying type can promote to bool");
4942 From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue,
4943 /*BasePath=*/nullptr, CCK)
4944 .get();
4945 } else {
4946 From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue,
4947 /*BasePath=*/nullptr, CCK)
4948 .get();
4949 }
4950 break;
4951 }
4952
4955 QualType StepTy = ToType;
4956 if (FromType->isVectorType() || ToType->isVectorType() ||
4957 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
4958 StepTy = adjustVectorOrConstantMatrixType(Context, FromType, ToType);
4959 From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue,
4960 /*BasePath=*/nullptr, CCK)
4961 .get();
4962 break;
4963 }
4964
4967 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4968 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4969 CastKind CK;
4970 if (FromEl->isRealFloatingType()) {
4971 if (ToEl->isRealFloatingType())
4972 CK = CK_FloatingComplexCast;
4973 else
4974 CK = CK_FloatingComplexToIntegralComplex;
4975 } else if (ToEl->isRealFloatingType()) {
4976 CK = CK_IntegralComplexToFloatingComplex;
4977 } else {
4978 CK = CK_IntegralComplexCast;
4979 }
4980 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4981 CCK)
4982 .get();
4983 break;
4984 }
4985
4986 case ICK_Floating_Integral: {
4987 QualType ElTy = ToType;
4988 QualType StepTy = ToType;
4989 if (FromType->isVectorType() || ToType->isVectorType() ||
4990 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
4991 StepTy =
4992 adjustVectorOrConstantMatrixType(Context, FromType, ToType, &ElTy);
4993 if (ElTy->isRealFloatingType())
4994 From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue,
4995 /*BasePath=*/nullptr, CCK)
4996 .get();
4997 else
4998 From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue,
4999 /*BasePath=*/nullptr, CCK)
5000 .get();
5001 break;
5002 }
5003
5005 assert((FromType->isFixedPointType() || ToType->isFixedPointType()) &&
5006 "Attempting implicit fixed point conversion without a fixed "
5007 "point operand");
5008 if (FromType->isFloatingType())
5009 From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint,
5010 VK_PRValue,
5011 /*BasePath=*/nullptr, CCK).get();
5012 else if (ToType->isFloatingType())
5013 From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating,
5014 VK_PRValue,
5015 /*BasePath=*/nullptr, CCK).get();
5016 else if (FromType->isIntegralType(Context))
5017 From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint,
5018 VK_PRValue,
5019 /*BasePath=*/nullptr, CCK).get();
5020 else if (ToType->isIntegralType(Context))
5021 From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral,
5022 VK_PRValue,
5023 /*BasePath=*/nullptr, CCK).get();
5024 else if (ToType->isBooleanType())
5025 From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean,
5026 VK_PRValue,
5027 /*BasePath=*/nullptr, CCK).get();
5028 else
5029 From = ImpCastExprToType(From, ToType, CK_FixedPointCast,
5030 VK_PRValue,
5031 /*BasePath=*/nullptr, CCK).get();
5032 break;
5033
5035 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
5036 /*BasePath=*/nullptr, CCK).get();
5037 break;
5038
5041 if (SCS.IncompatibleObjC && Action != AssignmentAction::Casting) {
5042 // Diagnose incompatible Objective-C conversions
5043 if (Action == AssignmentAction::Initializing ||
5045 Diag(From->getBeginLoc(),
5046 diag::ext_typecheck_convert_incompatible_pointer)
5047 << ToType << From->getType() << Action << From->getSourceRange()
5048 << 0;
5049 else
5050 Diag(From->getBeginLoc(),
5051 diag::ext_typecheck_convert_incompatible_pointer)
5052 << From->getType() << ToType << Action << From->getSourceRange()
5053 << 0;
5054
5055 if (From->getType()->isObjCObjectPointerType() &&
5056 ToType->isObjCObjectPointerType())
5058 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
5059 !ObjC().CheckObjCARCUnavailableWeakConversion(ToType,
5060 From->getType())) {
5061 if (Action == AssignmentAction::Initializing)
5062 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
5063 else
5064 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
5065 << (Action == AssignmentAction::Casting) << From->getType()
5066 << ToType << From->getSourceRange();
5067 }
5068
5069 // Defer address space conversion to the third conversion.
5070 QualType FromPteeType = From->getType()->getPointeeType();
5071 QualType ToPteeType = ToType->getPointeeType();
5072 QualType NewToType = ToType;
5073 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
5074 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
5075 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
5076 NewToType = Context.getAddrSpaceQualType(NewToType,
5077 FromPteeType.getAddressSpace());
5078 if (ToType->isObjCObjectPointerType())
5079 NewToType = Context.getObjCObjectPointerType(NewToType);
5080 else if (ToType->isBlockPointerType())
5081 NewToType = Context.getBlockPointerType(NewToType);
5082 else
5083 NewToType = Context.getPointerType(NewToType);
5084 }
5085
5086 CastKind Kind;
5087 CXXCastPath BasePath;
5088 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
5089 return ExprError();
5090
5091 // Make sure we extend blocks if necessary.
5092 // FIXME: doing this here is really ugly.
5093 if (Kind == CK_BlockPointerToObjCPointerCast) {
5094 ExprResult E = From;
5096 From = E.get();
5097 }
5098 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
5099 ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK);
5100 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
5101 .get();
5102 break;
5103 }
5104
5105 case ICK_Pointer_Member: {
5106 CastKind Kind;
5107 CXXCastPath BasePath;
5109 From->getType(), ToType->castAs<MemberPointerType>(), Kind, BasePath,
5110 From->getExprLoc(), From->getSourceRange(), CStyle,
5113 assert((Kind != CK_NullToMemberPointer ||
5116 "Expr must be null pointer constant!");
5117 break;
5119 break;
5121 llvm_unreachable("unexpected result");
5123 llvm_unreachable("Should not have been called if derivation isn't OK.");
5126 return ExprError();
5127 }
5128 if (CheckExceptionSpecCompatibility(From, ToType))
5129 return ExprError();
5130
5131 From =
5132 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
5133 break;
5134 }
5135
5137 // Perform half-to-boolean conversion via float.
5138 if (From->getType()->isHalfType()) {
5139 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
5140 FromType = Context.FloatTy;
5141 }
5142 QualType ElTy = FromType;
5143 QualType StepTy = ToType;
5144 if (FromType->isVectorType())
5145 ElTy = FromType->castAs<VectorType>()->getElementType();
5146 else if (FromType->isConstantMatrixType())
5147 ElTy = FromType->castAs<ConstantMatrixType>()->getElementType();
5148 if (getLangOpts().HLSL) {
5149 if (FromType->isVectorType() || ToType->isVectorType() ||
5150 FromType->isConstantMatrixType() || ToType->isConstantMatrixType())
5151 StepTy = adjustVectorOrConstantMatrixType(Context, FromType, ToType);
5152 }
5153
5154 From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy),
5155 VK_PRValue,
5156 /*BasePath=*/nullptr, CCK)
5157 .get();
5158 break;
5159 }
5160
5161 case ICK_Derived_To_Base: {
5162 CXXCastPath BasePath;
5164 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
5165 From->getSourceRange(), &BasePath, CStyle))
5166 return ExprError();
5167
5168 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
5169 CK_DerivedToBase, From->getValueKind(),
5170 &BasePath, CCK).get();
5171 break;
5172 }
5173
5175 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
5176 /*BasePath=*/nullptr, CCK)
5177 .get();
5178 break;
5179
5182 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
5183 /*BasePath=*/nullptr, CCK)
5184 .get();
5185 break;
5186
5187 case ICK_Vector_Splat: {
5188 // Vector splat from any arithmetic type to a vector.
5189 Expr *Elem = prepareVectorSplat(ToType, From).get();
5190 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
5191 /*BasePath=*/nullptr, CCK)
5192 .get();
5193 break;
5194 }
5195
5196 case ICK_Complex_Real:
5197 // Case 1. x -> _Complex y
5198 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
5199 QualType ElType = ToComplex->getElementType();
5200 bool isFloatingComplex = ElType->isRealFloatingType();
5201
5202 // x -> y
5203 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
5204 // do nothing
5205 } else if (From->getType()->isRealFloatingType()) {
5206 From = ImpCastExprToType(From, ElType,
5207 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
5208 } else {
5209 assert(From->getType()->isIntegerType());
5210 From = ImpCastExprToType(From, ElType,
5211 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
5212 }
5213 // y -> _Complex y
5214 From = ImpCastExprToType(From, ToType,
5215 isFloatingComplex ? CK_FloatingRealToComplex
5216 : CK_IntegralRealToComplex).get();
5217
5218 // Case 2. _Complex x -> y
5219 } else {
5220 auto *FromComplex = From->getType()->castAs<ComplexType>();
5221 QualType ElType = FromComplex->getElementType();
5222 bool isFloatingComplex = ElType->isRealFloatingType();
5223
5224 // _Complex x -> x
5225 From = ImpCastExprToType(From, ElType,
5226 isFloatingComplex ? CK_FloatingComplexToReal
5227 : CK_IntegralComplexToReal,
5228 VK_PRValue, /*BasePath=*/nullptr, CCK)
5229 .get();
5230
5231 // x -> y
5232 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
5233 // do nothing
5234 } else if (ToType->isRealFloatingType()) {
5235 From = ImpCastExprToType(From, ToType,
5236 isFloatingComplex ? CK_FloatingCast
5237 : CK_IntegralToFloating,
5238 VK_PRValue, /*BasePath=*/nullptr, CCK)
5239 .get();
5240 } else {
5241 assert(ToType->isIntegerType());
5242 From = ImpCastExprToType(From, ToType,
5243 isFloatingComplex ? CK_FloatingToIntegral
5244 : CK_IntegralCast,
5245 VK_PRValue, /*BasePath=*/nullptr, CCK)
5246 .get();
5247 }
5248 }
5249 break;
5250
5252 LangAS AddrSpaceL =
5254 LangAS AddrSpaceR =
5256 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR,
5257 getASTContext()) &&
5258 "Invalid cast");
5259 CastKind Kind =
5260 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
5261 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
5262 VK_PRValue, /*BasePath=*/nullptr, CCK)
5263 .get();
5264 break;
5265 }
5266
5268 ExprResult FromRes = From;
5269 AssignConvertType ConvTy =
5271 if (FromRes.isInvalid())
5272 return ExprError();
5273 From = FromRes.get();
5274 assert((ConvTy == AssignConvertType::Compatible) &&
5275 "Improper transparent union conversion");
5276 (void)ConvTy;
5277 break;
5278 }
5279
5282 From = ImpCastExprToType(From, ToType,
5283 CK_ZeroToOCLOpaqueType,
5284 From->getValueKind()).get();
5285 break;
5286
5291 case ICK_Qualification:
5300 llvm_unreachable("Improper second standard conversion");
5301 }
5302
5303 if (SCS.Dimension != ICK_Identity) {
5304 // If SCS.Element is not ICK_Identity the To and From types must be HLSL
5305 // vectors or matrices.
5306 assert(
5307 (ToType->isVectorType() || ToType->isConstantMatrixType() ||
5308 ToType->isBuiltinType()) &&
5309 "Dimension conversion output must be vector, matrix, or scalar type.");
5310 switch (SCS.Dimension) {
5311 case ICK_HLSL_Vector_Splat: {
5312 // Vector splat from any arithmetic type to a vector.
5313 Expr *Elem = prepareVectorSplat(ToType, From).get();
5314 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
5315 /*BasePath=*/nullptr, CCK)
5316 .get();
5317 break;
5318 }
5319 case ICK_HLSL_Matrix_Splat: {
5320 // Matrix splat from any arithmetic type to a matrix.
5321 Expr *Elem = prepareMatrixSplat(ToType, From).get();
5322 From =
5323 ImpCastExprToType(Elem, ToType, CK_HLSLAggregateSplatCast, VK_PRValue,
5324 /*BasePath=*/nullptr, CCK)
5325 .get();
5326 break;
5327 }
5329 // Note: HLSL built-in vectors are ExtVectors. Since this truncates a
5330 // vector to a smaller vector or to a scalar, this can only operate on
5331 // arguments where the source type is an ExtVector and the destination
5332 // type is destination type is either an ExtVectorType or a builtin scalar
5333 // type.
5334 auto *FromVec = From->getType()->castAs<VectorType>();
5335 QualType TruncTy = FromVec->getElementType();
5336 if (auto *ToVec = ToType->getAs<VectorType>())
5337 TruncTy = Context.getExtVectorType(TruncTy, ToVec->getNumElements());
5338 From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation,
5339 From->getValueKind())
5340 .get();
5341
5342 break;
5343 }
5345 auto *FromMat = From->getType()->castAs<ConstantMatrixType>();
5346 QualType TruncTy = FromMat->getElementType();
5347 if (auto *ToMat = ToType->getAs<ConstantMatrixType>())
5348 TruncTy = Context.getConstantMatrixType(TruncTy, ToMat->getNumRows(),
5349 ToMat->getNumColumns());
5350 From = ImpCastExprToType(From, TruncTy, CK_HLSLMatrixTruncation,
5351 From->getValueKind())
5352 .get();
5353 break;
5354 }
5355 case ICK_Identity:
5356 default:
5357 llvm_unreachable("Improper element standard conversion");
5358 }
5359 }
5360
5361 switch (SCS.Third) {
5362 case ICK_Identity:
5363 // Nothing to do.
5364 break;
5365
5367 // If both sides are functions (or pointers/references to them), there could
5368 // be incompatible exception declarations.
5369 if (CheckExceptionSpecCompatibility(From, ToType))
5370 return ExprError();
5371
5372 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
5373 /*BasePath=*/nullptr, CCK)
5374 .get();
5375 break;
5376
5377 case ICK_Qualification: {
5378 ExprValueKind VK = From->getValueKind();
5379 CastKind CK = CK_NoOp;
5380
5381 if (ToType->isReferenceType() &&
5382 ToType->getPointeeType().getAddressSpace() !=
5383 From->getType().getAddressSpace())
5384 CK = CK_AddressSpaceConversion;
5385
5386 if (ToType->isPointerType() &&
5387 ToType->getPointeeType().getAddressSpace() !=
5389 CK = CK_AddressSpaceConversion;
5390
5391 if (!isCast(CCK) &&
5392 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
5394 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
5395 << InitialFromType << ToType;
5396 }
5397
5398 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
5399 /*BasePath=*/nullptr, CCK)
5400 .get();
5401
5403 !getLangOpts().WritableStrings) {
5404 Diag(From->getBeginLoc(),
5406 ? diag::ext_deprecated_string_literal_conversion
5407 : diag::warn_deprecated_string_literal_conversion)
5408 << ToType.getNonReferenceType();
5409 }
5410
5411 break;
5412 }
5413
5414 default:
5415 llvm_unreachable("Improper third standard conversion");
5416 }
5417
5418 // If this conversion sequence involved a scalar -> atomic conversion, perform
5419 // that conversion now.
5420 if (!ToAtomicType.isNull()) {
5421 assert(Context.hasSameType(
5422 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
5423 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
5424 VK_PRValue, nullptr, CCK)
5425 .get();
5426 }
5427
5428 // Materialize a temporary if we're implicitly converting to a reference
5429 // type. This is not required by the C++ rules but is necessary to maintain
5430 // AST invariants.
5431 if (ToType->isReferenceType() && From->isPRValue()) {
5433 if (Res.isInvalid())
5434 return ExprError();
5435 From = Res.get();
5436 }
5437
5438 // If this conversion sequence succeeded and involved implicitly converting a
5439 // _Nullable type to a _Nonnull one, complain.
5440 if (!isCast(CCK))
5441 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
5442 From->getBeginLoc());
5443
5444 return From;
5445}
5446
5449 SourceLocation Loc,
5450 bool isIndirect) {
5451 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&
5452 "placeholders should have been weeded out by now");
5453
5454 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5455 // temporary materialization conversion otherwise.
5456 if (isIndirect)
5457 LHS = DefaultLvalueConversion(LHS.get());
5458 else if (LHS.get()->isPRValue())
5460 if (LHS.isInvalid())
5461 return QualType();
5462
5463 // The RHS always undergoes lvalue conversions.
5464 RHS = DefaultLvalueConversion(RHS.get());
5465 if (RHS.isInvalid()) return QualType();
5466
5467 const char *OpSpelling = isIndirect ? "->*" : ".*";
5468 // C++ 5.5p2
5469 // The binary operator .* [p3: ->*] binds its second operand, which shall
5470 // be of type "pointer to member of T" (where T is a completely-defined
5471 // class type) [...]
5472 QualType RHSType = RHS.get()->getType();
5473 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5474 if (!MemPtr) {
5475 Diag(Loc, diag::err_bad_memptr_rhs)
5476 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5477 return QualType();
5478 }
5479
5480 CXXRecordDecl *RHSClass = MemPtr->getMostRecentCXXRecordDecl();
5481
5482 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5483 // member pointer points must be completely-defined. However, there is no
5484 // reason for this semantic distinction, and the rule is not enforced by
5485 // other compilers. Therefore, we do not check this property, as it is
5486 // likely to be considered a defect.
5487
5488 // C++ 5.5p2
5489 // [...] to its first operand, which shall be of class T or of a class of
5490 // which T is an unambiguous and accessible base class. [p3: a pointer to
5491 // such a class]
5492 QualType LHSType = LHS.get()->getType();
5493 if (isIndirect) {
5494 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5495 LHSType = Ptr->getPointeeType();
5496 else {
5497 Diag(Loc, diag::err_bad_memptr_lhs)
5498 << OpSpelling << 1 << LHSType
5500 return QualType();
5501 }
5502 }
5503 CXXRecordDecl *LHSClass = LHSType->getAsCXXRecordDecl();
5504
5505 if (!declaresSameEntity(LHSClass, RHSClass)) {
5506 // If we want to check the hierarchy, we need a complete type.
5507 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5508 OpSpelling, (int)isIndirect)) {
5509 return QualType();
5510 }
5511
5512 if (!IsDerivedFrom(Loc, LHSClass, RHSClass)) {
5513 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5514 << (int)isIndirect << LHS.get()->getType();
5515 return QualType();
5516 }
5517
5518 // FIXME: use sugared type from member pointer.
5519 CanQualType RHSClassType = Context.getCanonicalTagType(RHSClass);
5520 CXXCastPath BasePath;
5522 LHSType, RHSClassType, Loc,
5523 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5524 &BasePath))
5525 return QualType();
5526
5527 // Cast LHS to type of use.
5528 QualType UseType =
5529 Context.getQualifiedType(RHSClassType, LHSType.getQualifiers());
5530 if (isIndirect)
5531 UseType = Context.getPointerType(UseType);
5532 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
5533 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5534 &BasePath);
5535 }
5536
5538 // Diagnose use of pointer-to-member type which when used as
5539 // the functional cast in a pointer-to-member expression.
5540 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5541 return QualType();
5542 }
5543
5544 // C++ 5.5p2
5545 // The result is an object or a function of the type specified by the
5546 // second operand.
5547 // The cv qualifiers are the union of those in the pointer and the left side,
5548 // in accordance with 5.5p5 and 5.2.5.
5549 QualType Result = MemPtr->getPointeeType();
5550 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5551
5552 // C++0x [expr.mptr.oper]p6:
5553 // In a .* expression whose object expression is an rvalue, the program is
5554 // ill-formed if the second operand is a pointer to member function with
5555 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5556 // expression is an lvalue, the program is ill-formed if the second operand
5557 // is a pointer to member function with ref-qualifier &&.
5558 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5559 switch (Proto->getRefQualifier()) {
5560 case RQ_None:
5561 // Do nothing
5562 break;
5563
5564 case RQ_LValue:
5565 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5566 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5567 // is (exactly) 'const'.
5568 if (Proto->isConst() && !Proto->isVolatile())
5570 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5571 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5572 else
5573 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5574 << RHSType << 1 << LHS.get()->getSourceRange();
5575 }
5576 break;
5577
5578 case RQ_RValue:
5579 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5580 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5581 << RHSType << 0 << LHS.get()->getSourceRange();
5582 break;
5583 }
5584 }
5585
5586 // C++ [expr.mptr.oper]p6:
5587 // The result of a .* expression whose second operand is a pointer
5588 // to a data member is of the same value category as its
5589 // first operand. The result of a .* expression whose second
5590 // operand is a pointer to a member function is a prvalue. The
5591 // result of an ->* expression is an lvalue if its second operand
5592 // is a pointer to data member and a prvalue otherwise.
5593 if (Result->isFunctionType()) {
5594 VK = VK_PRValue;
5595 return Context.BoundMemberTy;
5596 } else if (isIndirect) {
5597 VK = VK_LValue;
5598 } else {
5599 VK = LHS.get()->getValueKind();
5600 }
5601
5602 return Result;
5603}
5604
5605/// Try to convert a type to another according to C++11 5.16p3.
5606///
5607/// This is part of the parameter validation for the ? operator. If either
5608/// value operand is a class type, the two operands are attempted to be
5609/// converted to each other. This function does the conversion in one direction.
5610/// It returns true if the program is ill-formed and has already been diagnosed
5611/// as such.
5612static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5613 SourceLocation QuestionLoc,
5614 bool &HaveConversion,
5615 QualType &ToType) {
5616 HaveConversion = false;
5617 ToType = To->getType();
5618
5619 InitializationKind Kind =
5621 // C++11 5.16p3
5622 // The process for determining whether an operand expression E1 of type T1
5623 // can be converted to match an operand expression E2 of type T2 is defined
5624 // as follows:
5625 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5626 // implicitly converted to type "lvalue reference to T2", subject to the
5627 // constraint that in the conversion the reference must bind directly to
5628 // an lvalue.
5629 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5630 // implicitly converted to the type "rvalue reference to R2", subject to
5631 // the constraint that the reference must bind directly.
5632 if (To->isGLValue()) {
5633 QualType T = Self.Context.getReferenceQualifiedType(To);
5635
5636 InitializationSequence InitSeq(Self, Entity, Kind, From);
5637 if (InitSeq.isDirectReferenceBinding()) {
5638 ToType = T;
5639 HaveConversion = true;
5640 return false;
5641 }
5642
5643 if (InitSeq.isAmbiguous())
5644 return InitSeq.Diagnose(Self, Entity, Kind, From);
5645 }
5646
5647 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5648 // -- if E1 and E2 have class type, and the underlying class types are
5649 // the same or one is a base class of the other:
5650 QualType FTy = From->getType();
5651 QualType TTy = To->getType();
5652 const RecordType *FRec = FTy->getAsCanonical<RecordType>();
5653 const RecordType *TRec = TTy->getAsCanonical<RecordType>();
5654 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5655 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5656 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5657 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5658 // E1 can be converted to match E2 if the class of T2 is the
5659 // same type as, or a base class of, the class of T1, and
5660 // [cv2 > cv1].
5661 if (FRec == TRec || FDerivedFromT) {
5662 if (TTy.isAtLeastAsQualifiedAs(FTy, Self.getASTContext())) {
5664 InitializationSequence InitSeq(Self, Entity, Kind, From);
5665 if (InitSeq) {
5666 HaveConversion = true;
5667 return false;
5668 }
5669
5670 if (InitSeq.isAmbiguous())
5671 return InitSeq.Diagnose(Self, Entity, Kind, From);
5672 }
5673 }
5674
5675 return false;
5676 }
5677
5678 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5679 // implicitly converted to the type that expression E2 would have
5680 // if E2 were converted to an rvalue (or the type it has, if E2 is
5681 // an rvalue).
5682 //
5683 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5684 // to the array-to-pointer or function-to-pointer conversions.
5685 TTy = TTy.getNonLValueExprType(Self.Context);
5686
5688 InitializationSequence InitSeq(Self, Entity, Kind, From);
5689 HaveConversion = !InitSeq.Failed();
5690 ToType = TTy;
5691 if (InitSeq.isAmbiguous())
5692 return InitSeq.Diagnose(Self, Entity, Kind, From);
5693
5694 return false;
5695}
5696
5697/// Try to find a common type for two according to C++0x 5.16p5.
5698///
5699/// This is part of the parameter validation for the ? operator. If either
5700/// value operand is a class type, overload resolution is used to find a
5701/// conversion to a common type.
5703 SourceLocation QuestionLoc) {
5704 Expr *Args[2] = { LHS.get(), RHS.get() };
5705 OverloadCandidateSet CandidateSet(QuestionLoc,
5707 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5708 CandidateSet);
5709
5711 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5712 case OR_Success: {
5713 // We found a match. Perform the conversions on the arguments and move on.
5714 ExprResult LHSRes = Self.PerformImplicitConversion(
5715 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5717 if (LHSRes.isInvalid())
5718 break;
5719 LHS = LHSRes;
5720
5721 ExprResult RHSRes = Self.PerformImplicitConversion(
5722 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5724 if (RHSRes.isInvalid())
5725 break;
5726 RHS = RHSRes;
5727 if (Best->Function)
5728 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5729 return false;
5730 }
5731
5733
5734 // Emit a better diagnostic if one of the expressions is a null pointer
5735 // constant and the other is a pointer type. In this case, the user most
5736 // likely forgot to take the address of the other expression.
5737 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5738 return true;
5739
5740 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5741 << LHS.get()->getType() << RHS.get()->getType()
5742 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5743 return true;
5744
5745 case OR_Ambiguous:
5746 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5747 << LHS.get()->getType() << RHS.get()->getType()
5748 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5749 // FIXME: Print the possible common types by printing the return types of
5750 // the viable candidates.
5751 break;
5752
5753 case OR_Deleted:
5754 llvm_unreachable("Conditional operator has only built-in overloads");
5755 }
5756 return true;
5757}
5758
5759/// Perform an "extended" implicit conversion as returned by
5760/// TryClassUnification.
5763 InitializationKind Kind =
5765 Expr *Arg = E.get();
5766 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5767 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5768 if (Result.isInvalid())
5769 return true;
5770
5771 E = Result;
5772 return false;
5773}
5774
5775// Check the condition operand of ?: to see if it is valid for the GCC
5776// extension.
5778 QualType CondTy) {
5779 bool IsSVEVectorType = CondTy->isSveVLSBuiltinType();
5780 if (!CondTy->isVectorType() && !CondTy->isExtVectorType() && !IsSVEVectorType)
5781 return false;
5782 const QualType EltTy =
5783 IsSVEVectorType
5784 ? cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx)
5785 : cast<VectorType>(CondTy.getCanonicalType())->getElementType();
5786 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types");
5787 return EltTy->isIntegralType(Ctx);
5788}
5789
5791 ExprResult &RHS,
5792 SourceLocation QuestionLoc) {
5795
5796 QualType CondType = Cond.get()->getType();
5797 QualType LHSType = LHS.get()->getType();
5798 QualType RHSType = RHS.get()->getType();
5799
5800 bool LHSSizelessVector = LHSType->isSizelessVectorType();
5801 bool RHSSizelessVector = RHSType->isSizelessVectorType();
5802 bool LHSIsVector = LHSType->isVectorType() || LHSSizelessVector;
5803 bool RHSIsVector = RHSType->isVectorType() || RHSSizelessVector;
5804
5805 auto GetVectorInfo =
5806 [&](QualType Type) -> std::pair<QualType, llvm::ElementCount> {
5807 if (const auto *VT = Type->getAs<VectorType>())
5808 return std::make_pair(VT->getElementType(),
5809 llvm::ElementCount::getFixed(VT->getNumElements()));
5811 Context.getBuiltinVectorTypeInfo(Type->castAs<BuiltinType>());
5812 return std::make_pair(VectorInfo.ElementType, VectorInfo.EC);
5813 };
5814
5815 auto [CondElementTy, CondElementCount] = GetVectorInfo(CondType);
5816
5817 QualType ResultType;
5818 if (LHSIsVector && RHSIsVector) {
5819 if (CondType->isExtVectorType() != LHSType->isExtVectorType()) {
5820 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
5821 << /*isExtVectorNotSizeless=*/1;
5822 return {};
5823 }
5824
5825 // If both are vector types, they must be the same type.
5826 if (!Context.hasSameType(LHSType, RHSType)) {
5827 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
5828 << LHSType << RHSType;
5829 return {};
5830 }
5831 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
5832 } else if (LHSIsVector || RHSIsVector) {
5833 bool ResultSizeless = LHSSizelessVector || RHSSizelessVector;
5834 if (ResultSizeless != CondType->isSizelessVectorType()) {
5835 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
5836 << /*isExtVectorNotSizeless=*/0;
5837 return {};
5838 }
5839 if (ResultSizeless)
5840 ResultType = CheckSizelessVectorOperands(LHS, RHS, QuestionLoc,
5841 /*IsCompAssign*/ false,
5843 else
5844 ResultType = CheckVectorOperands(
5845 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
5846 /*AllowBoolConversions*/ false,
5847 /*AllowBoolOperation*/ true,
5848 /*ReportInvalid*/ true);
5849 if (ResultType.isNull())
5850 return {};
5851 } else {
5852 // Both are scalar.
5853 LHSType = LHSType.getUnqualifiedType();
5854 RHSType = RHSType.getUnqualifiedType();
5855 QualType ResultElementTy =
5856 Context.hasSameType(LHSType, RHSType)
5857 ? Context.getCommonSugaredType(LHSType, RHSType)
5858 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
5860
5861 if (ResultElementTy->isEnumeralType()) {
5862 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5863 << ResultElementTy;
5864 return {};
5865 }
5866 if (CondType->isExtVectorType()) {
5867 ResultType = Context.getExtVectorType(ResultElementTy,
5868 CondElementCount.getFixedValue());
5869 } else if (CondType->isSizelessVectorType()) {
5870 ResultType = Context.getScalableVectorType(
5871 ResultElementTy, CondElementCount.getKnownMinValue());
5872 // There are not scalable vector type mappings for all element counts.
5873 if (ResultType.isNull()) {
5874 Diag(QuestionLoc, diag::err_conditional_vector_scalar_type_unsupported)
5875 << ResultElementTy << CondType;
5876 return {};
5877 }
5878 } else {
5879 ResultType = Context.getVectorType(ResultElementTy,
5880 CondElementCount.getFixedValue(),
5882 }
5883 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
5884 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
5885 }
5886
5887 assert(!ResultType.isNull() &&
5888 (ResultType->isVectorType() || ResultType->isSizelessVectorType()) &&
5889 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&
5890 "Result should have been a vector type");
5891
5892 auto [ResultElementTy, ResultElementCount] = GetVectorInfo(ResultType);
5893 if (ResultElementCount != CondElementCount) {
5894 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
5895 << ResultType;
5896 return {};
5897 }
5898
5899 // Boolean vectors are permitted outside of OpenCL mode.
5900 if (Context.getTypeSize(ResultElementTy) !=
5901 Context.getTypeSize(CondElementTy) &&
5902 (!CondElementTy->isBooleanType() || LangOpts.OpenCL)) {
5903 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
5904 << CondType << ResultType;
5905 return {};
5906 }
5907
5908 return ResultType;
5909}
5910
5913 ExprObjectKind &OK,
5914 SourceLocation QuestionLoc) {
5915 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
5916 // pointers.
5917
5918 // Assume r-value.
5919 VK = VK_PRValue;
5920 OK = OK_Ordinary;
5921 bool IsVectorConditional =
5923
5924 // C++11 [expr.cond]p1
5925 // The first expression is contextually converted to bool.
5926 if (!Cond.get()->isTypeDependent()) {
5927 ExprResult CondRes = IsVectorConditional
5930 if (CondRes.isInvalid())
5931 return QualType();
5932 Cond = CondRes;
5933 } else {
5934 // To implement C++, the first expression typically doesn't alter the result
5935 // type of the conditional, however the GCC compatible vector extension
5936 // changes the result type to be that of the conditional. Since we cannot
5937 // know if this is a vector extension here, delay the conversion of the
5938 // LHS/RHS below until later.
5939 return Context.DependentTy;
5940 }
5941
5942
5943 // Either of the arguments dependent?
5944 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5945 return Context.DependentTy;
5946
5947 // C++11 [expr.cond]p2
5948 // If either the second or the third operand has type (cv) void, ...
5949 QualType LTy = LHS.get()->getType();
5950 QualType RTy = RHS.get()->getType();
5951 bool LVoid = LTy->isVoidType();
5952 bool RVoid = RTy->isVoidType();
5953 if (LVoid || RVoid) {
5954 // ... one of the following shall hold:
5955 // -- The second or the third operand (but not both) is a (possibly
5956 // parenthesized) throw-expression; the result is of the type
5957 // and value category of the other.
5958 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5959 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5960
5961 // Void expressions aren't legal in the vector-conditional expressions.
5962 if (IsVectorConditional) {
5963 SourceRange DiagLoc =
5964 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
5965 bool IsThrow = LVoid ? LThrow : RThrow;
5966 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
5967 << DiagLoc << IsThrow;
5968 return QualType();
5969 }
5970
5971 if (LThrow != RThrow) {
5972 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5973 VK = NonThrow->getValueKind();
5974 // DR (no number yet): the result is a bit-field if the
5975 // non-throw-expression operand is a bit-field.
5976 OK = NonThrow->getObjectKind();
5977 return NonThrow->getType();
5978 }
5979
5980 // -- Both the second and third operands have type void; the result is of
5981 // type void and is a prvalue.
5982 if (LVoid && RVoid)
5983 return Context.getCommonSugaredType(LTy, RTy);
5984
5985 // Neither holds, error.
5986 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5987 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5988 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5989 return QualType();
5990 }
5991
5992 // Neither is void.
5993 if (IsVectorConditional)
5994 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
5995
5996 // WebAssembly tables are not allowed as conditional LHS or RHS.
5997 if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) {
5998 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
5999 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6000 return QualType();
6001 }
6002
6003 // C++11 [expr.cond]p3
6004 // Otherwise, if the second and third operand have different types, and
6005 // either has (cv) class type [...] an attempt is made to convert each of
6006 // those operands to the type of the other.
6007 if (!Context.hasSameType(LTy, RTy) &&
6008 (LTy->isRecordType() || RTy->isRecordType())) {
6009 // These return true if a single direction is already ambiguous.
6010 QualType L2RType, R2LType;
6011 bool HaveL2R, HaveR2L;
6012 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6013 return QualType();
6014 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6015 return QualType();
6016
6017 // If both can be converted, [...] the program is ill-formed.
6018 if (HaveL2R && HaveR2L) {
6019 Diag(QuestionLoc, diag::err_conditional_ambiguous)
6020 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6021 return QualType();
6022 }
6023
6024 // If exactly one conversion is possible, that conversion is applied to
6025 // the chosen operand and the converted operands are used in place of the
6026 // original operands for the remainder of this section.
6027 if (HaveL2R) {
6028 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6029 return QualType();
6030 LTy = LHS.get()->getType();
6031 } else if (HaveR2L) {
6032 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6033 return QualType();
6034 RTy = RHS.get()->getType();
6035 }
6036 }
6037
6038 // C++11 [expr.cond]p3
6039 // if both are glvalues of the same value category and the same type except
6040 // for cv-qualification, an attempt is made to convert each of those
6041 // operands to the type of the other.
6042 // FIXME:
6043 // Resolving a defect in P0012R1: we extend this to cover all cases where
6044 // one of the operands is reference-compatible with the other, in order
6045 // to support conditionals between functions differing in noexcept. This
6046 // will similarly cover difference in array bounds after P0388R4.
6047 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6048 // that instead?
6049 ExprValueKind LVK = LHS.get()->getValueKind();
6050 ExprValueKind RVK = RHS.get()->getValueKind();
6051 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6052 // DerivedToBase was already handled by the class-specific case above.
6053 // FIXME: Should we allow ObjC conversions here?
6054 const ReferenceConversions AllowedConversions =
6055 ReferenceConversions::Qualification |
6056 ReferenceConversions::NestedQualification |
6057 ReferenceConversions::Function;
6058
6059 ReferenceConversions RefConv;
6060 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6062 !(RefConv & ~AllowedConversions) &&
6063 // [...] subject to the constraint that the reference must bind
6064 // directly [...]
6065 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6066 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6067 RTy = RHS.get()->getType();
6068 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6070 !(RefConv & ~AllowedConversions) &&
6071 !LHS.get()->refersToBitField() &&
6072 !LHS.get()->refersToVectorElement()) {
6073 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6074 LTy = LHS.get()->getType();
6075 }
6076 }
6077
6078 // C++11 [expr.cond]p4
6079 // If the second and third operands are glvalues of the same value
6080 // category and have the same type, the result is of that type and
6081 // value category and it is a bit-field if the second or the third
6082 // operand is a bit-field, or if both are bit-fields.
6083 // We only extend this to bitfields, not to the crazy other kinds of
6084 // l-values.
6085 bool Same = Context.hasSameType(LTy, RTy);
6086 if (Same && LVK == RVK && LVK != VK_PRValue &&
6089 VK = LHS.get()->getValueKind();
6090 if (LHS.get()->getObjectKind() == OK_BitField ||
6091 RHS.get()->getObjectKind() == OK_BitField)
6092 OK = OK_BitField;
6093 return Context.getCommonSugaredType(LTy, RTy);
6094 }
6095
6096 // C++11 [expr.cond]p5
6097 // Otherwise, the result is a prvalue. If the second and third operands
6098 // do not have the same type, and either has (cv) class type, ...
6099 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6100 // ... overload resolution is used to determine the conversions (if any)
6101 // to be applied to the operands. If the overload resolution fails, the
6102 // program is ill-formed.
6103 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6104 return QualType();
6105 }
6106
6107 // C++11 [expr.cond]p6
6108 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6109 // conversions are performed on the second and third operands.
6112 if (LHS.isInvalid() || RHS.isInvalid())
6113 return QualType();
6114 LTy = LHS.get()->getType();
6115 RTy = RHS.get()->getType();
6116
6117 // After those conversions, one of the following shall hold:
6118 // -- The second and third operands have the same type; the result
6119 // is of that type. If the operands have class type, the result
6120 // is a prvalue temporary of the result type, which is
6121 // copy-initialized from either the second operand or the third
6122 // operand depending on the value of the first operand.
6123 if (Context.hasSameType(LTy, RTy)) {
6124 if (LTy->isRecordType()) {
6125 // The operands have class type. Make a temporary copy.
6128 if (LHSCopy.isInvalid())
6129 return QualType();
6130
6133 if (RHSCopy.isInvalid())
6134 return QualType();
6135
6136 LHS = LHSCopy;
6137 RHS = RHSCopy;
6138 }
6139 return Context.getCommonSugaredType(LTy, RTy);
6140 }
6141
6142 // Extension: conditional operator involving vector types.
6143 if (LTy->isVectorType() || RTy->isVectorType())
6144 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
6145 /*AllowBothBool*/ true,
6146 /*AllowBoolConversions*/ false,
6147 /*AllowBoolOperation*/ false,
6148 /*ReportInvalid*/ true);
6149
6150 // -- The second and third operands have arithmetic or enumeration type;
6151 // the usual arithmetic conversions are performed to bring them to a
6152 // common type, and the result is of that type.
6153 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6154 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6156 if (LHS.isInvalid() || RHS.isInvalid())
6157 return QualType();
6158 if (ResTy.isNull()) {
6159 Diag(QuestionLoc,
6160 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6161 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6162 return QualType();
6163 }
6164
6165 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6166 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6167
6168 return ResTy;
6169 }
6170
6171 // -- The second and third operands have pointer type, or one has pointer
6172 // type and the other is a null pointer constant, or both are null
6173 // pointer constants, at least one of which is non-integral; pointer
6174 // conversions and qualification conversions are performed to bring them
6175 // to their composite pointer type. The result is of the composite
6176 // pointer type.
6177 // -- The second and third operands have pointer to member type, or one has
6178 // pointer to member type and the other is a null pointer constant;
6179 // pointer to member conversions and qualification conversions are
6180 // performed to bring them to a common type, whose cv-qualification
6181 // shall match the cv-qualification of either the second or the third
6182 // operand. The result is of the common type.
6183 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6184 if (!Composite.isNull())
6185 return Composite;
6186
6187 // Similarly, attempt to find composite type of two objective-c pointers.
6188 Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6189 if (LHS.isInvalid() || RHS.isInvalid())
6190 return QualType();
6191 if (!Composite.isNull())
6192 return Composite;
6193
6194 // Check if we are using a null with a non-pointer type.
6195 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6196 return QualType();
6197
6198 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6199 << LHS.get()->getType() << RHS.get()->getType()
6200 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6201 return QualType();
6202}
6203
6205 Expr *&E1, Expr *&E2,
6206 bool ConvertArgs) {
6207 assert(getLangOpts().CPlusPlus && "This function assumes C++");
6208
6209 // C++1z [expr]p14:
6210 // The composite pointer type of two operands p1 and p2 having types T1
6211 // and T2
6212 QualType T1 = E1->getType(), T2 = E2->getType();
6213
6214 // where at least one is a pointer or pointer to member type or
6215 // std::nullptr_t is:
6216 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6217 T1->isNullPtrType();
6218 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6219 T2->isNullPtrType();
6220 if (!T1IsPointerLike && !T2IsPointerLike)
6221 return QualType();
6222
6223 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6224 // This can't actually happen, following the standard, but we also use this
6225 // to implement the end of [expr.conv], which hits this case.
6226 //
6227 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6228 if (T1IsPointerLike &&
6230 if (ConvertArgs)
6231 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6232 ? CK_NullToMemberPointer
6233 : CK_NullToPointer).get();
6234 return T1;
6235 }
6236 if (T2IsPointerLike &&
6238 if (ConvertArgs)
6239 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6240 ? CK_NullToMemberPointer
6241 : CK_NullToPointer).get();
6242 return T2;
6243 }
6244
6245 // Now both have to be pointers or member pointers.
6246 if (!T1IsPointerLike || !T2IsPointerLike)
6247 return QualType();
6248 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6249 "nullptr_t should be a null pointer constant");
6250
6251 struct Step {
6252 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6253 // Qualifiers to apply under the step kind.
6254 Qualifiers Quals;
6255 /// The class for a pointer-to-member; a constant array type with a bound
6256 /// (if any) for an array.
6257 /// FIXME: Store Qualifier for pointer-to-member.
6258 const Type *ClassOrBound;
6259
6260 Step(Kind K, const Type *ClassOrBound = nullptr)
6261 : K(K), ClassOrBound(ClassOrBound) {}
6262 QualType rebuild(ASTContext &Ctx, QualType T) const {
6263 T = Ctx.getQualifiedType(T, Quals);
6264 switch (K) {
6265 case Pointer:
6266 return Ctx.getPointerType(T);
6267 case MemberPointer:
6268 return Ctx.getMemberPointerType(T, /*Qualifier=*/std::nullopt,
6269 ClassOrBound->getAsCXXRecordDecl());
6270 case ObjCPointer:
6271 return Ctx.getObjCObjectPointerType(T);
6272 case Array:
6273 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6274 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6276 else
6278 }
6279 llvm_unreachable("unknown step kind");
6280 }
6281 };
6282
6284
6285 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6286 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6287 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6288 // respectively;
6289 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6290 // to member of C2 of type cv2 U2" for some non-function type U, where
6291 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6292 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6293 // respectively;
6294 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6295 // T2;
6296 //
6297 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6298 // and to prepare to form the cv-combined type if so.
6299 QualType Composite1 = T1;
6300 QualType Composite2 = T2;
6301 unsigned NeedConstBefore = 0;
6302 while (true) {
6303 assert(!Composite1.isNull() && !Composite2.isNull());
6304
6305 Qualifiers Q1, Q2;
6306 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6307 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6308
6309 // Top-level qualifiers are ignored. Merge at all lower levels.
6310 if (!Steps.empty()) {
6311 // Find the qualifier union: (approximately) the unique minimal set of
6312 // qualifiers that is compatible with both types.
6314 Q2.getCVRUQualifiers());
6315
6316 // Under one level of pointer or pointer-to-member, we can change to an
6317 // unambiguous compatible address space.
6318 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6319 Quals.setAddressSpace(Q1.getAddressSpace());
6320 } else if (Steps.size() == 1) {
6321 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2, getASTContext());
6322 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1, getASTContext());
6323 if (MaybeQ1 == MaybeQ2) {
6324 // Exception for ptr size address spaces. Should be able to choose
6325 // either address space during comparison.
6328 MaybeQ1 = true;
6329 else
6330 return QualType(); // No unique best address space.
6331 }
6332 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6333 : Q2.getAddressSpace());
6334 } else {
6335 return QualType();
6336 }
6337
6338 // FIXME: In C, we merge __strong and none to __strong at the top level.
6339 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6340 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6341 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6342 assert(Steps.size() == 1);
6343 else
6344 return QualType();
6345
6346 // Mismatched lifetime qualifiers never compatibly include each other.
6347 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6348 Quals.setObjCLifetime(Q1.getObjCLifetime());
6349 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6350 assert(Steps.size() == 1);
6351 else
6352 return QualType();
6353
6355 Quals.setPointerAuth(Q1.getPointerAuth());
6356 else
6357 return QualType();
6358
6359 Steps.back().Quals = Quals;
6360 if (Q1 != Quals || Q2 != Quals)
6361 NeedConstBefore = Steps.size() - 1;
6362 }
6363
6364 // FIXME: Can we unify the following with UnwrapSimilarTypes?
6365
6366 const ArrayType *Arr1, *Arr2;
6367 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
6368 (Arr2 = Context.getAsArrayType(Composite2))) {
6369 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
6370 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
6371 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
6372 Composite1 = Arr1->getElementType();
6373 Composite2 = Arr2->getElementType();
6374 Steps.emplace_back(Step::Array, CAT1);
6375 continue;
6376 }
6377 bool IAT1 = isa<IncompleteArrayType>(Arr1);
6378 bool IAT2 = isa<IncompleteArrayType>(Arr2);
6379 if ((IAT1 && IAT2) ||
6380 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
6381 ((bool)CAT1 != (bool)CAT2) &&
6382 (Steps.empty() || Steps.back().K != Step::Array))) {
6383 // In C++20 onwards, we can unify an array of N T with an array of
6384 // a different or unknown bound. But we can't form an array whose
6385 // element type is an array of unknown bound by doing so.
6386 Composite1 = Arr1->getElementType();
6387 Composite2 = Arr2->getElementType();
6388 Steps.emplace_back(Step::Array);
6389 if (CAT1 || CAT2)
6390 NeedConstBefore = Steps.size();
6391 continue;
6392 }
6393 }
6394
6395 const PointerType *Ptr1, *Ptr2;
6396 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6397 (Ptr2 = Composite2->getAs<PointerType>())) {
6398 Composite1 = Ptr1->getPointeeType();
6399 Composite2 = Ptr2->getPointeeType();
6400 Steps.emplace_back(Step::Pointer);
6401 continue;
6402 }
6403
6404 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6405 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6406 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6407 Composite1 = ObjPtr1->getPointeeType();
6408 Composite2 = ObjPtr2->getPointeeType();
6409 Steps.emplace_back(Step::ObjCPointer);
6410 continue;
6411 }
6412
6413 const MemberPointerType *MemPtr1, *MemPtr2;
6414 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6415 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6416 Composite1 = MemPtr1->getPointeeType();
6417 Composite2 = MemPtr2->getPointeeType();
6418
6419 // At the top level, we can perform a base-to-derived pointer-to-member
6420 // conversion:
6421 //
6422 // - [...] where C1 is reference-related to C2 or C2 is
6423 // reference-related to C1
6424 //
6425 // (Note that the only kinds of reference-relatedness in scope here are
6426 // "same type or derived from".) At any other level, the class must
6427 // exactly match.
6428 CXXRecordDecl *Cls = nullptr,
6429 *Cls1 = MemPtr1->getMostRecentCXXRecordDecl(),
6430 *Cls2 = MemPtr2->getMostRecentCXXRecordDecl();
6431 if (declaresSameEntity(Cls1, Cls2))
6432 Cls = Cls1;
6433 else if (Steps.empty())
6434 Cls = IsDerivedFrom(Loc, Cls1, Cls2) ? Cls1
6435 : IsDerivedFrom(Loc, Cls2, Cls1) ? Cls2
6436 : nullptr;
6437 if (!Cls)
6438 return QualType();
6439
6440 Steps.emplace_back(Step::MemberPointer,
6441 Context.getCanonicalTagType(Cls).getTypePtr());
6442 continue;
6443 }
6444
6445 // Special case: at the top level, we can decompose an Objective-C pointer
6446 // and a 'cv void *'. Unify the qualifiers.
6447 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6448 Composite2->isObjCObjectPointerType()) ||
6449 (Composite1->isObjCObjectPointerType() &&
6450 Composite2->isVoidPointerType()))) {
6451 Composite1 = Composite1->getPointeeType();
6452 Composite2 = Composite2->getPointeeType();
6453 Steps.emplace_back(Step::Pointer);
6454 continue;
6455 }
6456
6457 // FIXME: block pointer types?
6458
6459 // Cannot unwrap any more types.
6460 break;
6461 }
6462
6463 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6464 // "pointer to function", where the function types are otherwise the same,
6465 // "pointer to function";
6466 // - if T1 or T2 is "pointer to member of C1 of type function", the other
6467 // type is "pointer to member of C2 of type noexcept function", and C1
6468 // is reference-related to C2 or C2 is reference-related to C1, where
6469 // the function types are otherwise the same, "pointer to member of C2 of
6470 // type function" or "pointer to member of C1 of type function",
6471 // respectively;
6472 //
6473 // We also support 'noreturn' here, so as a Clang extension we generalize the
6474 // above to:
6475 //
6476 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6477 // "pointer to member function" and the pointee types can be unified
6478 // by a function pointer conversion, that conversion is applied
6479 // before checking the following rules.
6480 //
6481 // We've already unwrapped down to the function types, and we want to merge
6482 // rather than just convert, so do this ourselves rather than calling
6483 // IsFunctionConversion.
6484 //
6485 // FIXME: In order to match the standard wording as closely as possible, we
6486 // currently only do this under a single level of pointers. Ideally, we would
6487 // allow this in general, and set NeedConstBefore to the relevant depth on
6488 // the side(s) where we changed anything. If we permit that, we should also
6489 // consider this conversion when determining type similarity and model it as
6490 // a qualification conversion.
6491 if (Steps.size() == 1) {
6492 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6493 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6494 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6495 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6496
6497 // The result is noreturn if both operands are.
6498 bool Noreturn =
6499 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6500 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6501 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6502
6503 bool CFIUncheckedCallee =
6505 EPI1.CFIUncheckedCallee = CFIUncheckedCallee;
6506 EPI2.CFIUncheckedCallee = CFIUncheckedCallee;
6507
6508 // The result is nothrow if both operands are.
6509 SmallVector<QualType, 8> ExceptionTypeStorage;
6510 EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs(
6511 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
6513
6514 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6515 FPT1->getParamTypes(), EPI1);
6516 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6517 FPT2->getParamTypes(), EPI2);
6518 }
6519 }
6520 }
6521
6522 // There are some more conversions we can perform under exactly one pointer.
6523 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6524 !Context.hasSameType(Composite1, Composite2)) {
6525 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6526 // "pointer to cv2 T", where T is an object type or void,
6527 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6528 if (Composite1->isVoidType() && Composite2->isObjectType())
6529 Composite2 = Composite1;
6530 else if (Composite2->isVoidType() && Composite1->isObjectType())
6531 Composite1 = Composite2;
6532 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6533 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6534 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6535 // T1, respectively;
6536 //
6537 // The "similar type" handling covers all of this except for the "T1 is a
6538 // base class of T2" case in the definition of reference-related.
6539 else if (IsDerivedFrom(Loc, Composite1, Composite2))
6540 Composite1 = Composite2;
6541 else if (IsDerivedFrom(Loc, Composite2, Composite1))
6542 Composite2 = Composite1;
6543 }
6544
6545 // At this point, either the inner types are the same or we have failed to
6546 // find a composite pointer type.
6547 if (!Context.hasSameType(Composite1, Composite2))
6548 return QualType();
6549
6550 // Per C++ [conv.qual]p3, add 'const' to every level before the last
6551 // differing qualifier.
6552 for (unsigned I = 0; I != NeedConstBefore; ++I)
6553 Steps[I].Quals.addConst();
6554
6555 // Rebuild the composite type.
6556 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
6557 for (auto &S : llvm::reverse(Steps))
6558 Composite = S.rebuild(Context, Composite);
6559
6560 if (ConvertArgs) {
6561 // Convert the expressions to the composite pointer type.
6562 InitializedEntity Entity =
6564 InitializationKind Kind =
6566
6567 InitializationSequence E1ToC(*this, Entity, Kind, E1);
6568 if (!E1ToC)
6569 return QualType();
6570
6571 InitializationSequence E2ToC(*this, Entity, Kind, E2);
6572 if (!E2ToC)
6573 return QualType();
6574
6575 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6576 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
6577 if (E1Result.isInvalid())
6578 return QualType();
6579 E1 = E1Result.get();
6580
6581 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
6582 if (E2Result.isInvalid())
6583 return QualType();
6584 E2 = E2Result.get();
6585 }
6586
6587 return Composite;
6588}
6589
6591 if (!E)
6592 return ExprError();
6593
6594 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6595
6596 // If the result is a glvalue, we shouldn't bind it.
6597 if (E->isGLValue())
6598 return E;
6599
6600 // In ARC, calls that return a retainable type can return retained,
6601 // in which case we have to insert a consuming cast.
6602 if (getLangOpts().ObjCAutoRefCount &&
6603 E->getType()->isObjCRetainableType()) {
6604
6605 bool ReturnsRetained;
6606
6607 // For actual calls, we compute this by examining the type of the
6608 // called value.
6609 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6610 Expr *Callee = Call->getCallee()->IgnoreParens();
6611 QualType T = Callee->getType();
6612
6613 if (T == Context.BoundMemberTy) {
6614 // Handle pointer-to-members.
6615 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6616 T = BinOp->getRHS()->getType();
6617 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6618 T = Mem->getMemberDecl()->getType();
6619 }
6620
6621 if (const PointerType *Ptr = T->getAs<PointerType>())
6622 T = Ptr->getPointeeType();
6623 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6624 T = Ptr->getPointeeType();
6625 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6626 T = MemPtr->getPointeeType();
6627
6628 auto *FTy = T->castAs<FunctionType>();
6629 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6630
6631 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6632 // type always produce a +1 object.
6633 } else if (isa<StmtExpr>(E)) {
6634 ReturnsRetained = true;
6635
6636 // We hit this case with the lambda conversion-to-block optimization;
6637 // we don't want any extra casts here.
6638 } else if (isa<CastExpr>(E) &&
6639 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6640 return E;
6641
6642 // For message sends and property references, we try to find an
6643 // actual method. FIXME: we should infer retention by selector in
6644 // cases where we don't have an actual method.
6645 } else {
6646 ObjCMethodDecl *D = nullptr;
6647 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6648 D = Send->getMethodDecl();
6649 } else if (auto *OL = dyn_cast<ObjCObjectLiteral>(E);
6650 OL && OL->isGlobalAllocation()) {
6651 return E;
6652 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6653 D = BoxedExpr->getBoxingMethod();
6654 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6655 // Don't do reclaims if we're using the zero-element array
6656 // constant.
6657 if (ArrayLit->getNumElements() == 0 &&
6658 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6659 return E;
6660
6661 D = ArrayLit->getArrayWithObjectsMethod();
6662 } else if (ObjCDictionaryLiteral *DictLit =
6663 dyn_cast<ObjCDictionaryLiteral>(E)) {
6664 // Don't do reclaims if we're using the zero-element dictionary
6665 // constant.
6666 if (DictLit->getNumElements() == 0 &&
6667 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6668 return E;
6669
6670 D = DictLit->getDictWithObjectsMethod();
6671 }
6672
6673 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6674
6675 // Don't do reclaims on performSelector calls; despite their
6676 // return type, the invoked method doesn't necessarily actually
6677 // return an object.
6678 if (!ReturnsRetained &&
6680 return E;
6681 }
6682
6683 // Don't reclaim an object of Class type.
6684 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6685 return E;
6686
6687 Cleanup.setExprNeedsCleanups(true);
6688
6689 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6690 : CK_ARCReclaimReturnedObject);
6691 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6693 }
6694
6696 Cleanup.setExprNeedsCleanups(true);
6697
6698 if (!getLangOpts().CPlusPlus)
6699 return E;
6700
6701 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6702 // a fast path for the common case that the type is directly a RecordType.
6703 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6704 const RecordType *RT = nullptr;
6705 while (!RT) {
6706 switch (T->getTypeClass()) {
6707 case Type::Record:
6708 RT = cast<RecordType>(T);
6709 break;
6710 case Type::ConstantArray:
6711 case Type::IncompleteArray:
6712 case Type::VariableArray:
6713 case Type::DependentSizedArray:
6714 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6715 break;
6716 default:
6717 return E;
6718 }
6719 }
6720
6721 // That should be enough to guarantee that this type is complete, if we're
6722 // not processing a decltype expression.
6723 auto *RD = cast<CXXRecordDecl>(RT->getDecl())->getDefinitionOrSelf();
6724 if (RD->isInvalidDecl() || RD->isDependentContext())
6725 return E;
6726
6727 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6730
6731 if (Destructor) {
6734 PDiag(diag::err_access_dtor_temp)
6735 << E->getType());
6737 return ExprError();
6738
6739 // If destructor is trivial, we can avoid the extra copy.
6740 if (Destructor->isTrivial())
6741 return E;
6742
6743 // We need a cleanup, but we don't need to remember the temporary.
6744 Cleanup.setExprNeedsCleanups(true);
6745 }
6746
6749
6750 if (IsDecltype)
6751 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6752
6753 return Bind;
6754}
6755
6758 if (SubExpr.isInvalid())
6759 return ExprError();
6760
6761 return MaybeCreateExprWithCleanups(SubExpr.get());
6762}
6763
6765 assert(SubExpr && "subexpression can't be null!");
6766
6768
6769 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6770 assert(ExprCleanupObjects.size() >= FirstCleanup);
6771 assert(Cleanup.exprNeedsCleanups() ||
6772 ExprCleanupObjects.size() == FirstCleanup);
6773 if (!Cleanup.exprNeedsCleanups())
6774 return SubExpr;
6775
6776 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6777 ExprCleanupObjects.size() - FirstCleanup);
6778
6779 auto *E = ExprWithCleanups::Create(
6780 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6782
6783 return E;
6784}
6785
6787 assert(SubStmt && "sub-statement can't be null!");
6788
6790
6791 if (!Cleanup.exprNeedsCleanups())
6792 return SubStmt;
6793
6794 // FIXME: In order to attach the temporaries, wrap the statement into
6795 // a StmtExpr; currently this is only used for asm statements.
6796 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6797 // a new AsmStmtWithTemporaries.
6798 CompoundStmt *CompStmt =
6801 Expr *E = new (Context)
6802 StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
6803 /*FIXME TemplateDepth=*/0);
6805}
6806
6808 assert(ExprEvalContexts.back().ExprContext ==
6810 "not in a decltype expression");
6811
6813 if (Result.isInvalid())
6814 return ExprError();
6815 E = Result.get();
6816
6817 // C++11 [expr.call]p11:
6818 // If a function call is a prvalue of object type,
6819 // -- if the function call is either
6820 // -- the operand of a decltype-specifier, or
6821 // -- the right operand of a comma operator that is the operand of a
6822 // decltype-specifier,
6823 // a temporary object is not introduced for the prvalue.
6824
6825 // Recursively rebuild ParenExprs and comma expressions to strip out the
6826 // outermost CXXBindTemporaryExpr, if any.
6827 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6828 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6829 if (SubExpr.isInvalid())
6830 return ExprError();
6831 if (SubExpr.get() == PE->getSubExpr())
6832 return E;
6833 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6834 }
6835 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6836 if (BO->getOpcode() == BO_Comma) {
6837 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6838 if (RHS.isInvalid())
6839 return ExprError();
6840 if (RHS.get() == BO->getRHS())
6841 return E;
6842 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
6843 BO->getType(), BO->getValueKind(),
6844 BO->getObjectKind(), BO->getOperatorLoc(),
6845 BO->getFPFeatures());
6846 }
6847 }
6848
6849 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6850 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6851 : nullptr;
6852 if (TopCall)
6853 E = TopCall;
6854 else
6855 TopBind = nullptr;
6856
6857 // Disable the special decltype handling now.
6858 ExprEvalContexts.back().ExprContext =
6860
6862 if (Result.isInvalid())
6863 return ExprError();
6864 E = Result.get();
6865
6866 // In MS mode, don't perform any extra checking of call return types within a
6867 // decltype expression.
6868 if (getLangOpts().MSVCCompat)
6869 return E;
6870
6871 // Perform the semantic checks we delayed until this point.
6872 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6873 I != N; ++I) {
6874 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6875 if (Call == TopCall)
6876 continue;
6877
6878 if (CheckCallReturnType(Call->getCallReturnType(Context),
6879 Call->getBeginLoc(), Call, Call->getDirectCallee()))
6880 return ExprError();
6881 }
6882
6883 // Now all relevant types are complete, check the destructors are accessible
6884 // and non-deleted, and annotate them on the temporaries.
6885 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6886 I != N; ++I) {
6888 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6889 if (Bind == TopBind)
6890 continue;
6891
6892 CXXTemporary *Temp = Bind->getTemporary();
6893
6894 CXXRecordDecl *RD =
6895 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6898
6899 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6900 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6901 PDiag(diag::err_access_dtor_temp)
6902 << Bind->getType());
6903 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6904 return ExprError();
6905
6906 // We need a cleanup, but we don't need to remember the temporary.
6907 Cleanup.setExprNeedsCleanups(true);
6908 }
6909
6910 // Possibly strip off the top CXXBindTemporaryExpr.
6911 return E;
6912}
6913
6914/// Note a set of 'operator->' functions that were used for a member access.
6916 ArrayRef<FunctionDecl *> OperatorArrows) {
6917 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6918 // FIXME: Make this configurable?
6919 unsigned Limit = 9;
6920 if (OperatorArrows.size() > Limit) {
6921 // Produce Limit-1 normal notes and one 'skipping' note.
6922 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6923 SkipCount = OperatorArrows.size() - (Limit - 1);
6924 }
6925
6926 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6927 if (I == SkipStart) {
6928 S.Diag(OperatorArrows[I]->getLocation(),
6929 diag::note_operator_arrows_suppressed)
6930 << SkipCount;
6931 I += SkipCount;
6932 } else {
6933 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6934 << OperatorArrows[I]->getCallResultType();
6935 ++I;
6936 }
6937 }
6938}
6939
6941 SourceLocation OpLoc,
6942 tok::TokenKind OpKind,
6943 ParsedType &ObjectType,
6944 bool &MayBePseudoDestructor) {
6945 // Since this might be a postfix expression, get rid of ParenListExprs.
6947 if (Result.isInvalid()) return ExprError();
6948 Base = Result.get();
6949
6951 if (Result.isInvalid()) return ExprError();
6952 Base = Result.get();
6953
6954 QualType BaseType = Base->getType();
6955 MayBePseudoDestructor = false;
6956 if (BaseType->isDependentType()) {
6957 // If we have a pointer to a dependent type and are using the -> operator,
6958 // the object type is the type that the pointer points to. We might still
6959 // have enough information about that type to do something useful.
6960 if (OpKind == tok::arrow)
6961 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6962 BaseType = Ptr->getPointeeType();
6963
6964 ObjectType = ParsedType::make(BaseType);
6965 MayBePseudoDestructor = true;
6966 return Base;
6967 }
6968
6969 // C++ [over.match.oper]p8:
6970 // [...] When operator->returns, the operator-> is applied to the value
6971 // returned, with the original second operand.
6972 if (OpKind == tok::arrow) {
6973 QualType StartingType = BaseType;
6974 bool NoArrowOperatorFound = false;
6975 bool FirstIteration = true;
6976 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6977 // The set of types we've considered so far.
6979 SmallVector<FunctionDecl*, 8> OperatorArrows;
6980 CTypes.insert(Context.getCanonicalType(BaseType));
6981
6982 while (BaseType->isRecordType()) {
6983 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6984 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6985 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6986 noteOperatorArrows(*this, OperatorArrows);
6987 Diag(OpLoc, diag::note_operator_arrow_depth)
6988 << getLangOpts().ArrowDepth;
6989 return ExprError();
6990 }
6991
6993 S, Base, OpLoc,
6994 // When in a template specialization and on the first loop iteration,
6995 // potentially give the default diagnostic (with the fixit in a
6996 // separate note) instead of having the error reported back to here
6997 // and giving a diagnostic with a fixit attached to the error itself.
6998 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6999 ? nullptr
7000 : &NoArrowOperatorFound);
7001 if (Result.isInvalid()) {
7002 if (NoArrowOperatorFound) {
7003 if (FirstIteration) {
7004 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7005 << BaseType << 1 << Base->getSourceRange()
7006 << FixItHint::CreateReplacement(OpLoc, ".");
7007 OpKind = tok::period;
7008 break;
7009 }
7010 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7011 << BaseType << Base->getSourceRange();
7012 CallExpr *CE = dyn_cast<CallExpr>(Base);
7013 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7014 Diag(CD->getBeginLoc(),
7015 diag::note_member_reference_arrow_from_operator_arrow);
7016 }
7017 }
7018 return ExprError();
7019 }
7020 Base = Result.get();
7021 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7022 OperatorArrows.push_back(OpCall->getDirectCallee());
7023 BaseType = Base->getType();
7024 CanQualType CBaseType = Context.getCanonicalType(BaseType);
7025 if (!CTypes.insert(CBaseType).second) {
7026 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7027 noteOperatorArrows(*this, OperatorArrows);
7028 return ExprError();
7029 }
7030 FirstIteration = false;
7031 }
7032
7033 if (OpKind == tok::arrow) {
7034 if (BaseType->isPointerType())
7035 BaseType = BaseType->getPointeeType();
7036 else if (auto *AT = Context.getAsArrayType(BaseType))
7037 BaseType = AT->getElementType();
7038 }
7039 }
7040
7041 // Objective-C properties allow "." access on Objective-C pointer types,
7042 // so adjust the base type to the object type itself.
7043 if (BaseType->isObjCObjectPointerType())
7044 BaseType = BaseType->getPointeeType();
7045
7046 // C++ [basic.lookup.classref]p2:
7047 // [...] If the type of the object expression is of pointer to scalar
7048 // type, the unqualified-id is looked up in the context of the complete
7049 // postfix-expression.
7050 //
7051 // This also indicates that we could be parsing a pseudo-destructor-name.
7052 // Note that Objective-C class and object types can be pseudo-destructor
7053 // expressions or normal member (ivar or property) access expressions, and
7054 // it's legal for the type to be incomplete if this is a pseudo-destructor
7055 // call. We'll do more incomplete-type checks later in the lookup process,
7056 // so just skip this check for ObjC types.
7057 if (!BaseType->isRecordType()) {
7058 ObjectType = ParsedType::make(BaseType);
7059 MayBePseudoDestructor = true;
7060 return Base;
7061 }
7062
7063 // The object type must be complete (or dependent), or
7064 // C++11 [expr.prim.general]p3:
7065 // Unlike the object expression in other contexts, *this is not required to
7066 // be of complete type for purposes of class member access (5.2.5) outside
7067 // the member function body.
7068 if (!BaseType->isDependentType() &&
7070 RequireCompleteType(OpLoc, BaseType,
7071 diag::err_incomplete_member_access)) {
7072 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7073 }
7074
7075 // C++ [basic.lookup.classref]p2:
7076 // If the id-expression in a class member access (5.2.5) is an
7077 // unqualified-id, and the type of the object expression is of a class
7078 // type C (or of pointer to a class type C), the unqualified-id is looked
7079 // up in the scope of class C. [...]
7080 ObjectType = ParsedType::make(BaseType);
7081 return Base;
7082}
7083
7084static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7085 tok::TokenKind &OpKind, SourceLocation OpLoc) {
7086 if (Base->hasPlaceholderType()) {
7088 if (result.isInvalid()) return true;
7089 Base = result.get();
7090 }
7091 ObjectType = Base->getType();
7092
7093 // C++ [expr.pseudo]p2:
7094 // The left-hand side of the dot operator shall be of scalar type. The
7095 // left-hand side of the arrow operator shall be of pointer to scalar type.
7096 // This scalar type is the object type.
7097 // Note that this is rather different from the normal handling for the
7098 // arrow operator.
7099 if (OpKind == tok::arrow) {
7100 // The operator requires a prvalue, so perform lvalue conversions.
7101 // Only do this if we might plausibly end with a pointer, as otherwise
7102 // this was likely to be intended to be a '.'.
7103 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7104 ObjectType->isFunctionType()) {
7106 if (BaseResult.isInvalid())
7107 return true;
7108 Base = BaseResult.get();
7109 ObjectType = Base->getType();
7110 }
7111
7112 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7113 ObjectType = Ptr->getPointeeType();
7114 } else if (!Base->isTypeDependent()) {
7115 // The user wrote "p->" when they probably meant "p."; fix it.
7116 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7117 << ObjectType << true
7118 << FixItHint::CreateReplacement(OpLoc, ".");
7119 if (S.isSFINAEContext())
7120 return true;
7121
7122 OpKind = tok::period;
7123 }
7124 }
7125
7126 return false;
7127}
7128
7129/// Check if it's ok to try and recover dot pseudo destructor calls on
7130/// pointer objects.
7131static bool
7133 QualType DestructedType) {
7134 // If this is a record type, check if its destructor is callable.
7135 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7136 if (RD->hasDefinition())
7138 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7139 return false;
7140 }
7141
7142 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7143 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7144 DestructedType->isVectorType();
7145}
7146
7148 SourceLocation OpLoc,
7149 tok::TokenKind OpKind,
7150 const CXXScopeSpec &SS,
7151 TypeSourceInfo *ScopeTypeInfo,
7152 SourceLocation CCLoc,
7153 SourceLocation TildeLoc,
7154 PseudoDestructorTypeStorage Destructed) {
7155 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7156
7157 QualType ObjectType;
7158 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7159 return ExprError();
7160
7161 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7162 !ObjectType->isVectorType() && !ObjectType->isMatrixType()) {
7163 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7164 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7165 else {
7166 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7167 << ObjectType << Base->getSourceRange();
7168 return ExprError();
7169 }
7170 }
7171
7172 // C++ [expr.pseudo]p2:
7173 // [...] The cv-unqualified versions of the object type and of the type
7174 // designated by the pseudo-destructor-name shall be the same type.
7175 if (DestructedTypeInfo) {
7176 QualType DestructedType = DestructedTypeInfo->getType();
7177 SourceLocation DestructedTypeStart =
7178 DestructedTypeInfo->getTypeLoc().getBeginLoc();
7179 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7180 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7181 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7182 // Foo *foo;
7183 // foo.~Foo();
7184 if (OpKind == tok::period && ObjectType->isPointerType() &&
7185 Context.hasSameUnqualifiedType(DestructedType,
7186 ObjectType->getPointeeType())) {
7187 auto Diagnostic =
7188 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7189 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7190
7191 // Issue a fixit only when the destructor is valid.
7193 *this, DestructedType))
7195
7196 // Recover by setting the object type to the destructed type and the
7197 // operator to '->'.
7198 ObjectType = DestructedType;
7199 OpKind = tok::arrow;
7200 } else {
7201 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7202 << ObjectType << DestructedType << Base->getSourceRange()
7203 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7204
7205 // Recover by setting the destructed type to the object type.
7206 DestructedType = ObjectType;
7207 DestructedTypeInfo =
7208 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7209 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7210 }
7211 } else if (DestructedType.getObjCLifetime() !=
7212 ObjectType.getObjCLifetime()) {
7213
7214 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7215 // Okay: just pretend that the user provided the correctly-qualified
7216 // type.
7217 } else {
7218 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7219 << ObjectType << DestructedType << Base->getSourceRange()
7220 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7221 }
7222
7223 // Recover by setting the destructed type to the object type.
7224 DestructedType = ObjectType;
7225 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7226 DestructedTypeStart);
7227 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7228 }
7229 }
7230 }
7231
7232 // C++ [expr.pseudo]p2:
7233 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7234 // form
7235 //
7236 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7237 //
7238 // shall designate the same scalar type.
7239 if (ScopeTypeInfo) {
7240 QualType ScopeType = ScopeTypeInfo->getType();
7241 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7242 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7243
7244 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
7245 diag::err_pseudo_dtor_type_mismatch)
7246 << ObjectType << ScopeType << Base->getSourceRange()
7247 << ScopeTypeInfo->getTypeLoc().getSourceRange();
7248
7249 ScopeType = QualType();
7250 ScopeTypeInfo = nullptr;
7251 }
7252 }
7253
7254 Expr *Result
7256 OpKind == tok::arrow, OpLoc,
7258 ScopeTypeInfo,
7259 CCLoc,
7260 TildeLoc,
7261 Destructed);
7262
7263 return Result;
7264}
7265
7267 SourceLocation OpLoc,
7268 tok::TokenKind OpKind,
7269 CXXScopeSpec &SS,
7270 UnqualifiedId &FirstTypeName,
7271 SourceLocation CCLoc,
7272 SourceLocation TildeLoc,
7273 UnqualifiedId &SecondTypeName) {
7274 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7275 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7276 "Invalid first type name in pseudo-destructor");
7277 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7278 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7279 "Invalid second type name in pseudo-destructor");
7280
7281 QualType ObjectType;
7282 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7283 return ExprError();
7284
7285 // Compute the object type that we should use for name lookup purposes. Only
7286 // record types and dependent types matter.
7287 ParsedType ObjectTypePtrForLookup;
7288 if (!SS.isSet()) {
7289 if (ObjectType->isRecordType())
7290 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7291 else if (ObjectType->isDependentType())
7292 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7293 }
7294
7295 // Convert the name of the type being destructed (following the ~) into a
7296 // type (with source-location information).
7297 QualType DestructedType;
7298 TypeSourceInfo *DestructedTypeInfo = nullptr;
7299 PseudoDestructorTypeStorage Destructed;
7300 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7301 ParsedType T = getTypeName(*SecondTypeName.Identifier,
7302 SecondTypeName.StartLocation,
7303 S, &SS, true, false, ObjectTypePtrForLookup,
7304 /*IsCtorOrDtorName*/true);
7305 if (!T &&
7306 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7307 (!SS.isSet() && ObjectType->isDependentType()))) {
7308 // The name of the type being destroyed is a dependent name, and we
7309 // couldn't find anything useful in scope. Just store the identifier and
7310 // it's location, and we'll perform (qualified) name lookup again at
7311 // template instantiation time.
7312 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7313 SecondTypeName.StartLocation);
7314 } else if (!T) {
7315 Diag(SecondTypeName.StartLocation,
7316 diag::err_pseudo_dtor_destructor_non_type)
7317 << SecondTypeName.Identifier << ObjectType;
7318 if (isSFINAEContext())
7319 return ExprError();
7320
7321 // Recover by assuming we had the right type all along.
7322 DestructedType = ObjectType;
7323 } else
7324 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7325 } else {
7326 // Resolve the template-id to a type.
7327 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7328 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7329 TemplateId->NumArgs);
7332 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
7333 TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name,
7334 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
7335 TemplateId->RAngleLoc,
7336 /*IsCtorOrDtorName*/ true);
7337 if (T.isInvalid() || !T.get()) {
7338 // Recover by assuming we had the right type all along.
7339 DestructedType = ObjectType;
7340 } else
7341 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7342 }
7343
7344 // If we've performed some kind of recovery, (re-)build the type source
7345 // information.
7346 if (!DestructedType.isNull()) {
7347 if (!DestructedTypeInfo)
7348 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7349 SecondTypeName.StartLocation);
7350 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7351 }
7352
7353 // Convert the name of the scope type (the type prior to '::') into a type.
7354 TypeSourceInfo *ScopeTypeInfo = nullptr;
7355 QualType ScopeType;
7356 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7357 FirstTypeName.Identifier) {
7358 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7359 ParsedType T = getTypeName(*FirstTypeName.Identifier,
7360 FirstTypeName.StartLocation,
7361 S, &SS, true, false, ObjectTypePtrForLookup,
7362 /*IsCtorOrDtorName*/true);
7363 if (!T) {
7364 Diag(FirstTypeName.StartLocation,
7365 diag::err_pseudo_dtor_destructor_non_type)
7366 << FirstTypeName.Identifier << ObjectType;
7367
7368 if (isSFINAEContext())
7369 return ExprError();
7370
7371 // Just drop this type. It's unnecessary anyway.
7372 ScopeType = QualType();
7373 } else
7374 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7375 } else {
7376 // Resolve the template-id to a type.
7377 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7378 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7379 TemplateId->NumArgs);
7382 /*ElaboratedKeywordLoc=*/SourceLocation(), SS,
7383 TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name,
7384 TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr,
7385 TemplateId->RAngleLoc,
7386 /*IsCtorOrDtorName*/ true);
7387 if (T.isInvalid() || !T.get()) {
7388 // Recover by dropping this type.
7389 ScopeType = QualType();
7390 } else
7391 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7392 }
7393 }
7394
7395 if (!ScopeType.isNull() && !ScopeTypeInfo)
7396 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7397 FirstTypeName.StartLocation);
7398
7399
7400 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7401 ScopeTypeInfo, CCLoc, TildeLoc,
7402 Destructed);
7403}
7404
7406 SourceLocation OpLoc,
7407 tok::TokenKind OpKind,
7408 SourceLocation TildeLoc,
7409 const DeclSpec& DS) {
7410 QualType ObjectType;
7411 QualType T;
7412 TypeLocBuilder TLB;
7413 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc) ||
7415 return ExprError();
7416
7417 switch (DS.getTypeSpecType()) {
7419 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
7420 return true;
7421 }
7423 T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
7424 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7425 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
7426 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
7427 break;
7428 }
7431 DS.getBeginLoc(), DS.getEllipsisLoc());
7433 cast<PackIndexingType>(T.getTypePtr())->getPattern(),
7434 DS.getBeginLoc());
7436 PITL.setEllipsisLoc(DS.getEllipsisLoc());
7437 break;
7438 }
7439 default:
7440 llvm_unreachable("Unsupported type in pseudo destructor");
7441 }
7442 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7443 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7444
7445 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7446 nullptr, SourceLocation(), TildeLoc,
7447 Destructed);
7448}
7449
7451 SourceLocation RParen) {
7452 // If the operand is an unresolved lookup expression, the expression is ill-
7453 // formed per [over.over]p1, because overloaded function names cannot be used
7454 // without arguments except in explicit contexts.
7455 ExprResult R = CheckPlaceholderExpr(Operand);
7456 if (R.isInvalid())
7457 return R;
7458
7459 R = CheckUnevaluatedOperand(R.get());
7460 if (R.isInvalid())
7461 return ExprError();
7462
7463 Operand = R.get();
7464
7465 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
7466 Operand->HasSideEffects(Context, false)) {
7467 // The expression operand for noexcept is in an unevaluated expression
7468 // context, so side effects could result in unintended consequences.
7469 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7470 }
7471
7472 CanThrowResult CanThrow = canThrow(Operand);
7473 return new (Context)
7474 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7475}
7476
7478 Expr *Operand, SourceLocation RParen) {
7479 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7480}
7481
7483 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
7484 DeclRefExpr *LHS = nullptr;
7485 bool IsCompoundAssign = false;
7486 bool isIncrementDecrementUnaryOp = false;
7487 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7488 if (BO->getLHS()->getType()->isDependentType() ||
7489 BO->getRHS()->getType()->isDependentType()) {
7490 if (BO->getOpcode() != BO_Assign)
7491 return;
7492 } else if (!BO->isAssignmentOp())
7493 return;
7494 else
7495 IsCompoundAssign = BO->isCompoundAssignmentOp();
7496 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
7497 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
7498 if (COCE->getOperator() != OO_Equal)
7499 return;
7500 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
7501 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7502 if (!UO->isIncrementDecrementOp())
7503 return;
7504 isIncrementDecrementUnaryOp = true;
7505 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
7506 }
7507 if (!LHS)
7508 return;
7509 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
7510 if (!VD)
7511 return;
7512 // Don't decrement RefsMinusAssignments if volatile variable with compound
7513 // assignment (+=, ...) or increment/decrement unary operator to avoid
7514 // potential unused-but-set-variable warning.
7515 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
7517 return;
7518 auto iter = RefsMinusAssignments.find(VD->getCanonicalDecl());
7519 if (iter == RefsMinusAssignments.end())
7520 return;
7521 iter->getSecond()--;
7522}
7523
7524/// Perform the conversions required for an expression used in a
7525/// context that ignores the result.
7528
7529 if (E->hasPlaceholderType()) {
7530 ExprResult result = CheckPlaceholderExpr(E);
7531 if (result.isInvalid()) return E;
7532 E = result.get();
7533 }
7534
7535 if (getLangOpts().CPlusPlus) {
7536 // The C++11 standard defines the notion of a discarded-value expression;
7537 // normally, we don't need to do anything to handle it, but if it is a
7538 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7539 // conversion.
7542 if (Res.isInvalid())
7543 return E;
7544 E = Res.get();
7545 } else {
7546 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7547 // it occurs as a discarded-value expression.
7549 }
7550
7551 // C++1z:
7552 // If the expression is a prvalue after this optional conversion, the
7553 // temporary materialization conversion is applied.
7554 //
7555 // We do not materialize temporaries by default in order to avoid creating
7556 // unnecessary temporary objects. If we skip this step, IR generation is
7557 // able to synthesize the storage for itself in the aggregate case, and
7558 // adding the extra node to the AST is just clutter.
7560 E->isPRValue() && !E->getType()->isVoidType()) {
7562 if (Res.isInvalid())
7563 return E;
7564 E = Res.get();
7565 }
7566 return E;
7567 }
7568
7569 // C99 6.3.2.1:
7570 // [Except in specific positions,] an lvalue that does not have
7571 // array type is converted to the value stored in the
7572 // designated object (and is no longer an lvalue).
7573 if (E->isPRValue()) {
7574 // In C, function designators (i.e. expressions of function type)
7575 // are r-values, but we still want to do function-to-pointer decay
7576 // on them. This is both technically correct and convenient for
7577 // some clients.
7578 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7580
7581 return E;
7582 }
7583
7584 // GCC seems to also exclude expressions of incomplete enum type.
7585 if (const auto *ED = E->getType()->getAsEnumDecl(); ED && !ED->isComplete()) {
7586 // FIXME: stupid workaround for a codegen bug!
7587 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7588 return E;
7589 }
7590
7592 if (Res.isInvalid())
7593 return E;
7594 E = Res.get();
7595
7596 if (!E->getType()->isVoidType())
7598 diag::err_incomplete_type);
7599 return E;
7600}
7601
7603 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7604 // it occurs as an unevaluated operand.
7606
7607 return E;
7608}
7609
7610// If we can unambiguously determine whether Var can never be used
7611// in a constant expression, return true.
7612// - if the variable and its initializer are non-dependent, then
7613// we can unambiguously check if the variable is a constant expression.
7614// - if the initializer is not value dependent - we can determine whether
7615// it can be used to initialize a constant expression. If Init can not
7616// be used to initialize a constant expression we conclude that Var can
7617// never be a constant expression.
7618// - FXIME: if the initializer is dependent, we can still do some analysis and
7619// identify certain cases unambiguously as non-const by using a Visitor:
7620// - such as those that involve odr-use of a ParmVarDecl, involve a new
7621// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7623 ASTContext &Context) {
7624 if (isa<ParmVarDecl>(Var)) return true;
7625 const VarDecl *DefVD = nullptr;
7626
7627 // If there is no initializer - this can not be a constant expression.
7628 const Expr *Init = Var->getAnyInitializer(DefVD);
7629 if (!Init)
7630 return true;
7631 assert(DefVD);
7632 if (DefVD->isWeak())
7633 return false;
7634
7635 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7636 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7637 // of value-dependent expressions, and use it here to determine whether the
7638 // initializer is a potential constant expression.
7639 return false;
7640 }
7641
7642 return !Var->isUsableInConstantExpressions(Context);
7643}
7644
7645/// Check if the current lambda has any potential captures
7646/// that must be captured by any of its enclosing lambdas that are ready to
7647/// capture. If there is a lambda that can capture a nested
7648/// potential-capture, go ahead and do so. Also, check to see if any
7649/// variables are uncaptureable or do not involve an odr-use so do not
7650/// need to be captured.
7651
7653 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7654
7655 assert(!S.isUnevaluatedContext());
7656 assert(S.CurContext->isDependentContext());
7657#ifndef NDEBUG
7658 DeclContext *DC = S.CurContext;
7659 while (isa_and_nonnull<CapturedDecl>(DC))
7660 DC = DC->getParent();
7661 assert(
7662 (CurrentLSI->CallOperator == DC || !CurrentLSI->AfterParameterList) &&
7663 "The current call operator must be synchronized with Sema's CurContext");
7664#endif // NDEBUG
7665
7666 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7667
7668 // All the potentially captureable variables in the current nested
7669 // lambda (within a generic outer lambda), must be captured by an
7670 // outer lambda that is enclosed within a non-dependent context.
7671 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
7672 // If the variable is clearly identified as non-odr-used and the full
7673 // expression is not instantiation dependent, only then do we not
7674 // need to check enclosing lambda's for speculative captures.
7675 // For e.g.:
7676 // Even though 'x' is not odr-used, it should be captured.
7677 // int test() {
7678 // const int x = 10;
7679 // auto L = [=](auto a) {
7680 // (void) +x + a;
7681 // };
7682 // }
7683 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7684 !IsFullExprInstantiationDependent)
7685 return;
7686
7687 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
7688 if (!UnderlyingVar)
7689 return;
7690
7691 // If we have a capture-capable lambda for the variable, go ahead and
7692 // capture the variable in that lambda (and all its enclosing lambdas).
7693 if (const UnsignedOrNone Index =
7695 S.FunctionScopes, Var, S))
7696 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
7697 const bool IsVarNeverAConstantExpression =
7699 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7700 // This full expression is not instantiation dependent or the variable
7701 // can not be used in a constant expression - which means
7702 // this variable must be odr-used here, so diagnose a
7703 // capture violation early, if the variable is un-captureable.
7704 // This is purely for diagnosing errors early. Otherwise, this
7705 // error would get diagnosed when the lambda becomes capture ready.
7706 QualType CaptureType, DeclRefType;
7707 SourceLocation ExprLoc = VarExpr->getExprLoc();
7708 if (S.tryCaptureVariable(Var, ExprLoc, TryCaptureKind::Implicit,
7709 /*EllipsisLoc*/ SourceLocation(),
7710 /*BuildAndDiagnose*/ false, CaptureType,
7711 DeclRefType, nullptr)) {
7712 // We will never be able to capture this variable, and we need
7713 // to be able to in any and all instantiations, so diagnose it.
7715 /*EllipsisLoc*/ SourceLocation(),
7716 /*BuildAndDiagnose*/ true, CaptureType,
7717 DeclRefType, nullptr);
7718 }
7719 }
7720 });
7721
7722 // Check if 'this' needs to be captured.
7723 if (CurrentLSI->hasPotentialThisCapture()) {
7724 // If we have a capture-capable lambda for 'this', go ahead and capture
7725 // 'this' in that lambda (and all its enclosing lambdas).
7726 if (const UnsignedOrNone Index =
7728 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
7729 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
7731 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7732 &FunctionScopeIndexOfCapturableLambda);
7733 }
7734 }
7735
7736 // Reset all the potential captures at the end of each full-expression.
7737 CurrentLSI->clearPotentialCaptures();
7738}
7739
7741 bool DiscardedValue, bool IsConstexpr,
7742 bool IsTemplateArgument) {
7743 ExprResult FullExpr = FE;
7744
7745 if (!FullExpr.get())
7746 return ExprError();
7747
7748 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
7749 return ExprError();
7750
7751 if (DiscardedValue) {
7752 // Top-level expressions default to 'id' when we're in a debugger.
7753 if (getLangOpts().DebuggerCastResultToId &&
7754 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7755 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7756 if (FullExpr.isInvalid())
7757 return ExprError();
7758 }
7759
7761 if (FullExpr.isInvalid())
7762 return ExprError();
7763
7765 if (FullExpr.isInvalid())
7766 return ExprError();
7767
7768 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
7769 }
7770
7771 if (FullExpr.isInvalid())
7772 return ExprError();
7773
7774 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7775
7776 // At the end of this full expression (which could be a deeply nested
7777 // lambda), if there is a potential capture within the nested lambda,
7778 // have the outer capture-able lambda try and capture it.
7779 // Consider the following code:
7780 // void f(int, int);
7781 // void f(const int&, double);
7782 // void foo() {
7783 // const int x = 10, y = 20;
7784 // auto L = [=](auto a) {
7785 // auto M = [=](auto b) {
7786 // f(x, b); <-- requires x to be captured by L and M
7787 // f(y, a); <-- requires y to be captured by L, but not all Ms
7788 // };
7789 // };
7790 // }
7791
7792 // FIXME: Also consider what happens for something like this that involves
7793 // the gnu-extension statement-expressions or even lambda-init-captures:
7794 // void f() {
7795 // const int n = 0;
7796 // auto L = [&](auto a) {
7797 // +n + ({ 0; a; });
7798 // };
7799 // }
7800 //
7801 // Here, we see +n, and then the full-expression 0; ends, so we don't
7802 // capture n (and instead remove it from our list of potential captures),
7803 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7804 // for us to see that we need to capture n after all.
7805
7806 LambdaScopeInfo *const CurrentLSI =
7807 getCurLambda(/*IgnoreCapturedRegions=*/true);
7808 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7809 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7810 // for an example of the code that might cause this asynchrony.
7811 // By ensuring we are in the context of a lambda's call operator
7812 // we can fix the bug (we only need to check whether we need to capture
7813 // if we are within a lambda's body); but per the comments in that
7814 // PR, a proper fix would entail :
7815 // "Alternative suggestion:
7816 // - Add to Sema an integer holding the smallest (outermost) scope
7817 // index that we are *lexically* within, and save/restore/set to
7818 // FunctionScopes.size() in InstantiatingTemplate's
7819 // constructor/destructor.
7820 // - Teach the handful of places that iterate over FunctionScopes to
7821 // stop at the outermost enclosing lexical scope."
7822 DeclContext *DC = CurContext;
7823 while (isa_and_nonnull<CapturedDecl>(DC))
7824 DC = DC->getParent();
7825 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7826 if (IsInLambdaDeclContext && CurrentLSI &&
7827 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7829 *this);
7831}
7832
7834 if (!FullStmt) return StmtError();
7835
7836 return MaybeCreateStmtWithCleanups(FullStmt);
7837}
7838
7841 const DeclarationNameInfo &TargetNameInfo) {
7842 DeclarationName TargetName = TargetNameInfo.getName();
7843 if (!TargetName)
7845
7846 // If the name itself is dependent, then the result is dependent.
7847 if (TargetName.isDependentName())
7849
7850 // Do the redeclaration lookup in the current scope.
7851 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7853 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType());
7854 R.suppressDiagnostics();
7855
7856 switch (R.getResultKind()) {
7862
7865
7868 }
7869
7870 llvm_unreachable("Invalid LookupResult Kind!");
7871}
7872
7874 SourceLocation KeywordLoc,
7875 bool IsIfExists,
7876 CXXScopeSpec &SS,
7877 UnqualifiedId &Name) {
7878 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7879
7880 // Check for an unexpanded parameter pack.
7881 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7882 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7883 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7884 return IfExistsResult::Error;
7885
7886 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7887}
7888
7890 return BuildExprRequirement(E, /*IsSimple=*/true,
7891 /*NoexceptLoc=*/SourceLocation(),
7892 /*ReturnTypeRequirement=*/{});
7893}
7894
7896 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
7897 const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) {
7898 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
7899 "Exactly one of TypeName and TemplateId must be specified.");
7900 TypeSourceInfo *TSI = nullptr;
7901 if (TypeName) {
7902 QualType T =
7904 SS.getWithLocInContext(Context), *TypeName, NameLoc,
7905 &TSI, /*DeducedTSTContext=*/false);
7906 if (T.isNull())
7907 return nullptr;
7908 } else {
7909 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
7910 TemplateId->NumArgs);
7911 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
7912 TemplateId->TemplateKWLoc,
7913 TemplateId->Template, TemplateId->Name,
7914 TemplateId->TemplateNameLoc,
7915 TemplateId->LAngleLoc, ArgsPtr,
7916 TemplateId->RAngleLoc);
7917 if (T.isInvalid())
7918 return nullptr;
7919 if (GetTypeFromParser(T.get(), &TSI).isNull())
7920 return nullptr;
7921 }
7922 return BuildTypeRequirement(TSI);
7923}
7924
7927 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
7928 /*ReturnTypeRequirement=*/{});
7929}
7930
7933 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
7934 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
7935 // C++2a [expr.prim.req.compound] p1.3.3
7936 // [..] the expression is deduced against an invented function template
7937 // F [...] F is a void function template with a single type template
7938 // parameter T declared with the constrained-parameter. Form a new
7939 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
7940 // around the constrained-parameter. F has a single parameter whose
7941 // type-specifier is cv T followed by the abstract-declarator. [...]
7942 //
7943 // The cv part is done in the calling function - we get the concept with
7944 // arguments and the abstract declarator with the correct CV qualification and
7945 // have to synthesize T and the single parameter of F.
7946 auto &II = Context.Idents.get("expr-type");
7949 SourceLocation(), Depth,
7950 /*Index=*/0, &II,
7951 /*Typename=*/true,
7952 /*ParameterPack=*/false,
7953 /*HasTypeConstraint=*/true);
7954
7955 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
7956 /*EllipsisLoc=*/SourceLocation(),
7957 /*AllowUnexpandedPack=*/true))
7958 // Just produce a requirement with no type requirements.
7959 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
7960
7963 ArrayRef<NamedDecl *>(TParam),
7965 /*RequiresClause=*/nullptr);
7966 return BuildExprRequirement(
7967 E, /*IsSimple=*/false, NoexceptLoc,
7969}
7970
7973 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
7976 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
7978 ReturnTypeRequirement.isDependent())
7980 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
7982 else if (ReturnTypeRequirement.isSubstitutionFailure())
7984 else if (ReturnTypeRequirement.isTypeConstraint()) {
7985 // C++2a [expr.prim.req]p1.3.3
7986 // The immediately-declared constraint ([temp]) of decltype((E)) shall
7987 // be satisfied.
7989 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
7990 QualType MatchedType = Context.getReferenceQualifiedType(E);
7992 Args.push_back(TemplateArgument(MatchedType));
7993
7994 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
7995
7996 MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/true);
7997 MLTAL.addOuterRetainedLevels(TPL->getDepth());
7998 const TypeConstraint *TC = Param->getTypeConstraint();
7999 assert(TC && "Type Constraint cannot be null here");
8000 auto *IDC = TC->getImmediatelyDeclaredConstraint();
8001 assert(IDC && "ImmediatelyDeclaredConstraint can't be null here.");
8002
8003 SFINAETrap Trap(*this);
8004 ExprResult Constraint = SubstExpr(IDC, MLTAL);
8005 bool HasError = Constraint.isInvalid();
8006 if (!HasError) {
8007 SubstitutedConstraintExpr =
8009 if (SubstitutedConstraintExpr->getSatisfaction().ContainsErrors)
8010 HasError = true;
8011 }
8012 if (HasError) {
8013 // FIXME: Capture diagnostics from the SFINAE trap and store them in the
8014 // requirement.
8016 createSubstDiagAt(IDC->getExprLoc(),
8017 [&](llvm::raw_ostream &OS) {
8018 IDC->printPretty(OS, /*Helper=*/nullptr,
8019 getPrintingPolicy());
8020 }),
8021 IsSimple, NoexceptLoc, ReturnTypeRequirement);
8022 }
8023 if (!SubstitutedConstraintExpr->isSatisfied())
8025 }
8026 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
8027 ReturnTypeRequirement, Status,
8028 SubstitutedConstraintExpr);
8029}
8030
8033 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
8034 bool IsSimple, SourceLocation NoexceptLoc,
8036 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
8037 IsSimple, NoexceptLoc,
8038 ReturnTypeRequirement);
8039}
8040
8045
8051
8055
8058 ConstraintSatisfaction Satisfaction;
8060 if (!Constraint->isInstantiationDependent() &&
8061 !Constraint->isValueDependent() &&
8063 /*TemplateArgs=*/{},
8064 Constraint->getSourceRange(), Satisfaction))
8065 return nullptr;
8066 return new (Context) concepts::NestedRequirement(Context, Constraint,
8067 Satisfaction);
8068}
8069
8071Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
8072 const ASTConstraintSatisfaction &Satisfaction) {
8074 InvalidConstraintEntity,
8076}
8077
8080 ArrayRef<ParmVarDecl *> LocalParameters,
8081 Scope *BodyScope) {
8082 assert(BodyScope);
8083
8085 RequiresKWLoc);
8086
8087 PushDeclContext(BodyScope, Body);
8088
8089 for (ParmVarDecl *Param : LocalParameters) {
8090 if (Param->getType()->isVoidType()) {
8091 if (LocalParameters.size() > 1) {
8092 Diag(Param->getBeginLoc(), diag::err_void_only_param);
8093 Param->setType(Context.IntTy);
8094 } else if (Param->getIdentifier()) {
8095 Diag(Param->getBeginLoc(), diag::err_param_with_void_type);
8096 Param->setType(Context.IntTy);
8097 } else if (Param->getType().hasQualifiers()) {
8098 Diag(Param->getBeginLoc(), diag::err_void_param_qualified);
8099 }
8100 } else if (Param->hasDefaultArg()) {
8101 // C++2a [expr.prim.req] p4
8102 // [...] A local parameter of a requires-expression shall not have a
8103 // default argument. [...]
8104 Diag(Param->getDefaultArgRange().getBegin(),
8105 diag::err_requires_expr_local_parameter_default_argument);
8106 // Ignore default argument and move on
8107 } else if (Param->isExplicitObjectParameter()) {
8108 // C++23 [dcl.fct]p6:
8109 // An explicit-object-parameter-declaration is a parameter-declaration
8110 // with a this specifier. An explicit-object-parameter-declaration
8111 // shall appear only as the first parameter-declaration of a
8112 // parameter-declaration-list of either:
8113 // - a member-declarator that declares a member function, or
8114 // - a lambda-declarator.
8115 //
8116 // The parameter-declaration-list of a requires-expression is not such
8117 // a context.
8118 Diag(Param->getExplicitObjectParamThisLoc(),
8119 diag::err_requires_expr_explicit_object_parameter);
8120 Param->setExplicitObjectParameterLoc(SourceLocation());
8121 }
8122
8123 Param->setDeclContext(Body);
8124 // If this has an identifier, add it to the scope stack.
8125 if (Param->getIdentifier()) {
8126 CheckShadow(BodyScope, Param);
8127 PushOnScopeChains(Param, BodyScope);
8128 }
8129 }
8130 return Body;
8131}
8132
8134 assert(CurContext && "DeclContext imbalance!");
8135 CurContext = CurContext->getLexicalParent();
8136 assert(CurContext && "Popped translation unit!");
8137}
8138
8140 SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body,
8141 SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters,
8142 SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements,
8143 SourceLocation ClosingBraceLoc) {
8144 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc,
8145 LocalParameters, RParenLoc, Requirements,
8146 ClosingBraceLoc);
8148 return ExprError();
8149 return RE;
8150}
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
Defines a function that returns the minimum OS versions supporting C++17's aligned allocation functio...
static bool CanThrow(Expr *E, ASTContext &Ctx)
Definition CFG.cpp:2848
static const char * getPlatformName(Darwin::DarwinPlatformKind Platform, Darwin::DarwinEnvironmentKind Environment)
Definition Darwin.cpp:3819
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines Expressions and AST nodes for C++2a concepts.
Result
Implement __builtin_bit_cast and related operations.
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
@ NotForRedeclaration
The lookup is a reference to this name that is not for the purpose of redeclaring the name.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, TypeAwareAllocationMode PassType, QualType allocType)
Determine whether a given type is a class for which 'delete[]' would call a member 'operator delete[]...
static void collectPublicBases(CXXRecordDecl *RD, llvm::DenseMap< CXXRecordDecl *, unsigned > &SubobjectsSeen, llvm::SmallPtrSetImpl< CXXRecordDecl * > &VBases, llvm::SetVector< CXXRecordDecl * > &PublicSubobjectsSeen, bool ParentIsPublic)
static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T)
Perform an "extended" implicit conversion as returned by TryClassUnification.
static void MaybeDecrementCount(Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool CheckDeleteOperator(Sema &S, SourceLocation StartLoc, SourceRange Range, bool Diagnose, CXXRecordDecl *NamingClass, DeclAccessPair Decl, FunctionDecl *Operator)
static void DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, const MismatchingNewDeleteDetector &Detector)
static void getUnambiguousPublicSubobjects(CXXRecordDecl *RD, llvm::SmallVectorImpl< CXXRecordDecl * > &Objects)
static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style, Expr *Init, bool IsCPlusPlus20)
static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S)
Check if the current lambda has any potential captures that must be captured by any of its enclosing ...
static void getUuidAttrOfType(Sema &SemaRef, QualType QT, llvm::SmallSetVector< const UuidAttr *, 1 > &UuidAttrs)
Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to a single GUID.
DeallocLookupMode
static QualType adjustVectorOrConstantMatrixType(ASTContext &Context, QualType FromTy, QualType ToType, QualType *ElTy=nullptr)
static QualType adjustCVQualifiersForCXXThisWithinLambda(ArrayRef< FunctionScopeInfo * > FunctionScopes, QualType ThisTy, DeclContext *CurSemaContext, ASTContext &ASTCtx)
static bool resolveAllocationOverloadInterior(Sema &S, LookupResult &R, SourceRange Range, ResolveMode Mode, SmallVectorImpl< Expr * > &Args, AlignedAllocationMode &PassAlignment, FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose)
static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Try to find a common type for two according to C++0x 5.16p5.
static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, SourceLocation QuestionLoc, bool &HaveConversion, QualType &ToType)
Try to convert a type to another according to C++11 5.16p3.
static bool resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl< Expr * > &Args, ImplicitAllocationParameters &IAP, FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose)
static UsualDeallocFnInfo resolveDeallocationOverload(Sema &S, LookupResult &R, const ImplicitDeallocationParameters &IDP, SourceLocation Loc, llvm::SmallVectorImpl< UsualDeallocFnInfo > *BestFns=nullptr)
Select the correct "usual" deallocation function to use from a selection of deallocation functions (e...
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType)
Determine whether a type has new-extended alignment.
static ExprResult BuildCXXCastArgument(Sema &S, SourceLocation CastLoc, QualType Ty, CastKind Kind, CXXMethodDecl *Method, DeclAccessPair FoundDecl, bool HadMultipleCandidates, Expr *From)
ResolveMode
static bool VariableCanNeverBeAConstantExpression(VarDecl *Var, ASTContext &Context)
static bool canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, QualType DestructedType)
Check if it's ok to try and recover dot pseudo destructor calls on pointer objects.
static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, tok::TokenKind &OpKind, SourceLocation OpLoc)
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, bool IsDelete, FunctionDecl *&Operator)
static bool isValidVectorForConditionalCondition(ASTContext &Ctx, QualType CondTy)
static void LookupGlobalDeallocationFunctions(Sema &S, SourceLocation Loc, LookupResult &FoundDelete, DeallocLookupMode Mode, DeclarationName Name)
static void noteOperatorArrows(Sema &S, ArrayRef< FunctionDecl * > OperatorArrows)
Note a set of 'operator->' functions that were used for a member access.
static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI)
static bool checkIncompatibleOBTConversion(Sema &S, QualType FromType, QualType ToType, Expr *From)
Check if an integral conversion involves incompatible overflow behavior types.
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD)
Determine whether the given function is a non-placement deallocation function.
This file declares semantic analysis for HLSL constructs.
This file provides some common utility functions for processing Lambdas.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis functions specific to PowerPC.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TokenKind enum and support functions.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
a trap message and trap category.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:229
TranslationUnitDecl * getTranslationUnitDecl() const
DeclarationNameTable DeclarationNames
Definition ASTContext.h:811
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:961
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
unsigned getTypeAlignIfKnown(QualType T, bool NeedsPreferredAlignment=false) const
Return the alignment of a type, in bits, or 0 if the type is incomplete and we cannot determine the a...
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:926
CanQualType getCanonicalTagType(const TagDecl *TD) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3954
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:316
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3784
QualType getElementType() const
Definition TypeBase.h:3796
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8244
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
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:5102
Pointer to a block type.
Definition TypeBase.h:3604
This class is used for builtin types like 'int'.
Definition TypeBase.h:3226
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition ExprCXX.cpp:1125
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:727
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
Represents a C++ constructor within a class.
Definition DeclCXX.h:2620
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2952
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition DeclCXX.h:2525
Expr * getInit() const
Get the initializer.
Definition DeclCXX.h:2587
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
bool isArrayForm() const
Definition ExprCXX.h:2656
SourceLocation getBeginLoc() const
Definition ExprCXX.h:2680
Represents a C++ destructor within a class.
Definition DeclCXX.h:2882
static CXXFunctionalCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, TypeSourceInfo *Written, CastKind Kind, Expr *Op, const CXXCastPath *Path, FPOptionsOverride FPO, SourceLocation LPLoc, SourceLocation RPLoc)
Definition ExprCXX.cpp:925
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2132
bool isVirtual() const
Definition DeclCXX.h:2187
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2271
QualType getFunctionObjectParameterType() const
Definition DeclCXX.h:2295
bool isConst() const
Definition DeclCXX.h:2184
static CXXNewExpr * Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, const ImplicitAllocationParameters &IAP, bool UsualArrayDeleteWantsSize, ArrayRef< Expr * > PlacementArgs, SourceRange TypeIdParens, std::optional< Expr * > ArraySize, CXXNewInitializationStyle InitializationStyle, Expr *Initializer, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, SourceRange DirectInitRange)
Create a c++ new expression.
Definition ExprCXX.cpp:298
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition ExprCXX.h:4309
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2749
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr)
Definition DeclCXX.cpp:132
base_class_range bases()
Definition DeclCXX.h:608
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
Definition DeclCXX.h:1214
capture_const_range captures() const
Definition DeclCXX.h:1097
ctor_range ctors() const
Definition DeclCXX.h:670
bool isAbstract() const
Determine whether this class has a pure virtual function.
Definition DeclCXX.h:1221
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
Definition DeclCXX.h:1408
bool hasDefinition() const
Definition DeclCXX.h:561
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition DeclCXX.cpp:2127
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2200
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
SourceLocation getLastQualifierNameLoc() const
Retrieve the location of the name in the last qualifier in this nested name specifier.
Definition DeclSpec.cpp:116
SourceLocation getEndLoc() const
Definition DeclSpec.h:87
SourceRange getRange() const
Definition DeclSpec.h:82
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Represents a C++ temporary.
Definition ExprCXX.h:1463
void setDestructor(const CXXDestructorDecl *Dtor)
Definition ExprCXX.h:1476
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition ExprCXX.cpp:1120
Represents the this expression in C++.
Definition ExprCXX.h:1158
static CXXThisExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType Ty, bool IsImplicit)
Definition ExprCXX.cpp:1592
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1212
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:852
static CXXUnresolvedConstructExpr * Create(const ASTContext &Context, QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool IsListInit)
Definition ExprCXX.cpp:1495
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1072
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
SourceLocation getBeginLoc() const
Definition Expr.h:3280
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3163
Expr * getCallee()
Definition Expr.h:3093
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
arg_range arguments()
Definition Expr.h:3198
Decl * getCalleeDecl()
Definition Expr.h:3123
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
Declaration of a class template.
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3337
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition Stmt.cpp:399
Represents the specialization of a concept - evaluates to a prvalue of type bool.
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
const ASTConstraintSatisfaction & getSatisfaction() const
Get elaborated satisfaction info about the template arguments' satisfaction of the named concept.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3822
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:251
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:291
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4449
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
lookup_result::iterator lookup_iterator
Definition DeclBase.h:2591
DeclContextLookupResult lookup_result
Definition DeclBase.h:2590
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isRecord() const
Definition DeclBase.h:2202
void addDecl(Decl *D)
Add the declaration D into this context.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
ValueDecl * getDecl()
Definition Expr.h:1341
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool hasAutoTypeSpec() const
Definition DeclSpec.h:580
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:545
TST getTypeSpecType() const
Definition DeclSpec.h:522
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
static const TST TST_typename_pack_indexing
Definition DeclSpec.h:286
ParsedType getRepAsType() const
Definition DeclSpec.h:532
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:609
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
static const TST TST_decltype
Definition DeclSpec.h:284
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
static const TST TST_decltype_auto
Definition DeclSpec.h:285
static const TST TST_error
Definition DeclSpec.h:301
SourceRange getTypeofParensRange() const
Definition DeclSpec.h:577
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setLocalOwningModule(Module *M)
Definition DeclBase.h:837
void setImplicit(bool I=true)
Definition DeclBase.h:602
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
@ ReachableWhenImported
This declaration has an owning module, and is visible to lookups that occurs within that module.
Definition DeclBase.h:242
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition DeclBase.h:894
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
bool isDependentName() const
Determines whether the name itself is dependent, e.g., because it involves a C++ type that is itself ...
bool isAnyOperatorDelete() const
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1948
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2446
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2095
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2132
void DropFirstTypeObject()
Definition DeclSpec.h:2463
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2442
bool isInvalidType() const
Definition DeclSpec.h:2762
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2130
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2291
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2288
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine a...
DiagnosticOptions & getDiagnosticOptions() const
Retrieve the diagnostic options.
Definition Diagnostic.h:603
Represents an enum.
Definition Decl.h:4033
bool isComplete() const
Returns true if this can be considered a complete type.
Definition Decl.h:4265
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition Decl.cpp:5068
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition Decl.h:4260
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1471
bool isLValue() const
Definition Expr.h:390
bool isRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:112
bool isReadIfDiscardedInCPlusPlus11() const
Determine whether an lvalue-to-rvalue conversion should implicitly be applied to this expression if i...
Definition Expr.cpp:2572
bool isGLValue() const
Definition Expr.h:287
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool refersToVectorElement() const
Returns whether this expression refers to a vector element.
Definition Expr.cpp:4290
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3097
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3093
bool isPRValue() const
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3346
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3695
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4075
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:282
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:415
QualType getType() const
Definition Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:458
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
Represents difference between two FPOptions values.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
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:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
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:104
FullExpr - Represents a "full-expression" node.
Definition Expr.h:1052
Represents a function declaration or definition.
Definition Decl.h:2018
static constexpr unsigned RequiredTypeAwareDeleteParameterCount
Count of mandatory parameters for type aware operator delete.
Definition Decl.h:2660
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2207
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4179
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2332
StringLiteral * getDeletedMessage() const
Get the message that indicates why this function was deleted.
Definition Decl.h:2776
QualType getReturnType() const
Definition Decl.h:2863
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2395
bool isReplaceableGlobalAllocationFunction(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition Decl.h:2612
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2558
bool isTypeAwareOperatorNewOrDelete() const
Determine whether this is a type aware operator new or delete.
Definition Decl.cpp:3533
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4543
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3800
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:3220
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5369
QualType getParamType(unsigned i) const
Definition TypeBase.h:5649
Declaration of a template function.
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4788
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4747
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4565
One of these records is kept for each identifier that is lexed.
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine whether this is a name reserved for the implementation (C99 7.1.3, C++ [lib....
ReservedLiteralSuffixIdStatus isReservedLiteralSuffixId() const
Determine whether this is a name reserved for future standardization or the implementation (C++ [usrl...
StringRef getName() const
Return the actual identifier string.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2078
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:673
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:677
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateValue(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool isImplicit=false)
Create a value initialization.
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
bool isAmbiguous() const
Determine whether this initialization failed due to an ambiguity.
bool Diagnose(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, ArrayRef< Expr * > Args)
Diagnose an potentially-invalid initialization sequence.
bool Failed() const
Determine whether the initialization sequence is invalid.
bool isDirectReferenceBinding() const
Determine whether this initialization is a direct reference binding (C++ [dcl.init....
Describes an entity that is being initialized.
static InitializedEntity InitializeException(SourceLocation ThrowLoc, QualType Type)
Create the initialization entity for an exception object.
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeNew(SourceLocation NewLoc, QualType Type, NewArrayKind IsVariableLengthArrayNew)
Create the initialization entity for an object allocated via new.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:980
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:1431
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:371
A class for iterating through a result set and possibly filtering out results.
Definition Lookup.h:677
void erase()
Erase the last element returned from this iterator.
Definition Lookup.h:723
Represents the results of name lookup.
Definition Lookup.h:147
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
Filter makeFilter()
Create a filter for this result set.
Definition Lookup.h:751
bool isAmbiguous() const
Definition Lookup.h:324
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition Lookup.h:452
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
A global _GUID constant.
Definition DeclCXX.h:4403
MSGuidDeclParts Parts
Definition DeclCXX.h:4405
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3715
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5618
QualType getPointeeType() const
Definition TypeBase.h:3733
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:266
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
A C++ nested-name-specifier augmented with source location information.
NamespaceAndPrefixLoc getAsNamespaceAndPrefix() const
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
@ MicrosoftSuper
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition ExprObjC.h:220
ObjCBoxedExpr - used for generalized expression boxing.
Definition ExprObjC.h:159
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition ExprObjC.h:342
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:971
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Represents a pointer to an Objective C object.
Definition TypeBase.h:8063
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8075
static OpaquePtr getFromOpaquePtr(void *P)
Definition Ownership.h:92
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(QualType P)
Definition Ownership.h:61
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2316
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
Represents a parameter to a function.
Definition Decl.h:1808
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:2931
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3390
QualType getPointeeType() const
Definition TypeBase.h:3400
Stores the type being destroyed by a pseudo-destructor expression.
Definition ExprCXX.h:2698
TypeSourceInfo * getTypeSourceInfo() const
Definition ExprCXX.h:2714
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8529
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3678
QualType withConst() const
Definition TypeBase.h:1174
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8445
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8571
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8485
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8630
QualType getCanonicalType() const
Definition TypeBase.h:8497
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8539
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:3038
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8518
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8491
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8610
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
GC getObjCGCAttr() const
Definition TypeBase.h:519
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
bool hasCVRQualifiers() const
Definition TypeBase.h:487
bool hasUnaligned() const
Definition TypeBase.h:511
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
unsigned getCVRUQualifiers() const
Definition TypeBase.h:489
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
void setObjCGCAttr(GC type)
Definition TypeBase.h:520
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
static Qualifiers fromCVRUMask(unsigned CVRU)
Definition TypeBase.h:441
LangAS getAddressSpace() const
Definition TypeBase.h:571
void setPointerAuth(PointerAuthQualifier Q)
Definition TypeBase.h:606
static std::string getAddrSpaceAsString(LangAS AS)
void setObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:548
Represents a struct/union/class.
Definition Decl.h:4347
Represents the body of a requires-expression.
Definition DeclCXX.h:2101
static RequiresExprBodyDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc)
Definition DeclCXX.cpp:2403
static RequiresExpr * Create(ASTContext &C, SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, SourceLocation LParenLoc, ArrayRef< ParmVarDecl * > LocalParameters, SourceLocation RParenLoc, ArrayRef< concepts::Requirement * > Requirements, SourceLocation RBraceLoc)
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:269
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:380
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:383
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
@ BlockScope
This is a scope that corresponds to a block/closure object.
Definition Scope.h:75
@ ClassScope
The scope of a struct/union/class definition.
Definition Scope.h:69
@ TryScope
This is the scope of a C++ try statement.
Definition Scope.h:105
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition Scope.h:51
@ ObjCMethodScope
This scope corresponds to an Objective-C method body.
Definition Scope.h:99
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
CUDAFunctionTarget CurrentTarget()
Gets the CUDA target for the current context.
Definition SemaCUDA.h:153
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
Definition SemaCUDA.cpp:908
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition SemaCUDA.cpp:406
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition SemaCUDA.cpp:308
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD, bool IsReinterpretCast=false)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
Definition SemaPPC.cpp:422
CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled=true)
Introduce a new scope where 'this' may be allowed (when enabled), using the given declaration (which ...
A RAII object to temporarily push a declaration context.
Definition Sema.h:3526
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10409
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12552
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
void DeclareGlobalNewDelete()
DeclareGlobalNewDelete - Declare the global forms of operator new and delete.
IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo)
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, ImplicitDeallocationParameters, DeclarationName Name, bool Diagnose=true)
ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXTypeid - Parse typeid( something ).
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc)
ActOnCXXUuidof - Parse __uuidof( something ).
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1141
QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8330
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupDestructorName
Look up a name following ~ in a destructor name.
Definition Sema.h:9435
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition Sema.h:9423
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9465
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:416
ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen)
bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack)
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, ImplicitDeallocationParameters, bool Diagnose=true)
bool CheckCXXThisType(SourceLocation Loc, QualType Type)
Check whether the type of 'this' is valid in the current context.
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
QualType tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc)
Looks for the std::type_identity template and instantiates it with Type, or returns a null type if ty...
SemaCUDA & CUDA()
Definition Sema.h:1473
bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl< Expr * > &ConvertedArgs, bool AllowExplicit=false, bool IsListInitialization=false)
Given a constructor and the set of arguments provided for the constructor, convert the arguments and ...
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7924
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7926
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7925
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1244
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10501
@ AR_inaccessible
Definition Sema.h:1687
ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc)
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor)
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
concepts::Requirement * ActOnSimpleRequirement(Expr *E)
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
concepts::Requirement * ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc)
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
FunctionDecl * FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal, DeclarationName Name)
concepts::Requirement::SubstitutionDiagnostic * createSubstDiagAt(SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using ASTConte...
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1725
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand)
ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
void DiagnoseExceptionUse(SourceLocation Loc, bool IsTry)
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
ASTContext & Context
Definition Sema.h:1308
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:686
ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc)
ActOnCXXNullPtrLiteral - Parse 'nullptr'.
ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a C++ typeid expression with a type operand.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
concepts::TypeRequirement * BuildTypeRequirement(TypeSourceInfo *Type)
AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType=QualType())
bool isStdTypeIdentity(QualType Ty, QualType *TypeArgument, const Decl **MalformedDecl=nullptr)
Tests whether Ty is an instance of std::type_identity and, if it is and TypeArgument is not NULL,...
SemaObjC & ObjC()
Definition Sema.h:1518
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ParsedType getDestructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext)
void CleanupVarDeclMarking()
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:759
ASTContext & getASTContext() const
Definition Sema.h:939
void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef< QualType > Params)
DeclareGlobalAllocationFunction - Declares a single implicit global allocation function if it doesn't...
bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE)
If the given requirees-expression contains an unexpanded reference to one of its own parameter packs,...
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
NamespaceDecl * getOrCreateStdNamespace()
Retrieve the special "std" namespace, which may require us to implicitly define the namespace.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName)
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose=true)
Checks access to an overloaded operator new or delete.
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
void ActOnFinishRequiresExpr()
ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, std::optional< Expr * > ArraySize, SourceRange DirectInitRange, Expr *Initializer)
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr)
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
bool CheckConstraintSatisfaction(ConstrainedDeclOrNestedRequirement Entity, ArrayRef< AssociatedConstraint > AssociatedConstraints, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction, const ConceptReference *TopLevelConceptId=nullptr, Expr **ConvertedExpr=nullptr)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
EnumDecl * getStdAlignValT() const
LazyDeclPtr StdBadAlloc
The C++ "std::bad_alloc" class, which is defined by the C++ standard library.
Definition Sema.h:8448
NamedReturnInfo getNamedReturnInfo(Expr *&E, SimplerImplicitMoveMode Mode=SimplerImplicitMoveMode::Normal)
Determine whether the given expression might be move-eligible or copy-elidable in either a (co_)retur...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, bool IsUDSuffix)
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition SemaStmt.cpp:405
FPOptions & getCurFPFeatures()
Definition Sema.h:934
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_IfExists
Microsoft __if_exists.
Definition Sema.h:14560
@ UPPC_IfNotExists
Microsoft __if_not_exists.
Definition Sema.h:14563
const LangOptions & getLangOpts() const
Definition Sema.h:932
StmtResult ActOnFinishFullStmt(Stmt *Stmt)
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
SemaOpenACC & OpenACC()
Definition Sema.h:1523
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:1307
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)
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1306
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2673
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
Check the use of the given variable as a C++ condition in an if, while, do-while, or switch statement...
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
SemaHLSL & HLSL()
Definition Sema.h:1483
CXXRecordDecl * getStdBadAlloc() const
ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization)
ActOnCXXTypeConstructExpr - Parse construction of a specified type.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext)
ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr)
Prepare SplattedExpr for a matrix splat operation, adding implicit casts if necessary.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:77
ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK)
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R)
Checks that a type is suitable as the allocated type in a new-expression.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7048
ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, SourceLocation LParenLoc, ArrayRef< ParmVarDecl * > LocalParameters, SourceLocation RParenLoc, ArrayRef< concepts::Requirement * > Requirements, SourceLocation ClosingBraceLoc)
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition Sema.cpp:869
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10520
CXXRecordDecl * getCurrentClass(Scope *S, const CXXScopeSpec *SS)
Get the class that is directly named by the current context.
ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc)
Build a Microsoft __uuidof expression with a type operand.
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7045
QualType DeduceTemplateSpecializationFromInitializer(TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init)
void MarkThisReferenced(CXXThisExpr *This)
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8271
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition Sema.h:9946
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
static bool isCast(CheckedConversionKind CCK)
Definition Sema.h:2572
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp=false)
Checks access to a constructor.
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType)
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8263
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1705
Stmt * MaybeCreateStmtWithCleanups(Stmt *SubStmt)
ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer)
Parsed a C++ 'new' expression (C++ 5.3.4).
ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen)
bool GlobalNewDeleteDeclared
A flag to remember whether the implicit forms of operator new and delete have been declared.
Definition Sema.h:8459
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
ExprResult TransformToPotentiallyEvaluated(Expr *E)
ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, CXXConstructionKind ConstructKind, SourceRange ParenRange)
BuildCXXConstructExpr - Creates a complete call to a constructor, including handling of its default a...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14055
SourceManager & getSourceManager() const
Definition Sema.h:937
QualType CXXThisTypeOverride
When non-NULL, the C++ 'this' expression is allowed despite the current context not being a non-stati...
Definition Sema.h:8530
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves=false)
Perform the initialization of a potentially-movable value, which is the result of return value.
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
CanThrowResult canThrow(const Stmt *E)
bool isThisOutsideMemberFunctionBody(QualType BaseType)
Determine whether the given type is the type of *this that is used outside of the body of a member fu...
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
concepts::ExprRequirement * BuildExprRequirement(Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement)
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13788
concepts::Requirement * ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId)
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, const IdentifierInfo &Name)
Handle the result of the special case name lookup for inheriting constructor declarations.
TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc, ImplicitTypenameContext IsImplicitTypename=ImplicitTypenameContext::No)
Called when the parser has parsed a C++ typename specifier, e.g., "typename T::type".
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15572
ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType)
RecordDecl * CXXTypeInfoDecl
The C++ "type_info" declaration, which is defined in <typeinfo>.
Definition Sema.h:8455
CXXConstructorDecl * LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals)
Look up the copying constructor for the given class.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition SemaDecl.cpp:276
RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef< ParmVarDecl * > LocalParameters, Scope *BodyScope)
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7052
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:125
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
SemaPPC & PPC()
Definition Sema.h:1538
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Delete-expressions to be analyzed at the end of translation unit.
Definition Sema.h:8466
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
void DiscardCleanupsInEvaluationContext()
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8403
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
bool CheckDestructor(CXXDestructorDecl *Destructor)
CheckDestructor - Checks a fully-formed destructor definition for well-formedness,...
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
DiagnosticsEngine & Diags
Definition Sema.h:1310
TypeAwareAllocationMode ShouldUseTypeAwareOperatorNewOrDelete() const
NamespaceDecl * getStdNamespace() const
ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope)
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:520
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
friend class InitializationSequence
Definition Sema.h:1588
concepts::NestedRequirement * BuildNestedRequirement(Expr *E)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
bool isUsualDeallocationFunction(const CXXMethodDecl *FD)
TypeResult ActOnTemplateIdType(Scope *S, ElaboratedTypeKeyword ElaboratedKeyword, SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName=false, bool IsClassName=false, ImplicitTypenameContext AllowImplicitTypename=ImplicitTypenameContext::No)
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2219
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ParsedType getConstructorName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext)
LazyDeclPtr StdAlignValT
The C++ "std::align_val_t" enum class, which is defined by the C++ standard library.
Definition Sema.h:8452
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6500
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
TemplateDeductionResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *Initializer, QualType &Result, sema::TemplateDeductionInfo &Info, bool DependentDeduction=false, bool IgnoreConstraints=false, TemplateSpecCandidateSet *FailedTSC=nullptr)
Deduce the type for an auto type-specifier (C++11 [dcl.spec.auto]p6)
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
concepts::Requirement * ActOnNestedRequirement(Expr *Constraint)
QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec=false)
Adjust the type ArgFunctionType to match the calling convention, noreturn, and optionally the excepti...
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType)
static ConditionResult ConditionError()
Definition Sema.h:7910
IdentifierResolver IdResolver
Definition Sema.h:3519
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
ExprResult ActOnCXXThis(SourceLocation Loc)
ExprResult ActOnDecltypeExpression(Expr *E)
Process the expression contained within a decltype.
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8748
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
DeclAccessPair FoundCopyConstructor
Definition Overload.h:392
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition Overload.h:324
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:391
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:334
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:318
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:314
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4598
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
StringRef getString() const
Definition Expr.h:1870
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with 'operator new(size_t)' is gua...
Definition TargetInfo.h:767
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
A template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Represents a template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Type
The template argument is a type.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
unsigned getDepth() const
Get the depth of this template parameter list in the set of template parameter lists.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
Represents a declaration of a type.
Definition Decl.h:3535
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
void pushTrivial(ASTContext &Context, QualType T, SourceLocation Loc)
Pushes 'T' with all locations pointing to 'Loc'.
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8416
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8427
The base class of the type hierarchy.
Definition TypeBase.h:1875
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:2661
bool isBlockPointerType() const
Definition TypeBase.h:8702
bool isVoidType() const
Definition TypeBase.h:9048
bool isBooleanType() const
Definition TypeBase.h:9185
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition TypeBase.h:9024
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isVoidPointerType() const
Definition Type.cpp:749
bool isArrayType() const
Definition TypeBase.h:8781
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2422
bool isConstantMatrixType() const
Definition TypeBase.h:8849
bool isPointerType() const
Definition TypeBase.h:8682
bool isArrayParameterType() const
Definition TypeBase.h:8797
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9092
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9342
bool isReferenceType() const
Definition TypeBase.h:8706
bool isEnumeralType() const
Definition TypeBase.h:8813
bool isScalarType() const
Definition TypeBase.h:9154
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2701
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2156
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isExtVectorType() const
Definition TypeBase.h:8825
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition Type.h:63
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8805
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2844
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9108
bool isHalfType() const
Definition TypeBase.h:9052
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition Type.cpp:2109
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2651
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9228
bool isMemberPointerType() const
Definition TypeBase.h:8763
bool isMatrixType() const
Definition TypeBase.h:8845
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2862
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5436
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isPointerOrReferenceType() const
Definition TypeBase.h:8686
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition Type.cpp:5380
bool isFunctionType() const
Definition TypeBase.h:8678
bool isObjCObjectPointerType() const
Definition TypeBase.h:8861
bool isVectorType() const
Definition TypeBase.h:8821
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2983
bool isFloatingType() const
Definition Type.cpp:2389
bool isAnyPointerType() const
Definition TypeBase.h:8690
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9275
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition Type.cpp:5386
bool isNullPtrType() const
Definition TypeBase.h:9085
bool isRecordType() const
Definition TypeBase.h:8809
bool isObjCRetainableType() const
Definition Type.cpp:5417
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2663
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1035
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:1247
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1244
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:1248
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition DeclSpec.h:1093
const IdentifierInfo * Identifier
When Kind == IK_Identifier, the parsed identifier, or when Kind == IK_UserLiteralId,...
Definition DeclSpec.h:1063
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1117
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1087
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5575
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3683
Represents a variable declaration or definition.
Definition Decl.h:924
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:2169
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2236
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:2507
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1371
Represents a GCC generic vector type.
Definition TypeBase.h:4237
TemplateParameterList * getTypeConstraintTemplateParameterList() const
A requires-expression requirement which queries the validity and properties of an expression ('simple...
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
A static requirement that can be used in a requires-expression to check properties of types and expre...
A requires-expression requirement which queries the existence of a type name or type template special...
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:712
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:762
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:759
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition ScopeInfo.h:1100
SourceLocation PotentialThisCaptureLocation
Definition ScopeInfo.h:954
bool hasPotentialThisCapture() const
Definition ScopeInfo.h:1006
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:888
bool lambdaCaptureShouldBeConst() const
bool hasPotentialCaptures() const
Definition ScopeInfo.h:1072
bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const
Definition ScopeInfo.h:1055
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:875
void visitPotentialCaptures(llvm::function_ref< void(ValueDecl *, Expr *)> Callback) const
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:896
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:883
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:878
Provides information about an attempted template argument deduction, whose success or failure was des...
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:47
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
bool NE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1469
ComparisonCategoryResult Compare(const T &X, const T &Y)
Helper to compare two comparable types.
Definition Primitives.h:40
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isLambdaCallWithImplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:50
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus17
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
VariadicCallType
Definition Sema.h:513
CanThrowResult
Possible results from evaluation of a noexcept expression.
AllocationFunctionScope
The scope in which to find allocation functions.
Definition Sema.h:791
@ Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition Sema.h:799
@ Global
Only look for allocation functions in the global scope.
Definition Sema.h:793
@ Class
Only look for allocation functions in the scope of the allocated class.
Definition Sema.h:796
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
bool isReservedInAllContexts(ReservedIdentifierStatus Status)
Determine whether an identifier is reserved in all contexts.
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ NotFound
No entity found met the criteria.
Definition Lookup.h:41
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition Lookup.h:54
@ Found
Name lookup found a single declaration that met the criteria.
Definition Lookup.h:50
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition Lookup.h:59
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition Lookup.h:46
AlignedAllocationMode alignedAllocationModeFromBool(bool IsAligned)
Definition ExprCXX.h:2273
@ Conditional
A conditional (?:) operator.
Definition Sema.h:669
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1797
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1800
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1803
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:155
UnsignedOrNone getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
@ Bind
'bind' clause, allowed on routine constructs.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1027
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1019
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1013
@ AS_public
Definition Specifiers.h:125
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
@ SC_None
Definition Specifiers.h:251
Expr * Cond
};
bool isAlignedAllocation(AlignedAllocationMode Mode)
Definition ExprCXX.h:2269
@ OMF_performSelector
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
AlignedAllocationMode
Definition ExprCXX.h:2267
StmtResult StmtError()
Definition Ownership.h:266
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
OptionalUnsigned< unsigned > UnsignedOrNone
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:214
@ ICK_HLSL_Matrix_Splat
HLSL matrix splat from scalar or boolean type.
Definition Overload.h:211
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition Overload.h:124
@ ICK_HLSL_Matrix_Truncation
HLSL Matrix truncation.
Definition Overload.h:202
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
llvm::VersionTuple alignedAllocMinVersion(llvm::Triple::OSType OS)
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:787
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ Class
The "class" keyword.
Definition TypeBase.h:6004
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
bool isTypeAwareAllocation(TypeAwareAllocationMode Mode)
Definition ExprCXX.h:2257
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
SizedDeallocationMode sizedDeallocationModeFromBool(bool IsSized)
Definition ExprCXX.h:2283
AssignmentAction
Definition Sema.h:216
@ Deduced
The normal deduced case.
Definition TypeBase.h:1814
inits_range inits()
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool isPtrSizeAddressSpace(LangAS AS)
SizedDeallocationMode
Definition ExprCXX.h:2277
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:153
bool isSizedDeallocation(SizedDeallocationMode Mode)
Definition ExprCXX.h:2279
TypeAwareAllocationMode
Definition ExprCXX.h:2255
IfExistsResult
Describes the result of an "if-exists" condition check.
Definition Sema.h:803
@ Dependent
The name is a dependent name, so the results will differ from one instantiation to the next.
Definition Sema.h:812
@ Exists
The symbol exists.
Definition Sema.h:805
@ Error
An error occurred.
Definition Sema.h:815
@ DoesNotExist
The symbol does not exist.
Definition Sema.h:808
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:306
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1301
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ Generic
not a target-specific vector type
Definition TypeBase.h:4198
U cast(CodeGen::Address addr)
Definition Address.h:327
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5989
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5979
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition TypeBase.h:5986
ReservedIdentifierStatus
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1763
CXXNewInitializationStyle
Definition ExprCXX.h:2244
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2249
@ None
New-expression has no initializer as written.
Definition ExprCXX.h:2246
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2252
@ EST_BasicNoexcept
noexcept
@ EST_Dynamic
throw(T1, T2)
CheckedConversionKind
The kind of conversion being performed.
Definition Sema.h:438
@ CStyleCast
A C-style cast.
Definition Sema.h:442
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:448
@ FunctionalCast
A functional-style cast.
Definition Sema.h:444
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
#define false
Definition stdbool.h:26
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:91
static ASTConstraintSatisfaction * Rebuild(const ASTContext &C, const ASTConstraintSatisfaction &Satisfaction)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
DeclarationName getName() const
getName - Returns the embedded declaration name.
unsigned hasStatic
True if this dimension included the 'static' keyword.
Definition DeclSpec.h:1352
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1361
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1283
ArrayTypeInfo Arr
Definition DeclSpec.h:1681
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1291
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5428
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition TypeBase.h:5431
Extra information about a function prototype.
Definition TypeBase.h:5454
AlignedAllocationMode PassAlignment
Definition ExprCXX.h:2311
TypeAwareAllocationMode PassTypeIdentity
Definition ExprCXX.h:2310
unsigned getNumImplicitArgs() const
Definition ExprCXX.h:2300
TypeAwareAllocationMode PassTypeIdentity
Definition ExprCXX.h:2342
SizedDeallocationMode PassSize
Definition ExprCXX.h:2344
AlignedAllocationMode PassAlignment
Definition ExprCXX.h:2343
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:489
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:511
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:502
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:506
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:497
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:516