1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
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
7 //===----------------------------------------------------------------------===//
10 /// Implements semantic analysis for C++ expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/Template.h"
15 #include "clang/Sema/SemaInternal.h"
16 #include "TreeTransform.h"
17 #include "TypeLocBuilder.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTLambda.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/CharUnits.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/ExprCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/RecursiveASTVisitor.h"
26 #include "clang/AST/TypeLoc.h"
27 #include "clang/Basic/AlignedAllocation.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/Initialization.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaLambda.h"
38 #include "clang/Sema/TemplateDeduction.h"
39 #include "llvm/ADT/APInt.h"
40 #include "llvm/ADT/STLExtras.h"
41 #include "llvm/Support/ErrorHandling.h"
42 using namespace clang;
45 /// Handle the result of the special case name lookup for inheriting
46 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47 /// constructor names in member using declarations, even if 'X' is not the
48 /// name of the corresponding type.
49 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
54 // Convert the nested-name-specifier into a type.
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
70 case NestedNameSpecifier::Global:
71 case NestedNameSpecifier::Super:
72 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
83 ParsedType Sema::getConstructorName(IdentifierInfo &II,
84 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 bool EnteringContext) {
87 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88 assert(CurClass && &II == CurClass->getIdentifier() &&
89 "not a constructor name");
91 // When naming a constructor as a member of a dependent context (eg, in a
92 // friend declaration or an inherited constructor declaration), form an
93 // unresolved "typename" type.
94 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
95 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96 return ParsedType::make(T);
99 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
102 // Find the injected-class-name declaration. Note that we make no attempt to
103 // diagnose cases where the injected-class-name is shadowed: the only
104 // declaration that can validly shadow the injected-class-name is a
105 // non-static data member, and if the class contains both a non-static data
106 // member and a constructor then it is ill-formed (we check that in
107 // CheckCompletedCXXClass).
108 CXXRecordDecl *InjectedClassName = nullptr;
109 for (NamedDecl *ND : CurClass->lookup(&II)) {
110 auto *RD = dyn_cast<CXXRecordDecl>(ND);
111 if (RD && RD->isInjectedClassName()) {
112 InjectedClassName = RD;
116 if (!InjectedClassName) {
117 if (!CurClass->isInvalidDecl()) {
118 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119 // properly. Work around it here for now.
120 Diag(SS.getLastQualifierNameLoc(),
121 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
126 QualType T = Context.getTypeDeclType(InjectedClassName);
127 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
130 return ParsedType::make(T);
133 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
135 SourceLocation NameLoc,
136 Scope *S, CXXScopeSpec &SS,
137 ParsedType ObjectTypePtr,
138 bool EnteringContext) {
139 // Determine where to perform name lookup.
141 // FIXME: This area of the standard is very messy, and the current
142 // wording is rather unclear about which scopes we search for the
143 // destructor name; see core issues 399 and 555. Issue 399 in
144 // particular shows where the current description of destructor name
145 // lookup is completely out of line with existing practice, e.g.,
146 // this appears to be ill-formed:
149 // template <typename T> struct S {
154 // void f(N::S<int>* s) {
155 // s->N::S<int>::~S();
158 // See also PR6358 and PR6359.
159 // For this reason, we're currently only doing the C++03 version of this
160 // code; the C++0x version has to wait until we get a proper spec.
162 DeclContext *LookupCtx = nullptr;
163 bool isDependent = false;
164 bool LookInScope = false;
169 // If we have an object type, it's because we are in a
170 // pseudo-destructor-expression or a member access expression, and
171 // we know what type we're looking for.
173 SearchType = GetTypeFromParser(ObjectTypePtr);
176 NestedNameSpecifier *NNS = SS.getScopeRep();
178 bool AlreadySearched = false;
179 bool LookAtPrefix = true;
180 // C++11 [basic.lookup.qual]p6:
181 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
182 // the type-names are looked up as types in the scope designated by the
183 // nested-name-specifier. Similarly, in a qualified-id of the form:
185 // nested-name-specifier[opt] class-name :: ~ class-name
187 // the second class-name is looked up in the same scope as the first.
189 // Here, we determine whether the code below is permitted to look at the
190 // prefix of the nested-name-specifier.
191 DeclContext *DC = computeDeclContext(SS, EnteringContext);
192 if (DC && DC->isFileContext()) {
193 AlreadySearched = true;
196 } else if (DC && isa<CXXRecordDecl>(DC)) {
197 LookAtPrefix = false;
201 // The second case from the C++03 rules quoted further above.
202 NestedNameSpecifier *Prefix = nullptr;
203 if (AlreadySearched) {
204 // Nothing left to do.
205 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
206 CXXScopeSpec PrefixSS;
207 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
208 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
209 isDependent = isDependentScopeSpecifier(PrefixSS);
210 } else if (ObjectTypePtr) {
211 LookupCtx = computeDeclContext(SearchType);
212 isDependent = SearchType->isDependentType();
214 LookupCtx = computeDeclContext(SS, EnteringContext);
215 isDependent = LookupCtx && LookupCtx->isDependentContext();
217 } else if (ObjectTypePtr) {
218 // C++ [basic.lookup.classref]p3:
219 // If the unqualified-id is ~type-name, the type-name is looked up
220 // in the context of the entire postfix-expression. If the type T
221 // of the object expression is of a class type C, the type-name is
222 // also looked up in the scope of class C. At least one of the
223 // lookups shall find a name that refers to (possibly
225 LookupCtx = computeDeclContext(SearchType);
226 isDependent = SearchType->isDependentType();
227 assert((isDependent || !SearchType->isIncompleteType()) &&
228 "Caller should have completed object type");
232 // Perform lookup into the current scope (only).
236 TypeDecl *NonMatchingTypeDecl = nullptr;
237 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
238 for (unsigned Step = 0; Step != 2; ++Step) {
239 // Look for the name first in the computed lookup context (if we
240 // have one) and, if that fails to find a match, in the scope (if
241 // we're allowed to look there).
243 if (Step == 0 && LookupCtx) {
244 if (RequireCompleteDeclContext(SS, LookupCtx))
246 LookupQualifiedName(Found, LookupCtx);
247 } else if (Step == 1 && LookInScope && S) {
248 LookupName(Found, S);
253 // FIXME: Should we be suppressing ambiguities here?
254 if (Found.isAmbiguous())
257 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
258 QualType T = Context.getTypeDeclType(Type);
259 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
261 if (SearchType.isNull() || SearchType->isDependentType() ||
262 Context.hasSameUnqualifiedType(T, SearchType)) {
263 // We found our type!
265 return CreateParsedType(T,
266 Context.getTrivialTypeSourceInfo(T, NameLoc));
269 if (!SearchType.isNull())
270 NonMatchingTypeDecl = Type;
273 // If the name that we found is a class template name, and it is
274 // the same name as the template name in the last part of the
275 // nested-name-specifier (if present) or the object type, then
276 // this is the destructor for that class.
277 // FIXME: This is a workaround until we get real drafting for core
278 // issue 399, for which there isn't even an obvious direction.
279 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
280 QualType MemberOfType;
282 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
283 // Figure out the type of the context, if it has one.
284 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
285 MemberOfType = Context.getTypeDeclType(Record);
288 if (MemberOfType.isNull())
289 MemberOfType = SearchType;
291 if (MemberOfType.isNull())
294 // We're referring into a class template specialization. If the
295 // class template we found is the same as the template being
296 // specialized, we found what we are looking for.
297 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
298 if (ClassTemplateSpecializationDecl *Spec
299 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
300 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
301 Template->getCanonicalDecl())
302 return CreateParsedType(
304 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
310 // We're referring to an unresolved class template
311 // specialization. Determine whether we class template we found
312 // is the same as the template being specialized or, if we don't
313 // know which template is being specialized, that it at least
314 // has the same name.
315 if (const TemplateSpecializationType *SpecType
316 = MemberOfType->getAs<TemplateSpecializationType>()) {
317 TemplateName SpecName = SpecType->getTemplateName();
319 // The class template we found is the same template being
321 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
322 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
323 return CreateParsedType(
325 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
330 // The class template we found has the same name as the
331 // (dependent) template name being specialized.
332 if (DependentTemplateName *DepTemplate
333 = SpecName.getAsDependentTemplateName()) {
334 if (DepTemplate->isIdentifier() &&
335 DepTemplate->getIdentifier() == Template->getIdentifier())
336 return CreateParsedType(
338 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
347 // We didn't find our type, but that's okay: it's dependent
350 // FIXME: What if we have no nested-name-specifier?
351 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
352 SS.getWithLocInContext(Context),
354 return ParsedType::make(T);
357 if (NonMatchingTypeDecl) {
358 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
359 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
361 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
363 } else if (ObjectTypePtr)
364 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
367 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
368 diag::err_destructor_class_name);
370 const DeclContext *Ctx = S->getEntity();
371 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
372 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
373 Class->getNameAsString());
380 ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
381 ParsedType ObjectType) {
382 if (DS.getTypeSpecType() == DeclSpec::TST_error)
385 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
386 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
390 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
391 "unexpected type in getDestructorType");
392 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
394 // If we know the type of the object, check that the correct destructor
395 // type was named now; we can give better diagnostics this way.
396 QualType SearchType = GetTypeFromParser(ObjectType);
397 if (!SearchType.isNull() && !SearchType->isDependentType() &&
398 !Context.hasSameUnqualifiedType(T, SearchType)) {
399 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
404 return ParsedType::make(T);
407 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
408 const UnqualifiedId &Name) {
409 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId);
414 switch (SS.getScopeRep()->getKind()) {
415 case NestedNameSpecifier::Identifier:
416 case NestedNameSpecifier::TypeSpec:
417 case NestedNameSpecifier::TypeSpecWithTemplate:
418 // Per C++11 [over.literal]p2, literal operators can only be declared at
419 // namespace scope. Therefore, this unqualified-id cannot name anything.
420 // Reject it early, because we have no AST representation for this in the
421 // case where the scope is dependent.
422 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
426 case NestedNameSpecifier::Global:
427 case NestedNameSpecifier::Super:
428 case NestedNameSpecifier::Namespace:
429 case NestedNameSpecifier::NamespaceAlias:
433 llvm_unreachable("unknown nested name specifier kind");
436 /// Build a C++ typeid expression with a type operand.
437 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
438 SourceLocation TypeidLoc,
439 TypeSourceInfo *Operand,
440 SourceLocation RParenLoc) {
441 // C++ [expr.typeid]p4:
442 // The top-level cv-qualifiers of the lvalue expression or the type-id
443 // that is the operand of typeid are always ignored.
444 // If the type of the type-id is a class type or a reference to a class
445 // type, the class shall be completely-defined.
448 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
450 if (T->getAs<RecordType>() &&
451 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
454 if (T->isVariablyModifiedType())
455 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
457 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
460 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
461 SourceRange(TypeidLoc, RParenLoc));
464 /// Build a C++ typeid expression with an expression operand.
465 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
466 SourceLocation TypeidLoc,
468 SourceLocation RParenLoc) {
469 bool WasEvaluated = false;
470 if (E && !E->isTypeDependent()) {
471 if (E->getType()->isPlaceholderType()) {
472 ExprResult result = CheckPlaceholderExpr(E);
473 if (result.isInvalid()) return ExprError();
477 QualType T = E->getType();
478 if (const RecordType *RecordT = T->getAs<RecordType>()) {
479 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
480 // C++ [expr.typeid]p3:
481 // [...] If the type of the expression is a class type, the class
482 // shall be completely-defined.
483 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
486 // C++ [expr.typeid]p3:
487 // When typeid is applied to an expression other than an glvalue of a
488 // polymorphic class type [...] [the] expression is an unevaluated
490 if (RecordD->isPolymorphic() && E->isGLValue()) {
491 // The subexpression is potentially evaluated; switch the context
492 // and recheck the subexpression.
493 ExprResult Result = TransformToPotentiallyEvaluated(E);
494 if (Result.isInvalid()) return ExprError();
497 // We require a vtable to query the type at run time.
498 MarkVTableUsed(TypeidLoc, RecordD);
503 ExprResult Result = CheckUnevaluatedOperand(E);
504 if (Result.isInvalid())
508 // C++ [expr.typeid]p4:
509 // [...] If the type of the type-id is a reference to a possibly
510 // cv-qualified type, the result of the typeid expression refers to a
511 // std::type_info object representing the cv-unqualified referenced
514 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
515 if (!Context.hasSameType(T, UnqualT)) {
517 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
521 if (E->getType()->isVariablyModifiedType())
522 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
524 else if (!inTemplateInstantiation() &&
525 E->HasSideEffects(Context, WasEvaluated)) {
526 // The expression operand for typeid is in an unevaluated expression
527 // context, so side effects could result in unintended consequences.
528 Diag(E->getExprLoc(), WasEvaluated
529 ? diag::warn_side_effects_typeid
530 : diag::warn_side_effects_unevaluated_context);
533 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
534 SourceRange(TypeidLoc, RParenLoc));
537 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
539 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
540 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
541 // typeid is not supported in OpenCL.
542 if (getLangOpts().OpenCLCPlusPlus) {
543 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
547 // Find the std::type_info type.
548 if (!getStdNamespace())
549 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
551 if (!CXXTypeInfoDecl) {
552 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
553 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
554 LookupQualifiedName(R, getStdNamespace());
555 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
556 // Microsoft's typeinfo doesn't have type_info in std but in the global
557 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
558 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
559 LookupQualifiedName(R, Context.getTranslationUnitDecl());
560 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
562 if (!CXXTypeInfoDecl)
563 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
566 if (!getLangOpts().RTTI) {
567 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
570 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
573 // The operand is a type; handle it as such.
574 TypeSourceInfo *TInfo = nullptr;
575 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
581 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
583 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
586 // The operand is an expression.
587 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
590 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
593 getUuidAttrOfType(Sema &SemaRef, QualType QT,
594 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
595 // Optionally remove one level of pointer, reference or array indirection.
596 const Type *Ty = QT.getTypePtr();
597 if (QT->isPointerType() || QT->isReferenceType())
598 Ty = QT->getPointeeType().getTypePtr();
599 else if (QT->isArrayType())
600 Ty = Ty->getBaseElementTypeUnsafe();
602 const auto *TD = Ty->getAsTagDecl();
606 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
607 UuidAttrs.insert(Uuid);
611 // __uuidof can grab UUIDs from template arguments.
612 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
613 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
614 for (const TemplateArgument &TA : TAL.asArray()) {
615 const UuidAttr *UuidForTA = nullptr;
616 if (TA.getKind() == TemplateArgument::Type)
617 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
618 else if (TA.getKind() == TemplateArgument::Declaration)
619 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
622 UuidAttrs.insert(UuidForTA);
627 /// Build a Microsoft __uuidof expression with a type operand.
628 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
629 SourceLocation TypeidLoc,
630 TypeSourceInfo *Operand,
631 SourceLocation RParenLoc) {
633 if (!Operand->getType()->isDependentType()) {
634 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
635 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
636 if (UuidAttrs.empty())
637 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
638 if (UuidAttrs.size() > 1)
639 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
640 UuidStr = UuidAttrs.back()->getGuid();
643 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
644 SourceRange(TypeidLoc, RParenLoc));
647 /// Build a Microsoft __uuidof expression with an expression operand.
648 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
649 SourceLocation TypeidLoc,
651 SourceLocation RParenLoc) {
653 if (!E->getType()->isDependentType()) {
654 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
655 UuidStr = "00000000-0000-0000-0000-000000000000";
657 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
658 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
659 if (UuidAttrs.empty())
660 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
661 if (UuidAttrs.size() > 1)
662 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
663 UuidStr = UuidAttrs.back()->getGuid();
667 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
668 SourceRange(TypeidLoc, RParenLoc));
671 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
673 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
674 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
675 // If MSVCGuidDecl has not been cached, do the lookup.
677 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
678 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
679 LookupQualifiedName(R, Context.getTranslationUnitDecl());
680 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
682 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
685 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
688 // The operand is a type; handle it as such.
689 TypeSourceInfo *TInfo = nullptr;
690 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
696 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
698 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
701 // The operand is an expression.
702 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
705 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
707 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
708 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
709 "Unknown C++ Boolean value!");
711 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
714 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
716 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
717 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
720 /// ActOnCXXThrow - Parse throw expressions.
722 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
723 bool IsThrownVarInScope = false;
725 // C++0x [class.copymove]p31:
726 // When certain criteria are met, an implementation is allowed to omit the
727 // copy/move construction of a class object [...]
729 // - in a throw-expression, when the operand is the name of a
730 // non-volatile automatic object (other than a function or catch-
731 // clause parameter) whose scope does not extend beyond the end of the
732 // innermost enclosing try-block (if there is one), the copy/move
733 // operation from the operand to the exception object (15.1) can be
734 // omitted by constructing the automatic object directly into the
736 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
737 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
738 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
739 for( ; S; S = S->getParent()) {
740 if (S->isDeclScope(Var)) {
741 IsThrownVarInScope = true;
746 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
747 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
755 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
758 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
759 bool IsThrownVarInScope) {
760 // Don't report an error if 'throw' is used in system headers.
761 if (!getLangOpts().CXXExceptions &&
762 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
763 // Delay error emission for the OpenMP device code.
764 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
767 // Exceptions aren't allowed in CUDA device code.
768 if (getLangOpts().CUDA)
769 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
770 << "throw" << CurrentCUDATarget();
772 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
773 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
775 if (Ex && !Ex->isTypeDependent()) {
776 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
777 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
780 // Initialize the exception result. This implicitly weeds out
781 // abstract types or types with inaccessible copy constructors.
783 // C++0x [class.copymove]p31:
784 // When certain criteria are met, an implementation is allowed to omit the
785 // copy/move construction of a class object [...]
787 // - in a throw-expression, when the operand is the name of a
788 // non-volatile automatic object (other than a function or
790 // parameter) whose scope does not extend beyond the end of the
791 // innermost enclosing try-block (if there is one), the copy/move
792 // operation from the operand to the exception object (15.1) can be
793 // omitted by constructing the automatic object directly into the
795 const VarDecl *NRVOVariable = nullptr;
796 if (IsThrownVarInScope)
797 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
799 InitializedEntity Entity = InitializedEntity::InitializeException(
800 OpLoc, ExceptionObjectTy,
801 /*NRVO=*/NRVOVariable != nullptr);
802 ExprResult Res = PerformMoveOrCopyInitialization(
803 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
810 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
814 collectPublicBases(CXXRecordDecl *RD,
815 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
816 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
817 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
818 bool ParentIsPublic) {
819 for (const CXXBaseSpecifier &BS : RD->bases()) {
820 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
822 // Virtual bases constitute the same subobject. Non-virtual bases are
823 // always distinct subobjects.
825 NewSubobject = VBases.insert(BaseDecl).second;
830 ++SubobjectsSeen[BaseDecl];
832 // Only add subobjects which have public access throughout the entire chain.
833 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
835 PublicSubobjectsSeen.insert(BaseDecl);
837 // Recurse on to each base subobject.
838 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
843 static void getUnambiguousPublicSubobjects(
844 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
845 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
846 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
847 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
848 SubobjectsSeen[RD] = 1;
849 PublicSubobjectsSeen.insert(RD);
850 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
851 /*ParentIsPublic=*/true);
853 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
854 // Skip ambiguous objects.
855 if (SubobjectsSeen[PublicSubobject] > 1)
858 Objects.push_back(PublicSubobject);
862 /// CheckCXXThrowOperand - Validate the operand of a throw.
863 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
864 QualType ExceptionObjectTy, Expr *E) {
865 // If the type of the exception would be an incomplete type or a pointer
866 // to an incomplete type other than (cv) void the program is ill-formed.
867 QualType Ty = ExceptionObjectTy;
868 bool isPointer = false;
869 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
870 Ty = Ptr->getPointeeType();
873 if (!isPointer || !Ty->isVoidType()) {
874 if (RequireCompleteType(ThrowLoc, Ty,
875 isPointer ? diag::err_throw_incomplete_ptr
876 : diag::err_throw_incomplete,
877 E->getSourceRange()))
880 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
881 diag::err_throw_abstract_type, E))
885 // If the exception has class type, we need additional handling.
886 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
890 // If we are throwing a polymorphic class type or pointer thereof,
891 // exception handling will make use of the vtable.
892 MarkVTableUsed(ThrowLoc, RD);
894 // If a pointer is thrown, the referenced object will not be destroyed.
898 // If the class has a destructor, we must be able to call it.
899 if (!RD->hasIrrelevantDestructor()) {
900 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
901 MarkFunctionReferenced(E->getExprLoc(), Destructor);
902 CheckDestructorAccess(E->getExprLoc(), Destructor,
903 PDiag(diag::err_access_dtor_exception) << Ty);
904 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
909 // The MSVC ABI creates a list of all types which can catch the exception
910 // object. This list also references the appropriate copy constructor to call
911 // if the object is caught by value and has a non-trivial copy constructor.
912 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
913 // We are only interested in the public, unambiguous bases contained within
914 // the exception object. Bases which are ambiguous or otherwise
915 // inaccessible are not catchable types.
916 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
917 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
919 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
920 // Attempt to lookup the copy constructor. Various pieces of machinery
921 // will spring into action, like template instantiation, which means this
922 // cannot be a simple walk of the class's decls. Instead, we must perform
923 // lookup and overload resolution.
924 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
925 if (!CD || CD->isDeleted())
928 // Mark the constructor referenced as it is used by this throw expression.
929 MarkFunctionReferenced(E->getExprLoc(), CD);
931 // Skip this copy constructor if it is trivial, we don't need to record it
932 // in the catchable type data.
936 // The copy constructor is non-trivial, create a mapping from this class
937 // type to this constructor.
938 // N.B. The selection of copy constructor is not sensitive to this
939 // particular throw-site. Lookup will be performed at the catch-site to
940 // ensure that the copy constructor is, in fact, accessible (via
941 // friendship or any other means).
942 Context.addCopyConstructorForExceptionObject(Subobject, CD);
944 // We don't keep the instantiated default argument expressions around so
945 // we must rebuild them here.
946 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
947 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
953 // Under the Itanium C++ ABI, memory for the exception object is allocated by
954 // the runtime with no ability for the compiler to request additional
955 // alignment. Warn if the exception type requires alignment beyond the minimum
956 // guaranteed by the target C++ runtime.
957 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
958 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
959 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
960 if (ExnObjAlign < TypeAlign) {
961 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
962 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
963 << Ty << (unsigned)TypeAlign.getQuantity()
964 << (unsigned)ExnObjAlign.getQuantity();
971 static QualType adjustCVQualifiersForCXXThisWithinLambda(
972 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
973 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
975 QualType ClassType = ThisTy->getPointeeType();
976 LambdaScopeInfo *CurLSI = nullptr;
977 DeclContext *CurDC = CurSemaContext;
979 // Iterate through the stack of lambdas starting from the innermost lambda to
980 // the outermost lambda, checking if '*this' is ever captured by copy - since
981 // that could change the cv-qualifiers of the '*this' object.
982 // The object referred to by '*this' starts out with the cv-qualifiers of its
983 // member function. We then start with the innermost lambda and iterate
984 // outward checking to see if any lambda performs a by-copy capture of '*this'
985 // - and if so, any nested lambda must respect the 'constness' of that
986 // capturing lamdbda's call operator.
989 // Since the FunctionScopeInfo stack is representative of the lexical
990 // nesting of the lambda expressions during initial parsing (and is the best
991 // place for querying information about captures about lambdas that are
992 // partially processed) and perhaps during instantiation of function templates
993 // that contain lambda expressions that need to be transformed BUT not
994 // necessarily during instantiation of a nested generic lambda's function call
995 // operator (which might even be instantiated at the end of the TU) - at which
996 // time the DeclContext tree is mature enough to query capture information
997 // reliably - we use a two pronged approach to walk through all the lexically
998 // enclosing lambda expressions:
1000 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1001 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1002 // enclosed by the call-operator of the LSI below it on the stack (while
1003 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1004 // the stack represents the innermost lambda.
1006 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1007 // represents a lambda's call operator. If it does, we must be instantiating
1008 // a generic lambda's call operator (represented by the Current LSI, and
1009 // should be the only scenario where an inconsistency between the LSI and the
1010 // DeclContext should occur), so climb out the DeclContexts if they
1011 // represent lambdas, while querying the corresponding closure types
1012 // regarding capture information.
1014 // 1) Climb down the function scope info stack.
1015 for (int I = FunctionScopes.size();
1016 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1017 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1018 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1019 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1020 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1022 if (!CurLSI->isCXXThisCaptured())
1025 auto C = CurLSI->getCXXThisCapture();
1027 if (C.isCopyCapture()) {
1028 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1029 if (CurLSI->CallOperator->isConst())
1030 ClassType.addConst();
1031 return ASTCtx.getPointerType(ClassType);
1035 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1036 // happen during instantiation of its nested generic lambda call operator)
1037 if (isLambdaCallOperator(CurDC)) {
1038 assert(CurLSI && "While computing 'this' capture-type for a generic "
1039 "lambda, we must have a corresponding LambdaScopeInfo");
1040 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
1041 "While computing 'this' capture-type for a generic lambda, when we "
1042 "run out of enclosing LSI's, yet the enclosing DC is a "
1043 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
1044 "lambda call oeprator");
1045 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
1047 auto IsThisCaptured =
1048 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1051 for (auto &&C : Closure->captures()) {
1052 if (C.capturesThis()) {
1053 if (C.getCaptureKind() == LCK_StarThis)
1055 if (Closure->getLambdaCallOperator()->isConst())
1063 bool IsByCopyCapture = false;
1064 bool IsConstCapture = false;
1065 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1067 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1068 if (IsByCopyCapture) {
1069 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1071 ClassType.addConst();
1072 return ASTCtx.getPointerType(ClassType);
1074 Closure = isLambdaCallOperator(Closure->getParent())
1075 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1079 return ASTCtx.getPointerType(ClassType);
1082 QualType Sema::getCurrentThisType() {
1083 DeclContext *DC = getFunctionLevelDeclContext();
1084 QualType ThisTy = CXXThisTypeOverride;
1086 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1087 if (method && method->isInstance())
1088 ThisTy = method->getThisType();
1091 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1092 inTemplateInstantiation()) {
1094 assert(isa<CXXRecordDecl>(DC) &&
1095 "Trying to get 'this' type from static method?");
1097 // This is a lambda call operator that is being instantiated as a default
1098 // initializer. DC must point to the enclosing class type, so we can recover
1099 // the 'this' type from it.
1101 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1102 // There are no cv-qualifiers for 'this' within default initializers,
1103 // per [expr.prim.general]p4.
1104 ThisTy = Context.getPointerType(ClassTy);
1107 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1108 // might need to be adjusted if the lambda or any of its enclosing lambda's
1109 // captures '*this' by copy.
1110 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1111 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1112 CurContext, Context);
1116 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1118 Qualifiers CXXThisTypeQuals,
1120 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1122 if (!Enabled || !ContextDecl)
1125 CXXRecordDecl *Record = nullptr;
1126 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1127 Record = Template->getTemplatedDecl();
1129 Record = cast<CXXRecordDecl>(ContextDecl);
1131 QualType T = S.Context.getRecordType(Record);
1132 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1134 S.CXXThisTypeOverride = S.Context.getPointerType(T);
1136 this->Enabled = true;
1140 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1142 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1146 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1147 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1148 const bool ByCopy) {
1149 // We don't need to capture this in an unevaluated context.
1150 if (isUnevaluatedContext() && !Explicit)
1153 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1155 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1156 ? *FunctionScopeIndexToStopAt
1157 : FunctionScopes.size() - 1;
1159 // Check that we can capture the *enclosing object* (referred to by '*this')
1160 // by the capturing-entity/closure (lambda/block/etc) at
1161 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1163 // Note: The *enclosing object* can only be captured by-value by a
1164 // closure that is a lambda, using the explicit notation:
1166 // Every other capture of the *enclosing object* results in its by-reference
1169 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1170 // stack), we can capture the *enclosing object* only if:
1171 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1172 // - or, 'L' has an implicit capture.
1174 // -- there is no enclosing closure
1175 // -- or, there is some enclosing closure 'E' that has already captured the
1176 // *enclosing object*, and every intervening closure (if any) between 'E'
1177 // and 'L' can implicitly capture the *enclosing object*.
1178 // -- or, every enclosing closure can implicitly capture the
1179 // *enclosing object*
1182 unsigned NumCapturingClosures = 0;
1183 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1184 if (CapturingScopeInfo *CSI =
1185 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1186 if (CSI->CXXThisCaptureIndex != 0) {
1187 // 'this' is already being captured; there isn't anything more to do.
1188 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1191 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1192 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1193 // This context can't implicitly capture 'this'; fail out.
1194 if (BuildAndDiagnose)
1195 Diag(Loc, diag::err_this_capture)
1196 << (Explicit && idx == MaxFunctionScopesIndex);
1199 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1200 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1201 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1202 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1203 (Explicit && idx == MaxFunctionScopesIndex)) {
1204 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1205 // iteration through can be an explicit capture, all enclosing closures,
1206 // if any, must perform implicit captures.
1208 // This closure can capture 'this'; continue looking upwards.
1209 NumCapturingClosures++;
1212 // This context can't implicitly capture 'this'; fail out.
1213 if (BuildAndDiagnose)
1214 Diag(Loc, diag::err_this_capture)
1215 << (Explicit && idx == MaxFunctionScopesIndex);
1220 if (!BuildAndDiagnose) return false;
1222 // If we got here, then the closure at MaxFunctionScopesIndex on the
1223 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1224 // (including implicit by-reference captures in any enclosing closures).
1226 // In the loop below, respect the ByCopy flag only for the closure requesting
1227 // the capture (i.e. first iteration through the loop below). Ignore it for
1228 // all enclosing closure's up to NumCapturingClosures (since they must be
1229 // implicitly capturing the *enclosing object* by reference (see loop
1232 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1233 "Only a lambda can capture the enclosing object (referred to by "
1235 QualType ThisTy = getCurrentThisType();
1236 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1237 --idx, --NumCapturingClosures) {
1238 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1240 // The type of the corresponding data member (not a 'this' pointer if 'by
1242 QualType CaptureType = ThisTy;
1244 // If we are capturing the object referred to by '*this' by copy, ignore
1245 // any cv qualifiers inherited from the type of the member function for
1246 // the type of the closure-type's corresponding data member and any use
1248 CaptureType = ThisTy->getPointeeType();
1249 CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1252 bool isNested = NumCapturingClosures > 1;
1253 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1258 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1259 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1260 /// is a non-lvalue expression whose value is the address of the object for
1261 /// which the function is called.
1263 QualType ThisTy = getCurrentThisType();
1264 if (ThisTy.isNull())
1265 return Diag(Loc, diag::err_invalid_this_use);
1266 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1269 Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1271 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1272 MarkThisReferenced(This);
1276 void Sema::MarkThisReferenced(CXXThisExpr *This) {
1277 CheckCXXThisCapture(This->getExprLoc());
1280 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1281 // If we're outside the body of a member function, then we'll have a specified
1283 if (CXXThisTypeOverride.isNull())
1286 // Determine whether we're looking into a class that's currently being
1288 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1289 return Class && Class->isBeingDefined();
1292 /// Parse construction of a specified type.
1293 /// Can be interpreted either as function-style casting ("int(x)")
1294 /// or class type construction ("ClassType(x,y,z)")
1295 /// or creation of a value-initialized type ("int()").
1297 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1298 SourceLocation LParenOrBraceLoc,
1300 SourceLocation RParenOrBraceLoc,
1301 bool ListInitialization) {
1305 TypeSourceInfo *TInfo;
1306 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1308 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1310 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1311 RParenOrBraceLoc, ListInitialization);
1312 // Avoid creating a non-type-dependent expression that contains typos.
1313 // Non-type-dependent expressions are liable to be discarded without
1314 // checking for embedded typos.
1315 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1316 !Result.get()->isTypeDependent())
1317 Result = CorrectDelayedTyposInExpr(Result.get());
1322 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1323 SourceLocation LParenOrBraceLoc,
1325 SourceLocation RParenOrBraceLoc,
1326 bool ListInitialization) {
1327 QualType Ty = TInfo->getType();
1328 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1330 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1331 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1332 // directly. We work around this by dropping the locations of the braces.
1333 SourceRange Locs = ListInitialization
1335 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1336 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1337 Exprs, Locs.getEnd());
1340 assert((!ListInitialization ||
1341 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1342 "List initialization must have initializer list as expression.");
1343 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1345 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1346 InitializationKind Kind =
1348 ? ListInitialization
1349 ? InitializationKind::CreateDirectList(
1350 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1351 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1353 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1356 // C++1z [expr.type.conv]p1:
1357 // If the type is a placeholder for a deduced class type, [...perform class
1358 // template argument deduction...]
1359 DeducedType *Deduced = Ty->getContainedDeducedType();
1360 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1361 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1365 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1368 // C++ [expr.type.conv]p1:
1369 // If the expression list is a parenthesized single expression, the type
1370 // conversion expression is equivalent (in definedness, and if defined in
1371 // meaning) to the corresponding cast expression.
1372 if (Exprs.size() == 1 && !ListInitialization &&
1373 !isa<InitListExpr>(Exprs[0])) {
1374 Expr *Arg = Exprs[0];
1375 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1379 // For an expression of the form T(), T shall not be an array type.
1380 QualType ElemTy = Ty;
1381 if (Ty->isArrayType()) {
1382 if (!ListInitialization)
1383 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1385 ElemTy = Context.getBaseElementType(Ty);
1388 // There doesn't seem to be an explicit rule against this but sanity demands
1389 // we only construct objects with object types.
1390 if (Ty->isFunctionType())
1391 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1392 << Ty << FullRange);
1394 // C++17 [expr.type.conv]p2:
1395 // If the type is cv void and the initializer is (), the expression is a
1396 // prvalue of the specified type that performs no initialization.
1397 if (!Ty->isVoidType() &&
1398 RequireCompleteType(TyBeginLoc, ElemTy,
1399 diag::err_invalid_incomplete_type_use, FullRange))
1402 // Otherwise, the expression is a prvalue of the specified type whose
1403 // result object is direct-initialized (11.6) with the initializer.
1404 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1405 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1407 if (Result.isInvalid())
1410 Expr *Inner = Result.get();
1411 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1412 Inner = BTE->getSubExpr();
1413 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1414 !isa<CXXScalarValueInitExpr>(Inner)) {
1415 // If we created a CXXTemporaryObjectExpr, that node also represents the
1416 // functional cast. Otherwise, create an explicit cast to represent
1417 // the syntactic form of a functional-style cast that was used here.
1419 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1420 // would give a more consistent AST representation than using a
1421 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1422 // is sometimes handled by initialization and sometimes not.
1423 QualType ResultType = Result.get()->getType();
1424 SourceRange Locs = ListInitialization
1426 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1427 Result = CXXFunctionalCastExpr::Create(
1428 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1429 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1435 bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1436 // [CUDA] Ignore this function, if we can't call it.
1437 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1438 if (getLangOpts().CUDA &&
1439 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1442 SmallVector<const FunctionDecl*, 4> PreventedBy;
1443 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1445 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1448 // In case of CUDA, return true if none of the 1-argument deallocator
1449 // functions are actually callable.
1450 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1451 assert(FD->getNumParams() == 1 &&
1452 "Only single-operand functions should be in PreventedBy");
1453 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1457 /// Determine whether the given function is a non-placement
1458 /// deallocation function.
1459 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1460 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1461 return S.isUsualDeallocationFunction(Method);
1463 if (FD->getOverloadedOperator() != OO_Delete &&
1464 FD->getOverloadedOperator() != OO_Array_Delete)
1467 unsigned UsualParams = 1;
1469 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1470 S.Context.hasSameUnqualifiedType(
1471 FD->getParamDecl(UsualParams)->getType(),
1472 S.Context.getSizeType()))
1475 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1476 S.Context.hasSameUnqualifiedType(
1477 FD->getParamDecl(UsualParams)->getType(),
1478 S.Context.getTypeDeclType(S.getStdAlignValT())))
1481 return UsualParams == FD->getNumParams();
1485 struct UsualDeallocFnInfo {
1486 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1487 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1488 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1489 Destroying(false), HasSizeT(false), HasAlignValT(false),
1490 CUDAPref(Sema::CFP_Native) {
1491 // A function template declaration is never a usual deallocation function.
1494 unsigned NumBaseParams = 1;
1495 if (FD->isDestroyingOperatorDelete()) {
1500 if (NumBaseParams < FD->getNumParams() &&
1501 S.Context.hasSameUnqualifiedType(
1502 FD->getParamDecl(NumBaseParams)->getType(),
1503 S.Context.getSizeType())) {
1508 if (NumBaseParams < FD->getNumParams() &&
1509 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1511 HasAlignValT = true;
1514 // In CUDA, determine how much we'd like / dislike to call this.
1515 if (S.getLangOpts().CUDA)
1516 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1517 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1520 explicit operator bool() const { return FD; }
1522 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1523 bool WantAlign) const {
1525 // A destroying operator delete is preferred over a non-destroying
1527 if (Destroying != Other.Destroying)
1530 // C++17 [expr.delete]p10:
1531 // If the type has new-extended alignment, a function with a parameter
1532 // of type std::align_val_t is preferred; otherwise a function without
1533 // such a parameter is preferred
1534 if (HasAlignValT != Other.HasAlignValT)
1535 return HasAlignValT == WantAlign;
1537 if (HasSizeT != Other.HasSizeT)
1538 return HasSizeT == WantSize;
1540 // Use CUDA call preference as a tiebreaker.
1541 return CUDAPref > Other.CUDAPref;
1544 DeclAccessPair Found;
1546 bool Destroying, HasSizeT, HasAlignValT;
1547 Sema::CUDAFunctionPreference CUDAPref;
1551 /// Determine whether a type has new-extended alignment. This may be called when
1552 /// the type is incomplete (for a delete-expression with an incomplete pointee
1553 /// type), in which case it will conservatively return false if the alignment is
1555 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1556 return S.getLangOpts().AlignedAllocation &&
1557 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1558 S.getASTContext().getTargetInfo().getNewAlign();
1561 /// Select the correct "usual" deallocation function to use from a selection of
1562 /// deallocation functions (either global or class-scope).
1563 static UsualDeallocFnInfo resolveDeallocationOverload(
1564 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1565 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1566 UsualDeallocFnInfo Best;
1568 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1569 UsualDeallocFnInfo Info(S, I.getPair());
1570 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1571 Info.CUDAPref == Sema::CFP_Never)
1577 BestFns->push_back(Info);
1581 if (Best.isBetterThan(Info, WantSize, WantAlign))
1584 // If more than one preferred function is found, all non-preferred
1585 // functions are eliminated from further consideration.
1586 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1591 BestFns->push_back(Info);
1597 /// Determine whether a given type is a class for which 'delete[]' would call
1598 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1599 /// we need to store the array size (even if the type is
1600 /// trivially-destructible).
1601 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1602 QualType allocType) {
1603 const RecordType *record =
1604 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1605 if (!record) return false;
1607 // Try to find an operator delete[] in class scope.
1609 DeclarationName deleteName =
1610 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1611 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1612 S.LookupQualifiedName(ops, record->getDecl());
1614 // We're just doing this for information.
1615 ops.suppressDiagnostics();
1617 // Very likely: there's no operator delete[].
1618 if (ops.empty()) return false;
1620 // If it's ambiguous, it should be illegal to call operator delete[]
1621 // on this thing, so it doesn't matter if we allocate extra space or not.
1622 if (ops.isAmbiguous()) return false;
1624 // C++17 [expr.delete]p10:
1625 // If the deallocation functions have class scope, the one without a
1626 // parameter of type std::size_t is selected.
1627 auto Best = resolveDeallocationOverload(
1628 S, ops, /*WantSize*/false,
1629 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1630 return Best && Best.HasSizeT;
1633 /// Parsed a C++ 'new' expression (C++ 5.3.4).
1636 /// @code new (memory) int[size][4] @endcode
1638 /// @code ::new Foo(23, "hello") @endcode
1640 /// \param StartLoc The first location of the expression.
1641 /// \param UseGlobal True if 'new' was prefixed with '::'.
1642 /// \param PlacementLParen Opening paren of the placement arguments.
1643 /// \param PlacementArgs Placement new arguments.
1644 /// \param PlacementRParen Closing paren of the placement arguments.
1645 /// \param TypeIdParens If the type is in parens, the source range.
1646 /// \param D The type to be allocated, as well as array dimensions.
1647 /// \param Initializer The initializing expression or initializer-list, or null
1648 /// if there is none.
1650 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1651 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1652 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1653 Declarator &D, Expr *Initializer) {
1654 Optional<Expr *> ArraySize;
1655 // If the specified type is an array, unwrap it and save the expression.
1656 if (D.getNumTypeObjects() > 0 &&
1657 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1658 DeclaratorChunk &Chunk = D.getTypeObject(0);
1659 if (D.getDeclSpec().hasAutoTypeSpec())
1660 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1661 << D.getSourceRange());
1662 if (Chunk.Arr.hasStatic)
1663 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1664 << D.getSourceRange());
1665 if (!Chunk.Arr.NumElts && !Initializer)
1666 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1667 << D.getSourceRange());
1669 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1670 D.DropFirstTypeObject();
1673 // Every dimension shall be of constant size.
1675 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1676 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1679 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1680 if (Expr *NumElts = (Expr *)Array.NumElts) {
1681 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1682 if (getLangOpts().CPlusPlus14) {
1683 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1684 // shall be a converted constant expression (5.19) of type std::size_t
1685 // and shall evaluate to a strictly positive value.
1686 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1687 assert(IntWidth && "Builtin type of size 0?");
1688 llvm::APSInt Value(IntWidth);
1690 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1695 = VerifyIntegerConstantExpression(NumElts, nullptr,
1696 diag::err_new_array_nonconst)
1706 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1707 QualType AllocType = TInfo->getType();
1708 if (D.isInvalidType())
1711 SourceRange DirectInitRange;
1712 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1713 DirectInitRange = List->getSourceRange();
1715 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1716 PlacementLParen, PlacementArgs, PlacementRParen,
1717 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1721 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1725 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1726 return PLE->getNumExprs() == 0;
1727 if (isa<ImplicitValueInitExpr>(Init))
1729 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1730 return !CCE->isListInitialization() &&
1731 CCE->getConstructor()->isDefaultConstructor();
1732 else if (Style == CXXNewExpr::ListInit) {
1733 assert(isa<InitListExpr>(Init) &&
1734 "Shouldn't create list CXXConstructExprs for arrays.");
1741 Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1742 if (!getLangOpts().AlignedAllocationUnavailable)
1746 bool IsAligned = false;
1747 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1752 // Emit a diagnostic if an aligned allocation/deallocation function that is not
1753 // implemented in the standard library is selected.
1754 void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1755 SourceLocation Loc) {
1756 if (isUnavailableAlignedAllocationFunction(FD)) {
1757 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1758 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1759 getASTContext().getTargetInfo().getPlatformName());
1761 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1762 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1763 Diag(Loc, diag::err_aligned_allocation_unavailable)
1764 << IsDelete << FD.getType().getAsString() << OSName
1765 << alignedAllocMinVersion(T.getOS()).getAsString();
1766 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1771 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1772 SourceLocation PlacementLParen,
1773 MultiExprArg PlacementArgs,
1774 SourceLocation PlacementRParen,
1775 SourceRange TypeIdParens,
1777 TypeSourceInfo *AllocTypeInfo,
1778 Optional<Expr *> ArraySize,
1779 SourceRange DirectInitRange,
1780 Expr *Initializer) {
1781 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1782 SourceLocation StartLoc = Range.getBegin();
1784 CXXNewExpr::InitializationStyle initStyle;
1785 if (DirectInitRange.isValid()) {
1786 assert(Initializer && "Have parens but no initializer.");
1787 initStyle = CXXNewExpr::CallInit;
1788 } else if (Initializer && isa<InitListExpr>(Initializer))
1789 initStyle = CXXNewExpr::ListInit;
1791 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1792 isa<CXXConstructExpr>(Initializer)) &&
1793 "Initializer expression that cannot have been implicitly created.");
1794 initStyle = CXXNewExpr::NoInit;
1797 Expr **Inits = &Initializer;
1798 unsigned NumInits = Initializer ? 1 : 0;
1799 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1800 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1801 Inits = List->getExprs();
1802 NumInits = List->getNumExprs();
1805 // C++11 [expr.new]p15:
1806 // A new-expression that creates an object of type T initializes that
1807 // object as follows:
1808 InitializationKind Kind
1809 // - If the new-initializer is omitted, the object is default-
1810 // initialized (8.5); if no initialization is performed,
1811 // the object has indeterminate value
1812 = initStyle == CXXNewExpr::NoInit
1813 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1814 // - Otherwise, the new-initializer is interpreted according to
1816 // initialization rules of 8.5 for direct-initialization.
1817 : initStyle == CXXNewExpr::ListInit
1818 ? InitializationKind::CreateDirectList(
1819 TypeRange.getBegin(), Initializer->getBeginLoc(),
1820 Initializer->getEndLoc())
1821 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1822 DirectInitRange.getBegin(),
1823 DirectInitRange.getEnd());
1825 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1826 auto *Deduced = AllocType->getContainedDeducedType();
1827 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1830 Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1831 diag::err_deduced_class_template_compound_type)
1833 << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
1835 InitializedEntity Entity
1836 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1837 AllocType = DeduceTemplateSpecializationFromInitializer(
1838 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1839 if (AllocType.isNull())
1841 } else if (Deduced) {
1842 bool Braced = (initStyle == CXXNewExpr::ListInit);
1843 if (NumInits == 1) {
1844 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1845 Inits = p->getInits();
1846 NumInits = p->getNumInits();
1851 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1852 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1853 << AllocType << TypeRange);
1855 Expr *FirstBad = Inits[1];
1856 return ExprError(Diag(FirstBad->getBeginLoc(),
1857 diag::err_auto_new_ctor_multiple_expressions)
1858 << AllocType << TypeRange);
1860 if (Braced && !getLangOpts().CPlusPlus17)
1861 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1862 << AllocType << TypeRange;
1863 Expr *Deduce = Inits[0];
1864 QualType DeducedType;
1865 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1866 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1867 << AllocType << Deduce->getType()
1868 << TypeRange << Deduce->getSourceRange());
1869 if (DeducedType.isNull())
1871 AllocType = DeducedType;
1874 // Per C++0x [expr.new]p5, the type being constructed may be a
1875 // typedef of an array type.
1877 if (const ConstantArrayType *Array
1878 = Context.getAsConstantArrayType(AllocType)) {
1879 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1880 Context.getSizeType(),
1881 TypeRange.getEnd());
1882 AllocType = Array->getElementType();
1886 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1889 // In ARC, infer 'retaining' for the allocated
1890 if (getLangOpts().ObjCAutoRefCount &&
1891 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1892 AllocType->isObjCLifetimeType()) {
1893 AllocType = Context.getLifetimeQualifiedType(AllocType,
1894 AllocType->getObjCARCImplicitLifetime());
1897 QualType ResultType = Context.getPointerType(AllocType);
1899 if (ArraySize && *ArraySize &&
1900 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1901 ExprResult result = CheckPlaceholderExpr(*ArraySize);
1902 if (result.isInvalid()) return ExprError();
1903 ArraySize = result.get();
1905 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1906 // integral or enumeration type with a non-negative value."
1907 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1908 // enumeration type, or a class type for which a single non-explicit
1909 // conversion function to integral or unscoped enumeration type exists.
1910 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1912 llvm::Optional<uint64_t> KnownArraySize;
1913 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
1914 ExprResult ConvertedSize;
1915 if (getLangOpts().CPlusPlus14) {
1916 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1918 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
1921 if (!ConvertedSize.isInvalid() &&
1922 (*ArraySize)->getType()->getAs<RecordType>())
1923 // Diagnose the compatibility of this conversion.
1924 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1925 << (*ArraySize)->getType() << 0 << "'size_t'";
1927 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1932 SizeConvertDiagnoser(Expr *ArraySize)
1933 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1934 ArraySize(ArraySize) {}
1936 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1937 QualType T) override {
1938 return S.Diag(Loc, diag::err_array_size_not_integral)
1939 << S.getLangOpts().CPlusPlus11 << T;
1942 SemaDiagnosticBuilder diagnoseIncomplete(
1943 Sema &S, SourceLocation Loc, QualType T) override {
1944 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1945 << T << ArraySize->getSourceRange();
1948 SemaDiagnosticBuilder diagnoseExplicitConv(
1949 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1950 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1953 SemaDiagnosticBuilder noteExplicitConv(
1954 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1955 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1956 << ConvTy->isEnumeralType() << ConvTy;
1959 SemaDiagnosticBuilder diagnoseAmbiguous(
1960 Sema &S, SourceLocation Loc, QualType T) override {
1961 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1964 SemaDiagnosticBuilder noteAmbiguous(
1965 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1966 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1967 << ConvTy->isEnumeralType() << ConvTy;
1970 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1972 QualType ConvTy) override {
1974 S.getLangOpts().CPlusPlus11
1975 ? diag::warn_cxx98_compat_array_size_conversion
1976 : diag::ext_array_size_conversion)
1977 << T << ConvTy->isEnumeralType() << ConvTy;
1979 } SizeDiagnoser(*ArraySize);
1981 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
1984 if (ConvertedSize.isInvalid())
1987 ArraySize = ConvertedSize.get();
1988 QualType SizeType = (*ArraySize)->getType();
1990 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1993 // C++98 [expr.new]p7:
1994 // The expression in a direct-new-declarator shall have integral type
1995 // with a non-negative value.
1997 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1998 // per CWG1464. Otherwise, if it's not a constant, we must have an
1999 // unparenthesized array type.
2000 if (!(*ArraySize)->isValueDependent()) {
2002 // We've already performed any required implicit conversion to integer or
2003 // unscoped enumeration type.
2004 // FIXME: Per CWG1464, we are required to check the value prior to
2005 // converting to size_t. This will never find a negative array size in
2006 // C++14 onwards, because Value is always unsigned here!
2007 if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
2008 if (Value.isSigned() && Value.isNegative()) {
2009 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2010 diag::err_typecheck_negative_array_size)
2011 << (*ArraySize)->getSourceRange());
2014 if (!AllocType->isDependentType()) {
2015 unsigned ActiveSizeBits =
2016 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
2017 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2019 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2020 << Value.toString(10) << (*ArraySize)->getSourceRange());
2023 KnownArraySize = Value.getZExtValue();
2024 } else if (TypeIdParens.isValid()) {
2025 // Can't have dynamic array size when the type-id is in parentheses.
2026 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2027 << (*ArraySize)->getSourceRange()
2028 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2029 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2031 TypeIdParens = SourceRange();
2035 // Note that we do *not* convert the argument in any way. It can
2036 // be signed, larger than size_t, whatever.
2039 FunctionDecl *OperatorNew = nullptr;
2040 FunctionDecl *OperatorDelete = nullptr;
2041 unsigned Alignment =
2042 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2043 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2044 bool PassAlignment = getLangOpts().AlignedAllocation &&
2045 Alignment > NewAlignment;
2047 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2048 if (!AllocType->isDependentType() &&
2049 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2050 FindAllocationFunctions(
2051 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2052 AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2053 OperatorNew, OperatorDelete))
2056 // If this is an array allocation, compute whether the usual array
2057 // deallocation function for the type has a size_t parameter.
2058 bool UsualArrayDeleteWantsSize = false;
2059 if (ArraySize && !AllocType->isDependentType())
2060 UsualArrayDeleteWantsSize =
2061 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2063 SmallVector<Expr *, 8> AllPlaceArgs;
2065 const FunctionProtoType *Proto =
2066 OperatorNew->getType()->getAs<FunctionProtoType>();
2067 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2068 : VariadicDoesNotApply;
2070 // We've already converted the placement args, just fill in any default
2071 // arguments. Skip the first parameter because we don't have a corresponding
2072 // argument. Skip the second parameter too if we're passing in the
2073 // alignment; we've already filled it in.
2074 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2075 PassAlignment ? 2 : 1, PlacementArgs,
2076 AllPlaceArgs, CallType))
2079 if (!AllPlaceArgs.empty())
2080 PlacementArgs = AllPlaceArgs;
2082 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2083 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2085 // FIXME: Missing call to CheckFunctionCall or equivalent
2087 // Warn if the type is over-aligned and is being allocated by (unaligned)
2088 // global operator new.
2089 if (PlacementArgs.empty() && !PassAlignment &&
2090 (OperatorNew->isImplicit() ||
2091 (OperatorNew->getBeginLoc().isValid() &&
2092 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2093 if (Alignment > NewAlignment)
2094 Diag(StartLoc, diag::warn_overaligned_type)
2096 << unsigned(Alignment / Context.getCharWidth())
2097 << unsigned(NewAlignment / Context.getCharWidth());
2101 // Array 'new' can't have any initializers except empty parentheses.
2102 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2103 // dialect distinction.
2104 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2105 SourceRange InitRange(Inits[0]->getBeginLoc(),
2106 Inits[NumInits - 1]->getEndLoc());
2107 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2111 // If we can perform the initialization, and we've not already done so,
2113 if (!AllocType->isDependentType() &&
2114 !Expr::hasAnyTypeDependentArguments(
2115 llvm::makeArrayRef(Inits, NumInits))) {
2116 // The type we initialize is the complete type, including the array bound.
2119 InitType = Context.getConstantArrayType(
2121 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2123 *ArraySize, ArrayType::Normal, 0);
2126 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2128 InitType = AllocType;
2130 InitializedEntity Entity
2131 = InitializedEntity::InitializeNew(StartLoc, InitType);
2132 InitializationSequence InitSeq(*this, Entity, Kind,
2133 MultiExprArg(Inits, NumInits));
2134 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2135 MultiExprArg(Inits, NumInits));
2136 if (FullInit.isInvalid())
2139 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2140 // we don't want the initialized object to be destructed.
2141 // FIXME: We should not create these in the first place.
2142 if (CXXBindTemporaryExpr *Binder =
2143 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2144 FullInit = Binder->getSubExpr();
2146 Initializer = FullInit.get();
2148 // FIXME: If we have a KnownArraySize, check that the array bound of the
2149 // initializer is no greater than that constant value.
2151 if (ArraySize && !*ArraySize) {
2152 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2154 // FIXME: Track that the array size was inferred rather than explicitly
2156 ArraySize = IntegerLiteral::Create(
2157 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2159 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2160 << Initializer->getSourceRange();
2165 // Mark the new and delete operators as referenced.
2167 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2169 MarkFunctionReferenced(StartLoc, OperatorNew);
2171 if (OperatorDelete) {
2172 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2174 MarkFunctionReferenced(StartLoc, OperatorDelete);
2177 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2178 PassAlignment, UsualArrayDeleteWantsSize,
2179 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2180 Initializer, ResultType, AllocTypeInfo, Range,
2184 /// Checks that a type is suitable as the allocated type
2185 /// in a new-expression.
2186 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2188 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2189 // abstract class type or array thereof.
2190 if (AllocType->isFunctionType())
2191 return Diag(Loc, diag::err_bad_new_type)
2192 << AllocType << 0 << R;
2193 else if (AllocType->isReferenceType())
2194 return Diag(Loc, diag::err_bad_new_type)
2195 << AllocType << 1 << R;
2196 else if (!AllocType->isDependentType() &&
2197 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2199 else if (RequireNonAbstractType(Loc, AllocType,
2200 diag::err_allocation_of_abstract_type))
2202 else if (AllocType->isVariablyModifiedType())
2203 return Diag(Loc, diag::err_variably_modified_new_type)
2205 else if (AllocType.getAddressSpace() != LangAS::Default &&
2206 !getLangOpts().OpenCLCPlusPlus)
2207 return Diag(Loc, diag::err_address_space_qualified_new)
2208 << AllocType.getUnqualifiedType()
2209 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2210 else if (getLangOpts().ObjCAutoRefCount) {
2211 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2212 QualType BaseAllocType = Context.getBaseElementType(AT);
2213 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2214 BaseAllocType->isObjCLifetimeType())
2215 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2223 static bool resolveAllocationOverload(
2224 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2225 bool &PassAlignment, FunctionDecl *&Operator,
2226 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2227 OverloadCandidateSet Candidates(R.getNameLoc(),
2228 OverloadCandidateSet::CSK_Normal);
2229 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2230 Alloc != AllocEnd; ++Alloc) {
2231 // Even member operator new/delete are implicitly treated as
2232 // static, so don't use AddMemberCandidate.
2233 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2235 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2236 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2237 /*ExplicitTemplateArgs=*/nullptr, Args,
2239 /*SuppressUserConversions=*/false);
2243 FunctionDecl *Fn = cast<FunctionDecl>(D);
2244 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2245 /*SuppressUserConversions=*/false);
2248 // Do the resolution.
2249 OverloadCandidateSet::iterator Best;
2250 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2253 FunctionDecl *FnDecl = Best->Function;
2254 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2255 Best->FoundDecl) == Sema::AR_inaccessible)
2262 case OR_No_Viable_Function:
2263 // C++17 [expr.new]p13:
2264 // If no matching function is found and the allocated object type has
2265 // new-extended alignment, the alignment argument is removed from the
2266 // argument list, and overload resolution is performed again.
2267 if (PassAlignment) {
2268 PassAlignment = false;
2270 Args.erase(Args.begin() + 1);
2271 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2272 Operator, &Candidates, AlignArg,
2276 // MSVC will fall back on trying to find a matching global operator new
2277 // if operator new[] cannot be found. Also, MSVC will leak by not
2278 // generating a call to operator delete or operator delete[], but we
2279 // will not replicate that bug.
2280 // FIXME: Find out how this interacts with the std::align_val_t fallback
2281 // once MSVC implements it.
2282 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2283 S.Context.getLangOpts().MSVCCompat) {
2285 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2286 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2287 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2288 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2289 Operator, /*Candidates=*/nullptr,
2290 /*AlignArg=*/nullptr, Diagnose);
2294 PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2295 << R.getLookupName() << Range);
2297 // If we have aligned candidates, only note the align_val_t candidates
2298 // from AlignedCandidates and the non-align_val_t candidates from
2300 if (AlignedCandidates) {
2301 auto IsAligned = [](OverloadCandidate &C) {
2302 return C.Function->getNumParams() > 1 &&
2303 C.Function->getParamDecl(1)->getType()->isAlignValT();
2305 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2307 // This was an overaligned allocation, so list the aligned candidates
2309 Args.insert(Args.begin() + 1, AlignArg);
2310 AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
2311 R.getNameLoc(), IsAligned);
2312 Args.erase(Args.begin() + 1);
2313 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2316 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
2323 Candidates.NoteCandidates(
2324 PartialDiagnosticAt(R.getNameLoc(),
2325 S.PDiag(diag::err_ovl_ambiguous_call)
2326 << R.getLookupName() << Range),
2327 S, OCD_AmbiguousCandidates, Args);
2333 Candidates.NoteCandidates(
2334 PartialDiagnosticAt(R.getNameLoc(),
2335 S.PDiag(diag::err_ovl_deleted_call)
2336 << R.getLookupName() << Range),
2337 S, OCD_AllCandidates, Args);
2342 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2345 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2346 AllocationFunctionScope NewScope,
2347 AllocationFunctionScope DeleteScope,
2348 QualType AllocType, bool IsArray,
2349 bool &PassAlignment, MultiExprArg PlaceArgs,
2350 FunctionDecl *&OperatorNew,
2351 FunctionDecl *&OperatorDelete,
2353 // --- Choosing an allocation function ---
2354 // C++ 5.3.4p8 - 14 & 18
2355 // 1) If looking in AFS_Global scope for allocation functions, only look in
2356 // the global scope. Else, if AFS_Class, only look in the scope of the
2357 // allocated class. If AFS_Both, look in both.
2358 // 2) If an array size is given, look for operator new[], else look for
2360 // 3) The first argument is always size_t. Append the arguments from the
2363 SmallVector<Expr*, 8> AllocArgs;
2364 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2366 // We don't care about the actual value of these arguments.
2367 // FIXME: Should the Sema create the expression and embed it in the syntax
2368 // tree? Or should the consumer just recalculate the value?
2369 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2370 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2371 Context.getTargetInfo().getPointerWidth(0)),
2372 Context.getSizeType(),
2374 AllocArgs.push_back(&Size);
2376 QualType AlignValT = Context.VoidTy;
2377 if (PassAlignment) {
2378 DeclareGlobalNewDelete();
2379 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2381 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2383 AllocArgs.push_back(&Align);
2385 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2387 // C++ [expr.new]p8:
2388 // If the allocated type is a non-array type, the allocation
2389 // function's name is operator new and the deallocation function's
2390 // name is operator delete. If the allocated type is an array
2391 // type, the allocation function's name is operator new[] and the
2392 // deallocation function's name is operator delete[].
2393 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2394 IsArray ? OO_Array_New : OO_New);
2396 QualType AllocElemType = Context.getBaseElementType(AllocType);
2398 // Find the allocation function.
2400 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2402 // C++1z [expr.new]p9:
2403 // If the new-expression begins with a unary :: operator, the allocation
2404 // function's name is looked up in the global scope. Otherwise, if the
2405 // allocated type is a class type T or array thereof, the allocation
2406 // function's name is looked up in the scope of T.
2407 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2408 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2410 // We can see ambiguity here if the allocation function is found in
2411 // multiple base classes.
2412 if (R.isAmbiguous())
2415 // If this lookup fails to find the name, or if the allocated type is not
2416 // a class type, the allocation function's name is looked up in the
2419 if (NewScope == AFS_Class)
2422 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2425 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2426 if (PlaceArgs.empty()) {
2427 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2429 Diag(StartLoc, diag::err_openclcxx_placement_new);
2434 assert(!R.empty() && "implicitly declared allocation functions not found");
2435 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2437 // We do our own custom access checks below.
2438 R.suppressDiagnostics();
2440 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2441 OperatorNew, /*Candidates=*/nullptr,
2442 /*AlignArg=*/nullptr, Diagnose))
2446 // We don't need an operator delete if we're running under -fno-exceptions.
2447 if (!getLangOpts().Exceptions) {
2448 OperatorDelete = nullptr;
2452 // Note, the name of OperatorNew might have been changed from array to
2453 // non-array by resolveAllocationOverload.
2454 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2455 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2459 // C++ [expr.new]p19:
2461 // If the new-expression begins with a unary :: operator, the
2462 // deallocation function's name is looked up in the global
2463 // scope. Otherwise, if the allocated type is a class type T or an
2464 // array thereof, the deallocation function's name is looked up in
2465 // the scope of T. If this lookup fails to find the name, or if
2466 // the allocated type is not a class type or array thereof, the
2467 // deallocation function's name is looked up in the global scope.
2468 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2469 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2471 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2472 LookupQualifiedName(FoundDelete, RD);
2474 if (FoundDelete.isAmbiguous())
2475 return true; // FIXME: clean up expressions?
2477 bool FoundGlobalDelete = FoundDelete.empty();
2478 if (FoundDelete.empty()) {
2479 if (DeleteScope == AFS_Class)
2482 DeclareGlobalNewDelete();
2483 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2486 FoundDelete.suppressDiagnostics();
2488 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2490 // Whether we're looking for a placement operator delete is dictated
2491 // by whether we selected a placement operator new, not by whether
2492 // we had explicit placement arguments. This matters for things like
2493 // struct A { void *operator new(size_t, int = 0); ... };
2496 // We don't have any definition for what a "placement allocation function"
2497 // is, but we assume it's any allocation function whose
2498 // parameter-declaration-clause is anything other than (size_t).
2500 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2501 // This affects whether an exception from the constructor of an overaligned
2502 // type uses the sized or non-sized form of aligned operator delete.
2503 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2504 OperatorNew->isVariadic();
2506 if (isPlacementNew) {
2507 // C++ [expr.new]p20:
2508 // A declaration of a placement deallocation function matches the
2509 // declaration of a placement allocation function if it has the
2510 // same number of parameters and, after parameter transformations
2511 // (8.3.5), all parameter types except the first are
2514 // To perform this comparison, we compute the function type that
2515 // the deallocation function should have, and use that type both
2516 // for template argument deduction and for comparison purposes.
2517 QualType ExpectedFunctionType;
2519 const FunctionProtoType *Proto
2520 = OperatorNew->getType()->getAs<FunctionProtoType>();
2522 SmallVector<QualType, 4> ArgTypes;
2523 ArgTypes.push_back(Context.VoidPtrTy);
2524 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2525 ArgTypes.push_back(Proto->getParamType(I));
2527 FunctionProtoType::ExtProtoInfo EPI;
2528 // FIXME: This is not part of the standard's rule.
2529 EPI.Variadic = Proto->isVariadic();
2531 ExpectedFunctionType
2532 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2535 for (LookupResult::iterator D = FoundDelete.begin(),
2536 DEnd = FoundDelete.end();
2538 FunctionDecl *Fn = nullptr;
2539 if (FunctionTemplateDecl *FnTmpl =
2540 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2541 // Perform template argument deduction to try to match the
2542 // expected function type.
2543 TemplateDeductionInfo Info(StartLoc);
2544 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2548 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2550 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2551 ExpectedFunctionType,
2552 /*AdjustExcpetionSpec*/true),
2553 ExpectedFunctionType))
2554 Matches.push_back(std::make_pair(D.getPair(), Fn));
2557 if (getLangOpts().CUDA)
2558 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2560 // C++1y [expr.new]p22:
2561 // For a non-placement allocation function, the normal deallocation
2562 // function lookup is used
2564 // Per [expr.delete]p10, this lookup prefers a member operator delete
2565 // without a size_t argument, but prefers a non-member operator delete
2566 // with a size_t where possible (which it always is in this case).
2567 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2568 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2569 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2570 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2573 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2575 // If we failed to select an operator, all remaining functions are viable
2577 for (auto Fn : BestDeallocFns)
2578 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2582 // C++ [expr.new]p20:
2583 // [...] If the lookup finds a single matching deallocation
2584 // function, that function will be called; otherwise, no
2585 // deallocation function will be called.
2586 if (Matches.size() == 1) {
2587 OperatorDelete = Matches[0].second;
2589 // C++1z [expr.new]p23:
2590 // If the lookup finds a usual deallocation function (3.7.4.2)
2591 // with a parameter of type std::size_t and that function, considered
2592 // as a placement deallocation function, would have been
2593 // selected as a match for the allocation function, the program
2595 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2596 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2597 UsualDeallocFnInfo Info(*this,
2598 DeclAccessPair::make(OperatorDelete, AS_public));
2599 // Core issue, per mail to core reflector, 2016-10-09:
2600 // If this is a member operator delete, and there is a corresponding
2601 // non-sized member operator delete, this isn't /really/ a sized
2602 // deallocation function, it just happens to have a size_t parameter.
2603 bool IsSizedDelete = Info.HasSizeT;
2604 if (IsSizedDelete && !FoundGlobalDelete) {
2605 auto NonSizedDelete =
2606 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2607 /*WantAlign*/Info.HasAlignValT);
2608 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2609 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2610 IsSizedDelete = false;
2613 if (IsSizedDelete) {
2614 SourceRange R = PlaceArgs.empty()
2616 : SourceRange(PlaceArgs.front()->getBeginLoc(),
2617 PlaceArgs.back()->getEndLoc());
2618 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2619 if (!OperatorDelete->isImplicit())
2620 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2625 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2627 } else if (!Matches.empty()) {
2628 // We found multiple suitable operators. Per [expr.new]p20, that means we
2629 // call no 'operator delete' function, but we should at least warn the user.
2630 // FIXME: Suppress this warning if the construction cannot throw.
2631 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2632 << DeleteName << AllocElemType;
2634 for (auto &Match : Matches)
2635 Diag(Match.second->getLocation(),
2636 diag::note_member_declared_here) << DeleteName;
2642 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2643 /// delete. These are:
2646 /// void* operator new(std::size_t) throw(std::bad_alloc);
2647 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2648 /// void operator delete(void *) throw();
2649 /// void operator delete[](void *) throw();
2651 /// void* operator new(std::size_t);
2652 /// void* operator new[](std::size_t);
2653 /// void operator delete(void *) noexcept;
2654 /// void operator delete[](void *) noexcept;
2656 /// void* operator new(std::size_t);
2657 /// void* operator new[](std::size_t);
2658 /// void operator delete(void *) noexcept;
2659 /// void operator delete[](void *) noexcept;
2660 /// void operator delete(void *, std::size_t) noexcept;
2661 /// void operator delete[](void *, std::size_t) noexcept;
2663 /// Note that the placement and nothrow forms of new are *not* implicitly
2664 /// declared. Their use requires including \<new\>.
2665 void Sema::DeclareGlobalNewDelete() {
2666 if (GlobalNewDeleteDeclared)
2669 // The implicitly declared new and delete operators
2670 // are not supported in OpenCL.
2671 if (getLangOpts().OpenCLCPlusPlus)
2674 // C++ [basic.std.dynamic]p2:
2675 // [...] The following allocation and deallocation functions (18.4) are
2676 // implicitly declared in global scope in each translation unit of a
2680 // void* operator new(std::size_t) throw(std::bad_alloc);
2681 // void* operator new[](std::size_t) throw(std::bad_alloc);
2682 // void operator delete(void*) throw();
2683 // void operator delete[](void*) throw();
2685 // void* operator new(std::size_t);
2686 // void* operator new[](std::size_t);
2687 // void operator delete(void*) noexcept;
2688 // void operator delete[](void*) noexcept;
2690 // void* operator new(std::size_t);
2691 // void* operator new[](std::size_t);
2692 // void operator delete(void*) noexcept;
2693 // void operator delete[](void*) noexcept;
2694 // void operator delete(void*, std::size_t) noexcept;
2695 // void operator delete[](void*, std::size_t) noexcept;
2697 // These implicit declarations introduce only the function names operator
2698 // new, operator new[], operator delete, operator delete[].
2700 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2701 // "std" or "bad_alloc" as necessary to form the exception specification.
2702 // However, we do not make these implicit declarations visible to name
2704 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2705 // The "std::bad_alloc" class has not yet been declared, so build it
2707 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2708 getOrCreateStdNamespace(),
2709 SourceLocation(), SourceLocation(),
2710 &PP.getIdentifierTable().get("bad_alloc"),
2712 getStdBadAlloc()->setImplicit(true);
2714 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2715 // The "std::align_val_t" enum class has not yet been declared, so build it
2717 auto *AlignValT = EnumDecl::Create(
2718 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2719 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2720 AlignValT->setIntegerType(Context.getSizeType());
2721 AlignValT->setPromotionType(Context.getSizeType());
2722 AlignValT->setImplicit(true);
2723 StdAlignValT = AlignValT;
2726 GlobalNewDeleteDeclared = true;
2728 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2729 QualType SizeT = Context.getSizeType();
2731 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2732 QualType Return, QualType Param) {
2733 llvm::SmallVector<QualType, 3> Params;
2734 Params.push_back(Param);
2736 // Create up to four variants of the function (sized/aligned).
2737 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2738 (Kind == OO_Delete || Kind == OO_Array_Delete);
2739 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2741 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2742 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2743 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2745 Params.push_back(SizeT);
2747 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2749 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2751 DeclareGlobalAllocationFunction(
2752 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2760 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2761 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2762 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2763 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2766 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2767 /// allocation function if it doesn't already exist.
2768 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2770 ArrayRef<QualType> Params) {
2771 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2773 // Check if this function is already declared.
2774 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2775 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2776 Alloc != AllocEnd; ++Alloc) {
2777 // Only look at non-template functions, as it is the predefined,
2778 // non-templated allocation function we are trying to declare here.
2779 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2780 if (Func->getNumParams() == Params.size()) {
2781 llvm::SmallVector<QualType, 3> FuncParams;
2782 for (auto *P : Func->parameters())
2783 FuncParams.push_back(
2784 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2785 if (llvm::makeArrayRef(FuncParams) == Params) {
2786 // Make the function visible to name lookup, even if we found it in
2787 // an unimported module. It either is an implicitly-declared global
2788 // allocation function, or is suppressing that function.
2789 Func->setVisibleDespiteOwningModule();
2796 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2797 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
2799 QualType BadAllocType;
2800 bool HasBadAllocExceptionSpec
2801 = (Name.getCXXOverloadedOperator() == OO_New ||
2802 Name.getCXXOverloadedOperator() == OO_Array_New);
2803 if (HasBadAllocExceptionSpec) {
2804 if (!getLangOpts().CPlusPlus11) {
2805 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2806 assert(StdBadAlloc && "Must have std::bad_alloc declared");
2807 EPI.ExceptionSpec.Type = EST_Dynamic;
2808 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2812 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2815 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2816 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2817 FunctionDecl *Alloc = FunctionDecl::Create(
2818 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2819 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2820 Alloc->setImplicit();
2821 // Global allocation functions should always be visible.
2822 Alloc->setVisibleDespiteOwningModule();
2824 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2825 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2826 ? VisibilityAttr::Hidden
2827 : VisibilityAttr::Default));
2829 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2830 for (QualType T : Params) {
2831 ParamDecls.push_back(ParmVarDecl::Create(
2832 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2833 /*TInfo=*/nullptr, SC_None, nullptr));
2834 ParamDecls.back()->setImplicit();
2836 Alloc->setParams(ParamDecls);
2838 Alloc->addAttr(ExtraAttr);
2839 Context.getTranslationUnitDecl()->addDecl(Alloc);
2840 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2844 CreateAllocationFunctionDecl(nullptr);
2846 // Host and device get their own declaration so each can be
2847 // defined or re-declared independently.
2848 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2849 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2853 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2854 bool CanProvideSize,
2856 DeclarationName Name) {
2857 DeclareGlobalNewDelete();
2859 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2860 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2862 // FIXME: It's possible for this to result in ambiguity, through a
2863 // user-declared variadic operator delete or the enable_if attribute. We
2864 // should probably not consider those cases to be usual deallocation
2865 // functions. But for now we just make an arbitrary choice in that case.
2866 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2868 assert(Result.FD && "operator delete missing from global scope?");
2872 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2873 CXXRecordDecl *RD) {
2874 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2876 FunctionDecl *OperatorDelete = nullptr;
2877 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2880 return OperatorDelete;
2882 // If there's no class-specific operator delete, look up the global
2883 // non-array delete.
2884 return FindUsualDeallocationFunction(
2885 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2889 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2890 DeclarationName Name,
2891 FunctionDecl *&Operator, bool Diagnose) {
2892 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2893 // Try to find operator delete/operator delete[] in class scope.
2894 LookupQualifiedName(Found, RD);
2896 if (Found.isAmbiguous())
2899 Found.suppressDiagnostics();
2901 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2903 // C++17 [expr.delete]p10:
2904 // If the deallocation functions have class scope, the one without a
2905 // parameter of type std::size_t is selected.
2906 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2907 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2908 /*WantAlign*/ Overaligned, &Matches);
2910 // If we could find an overload, use it.
2911 if (Matches.size() == 1) {
2912 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2914 // FIXME: DiagnoseUseOfDecl?
2915 if (Operator->isDeleted()) {
2917 Diag(StartLoc, diag::err_deleted_function_use);
2918 NoteDeletedFunction(Operator);
2923 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2924 Matches[0].Found, Diagnose) == AR_inaccessible)
2930 // We found multiple suitable operators; complain about the ambiguity.
2931 // FIXME: The standard doesn't say to do this; it appears that the intent
2932 // is that this should never happen.
2933 if (!Matches.empty()) {
2935 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2937 for (auto &Match : Matches)
2938 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2943 // We did find operator delete/operator delete[] declarations, but
2944 // none of them were suitable.
2945 if (!Found.empty()) {
2947 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2950 for (NamedDecl *D : Found)
2951 Diag(D->getUnderlyingDecl()->getLocation(),
2952 diag::note_member_declared_here) << Name;
2962 /// Checks whether delete-expression, and new-expression used for
2963 /// initializing deletee have the same array form.
2964 class MismatchingNewDeleteDetector {
2966 enum MismatchResult {
2967 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2969 /// Indicates that variable is initialized with mismatching form of \a new.
2971 /// Indicates that member is initialized with mismatching form of \a new.
2972 MemberInitMismatches,
2973 /// Indicates that 1 or more constructors' definitions could not been
2974 /// analyzed, and they will be checked again at the end of translation unit.
2978 /// \param EndOfTU True, if this is the final analysis at the end of
2979 /// translation unit. False, if this is the initial analysis at the point
2980 /// delete-expression was encountered.
2981 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2982 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2983 HasUndefinedConstructors(false) {}
2985 /// Checks whether pointee of a delete-expression is initialized with
2986 /// matching form of new-expression.
2988 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2989 /// point where delete-expression is encountered, then a warning will be
2990 /// issued immediately. If return value is \c AnalyzeLater at the point where
2991 /// delete-expression is seen, then member will be analyzed at the end of
2992 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2993 /// couldn't be analyzed. If at least one constructor initializes the member
2994 /// with matching type of new, the return value is \c NoMismatch.
2995 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2996 /// Analyzes a class member.
2997 /// \param Field Class member to analyze.
2998 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2999 /// for deleting the \p Field.
3000 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3002 /// List of mismatching new-expressions used for initialization of the pointee
3003 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3004 /// Indicates whether delete-expression was in array form.
3009 /// Indicates that there is at least one constructor without body.
3010 bool HasUndefinedConstructors;
3011 /// Returns \c CXXNewExpr from given initialization expression.
3012 /// \param E Expression used for initializing pointee in delete-expression.
3013 /// E can be a single-element \c InitListExpr consisting of new-expression.
3014 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3015 /// Returns whether member is initialized with mismatching form of
3016 /// \c new either by the member initializer or in-class initialization.
3018 /// If bodies of all constructors are not visible at the end of translation
3019 /// unit or at least one constructor initializes member with the matching
3020 /// form of \c new, mismatch cannot be proven, and this function will return
3022 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3023 /// Returns whether variable is initialized with mismatching form of
3026 /// If variable is initialized with matching form of \c new or variable is not
3027 /// initialized with a \c new expression, this function will return true.
3028 /// If variable is initialized with mismatching form of \c new, returns false.
3029 /// \param D Variable to analyze.
3030 bool hasMatchingVarInit(const DeclRefExpr *D);
3031 /// Checks whether the constructor initializes pointee with mismatching
3034 /// Returns true, if member is initialized with matching form of \c new in
3035 /// member initializer list. Returns false, if member is initialized with the
3036 /// matching form of \c new in this constructor's initializer or given
3037 /// constructor isn't defined at the point where delete-expression is seen, or
3038 /// member isn't initialized by the constructor.
3039 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3040 /// Checks whether member is initialized with matching form of
3041 /// \c new in member initializer list.
3042 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3043 /// Checks whether member is initialized with mismatching form of \c new by
3044 /// in-class initializer.
3045 MismatchResult analyzeInClassInitializer();
3049 MismatchingNewDeleteDetector::MismatchResult
3050 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3052 assert(DE && "Expected delete-expression");
3053 IsArrayForm = DE->isArrayForm();
3054 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3055 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3056 return analyzeMemberExpr(ME);
3057 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3058 if (!hasMatchingVarInit(D))
3059 return VarInitMismatches;
3065 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3066 assert(E != nullptr && "Expected a valid initializer expression");
3067 E = E->IgnoreParenImpCasts();
3068 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3069 if (ILE->getNumInits() == 1)
3070 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3073 return dyn_cast_or_null<const CXXNewExpr>(E);
3076 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3077 const CXXCtorInitializer *CI) {
3078 const CXXNewExpr *NE = nullptr;
3079 if (Field == CI->getMember() &&
3080 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3081 if (NE->isArray() == IsArrayForm)
3084 NewExprs.push_back(NE);
3089 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3090 const CXXConstructorDecl *CD) {
3091 if (CD->isImplicit())
3093 const FunctionDecl *Definition = CD;
3094 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3095 HasUndefinedConstructors = true;
3098 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3099 if (hasMatchingNewInCtorInit(CI))
3105 MismatchingNewDeleteDetector::MismatchResult
3106 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3107 assert(Field != nullptr && "This should be called only for members");
3108 const Expr *InitExpr = Field->getInClassInitializer();
3110 return EndOfTU ? NoMismatch : AnalyzeLater;
3111 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3112 if (NE->isArray() != IsArrayForm) {
3113 NewExprs.push_back(NE);
3114 return MemberInitMismatches;
3120 MismatchingNewDeleteDetector::MismatchResult
3121 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3122 bool DeleteWasArrayForm) {
3123 assert(Field != nullptr && "Analysis requires a valid class member.");
3124 this->Field = Field;
3125 IsArrayForm = DeleteWasArrayForm;
3126 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3127 for (const auto *CD : RD->ctors()) {
3128 if (hasMatchingNewInCtor(CD))
3131 if (HasUndefinedConstructors)
3132 return EndOfTU ? NoMismatch : AnalyzeLater;
3133 if (!NewExprs.empty())
3134 return MemberInitMismatches;
3135 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3139 MismatchingNewDeleteDetector::MismatchResult
3140 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3141 assert(ME != nullptr && "Expected a member expression");
3142 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3143 return analyzeField(F, IsArrayForm);
3147 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3148 const CXXNewExpr *NE = nullptr;
3149 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3150 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3151 NE->isArray() != IsArrayForm) {
3152 NewExprs.push_back(NE);
3155 return NewExprs.empty();
3159 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3160 const MismatchingNewDeleteDetector &Detector) {
3161 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3163 if (!Detector.IsArrayForm)
3164 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3166 SourceLocation RSquare = Lexer::findLocationAfterToken(
3167 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3168 SemaRef.getLangOpts(), true);
3169 if (RSquare.isValid())
3170 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3172 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3173 << Detector.IsArrayForm << H;
3175 for (const auto *NE : Detector.NewExprs)
3176 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3177 << Detector.IsArrayForm;
3180 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3181 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3183 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3184 switch (Detector.analyzeDeleteExpr(DE)) {
3185 case MismatchingNewDeleteDetector::VarInitMismatches:
3186 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3187 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3190 case MismatchingNewDeleteDetector::AnalyzeLater: {
3191 DeleteExprs[Detector.Field].push_back(
3192 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3195 case MismatchingNewDeleteDetector::NoMismatch:
3200 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3201 bool DeleteWasArrayForm) {
3202 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3203 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3204 case MismatchingNewDeleteDetector::VarInitMismatches:
3205 llvm_unreachable("This analysis should have been done for class members.");
3206 case MismatchingNewDeleteDetector::AnalyzeLater:
3207 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3208 "translation unit.");
3209 case MismatchingNewDeleteDetector::MemberInitMismatches:
3210 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3212 case MismatchingNewDeleteDetector::NoMismatch:
3217 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3218 /// @code ::delete ptr; @endcode
3220 /// @code delete [] ptr; @endcode
3222 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3223 bool ArrayForm, Expr *ExE) {
3224 // C++ [expr.delete]p1:
3225 // The operand shall have a pointer type, or a class type having a single
3226 // non-explicit conversion function to a pointer type. The result has type
3229 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3231 ExprResult Ex = ExE;
3232 FunctionDecl *OperatorDelete = nullptr;
3233 bool ArrayFormAsWritten = ArrayForm;
3234 bool UsualArrayDeleteWantsSize = false;
3236 if (!Ex.get()->isTypeDependent()) {
3237 // Perform lvalue-to-rvalue cast, if needed.
3238 Ex = DefaultLvalueConversion(Ex.get());
3242 QualType Type = Ex.get()->getType();
3244 class DeleteConverter : public ContextualImplicitConverter {
3246 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3248 bool match(QualType ConvType) override {
3249 // FIXME: If we have an operator T* and an operator void*, we must pick
3251 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3252 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3257 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3258 QualType T) override {
3259 return S.Diag(Loc, diag::err_delete_operand) << T;
3262 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3263 QualType T) override {
3264 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3267 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3269 QualType ConvTy) override {
3270 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3273 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3274 QualType ConvTy) override {
3275 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3279 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3280 QualType T) override {
3281 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3284 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3285 QualType ConvTy) override {
3286 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3290 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3292 QualType ConvTy) override {
3293 llvm_unreachable("conversion functions are permitted");
3297 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3300 Type = Ex.get()->getType();
3301 if (!Converter.match(Type))
3302 // FIXME: PerformContextualImplicitConversion should return ExprError
3303 // itself in this case.
3306 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3307 QualType PointeeElem = Context.getBaseElementType(Pointee);
3309 if (Pointee.getAddressSpace() != LangAS::Default &&
3310 !getLangOpts().OpenCLCPlusPlus)
3311 return Diag(Ex.get()->getBeginLoc(),
3312 diag::err_address_space_qualified_delete)
3313 << Pointee.getUnqualifiedType()
3314 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3316 CXXRecordDecl *PointeeRD = nullptr;
3317 if (Pointee->isVoidType() && !isSFINAEContext()) {
3318 // The C++ standard bans deleting a pointer to a non-object type, which
3319 // effectively bans deletion of "void*". However, most compilers support
3320 // this, so we treat it as a warning unless we're in a SFINAE context.
3321 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3322 << Type << Ex.get()->getSourceRange();
3323 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3324 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3325 << Type << Ex.get()->getSourceRange());
3326 } else if (!Pointee->isDependentType()) {
3327 // FIXME: This can result in errors if the definition was imported from a
3328 // module but is hidden.
3329 if (!RequireCompleteType(StartLoc, Pointee,
3330 diag::warn_delete_incomplete, Ex.get())) {
3331 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3332 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3336 if (Pointee->isArrayType() && !ArrayForm) {
3337 Diag(StartLoc, diag::warn_delete_array_type)
3338 << Type << Ex.get()->getSourceRange()
3339 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3343 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3344 ArrayForm ? OO_Array_Delete : OO_Delete);
3348 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3352 // If we're allocating an array of records, check whether the
3353 // usual operator delete[] has a size_t parameter.
3355 // If the user specifically asked to use the global allocator,
3356 // we'll need to do the lookup into the class.
3358 UsualArrayDeleteWantsSize =
3359 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3361 // Otherwise, the usual operator delete[] should be the
3362 // function we just found.
3363 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3364 UsualArrayDeleteWantsSize =
3365 UsualDeallocFnInfo(*this,
3366 DeclAccessPair::make(OperatorDelete, AS_public))
3370 if (!PointeeRD->hasIrrelevantDestructor())
3371 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3372 MarkFunctionReferenced(StartLoc,
3373 const_cast<CXXDestructorDecl*>(Dtor));
3374 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3378 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3379 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3380 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3384 if (!OperatorDelete) {
3385 if (getLangOpts().OpenCLCPlusPlus) {
3386 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3390 bool IsComplete = isCompleteType(StartLoc, Pointee);
3391 bool CanProvideSize =
3392 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3393 Pointee.isDestructedType());
3394 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3396 // Look for a global declaration.
3397 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3398 Overaligned, DeleteName);
3401 MarkFunctionReferenced(StartLoc, OperatorDelete);
3403 // Check access and ambiguity of destructor if we're going to call it.
3404 // Note that this is required even for a virtual delete.
3405 bool IsVirtualDelete = false;
3407 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3408 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3409 PDiag(diag::err_access_dtor) << PointeeElem);
3410 IsVirtualDelete = Dtor->isVirtual();
3414 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3416 // Convert the operand to the type of the first parameter of operator
3417 // delete. This is only necessary if we selected a destroying operator
3418 // delete that we are going to call (non-virtually); converting to void*
3419 // is trivial and left to AST consumers to handle.
3420 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3421 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3422 Qualifiers Qs = Pointee.getQualifiers();
3423 if (Qs.hasCVRQualifiers()) {
3424 // Qualifiers are irrelevant to this conversion; we're only looking
3425 // for access and ambiguity.
3426 Qs.removeCVRQualifiers();
3427 QualType Unqual = Context.getPointerType(
3428 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3429 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3431 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3437 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3438 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3439 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3440 AnalyzeDeleteExprMismatch(Result);
3444 static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3446 FunctionDecl *&Operator) {
3448 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3449 IsDelete ? OO_Delete : OO_New);
3451 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3452 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3453 assert(!R.empty() && "implicitly declared allocation functions not found");
3454 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
3456 // We do our own custom access checks below.
3457 R.suppressDiagnostics();
3459 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3460 OverloadCandidateSet Candidates(R.getNameLoc(),
3461 OverloadCandidateSet::CSK_Normal);
3462 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3463 FnOvl != FnOvlEnd; ++FnOvl) {
3464 // Even member operator new/delete are implicitly treated as
3465 // static, so don't use AddMemberCandidate.
3466 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3468 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3469 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3470 /*ExplicitTemplateArgs=*/nullptr, Args,
3472 /*SuppressUserConversions=*/false);
3476 FunctionDecl *Fn = cast<FunctionDecl>(D);
3477 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3478 /*SuppressUserConversions=*/false);
3481 SourceRange Range = TheCall->getSourceRange();
3483 // Do the resolution.
3484 OverloadCandidateSet::iterator Best;
3485 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3488 FunctionDecl *FnDecl = Best->Function;
3489 assert(R.getNamingClass() == nullptr &&
3490 "class members should not be considered");
3492 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3493 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3494 << (IsDelete ? 1 : 0) << Range;
3495 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3496 << R.getLookupName() << FnDecl->getSourceRange();
3504 case OR_No_Viable_Function:
3505 Candidates.NoteCandidates(
3506 PartialDiagnosticAt(R.getNameLoc(),
3507 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3508 << R.getLookupName() << Range),
3509 S, OCD_AllCandidates, Args);
3513 Candidates.NoteCandidates(
3514 PartialDiagnosticAt(R.getNameLoc(),
3515 S.PDiag(diag::err_ovl_ambiguous_call)
3516 << R.getLookupName() << Range),
3517 S, OCD_AmbiguousCandidates, Args);
3521 Candidates.NoteCandidates(
3522 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3523 << R.getLookupName() << Range),
3524 S, OCD_AllCandidates, Args);
3528 llvm_unreachable("Unreachable, bad result from BestViableFunction");
3532 Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3534 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3535 if (!getLangOpts().CPlusPlus) {
3536 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3537 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3541 // CodeGen assumes it can find the global new and delete to call,
3542 // so ensure that they are declared.
3543 DeclareGlobalNewDelete();
3545 FunctionDecl *OperatorNewOrDelete = nullptr;
3546 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3547 OperatorNewOrDelete))
3549 assert(OperatorNewOrDelete && "should be found");
3551 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3552 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3554 TheCall->setType(OperatorNewOrDelete->getReturnType());
3555 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3556 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3557 InitializedEntity Entity =
3558 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3559 ExprResult Arg = PerformCopyInitialization(
3560 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3561 if (Arg.isInvalid())
3563 TheCall->setArg(i, Arg.get());
3565 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3566 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&
3567 "Callee expected to be implicit cast to a builtin function pointer");
3568 Callee->setType(OperatorNewOrDelete->getType());
3570 return TheCallResult;
3573 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3574 bool IsDelete, bool CallCanBeVirtual,
3575 bool WarnOnNonAbstractTypes,
3576 SourceLocation DtorLoc) {
3577 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3580 // C++ [expr.delete]p3:
3581 // In the first alternative (delete object), if the static type of the
3582 // object to be deleted is different from its dynamic type, the static
3583 // type shall be a base class of the dynamic type of the object to be
3584 // deleted and the static type shall have a virtual destructor or the
3585 // behavior is undefined.
3587 const CXXRecordDecl *PointeeRD = dtor->getParent();
3588 // Note: a final class cannot be derived from, no issue there
3589 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3592 // If the superclass is in a system header, there's nothing that can be done.
3593 // The `delete` (where we emit the warning) can be in a system header,
3594 // what matters for this warning is where the deleted type is defined.
3595 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3598 QualType ClassType = dtor->getThisType()->getPointeeType();
3599 if (PointeeRD->isAbstract()) {
3600 // If the class is abstract, we warn by default, because we're
3601 // sure the code has undefined behavior.
3602 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3604 } else if (WarnOnNonAbstractTypes) {
3605 // Otherwise, if this is not an array delete, it's a bit suspect,
3606 // but not necessarily wrong.
3607 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3611 std::string TypeStr;
3612 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3613 Diag(DtorLoc, diag::note_delete_non_virtual)
3614 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3618 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3619 SourceLocation StmtLoc,
3622 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3624 return ConditionError();
3625 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3626 CK == ConditionKind::ConstexprIf);
3629 /// Check the use of the given variable as a C++ condition in an if,
3630 /// while, do-while, or switch statement.
3631 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3632 SourceLocation StmtLoc,
3634 if (ConditionVar->isInvalidDecl())
3637 QualType T = ConditionVar->getType();
3639 // C++ [stmt.select]p2:
3640 // The declarator shall not specify a function or an array.
3641 if (T->isFunctionType())
3642 return ExprError(Diag(ConditionVar->getLocation(),
3643 diag::err_invalid_use_of_function_type)
3644 << ConditionVar->getSourceRange());
3645 else if (T->isArrayType())
3646 return ExprError(Diag(ConditionVar->getLocation(),
3647 diag::err_invalid_use_of_array_type)
3648 << ConditionVar->getSourceRange());
3650 ExprResult Condition = BuildDeclRefExpr(
3651 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3652 ConditionVar->getLocation());
3655 case ConditionKind::Boolean:
3656 return CheckBooleanCondition(StmtLoc, Condition.get());
3658 case ConditionKind::ConstexprIf:
3659 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3661 case ConditionKind::Switch:
3662 return CheckSwitchCondition(StmtLoc, Condition.get());
3665 llvm_unreachable("unexpected condition kind");
3668 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3669 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3671 // The value of a condition that is an initialized declaration in a statement
3672 // other than a switch statement is the value of the declared variable
3673 // implicitly converted to type bool. If that conversion is ill-formed, the
3674 // program is ill-formed.
3675 // The value of a condition that is an expression is the value of the
3676 // expression, implicitly converted to bool.
3678 // FIXME: Return this value to the caller so they don't need to recompute it.
3679 llvm::APSInt Value(/*BitWidth*/1);
3680 return (IsConstexpr && !CondExpr->isValueDependent())
3681 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3683 : PerformContextuallyConvertToBool(CondExpr);
3686 /// Helper function to determine whether this is the (deprecated) C++
3687 /// conversion from a string literal to a pointer to non-const char or
3688 /// non-const wchar_t (for narrow and wide string literals,
3691 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3692 // Look inside the implicit cast, if it exists.
3693 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3694 From = Cast->getSubExpr();
3696 // A string literal (2.13.4) that is not a wide string literal can
3697 // be converted to an rvalue of type "pointer to char"; a wide
3698 // string literal can be converted to an rvalue of type "pointer
3699 // to wchar_t" (C++ 4.2p2).
3700 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3701 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3702 if (const BuiltinType *ToPointeeType
3703 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3704 // This conversion is considered only when there is an
3705 // explicit appropriate pointer target type (C++ 4.2p2).
3706 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3707 switch (StrLit->getKind()) {
3708 case StringLiteral::UTF8:
3709 case StringLiteral::UTF16:
3710 case StringLiteral::UTF32:
3711 // We don't allow UTF literals to be implicitly converted
3713 case StringLiteral::Ascii:
3714 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3715 ToPointeeType->getKind() == BuiltinType::Char_S);
3716 case StringLiteral::Wide:
3717 return Context.typesAreCompatible(Context.getWideCharType(),
3718 QualType(ToPointeeType, 0));
3726 static ExprResult BuildCXXCastArgument(Sema &S,
3727 SourceLocation CastLoc,
3730 CXXMethodDecl *Method,
3731 DeclAccessPair FoundDecl,
3732 bool HadMultipleCandidates,
3735 default: llvm_unreachable("Unhandled cast kind!");
3736 case CK_ConstructorConversion: {
3737 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3738 SmallVector<Expr*, 8> ConstructorArgs;
3740 if (S.RequireNonAbstractType(CastLoc, Ty,
3741 diag::err_allocation_of_abstract_type))
3744 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3747 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3748 InitializedEntity::InitializeTemporary(Ty));
3749 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3752 ExprResult Result = S.BuildCXXConstructExpr(
3753 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3754 ConstructorArgs, HadMultipleCandidates,
3755 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3756 CXXConstructExpr::CK_Complete, SourceRange());
3757 if (Result.isInvalid())
3760 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3763 case CK_UserDefinedConversion: {
3764 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3766 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3767 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3770 // Create an implicit call expr that calls it.
3771 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3772 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3773 HadMultipleCandidates);
3774 if (Result.isInvalid())
3776 // Record usage of conversion in an implicit cast.
3777 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3778 CK_UserDefinedConversion, Result.get(),
3779 nullptr, Result.get()->getValueKind());
3781 return S.MaybeBindToTemporary(Result.get());
3786 /// PerformImplicitConversion - Perform an implicit conversion of the
3787 /// expression From to the type ToType using the pre-computed implicit
3788 /// conversion sequence ICS. Returns the converted
3789 /// expression. Action is the kind of conversion we're performing,
3790 /// used in the error message.
3792 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3793 const ImplicitConversionSequence &ICS,
3794 AssignmentAction Action,
3795 CheckedConversionKind CCK) {
3796 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3797 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3800 switch (ICS.getKind()) {
3801 case ImplicitConversionSequence::StandardConversion: {
3802 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3804 if (Res.isInvalid())
3810 case ImplicitConversionSequence::UserDefinedConversion: {
3812 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3814 QualType BeforeToType;
3815 assert(FD && "no conversion function for user-defined conversion seq");
3816 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3817 CastKind = CK_UserDefinedConversion;
3819 // If the user-defined conversion is specified by a conversion function,
3820 // the initial standard conversion sequence converts the source type to
3821 // the implicit object parameter of the conversion function.
3822 BeforeToType = Context.getTagDeclType(Conv->getParent());
3824 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3825 CastKind = CK_ConstructorConversion;
3826 // Do no conversion if dealing with ... for the first conversion.
3827 if (!ICS.UserDefined.EllipsisConversion) {
3828 // If the user-defined conversion is specified by a constructor, the
3829 // initial standard conversion sequence converts the source type to
3830 // the type required by the argument of the constructor
3831 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3834 // Watch out for ellipsis conversion.
3835 if (!ICS.UserDefined.EllipsisConversion) {
3837 PerformImplicitConversion(From, BeforeToType,
3838 ICS.UserDefined.Before, AA_Converting,
3840 if (Res.isInvalid())
3845 ExprResult CastArg = BuildCXXCastArgument(
3846 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3847 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3848 ICS.UserDefined.HadMultipleCandidates, From);
3850 if (CastArg.isInvalid())
3853 From = CastArg.get();
3855 // C++ [over.match.oper]p7:
3856 // [...] the second standard conversion sequence of a user-defined
3857 // conversion sequence is not applied.
3858 if (CCK == CCK_ForBuiltinOverloadedOp)
3861 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3862 AA_Converting, CCK);
3865 case ImplicitConversionSequence::AmbiguousConversion:
3866 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3867 PDiag(diag::err_typecheck_ambiguous_condition)
3868 << From->getSourceRange());
3871 case ImplicitConversionSequence::EllipsisConversion:
3872 llvm_unreachable("Cannot perform an ellipsis conversion");
3874 case ImplicitConversionSequence::BadConversion:
3876 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3877 From->getType(), From, Action);
3878 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
3882 // Everything went well.
3886 /// PerformImplicitConversion - Perform an implicit conversion of the
3887 /// expression From to the type ToType by following the standard
3888 /// conversion sequence SCS. Returns the converted
3889 /// expression. Flavor is the context in which we're performing this
3890 /// conversion, for use in error messages.
3892 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3893 const StandardConversionSequence& SCS,
3894 AssignmentAction Action,
3895 CheckedConversionKind CCK) {
3896 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3898 // Overall FIXME: we are recomputing too many types here and doing far too
3899 // much extra work. What this means is that we need to keep track of more
3900 // information that is computed when we try the implicit conversion initially,
3901 // so that we don't need to recompute anything here.
3902 QualType FromType = From->getType();
3904 if (SCS.CopyConstructor) {
3905 // FIXME: When can ToType be a reference type?
3906 assert(!ToType->isReferenceType());
3907 if (SCS.Second == ICK_Derived_To_Base) {
3908 SmallVector<Expr*, 8> ConstructorArgs;
3909 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3910 From, /*FIXME:ConstructLoc*/SourceLocation(),
3913 return BuildCXXConstructExpr(
3914 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3915 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3916 ConstructorArgs, /*HadMultipleCandidates*/ false,
3917 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3918 CXXConstructExpr::CK_Complete, SourceRange());
3920 return BuildCXXConstructExpr(
3921 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3922 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3923 From, /*HadMultipleCandidates*/ false,
3924 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3925 CXXConstructExpr::CK_Complete, SourceRange());
3928 // Resolve overloaded function references.
3929 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3930 DeclAccessPair Found;
3931 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3936 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
3939 From = FixOverloadedFunctionReference(From, Found, Fn);
3940 FromType = From->getType();
3943 // If we're converting to an atomic type, first convert to the corresponding
3945 QualType ToAtomicType;
3946 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3947 ToAtomicType = ToType;
3948 ToType = ToAtomic->getValueType();
3951 QualType InitialFromType = FromType;
3952 // Perform the first implicit conversion.
3953 switch (SCS.First) {
3955 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3956 FromType = FromAtomic->getValueType().getUnqualifiedType();
3957 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3958 From, /*BasePath=*/nullptr, VK_RValue);
3962 case ICK_Lvalue_To_Rvalue: {
3963 assert(From->getObjectKind() != OK_ObjCProperty);
3964 ExprResult FromRes = DefaultLvalueConversion(From);
3965 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
3966 From = FromRes.get();
3967 FromType = From->getType();
3971 case ICK_Array_To_Pointer:
3972 FromType = Context.getArrayDecayedType(FromType);
3973 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3974 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3977 case ICK_Function_To_Pointer:
3978 FromType = Context.getPointerType(FromType);
3979 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3980 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3984 llvm_unreachable("Improper first standard conversion");
3987 // Perform the second implicit conversion
3988 switch (SCS.Second) {
3990 // C++ [except.spec]p5:
3991 // [For] assignment to and initialization of pointers to functions,
3992 // pointers to member functions, and references to functions: the
3993 // target entity shall allow at least the exceptions allowed by the
3994 // source value in the assignment or initialization.
3997 case AA_Initializing:
3998 // Note, function argument passing and returning are initialization.
4002 case AA_Passing_CFAudited:
4003 if (CheckExceptionSpecCompatibility(From, ToType))
4009 // Casts and implicit conversions are not initialization, so are not
4010 // checked for exception specification mismatches.
4013 // Nothing else to do.
4016 case ICK_Integral_Promotion:
4017 case ICK_Integral_Conversion:
4018 if (ToType->isBooleanType()) {
4019 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
4020 SCS.Second == ICK_Integral_Promotion &&
4021 "only enums with fixed underlying type can promote to bool");
4022 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
4023 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4025 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
4026 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4030 case ICK_Floating_Promotion:
4031 case ICK_Floating_Conversion:
4032 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4033 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4036 case ICK_Complex_Promotion:
4037 case ICK_Complex_Conversion: {
4038 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4039 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4041 if (FromEl->isRealFloatingType()) {
4042 if (ToEl->isRealFloatingType())
4043 CK = CK_FloatingComplexCast;
4045 CK = CK_FloatingComplexToIntegralComplex;
4046 } else if (ToEl->isRealFloatingType()) {
4047 CK = CK_IntegralComplexToFloatingComplex;
4049 CK = CK_IntegralComplexCast;
4051 From = ImpCastExprToType(From, ToType, CK,
4052 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4056 case ICK_Floating_Integral:
4057 if (ToType->isRealFloatingType())
4058 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4059 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4061 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4062 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4065 case ICK_Compatible_Conversion:
4066 From = ImpCastExprToType(From, ToType, CK_NoOp,
4067 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4070 case ICK_Writeback_Conversion:
4071 case ICK_Pointer_Conversion: {
4072 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4073 // Diagnose incompatible Objective-C conversions
4074 if (Action == AA_Initializing || Action == AA_Assigning)
4075 Diag(From->getBeginLoc(),
4076 diag::ext_typecheck_convert_incompatible_pointer)
4077 << ToType << From->getType() << Action << From->getSourceRange()
4080 Diag(From->getBeginLoc(),
4081 diag::ext_typecheck_convert_incompatible_pointer)
4082 << From->getType() << ToType << Action << From->getSourceRange()
4085 if (From->getType()->isObjCObjectPointerType() &&
4086 ToType->isObjCObjectPointerType())
4087 EmitRelatedResultTypeNote(From);
4088 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4089 !CheckObjCARCUnavailableWeakConversion(ToType,
4091 if (Action == AA_Initializing)
4092 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4094 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4095 << (Action == AA_Casting) << From->getType() << ToType
4096 << From->getSourceRange();
4099 // Defer address space conversion to the third conversion.
4100 QualType FromPteeType = From->getType()->getPointeeType();
4101 QualType ToPteeType = ToType->getPointeeType();
4102 QualType NewToType = ToType;
4103 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4104 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4105 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4106 NewToType = Context.getAddrSpaceQualType(NewToType,
4107 FromPteeType.getAddressSpace());
4108 if (ToType->isObjCObjectPointerType())
4109 NewToType = Context.getObjCObjectPointerType(NewToType);
4110 else if (ToType->isBlockPointerType())
4111 NewToType = Context.getBlockPointerType(NewToType);
4113 NewToType = Context.getPointerType(NewToType);
4117 CXXCastPath BasePath;
4118 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4121 // Make sure we extend blocks if necessary.
4122 // FIXME: doing this here is really ugly.
4123 if (Kind == CK_BlockPointerToObjCPointerCast) {
4124 ExprResult E = From;
4125 (void) PrepareCastToObjCObjectPointer(E);
4128 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4129 CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4130 From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK)
4135 case ICK_Pointer_Member: {
4137 CXXCastPath BasePath;
4138 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4140 if (CheckExceptionSpecCompatibility(From, ToType))
4143 // We may not have been able to figure out what this member pointer resolved
4144 // to up until this exact point. Attempt to lock-in it's inheritance model.
4145 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4146 (void)isCompleteType(From->getExprLoc(), From->getType());
4147 (void)isCompleteType(From->getExprLoc(), ToType);
4150 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4155 case ICK_Boolean_Conversion:
4156 // Perform half-to-boolean conversion via float.
4157 if (From->getType()->isHalfType()) {
4158 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4159 FromType = Context.FloatTy;
4162 From = ImpCastExprToType(From, Context.BoolTy,
4163 ScalarTypeToBooleanCastKind(FromType),
4164 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4167 case ICK_Derived_To_Base: {
4168 CXXCastPath BasePath;
4169 if (CheckDerivedToBaseConversion(
4170 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4171 From->getSourceRange(), &BasePath, CStyle))
4174 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4175 CK_DerivedToBase, From->getValueKind(),
4176 &BasePath, CCK).get();
4180 case ICK_Vector_Conversion:
4181 From = ImpCastExprToType(From, ToType, CK_BitCast,
4182 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4185 case ICK_Vector_Splat: {
4186 // Vector splat from any arithmetic type to a vector.
4187 Expr *Elem = prepareVectorSplat(ToType, From).get();
4188 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4189 /*BasePath=*/nullptr, CCK).get();
4193 case ICK_Complex_Real:
4194 // Case 1. x -> _Complex y
4195 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4196 QualType ElType = ToComplex->getElementType();
4197 bool isFloatingComplex = ElType->isRealFloatingType();
4200 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4202 } else if (From->getType()->isRealFloatingType()) {
4203 From = ImpCastExprToType(From, ElType,
4204 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4206 assert(From->getType()->isIntegerType());
4207 From = ImpCastExprToType(From, ElType,
4208 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4211 From = ImpCastExprToType(From, ToType,
4212 isFloatingComplex ? CK_FloatingRealToComplex
4213 : CK_IntegralRealToComplex).get();
4215 // Case 2. _Complex x -> y
4217 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4218 assert(FromComplex);
4220 QualType ElType = FromComplex->getElementType();
4221 bool isFloatingComplex = ElType->isRealFloatingType();
4224 From = ImpCastExprToType(From, ElType,
4225 isFloatingComplex ? CK_FloatingComplexToReal
4226 : CK_IntegralComplexToReal,
4227 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4230 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4232 } else if (ToType->isRealFloatingType()) {
4233 From = ImpCastExprToType(From, ToType,
4234 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
4235 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4237 assert(ToType->isIntegerType());
4238 From = ImpCastExprToType(From, ToType,
4239 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4240 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4245 case ICK_Block_Pointer_Conversion: {
4247 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4249 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4250 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&
4253 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4254 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4255 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4259 case ICK_TransparentUnionConversion: {
4260 ExprResult FromRes = From;
4261 Sema::AssignConvertType ConvTy =
4262 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4263 if (FromRes.isInvalid())
4265 From = FromRes.get();
4266 assert ((ConvTy == Sema::Compatible) &&
4267 "Improper transparent union conversion");
4272 case ICK_Zero_Event_Conversion:
4273 case ICK_Zero_Queue_Conversion:
4274 From = ImpCastExprToType(From, ToType,
4275 CK_ZeroToOCLOpaqueType,
4276 From->getValueKind()).get();
4279 case ICK_Lvalue_To_Rvalue:
4280 case ICK_Array_To_Pointer:
4281 case ICK_Function_To_Pointer:
4282 case ICK_Function_Conversion:
4283 case ICK_Qualification:
4284 case ICK_Num_Conversion_Kinds:
4285 case ICK_C_Only_Conversion:
4286 case ICK_Incompatible_Pointer_Conversion:
4287 llvm_unreachable("Improper second standard conversion");
4290 switch (SCS.Third) {
4295 case ICK_Function_Conversion:
4296 // If both sides are functions (or pointers/references to them), there could
4297 // be incompatible exception declarations.
4298 if (CheckExceptionSpecCompatibility(From, ToType))
4301 From = ImpCastExprToType(From, ToType, CK_NoOp,
4302 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4305 case ICK_Qualification: {
4306 // The qualification keeps the category of the inner expression, unless the
4307 // target type isn't a reference.
4309 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4311 CastKind CK = CK_NoOp;
4313 if (ToType->isReferenceType() &&
4314 ToType->getPointeeType().getAddressSpace() !=
4315 From->getType().getAddressSpace())
4316 CK = CK_AddressSpaceConversion;
4318 if (ToType->isPointerType() &&
4319 ToType->getPointeeType().getAddressSpace() !=
4320 From->getType()->getPointeeType().getAddressSpace())
4321 CK = CK_AddressSpaceConversion;
4323 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4324 /*BasePath=*/nullptr, CCK)
4327 if (SCS.DeprecatedStringLiteralToCharPtr &&
4328 !getLangOpts().WritableStrings) {
4329 Diag(From->getBeginLoc(),
4330 getLangOpts().CPlusPlus11
4331 ? diag::ext_deprecated_string_literal_conversion
4332 : diag::warn_deprecated_string_literal_conversion)
4333 << ToType.getNonReferenceType();
4340 llvm_unreachable("Improper third standard conversion");
4343 // If this conversion sequence involved a scalar -> atomic conversion, perform
4344 // that conversion now.
4345 if (!ToAtomicType.isNull()) {
4346 assert(Context.hasSameType(
4347 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
4348 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4349 VK_RValue, nullptr, CCK).get();
4352 // If this conversion sequence succeeded and involved implicitly converting a
4353 // _Nullable type to a _Nonnull one, complain.
4355 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4356 From->getBeginLoc());
4361 /// Check the completeness of a type in a unary type trait.
4363 /// If the particular type trait requires a complete type, tries to complete
4364 /// it. If completing the type fails, a diagnostic is emitted and false
4365 /// returned. If completing the type succeeds or no completion was required,
4367 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4370 // C++0x [meta.unary.prop]p3:
4371 // For all of the class templates X declared in this Clause, instantiating
4372 // that template with a template argument that is a class template
4373 // specialization may result in the implicit instantiation of the template
4374 // argument if and only if the semantics of X require that the argument
4375 // must be a complete type.
4376 // We apply this rule to all the type trait expressions used to implement
4377 // these class templates. We also try to follow any GCC documented behavior
4378 // in these expressions to ensure portability of standard libraries.
4380 default: llvm_unreachable("not a UTT");
4381 // is_complete_type somewhat obviously cannot require a complete type.
4382 case UTT_IsCompleteType:
4385 // These traits are modeled on the type predicates in C++0x
4386 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4387 // requiring a complete type, as whether or not they return true cannot be
4388 // impacted by the completeness of the type.
4390 case UTT_IsIntegral:
4391 case UTT_IsFloatingPoint:
4394 case UTT_IsLvalueReference:
4395 case UTT_IsRvalueReference:
4396 case UTT_IsMemberFunctionPointer:
4397 case UTT_IsMemberObjectPointer:
4401 case UTT_IsFunction:
4402 case UTT_IsReference:
4403 case UTT_IsArithmetic:
4404 case UTT_IsFundamental:
4407 case UTT_IsCompound:
4408 case UTT_IsMemberPointer:
4411 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4412 // which requires some of its traits to have the complete type. However,
4413 // the completeness of the type cannot impact these traits' semantics, and
4414 // so they don't require it. This matches the comments on these traits in
4417 case UTT_IsVolatile:
4419 case UTT_IsUnsigned:
4421 // This type trait always returns false, checking the type is moot.
4422 case UTT_IsInterfaceClass:
4425 // C++14 [meta.unary.prop]:
4426 // If T is a non-union class type, T shall be a complete type.
4428 case UTT_IsPolymorphic:
4429 case UTT_IsAbstract:
4430 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4432 return !S.RequireCompleteType(
4433 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4436 // C++14 [meta.unary.prop]:
4437 // If T is a class type, T shall be a complete type.
4440 if (ArgTy->getAsCXXRecordDecl())
4441 return !S.RequireCompleteType(
4442 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4445 // C++1z [meta.unary.prop]:
4446 // remove_all_extents_t<T> shall be a complete type or cv void.
4447 case UTT_IsAggregate:
4449 case UTT_IsTriviallyCopyable:
4450 case UTT_IsStandardLayout:
4453 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4454 // or an array of unknown bound. But GCC actually imposes the same constraints
4456 case UTT_HasNothrowAssign:
4457 case UTT_HasNothrowMoveAssign:
4458 case UTT_HasNothrowConstructor:
4459 case UTT_HasNothrowCopy:
4460 case UTT_HasTrivialAssign:
4461 case UTT_HasTrivialMoveAssign:
4462 case UTT_HasTrivialDefaultConstructor:
4463 case UTT_HasTrivialMoveConstructor:
4464 case UTT_HasTrivialCopy:
4465 case UTT_HasTrivialDestructor:
4466 case UTT_HasVirtualDestructor:
4467 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4470 // C++1z [meta.unary.prop]:
4471 // T shall be a complete type, cv void, or an array of unknown bound.
4472 case UTT_IsDestructible:
4473 case UTT_IsNothrowDestructible:
4474 case UTT_IsTriviallyDestructible:
4475 case UTT_HasUniqueObjectRepresentations:
4476 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4479 return !S.RequireCompleteType(
4480 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4484 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4485 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4486 bool (CXXRecordDecl::*HasTrivial)() const,
4487 bool (CXXRecordDecl::*HasNonTrivial)() const,
4488 bool (CXXMethodDecl::*IsDesiredOp)() const)
4490 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4491 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4494 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4495 DeclarationNameInfo NameInfo(Name, KeyLoc);
4496 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4497 if (Self.LookupQualifiedName(Res, RD)) {
4498 bool FoundOperator = false;
4499 Res.suppressDiagnostics();
4500 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4501 Op != OpEnd; ++Op) {
4502 if (isa<FunctionTemplateDecl>(*Op))
4505 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4506 if((Operator->*IsDesiredOp)()) {
4507 FoundOperator = true;
4508 const FunctionProtoType *CPT =
4509 Operator->getType()->getAs<FunctionProtoType>();
4510 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4511 if (!CPT || !CPT->isNothrow())
4515 return FoundOperator;
4520 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4521 SourceLocation KeyLoc, QualType T) {
4522 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4524 ASTContext &C = Self.Context;
4526 default: llvm_unreachable("not a UTT");
4527 // Type trait expressions corresponding to the primary type category
4528 // predicates in C++0x [meta.unary.cat].
4530 return T->isVoidType();
4531 case UTT_IsIntegral:
4532 return T->isIntegralType(C);
4533 case UTT_IsFloatingPoint:
4534 return T->isFloatingType();
4536 return T->isArrayType();
4538 return T->isPointerType();
4539 case UTT_IsLvalueReference:
4540 return T->isLValueReferenceType();
4541 case UTT_IsRvalueReference:
4542 return T->isRValueReferenceType();
4543 case UTT_IsMemberFunctionPointer:
4544 return T->isMemberFunctionPointerType();
4545 case UTT_IsMemberObjectPointer:
4546 return T->isMemberDataPointerType();
4548 return T->isEnumeralType();
4550 return T->isUnionType();
4552 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4553 case UTT_IsFunction:
4554 return T->isFunctionType();
4556 // Type trait expressions which correspond to the convenient composition
4557 // predicates in C++0x [meta.unary.comp].
4558 case UTT_IsReference:
4559 return T->isReferenceType();
4560 case UTT_IsArithmetic:
4561 return T->isArithmeticType() && !T->isEnumeralType();
4562 case UTT_IsFundamental:
4563 return T->isFundamentalType();
4565 return T->isObjectType();
4567 // Note: semantic analysis depends on Objective-C lifetime types to be
4568 // considered scalar types. However, such types do not actually behave
4569 // like scalar types at run time (since they may require retain/release
4570 // operations), so we report them as non-scalar.
4571 if (T->isObjCLifetimeType()) {
4572 switch (T.getObjCLifetime()) {
4573 case Qualifiers::OCL_None:
4574 case Qualifiers::OCL_ExplicitNone:
4577 case Qualifiers::OCL_Strong:
4578 case Qualifiers::OCL_Weak:
4579 case Qualifiers::OCL_Autoreleasing:
4584 return T->isScalarType();
4585 case UTT_IsCompound:
4586 return T->isCompoundType();
4587 case UTT_IsMemberPointer:
4588 return T->isMemberPointerType();
4590 // Type trait expressions which correspond to the type property predicates
4591 // in C++0x [meta.unary.prop].
4593 return T.isConstQualified();
4594 case UTT_IsVolatile:
4595 return T.isVolatileQualified();
4597 return T.isTrivialType(C);
4598 case UTT_IsTriviallyCopyable:
4599 return T.isTriviallyCopyableType(C);
4600 case UTT_IsStandardLayout:
4601 return T->isStandardLayoutType();
4603 return T.isPODType(C);
4605 return T->isLiteralType(C);
4607 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4608 return !RD->isUnion() && RD->isEmpty();
4610 case UTT_IsPolymorphic:
4611 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4612 return !RD->isUnion() && RD->isPolymorphic();
4614 case UTT_IsAbstract:
4615 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4616 return !RD->isUnion() && RD->isAbstract();
4618 case UTT_IsAggregate:
4619 // Report vector extensions and complex types as aggregates because they
4620 // support aggregate initialization. GCC mirrors this behavior for vectors
4621 // but not _Complex.
4622 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4623 T->isAnyComplexType();
4624 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4625 // even then only when it is used with the 'interface struct ...' syntax
4626 // Clang doesn't support /CLR which makes this type trait moot.
4627 case UTT_IsInterfaceClass:
4631 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4632 return RD->hasAttr<FinalAttr>();
4635 // Enum types should always return false.
4636 // Floating points should always return true.
4637 return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType());
4638 case UTT_IsUnsigned:
4639 return T->isUnsignedIntegerType();
4641 // Type trait expressions which query classes regarding their construction,
4642 // destruction, and copying. Rather than being based directly on the
4643 // related type predicates in the standard, they are specified by both
4644 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4647 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4648 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4650 // Note that these builtins do not behave as documented in g++: if a class
4651 // has both a trivial and a non-trivial special member of a particular kind,
4652 // they return false! For now, we emulate this behavior.
4653 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4654 // does not correctly compute triviality in the presence of multiple special
4655 // members of the same kind. Revisit this once the g++ bug is fixed.
4656 case UTT_HasTrivialDefaultConstructor:
4657 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4658 // If __is_pod (type) is true then the trait is true, else if type is
4659 // a cv class or union type (or array thereof) with a trivial default
4660 // constructor ([class.ctor]) then the trait is true, else it is false.
4663 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4664 return RD->hasTrivialDefaultConstructor() &&
4665 !RD->hasNonTrivialDefaultConstructor();
4667 case UTT_HasTrivialMoveConstructor:
4668 // This trait is implemented by MSVC 2012 and needed to parse the
4669 // standard library headers. Specifically this is used as the logic
4670 // behind std::is_trivially_move_constructible (20.9.4.3).
4673 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4674 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4676 case UTT_HasTrivialCopy:
4677 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4678 // If __is_pod (type) is true or type is a reference type then
4679 // the trait is true, else if type is a cv class or union type
4680 // with a trivial copy constructor ([class.copy]) then the trait
4681 // is true, else it is false.
4682 if (T.isPODType(C) || T->isReferenceType())
4684 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4685 return RD->hasTrivialCopyConstructor() &&
4686 !RD->hasNonTrivialCopyConstructor();
4688 case UTT_HasTrivialMoveAssign:
4689 // This trait is implemented by MSVC 2012 and needed to parse the
4690 // standard library headers. Specifically it is used as the logic
4691 // behind std::is_trivially_move_assignable (20.9.4.3)
4694 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4695 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4697 case UTT_HasTrivialAssign:
4698 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4699 // If type is const qualified or is a reference type then the
4700 // trait is false. Otherwise if __is_pod (type) is true then the
4701 // trait is true, else if type is a cv class or union type with
4702 // a trivial copy assignment ([class.copy]) then the trait is
4703 // true, else it is false.
4704 // Note: the const and reference restrictions are interesting,
4705 // given that const and reference members don't prevent a class
4706 // from having a trivial copy assignment operator (but do cause
4707 // errors if the copy assignment operator is actually used, q.v.
4708 // [class.copy]p12).
4710 if (T.isConstQualified())
4714 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4715 return RD->hasTrivialCopyAssignment() &&
4716 !RD->hasNonTrivialCopyAssignment();
4718 case UTT_IsDestructible:
4719 case UTT_IsTriviallyDestructible:
4720 case UTT_IsNothrowDestructible:
4721 // C++14 [meta.unary.prop]:
4722 // For reference types, is_destructible<T>::value is true.
4723 if (T->isReferenceType())
4726 // Objective-C++ ARC: autorelease types don't require destruction.
4727 if (T->isObjCLifetimeType() &&
4728 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4731 // C++14 [meta.unary.prop]:
4732 // For incomplete types and function types, is_destructible<T>::value is
4734 if (T->isIncompleteType() || T->isFunctionType())
4737 // A type that requires destruction (via a non-trivial destructor or ARC
4738 // lifetime semantics) is not trivially-destructible.
4739 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4742 // C++14 [meta.unary.prop]:
4743 // For object types and given U equal to remove_all_extents_t<T>, if the
4744 // expression std::declval<U&>().~U() is well-formed when treated as an
4745 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4746 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4747 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4750 // C++14 [dcl.fct.def.delete]p2:
4751 // A program that refers to a deleted function implicitly or
4752 // explicitly, other than to declare it, is ill-formed.
4753 if (Destructor->isDeleted())
4755 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4757 if (UTT == UTT_IsNothrowDestructible) {
4758 const FunctionProtoType *CPT =
4759 Destructor->getType()->getAs<FunctionProtoType>();
4760 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4761 if (!CPT || !CPT->isNothrow())
4767 case UTT_HasTrivialDestructor:
4768 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4769 // If __is_pod (type) is true or type is a reference type
4770 // then the trait is true, else if type is a cv class or union
4771 // type (or array thereof) with a trivial destructor
4772 // ([class.dtor]) then the trait is true, else it is
4774 if (T.isPODType(C) || T->isReferenceType())
4777 // Objective-C++ ARC: autorelease types don't require destruction.
4778 if (T->isObjCLifetimeType() &&
4779 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4782 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4783 return RD->hasTrivialDestructor();
4785 // TODO: Propagate nothrowness for implicitly declared special members.
4786 case UTT_HasNothrowAssign:
4787 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4788 // If type is const qualified or is a reference type then the
4789 // trait is false. Otherwise if __has_trivial_assign (type)
4790 // is true then the trait is true, else if type is a cv class
4791 // or union type with copy assignment operators that are known
4792 // not to throw an exception then the trait is true, else it is
4794 if (C.getBaseElementType(T).isConstQualified())
4796 if (T->isReferenceType())
4798 if (T.isPODType(C) || T->isObjCLifetimeType())
4801 if (const RecordType *RT = T->getAs<RecordType>())
4802 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4803 &CXXRecordDecl::hasTrivialCopyAssignment,
4804 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4805 &CXXMethodDecl::isCopyAssignmentOperator);
4807 case UTT_HasNothrowMoveAssign:
4808 // This trait is implemented by MSVC 2012 and needed to parse the
4809 // standard library headers. Specifically this is used as the logic
4810 // behind std::is_nothrow_move_assignable (20.9.4.3).
4814 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4815 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4816 &CXXRecordDecl::hasTrivialMoveAssignment,
4817 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4818 &CXXMethodDecl::isMoveAssignmentOperator);
4820 case UTT_HasNothrowCopy:
4821 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4822 // If __has_trivial_copy (type) is true then the trait is true, else
4823 // if type is a cv class or union type with copy constructors that are
4824 // known not to throw an exception then the trait is true, else it is
4826 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4828 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4829 if (RD->hasTrivialCopyConstructor() &&
4830 !RD->hasNonTrivialCopyConstructor())
4833 bool FoundConstructor = false;
4835 for (const auto *ND : Self.LookupConstructors(RD)) {
4836 // A template constructor is never a copy constructor.
4837 // FIXME: However, it may actually be selected at the actual overload
4838 // resolution point.
4839 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4841 // UsingDecl itself is not a constructor
4842 if (isa<UsingDecl>(ND))
4844 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4845 if (Constructor->isCopyConstructor(FoundTQs)) {
4846 FoundConstructor = true;
4847 const FunctionProtoType *CPT
4848 = Constructor->getType()->getAs<FunctionProtoType>();
4849 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4852 // TODO: check whether evaluating default arguments can throw.
4853 // For now, we'll be conservative and assume that they can throw.
4854 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4859 return FoundConstructor;
4862 case UTT_HasNothrowConstructor:
4863 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4864 // If __has_trivial_constructor (type) is true then the trait is
4865 // true, else if type is a cv class or union type (or array
4866 // thereof) with a default constructor that is known not to
4867 // throw an exception then the trait is true, else it is false.
4868 if (T.isPODType(C) || T->isObjCLifetimeType())
4870 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4871 if (RD->hasTrivialDefaultConstructor() &&
4872 !RD->hasNonTrivialDefaultConstructor())
4875 bool FoundConstructor = false;
4876 for (const auto *ND : Self.LookupConstructors(RD)) {
4877 // FIXME: In C++0x, a constructor template can be a default constructor.
4878 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4880 // UsingDecl itself is not a constructor
4881 if (isa<UsingDecl>(ND))
4883 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4884 if (Constructor->isDefaultConstructor()) {
4885 FoundConstructor = true;
4886 const FunctionProtoType *CPT
4887 = Constructor->getType()->getAs<FunctionProtoType>();
4888 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4891 // FIXME: check whether evaluating default arguments can throw.
4892 // For now, we'll be conservative and assume that they can throw.
4893 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4897 return FoundConstructor;
4900 case UTT_HasVirtualDestructor:
4901 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4902 // If type is a class type with a virtual destructor ([class.dtor])
4903 // then the trait is true, else it is false.
4904 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4905 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4906 return Destructor->isVirtual();
4909 // These type trait expressions are modeled on the specifications for the
4910 // Embarcadero C++0x type trait functions:
4911 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4912 case UTT_IsCompleteType:
4913 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4914 // Returns True if and only if T is a complete type at the point of the
4916 return !T->isIncompleteType();
4917 case UTT_HasUniqueObjectRepresentations:
4918 return C.hasUniqueObjectRepresentations(T);
4922 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4923 QualType RhsT, SourceLocation KeyLoc);
4925 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4926 ArrayRef<TypeSourceInfo *> Args,
4927 SourceLocation RParenLoc) {
4928 if (Kind <= UTT_Last)
4929 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4931 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4932 // traits to avoid duplication.
4933 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4934 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4935 Args[1]->getType(), RParenLoc);
4938 case clang::BTT_ReferenceBindsToTemporary:
4939 case clang::TT_IsConstructible:
4940 case clang::TT_IsNothrowConstructible:
4941 case clang::TT_IsTriviallyConstructible: {
4942 // C++11 [meta.unary.prop]:
4943 // is_trivially_constructible is defined as:
4945 // is_constructible<T, Args...>::value is true and the variable
4946 // definition for is_constructible, as defined below, is known to call
4947 // no operation that is not trivial.
4949 // The predicate condition for a template specialization
4950 // is_constructible<T, Args...> shall be satisfied if and only if the
4951 // following variable definition would be well-formed for some invented
4954 // T t(create<Args>()...);
4955 assert(!Args.empty());
4957 // Precondition: T and all types in the parameter pack Args shall be
4958 // complete types, (possibly cv-qualified) void, or arrays of
4960 for (const auto *TSI : Args) {
4961 QualType ArgTy = TSI->getType();
4962 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4965 if (S.RequireCompleteType(KWLoc, ArgTy,
4966 diag::err_incomplete_type_used_in_type_trait_expr))
4970 // Make sure the first argument is not incomplete nor a function type.
4971 QualType T = Args[0]->getType();
4972 if (T->isIncompleteType() || T->isFunctionType())
4975 // Make sure the first argument is not an abstract type.
4976 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4977 if (RD && RD->isAbstract())
4980 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4981 SmallVector<Expr *, 2> ArgExprs;
4982 ArgExprs.reserve(Args.size() - 1);
4983 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4984 QualType ArgTy = Args[I]->getType();
4985 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4986 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4987 OpaqueArgExprs.push_back(
4988 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4989 ArgTy.getNonLValueExprType(S.Context),
4990 Expr::getValueKindForType(ArgTy)));
4992 for (Expr &E : OpaqueArgExprs)
4993 ArgExprs.push_back(&E);
4995 // Perform the initialization in an unevaluated context within a SFINAE
4996 // trap at translation unit scope.
4997 EnterExpressionEvaluationContext Unevaluated(
4998 S, Sema::ExpressionEvaluationContext::Unevaluated);
4999 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5000 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5001 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
5002 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5004 InitializationSequence Init(S, To, InitKind, ArgExprs);
5008 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5009 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5012 if (Kind == clang::TT_IsConstructible)
5015 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
5016 if (!T->isReferenceType())
5019 return !Init.isDirectReferenceBinding();
5022 if (Kind == clang::TT_IsNothrowConstructible)
5023 return S.canThrow(Result.get()) == CT_Cannot;
5025 if (Kind == clang::TT_IsTriviallyConstructible) {
5026 // Under Objective-C ARC and Weak, if the destination has non-trivial
5027 // Objective-C lifetime, this is a non-trivial construction.
5028 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5031 // The initialization succeeded; now make sure there are no non-trivial
5033 return !Result.get()->hasNonTrivialCall(S.Context);
5036 llvm_unreachable("unhandled type trait");
5039 default: llvm_unreachable("not a TT");
5045 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5046 ArrayRef<TypeSourceInfo *> Args,
5047 SourceLocation RParenLoc) {
5048 QualType ResultType = Context.getLogicalOperationType();
5050 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5051 *this, Kind, KWLoc, Args[0]->getType()))
5054 bool Dependent = false;
5055 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5056 if (Args[I]->getType()->isDependentType()) {
5062 bool Result = false;
5064 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5066 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5070 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5071 ArrayRef<ParsedType> Args,
5072 SourceLocation RParenLoc) {
5073 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5074 ConvertedArgs.reserve(Args.size());
5076 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5077 TypeSourceInfo *TInfo;
5078 QualType T = GetTypeFromParser(Args[I], &TInfo);
5080 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5082 ConvertedArgs.push_back(TInfo);
5085 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5088 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5089 QualType RhsT, SourceLocation KeyLoc) {
5090 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
5091 "Cannot evaluate traits of dependent types");
5094 case BTT_IsBaseOf: {
5095 // C++0x [meta.rel]p2
5096 // Base is a base class of Derived without regard to cv-qualifiers or
5097 // Base and Derived are not unions and name the same class type without
5098 // regard to cv-qualifiers.
5100 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5101 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5102 if (!rhsRecord || !lhsRecord) {
5103 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5104 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5105 if (!LHSObjTy || !RHSObjTy)
5108 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5109 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5110 if (!BaseInterface || !DerivedInterface)
5113 if (Self.RequireCompleteType(
5114 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5117 return BaseInterface->isSuperClassOf(DerivedInterface);
5120 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
5121 == (lhsRecord == rhsRecord));
5123 // Unions are never base classes, and never have base classes.
5124 // It doesn't matter if they are complete or not. See PR#41843
5125 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5127 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5130 if (lhsRecord == rhsRecord)
5133 // C++0x [meta.rel]p2:
5134 // If Base and Derived are class types and are different types
5135 // (ignoring possible cv-qualifiers) then Derived shall be a
5137 if (Self.RequireCompleteType(KeyLoc, RhsT,
5138 diag::err_incomplete_type_used_in_type_trait_expr))
5141 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5142 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5145 return Self.Context.hasSameType(LhsT, RhsT);
5146 case BTT_TypeCompatible: {
5147 // GCC ignores cv-qualifiers on arrays for this builtin.
5148 Qualifiers LhsQuals, RhsQuals;
5149 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5150 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5151 return Self.Context.typesAreCompatible(Lhs, Rhs);
5153 case BTT_IsConvertible:
5154 case BTT_IsConvertibleTo: {
5155 // C++0x [meta.rel]p4:
5156 // Given the following function prototype:
5158 // template <class T>
5159 // typename add_rvalue_reference<T>::type create();
5161 // the predicate condition for a template specialization
5162 // is_convertible<From, To> shall be satisfied if and only if
5163 // the return expression in the following code would be
5164 // well-formed, including any implicit conversions to the return
5165 // type of the function:
5168 // return create<From>();
5171 // Access checking is performed as if in a context unrelated to To and
5172 // From. Only the validity of the immediate context of the expression
5173 // of the return-statement (including conversions to the return type)
5176 // We model the initialization as a copy-initialization of a temporary
5177 // of the appropriate type, which for this expression is identical to the
5178 // return statement (since NRVO doesn't apply).
5180 // Functions aren't allowed to return function or array types.
5181 if (RhsT->isFunctionType() || RhsT->isArrayType())
5184 // A return statement in a void function must have void type.
5185 if (RhsT->isVoidType())
5186 return LhsT->isVoidType();
5188 // A function definition requires a complete, non-abstract return type.
5189 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5192 // Compute the result of add_rvalue_reference.
5193 if (LhsT->isObjectType() || LhsT->isFunctionType())
5194 LhsT = Self.Context.getRValueReferenceType(LhsT);
5196 // Build a fake source and destination for initialization.
5197 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5198 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5199 Expr::getValueKindForType(LhsT));
5200 Expr *FromPtr = &From;
5201 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5204 // Perform the initialization in an unevaluated context within a SFINAE
5205 // trap at translation unit scope.
5206 EnterExpressionEvaluationContext Unevaluated(
5207 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5208 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5209 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5210 InitializationSequence Init(Self, To, Kind, FromPtr);
5214 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5215 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5218 case BTT_IsAssignable:
5219 case BTT_IsNothrowAssignable:
5220 case BTT_IsTriviallyAssignable: {
5221 // C++11 [meta.unary.prop]p3:
5222 // is_trivially_assignable is defined as:
5223 // is_assignable<T, U>::value is true and the assignment, as defined by
5224 // is_assignable, is known to call no operation that is not trivial
5226 // is_assignable is defined as:
5227 // The expression declval<T>() = declval<U>() is well-formed when
5228 // treated as an unevaluated operand (Clause 5).
5230 // For both, T and U shall be complete types, (possibly cv-qualified)
5231 // void, or arrays of unknown bound.
5232 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5233 Self.RequireCompleteType(KeyLoc, LhsT,
5234 diag::err_incomplete_type_used_in_type_trait_expr))
5236 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5237 Self.RequireCompleteType(KeyLoc, RhsT,
5238 diag::err_incomplete_type_used_in_type_trait_expr))
5241 // cv void is never assignable.
5242 if (LhsT->isVoidType() || RhsT->isVoidType())
5245 // Build expressions that emulate the effect of declval<T>() and
5247 if (LhsT->isObjectType() || LhsT->isFunctionType())
5248 LhsT = Self.Context.getRValueReferenceType(LhsT);
5249 if (RhsT->isObjectType() || RhsT->isFunctionType())
5250 RhsT = Self.Context.getRValueReferenceType(RhsT);
5251 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5252 Expr::getValueKindForType(LhsT));
5253 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5254 Expr::getValueKindForType(RhsT));
5256 // Attempt the assignment in an unevaluated context within a SFINAE
5257 // trap at translation unit scope.
5258 EnterExpressionEvaluationContext Unevaluated(
5259 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5260 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5261 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5262 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5264 if (Result.isInvalid())
5267 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5268 Self.CheckUnusedVolatileAssignment(Result.get());
5270 if (SFINAE.hasErrorOccurred())
5273 if (BTT == BTT_IsAssignable)
5276 if (BTT == BTT_IsNothrowAssignable)
5277 return Self.canThrow(Result.get()) == CT_Cannot;
5279 if (BTT == BTT_IsTriviallyAssignable) {
5280 // Under Objective-C ARC and Weak, if the destination has non-trivial
5281 // Objective-C lifetime, this is a non-trivial assignment.
5282 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5285 return !Result.get()->hasNonTrivialCall(Self.Context);
5288 llvm_unreachable("unhandled type trait");
5291 default: llvm_unreachable("not a BTT");
5293 llvm_unreachable("Unknown type trait or not implemented");
5296 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5297 SourceLocation KWLoc,
5300 SourceLocation RParen) {
5301 TypeSourceInfo *TSInfo;
5302 QualType T = GetTypeFromParser(Ty, &TSInfo);
5304 TSInfo = Context.getTrivialTypeSourceInfo(T);
5306 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5309 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5310 QualType T, Expr *DimExpr,
5311 SourceLocation KeyLoc) {
5312 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
5316 if (T->isArrayType()) {
5318 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5320 T = AT->getElementType();
5326 case ATT_ArrayExtent: {
5329 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5330 diag::err_dimension_expr_not_constant_integer,
5333 if (Value.isSigned() && Value.isNegative()) {
5334 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5335 << DimExpr->getSourceRange();
5338 Dim = Value.getLimitedValue();
5340 if (T->isArrayType()) {
5342 bool Matched = false;
5343 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5349 T = AT->getElementType();
5352 if (Matched && T->isArrayType()) {
5353 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5354 return CAT->getSize().getLimitedValue();
5360 llvm_unreachable("Unknown type trait or not implemented");
5363 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5364 SourceLocation KWLoc,
5365 TypeSourceInfo *TSInfo,
5367 SourceLocation RParen) {
5368 QualType T = TSInfo->getType();
5370 // FIXME: This should likely be tracked as an APInt to remove any host
5371 // assumptions about the width of size_t on the target.
5373 if (!T->isDependentType())
5374 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5376 // While the specification for these traits from the Embarcadero C++
5377 // compiler's documentation says the return type is 'unsigned int', Clang
5378 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5379 // compiler, there is no difference. On several other platforms this is an
5380 // important distinction.
5381 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5382 RParen, Context.getSizeType());
5385 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5386 SourceLocation KWLoc,
5388 SourceLocation RParen) {
5389 // If error parsing the expression, ignore.
5393 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5398 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5400 case ET_IsLValueExpr: return E->isLValue();
5401 case ET_IsRValueExpr: return E->isRValue();
5403 llvm_unreachable("Expression trait not covered by switch");
5406 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5407 SourceLocation KWLoc,
5409 SourceLocation RParen) {
5410 if (Queried->isTypeDependent()) {
5411 // Delay type-checking for type-dependent expressions.
5412 } else if (Queried->getType()->isPlaceholderType()) {
5413 ExprResult PE = CheckPlaceholderExpr(Queried);
5414 if (PE.isInvalid()) return ExprError();
5415 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5418 bool Value = EvaluateExpressionTrait(ET, Queried);
5420 return new (Context)
5421 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5424 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5428 assert(!LHS.get()->getType()->isPlaceholderType() &&
5429 !RHS.get()->getType()->isPlaceholderType() &&
5430 "placeholders should have been weeded out by now");
5432 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5433 // temporary materialization conversion otherwise.
5435 LHS = DefaultLvalueConversion(LHS.get());
5436 else if (LHS.get()->isRValue())
5437 LHS = TemporaryMaterializationConversion(LHS.get());
5438 if (LHS.isInvalid())
5441 // The RHS always undergoes lvalue conversions.
5442 RHS = DefaultLvalueConversion(RHS.get());
5443 if (RHS.isInvalid()) return QualType();
5445 const char *OpSpelling = isIndirect ? "->*" : ".*";
5447 // The binary operator .* [p3: ->*] binds its second operand, which shall
5448 // be of type "pointer to member of T" (where T is a completely-defined
5449 // class type) [...]
5450 QualType RHSType = RHS.get()->getType();
5451 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5453 Diag(Loc, diag::err_bad_memptr_rhs)
5454 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5458 QualType Class(MemPtr->getClass(), 0);
5460 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5461 // member pointer points must be completely-defined. However, there is no
5462 // reason for this semantic distinction, and the rule is not enforced by
5463 // other compilers. Therefore, we do not check this property, as it is
5464 // likely to be considered a defect.
5467 // [...] to its first operand, which shall be of class T or of a class of
5468 // which T is an unambiguous and accessible base class. [p3: a pointer to
5470 QualType LHSType = LHS.get()->getType();
5472 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5473 LHSType = Ptr->getPointeeType();
5475 Diag(Loc, diag::err_bad_memptr_lhs)
5476 << OpSpelling << 1 << LHSType
5477 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5482 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5483 // If we want to check the hierarchy, we need a complete type.
5484 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5485 OpSpelling, (int)isIndirect)) {
5489 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5490 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5491 << (int)isIndirect << LHS.get()->getType();
5495 CXXCastPath BasePath;
5496 if (CheckDerivedToBaseConversion(
5497 LHSType, Class, Loc,
5498 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5502 // Cast LHS to type of use.
5503 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5505 UseType = Context.getPointerType(UseType);
5506 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5507 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5511 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5512 // Diagnose use of pointer-to-member type which when used as
5513 // the functional cast in a pointer-to-member expression.
5514 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5519 // The result is an object or a function of the type specified by the
5521 // The cv qualifiers are the union of those in the pointer and the left side,
5522 // in accordance with 5.5p5 and 5.2.5.
5523 QualType Result = MemPtr->getPointeeType();
5524 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5526 // C++0x [expr.mptr.oper]p6:
5527 // In a .* expression whose object expression is an rvalue, the program is
5528 // ill-formed if the second operand is a pointer to member function with
5529 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5530 // expression is an lvalue, the program is ill-formed if the second operand
5531 // is a pointer to member function with ref-qualifier &&.
5532 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5533 switch (Proto->getRefQualifier()) {
5539 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5540 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5541 // is (exactly) 'const'.
5542 if (Proto->isConst() && !Proto->isVolatile())
5543 Diag(Loc, getLangOpts().CPlusPlus2a
5544 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5545 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5547 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5548 << RHSType << 1 << LHS.get()->getSourceRange();
5553 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5554 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5555 << RHSType << 0 << LHS.get()->getSourceRange();
5560 // C++ [expr.mptr.oper]p6:
5561 // The result of a .* expression whose second operand is a pointer
5562 // to a data member is of the same value category as its
5563 // first operand. The result of a .* expression whose second
5564 // operand is a pointer to a member function is a prvalue. The
5565 // result of an ->* expression is an lvalue if its second operand
5566 // is a pointer to data member and a prvalue otherwise.
5567 if (Result->isFunctionType()) {
5569 return Context.BoundMemberTy;
5570 } else if (isIndirect) {
5573 VK = LHS.get()->getValueKind();
5579 /// Try to convert a type to another according to C++11 5.16p3.
5581 /// This is part of the parameter validation for the ? operator. If either
5582 /// value operand is a class type, the two operands are attempted to be
5583 /// converted to each other. This function does the conversion in one direction.
5584 /// It returns true if the program is ill-formed and has already been diagnosed
5586 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5587 SourceLocation QuestionLoc,
5588 bool &HaveConversion,
5590 HaveConversion = false;
5591 ToType = To->getType();
5593 InitializationKind Kind =
5594 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
5596 // The process for determining whether an operand expression E1 of type T1
5597 // can be converted to match an operand expression E2 of type T2 is defined
5599 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5600 // implicitly converted to type "lvalue reference to T2", subject to the
5601 // constraint that in the conversion the reference must bind directly to
5603 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5604 // implicitly converted to the type "rvalue reference to R2", subject to
5605 // the constraint that the reference must bind directly.
5606 if (To->isLValue() || To->isXValue()) {
5607 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5608 : Self.Context.getRValueReferenceType(ToType);
5610 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5612 InitializationSequence InitSeq(Self, Entity, Kind, From);
5613 if (InitSeq.isDirectReferenceBinding()) {
5615 HaveConversion = true;
5619 if (InitSeq.isAmbiguous())
5620 return InitSeq.Diagnose(Self, Entity, Kind, From);
5623 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5624 // -- if E1 and E2 have class type, and the underlying class types are
5625 // the same or one is a base class of the other:
5626 QualType FTy = From->getType();
5627 QualType TTy = To->getType();
5628 const RecordType *FRec = FTy->getAs<RecordType>();
5629 const RecordType *TRec = TTy->getAs<RecordType>();
5630 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5631 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5632 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5633 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5634 // E1 can be converted to match E2 if the class of T2 is the
5635 // same type as, or a base class of, the class of T1, and
5637 if (FRec == TRec || FDerivedFromT) {
5638 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5639 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5640 InitializationSequence InitSeq(Self, Entity, Kind, From);
5642 HaveConversion = true;
5646 if (InitSeq.isAmbiguous())
5647 return InitSeq.Diagnose(Self, Entity, Kind, From);
5654 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5655 // implicitly converted to the type that expression E2 would have
5656 // if E2 were converted to an rvalue (or the type it has, if E2 is
5659 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5660 // to the array-to-pointer or function-to-pointer conversions.
5661 TTy = TTy.getNonLValueExprType(Self.Context);
5663 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5664 InitializationSequence InitSeq(Self, Entity, Kind, From);
5665 HaveConversion = !InitSeq.Failed();
5667 if (InitSeq.isAmbiguous())
5668 return InitSeq.Diagnose(Self, Entity, Kind, From);
5673 /// Try to find a common type for two according to C++0x 5.16p5.
5675 /// This is part of the parameter validation for the ? operator. If either
5676 /// value operand is a class type, overload resolution is used to find a
5677 /// conversion to a common type.
5678 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5679 SourceLocation QuestionLoc) {
5680 Expr *Args[2] = { LHS.get(), RHS.get() };
5681 OverloadCandidateSet CandidateSet(QuestionLoc,
5682 OverloadCandidateSet::CSK_Operator);
5683 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5686 OverloadCandidateSet::iterator Best;
5687 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5689 // We found a match. Perform the conversions on the arguments and move on.
5690 ExprResult LHSRes = Self.PerformImplicitConversion(
5691 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5692 Sema::AA_Converting);
5693 if (LHSRes.isInvalid())
5697 ExprResult RHSRes = Self.PerformImplicitConversion(
5698 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5699 Sema::AA_Converting);
5700 if (RHSRes.isInvalid())
5704 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5708 case OR_No_Viable_Function:
5710 // Emit a better diagnostic if one of the expressions is a null pointer
5711 // constant and the other is a pointer type. In this case, the user most
5712 // likely forgot to take the address of the other expression.
5713 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5716 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5717 << LHS.get()->getType() << RHS.get()->getType()
5718 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5722 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5723 << LHS.get()->getType() << RHS.get()->getType()
5724 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5725 // FIXME: Print the possible common types by printing the return types of
5726 // the viable candidates.
5730 llvm_unreachable("Conditional operator has only built-in overloads");
5735 /// Perform an "extended" implicit conversion as returned by
5736 /// TryClassUnification.
5737 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5738 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5739 InitializationKind Kind =
5740 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
5741 Expr *Arg = E.get();
5742 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5743 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5744 if (Result.isInvalid())
5751 // Check the condition operand of ?: to see if it is valid for the GCC
5753 static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
5755 if (!CondTy->isVectorType() || CondTy->isExtVectorType())
5757 const QualType EltTy =
5758 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
5760 assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() &&
5761 "Vectors cant be boolean or enum types");
5762 return EltTy->isIntegralType(Ctx);
5765 QualType Sema::CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
5767 SourceLocation QuestionLoc) {
5768 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5769 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5771 QualType CondType = Cond.get()->getType();
5772 const auto *CondVT = CondType->getAs<VectorType>();
5773 QualType CondElementTy = CondVT->getElementType();
5774 unsigned CondElementCount = CondVT->getNumElements();
5775 QualType LHSType = LHS.get()->getType();
5776 const auto *LHSVT = LHSType->getAs<VectorType>();
5777 QualType RHSType = RHS.get()->getType();
5778 const auto *RHSVT = RHSType->getAs<VectorType>();
5780 QualType ResultType;
5782 // FIXME: In the future we should define what the Extvector conditional
5783 // operator looks like.
5784 if (LHSVT && isa<ExtVectorType>(LHSVT)) {
5785 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5786 << /*isExtVector*/ true << LHSType;
5790 if (RHSVT && isa<ExtVectorType>(RHSVT)) {
5791 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5792 << /*isExtVector*/ true << RHSType;
5796 if (LHSVT && RHSVT) {
5797 // If both are vector types, they must be the same type.
5798 if (!Context.hasSameType(LHSType, RHSType)) {
5799 Diag(QuestionLoc, diag::err_conditional_vector_mismatched_vectors)
5800 << LHSType << RHSType;
5803 ResultType = LHSType;
5804 } else if (LHSVT || RHSVT) {
5805 ResultType = CheckVectorOperands(
5806 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
5807 /*AllowBoolConversions*/ false);
5808 if (ResultType.isNull())
5812 QualType ResultElementTy;
5813 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
5814 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
5816 if (Context.hasSameType(LHSType, RHSType))
5817 ResultElementTy = LHSType;
5820 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
5822 if (ResultElementTy->isEnumeralType()) {
5823 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
5824 << /*isExtVector*/ false << ResultElementTy;
5827 ResultType = Context.getVectorType(
5828 ResultElementTy, CondType->getAs<VectorType>()->getNumElements(),
5829 VectorType::GenericVector);
5831 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
5832 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
5835 assert(!ResultType.isNull() && ResultType->isVectorType() &&
5836 "Result should have been a vector type");
5837 QualType ResultElementTy = ResultType->getAs<VectorType>()->getElementType();
5838 unsigned ResultElementCount =
5839 ResultType->getAs<VectorType>()->getNumElements();
5841 if (ResultElementCount != CondElementCount) {
5842 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
5847 if (Context.getTypeSize(ResultElementTy) !=
5848 Context.getTypeSize(CondElementTy)) {
5849 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
5857 /// Check the operands of ?: under C++ semantics.
5859 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5860 /// extension. In this case, LHS == Cond. (But they're not aliases.)
5862 /// This function also implements GCC's vector extension for conditionals.
5863 /// GCC's vector extension permits the use of a?b:c where the type of
5864 /// a is that of a integer vector with the same number of elements and
5865 /// size as the vectors of b and c. If one of either b or c is a scalar
5866 /// it is implicitly converted to match the type of the vector.
5867 /// Otherwise the expression is ill-formed. If both b and c are scalars,
5868 /// then b and c are checked and converted to the type of a if possible.
5869 /// Unlike the OpenCL ?: operator, the expression is evaluated as
5870 /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5871 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5872 ExprResult &RHS, ExprValueKind &VK,
5874 SourceLocation QuestionLoc) {
5875 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
5881 bool IsVectorConditional =
5882 isValidVectorForConditionalCondition(Context, Cond.get()->getType());
5884 // C++11 [expr.cond]p1
5885 // The first expression is contextually converted to bool.
5886 if (!Cond.get()->isTypeDependent()) {
5887 ExprResult CondRes = IsVectorConditional
5888 ? DefaultFunctionArrayLvalueConversion(Cond.get())
5889 : CheckCXXBooleanCondition(Cond.get());
5890 if (CondRes.isInvalid())
5894 // To implement C++, the first expression typically doesn't alter the result
5895 // type of the conditional, however the GCC compatible vector extension
5896 // changes the result type to be that of the conditional. Since we cannot
5897 // know if this is a vector extension here, delay the conversion of the
5898 // LHS/RHS below until later.
5899 return Context.DependentTy;
5903 // Either of the arguments dependent?
5904 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5905 return Context.DependentTy;
5907 // C++11 [expr.cond]p2
5908 // If either the second or the third operand has type (cv) void, ...
5909 QualType LTy = LHS.get()->getType();
5910 QualType RTy = RHS.get()->getType();
5911 bool LVoid = LTy->isVoidType();
5912 bool RVoid = RTy->isVoidType();
5913 if (LVoid || RVoid) {
5914 // ... one of the following shall hold:
5915 // -- The second or the third operand (but not both) is a (possibly
5916 // parenthesized) throw-expression; the result is of the type
5917 // and value category of the other.
5918 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5919 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5921 // Void expressions aren't legal in the vector-conditional expressions.
5922 if (IsVectorConditional) {
5923 SourceRange DiagLoc =
5924 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
5925 bool IsThrow = LVoid ? LThrow : RThrow;
5926 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
5927 << DiagLoc << IsThrow;
5931 if (LThrow != RThrow) {
5932 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5933 VK = NonThrow->getValueKind();
5934 // DR (no number yet): the result is a bit-field if the
5935 // non-throw-expression operand is a bit-field.
5936 OK = NonThrow->getObjectKind();
5937 return NonThrow->getType();
5940 // -- Both the second and third operands have type void; the result is of
5941 // type void and is a prvalue.
5943 return Context.VoidTy;
5945 // Neither holds, error.
5946 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5947 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5948 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5953 if (IsVectorConditional)
5954 return CheckGNUVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
5956 // C++11 [expr.cond]p3
5957 // Otherwise, if the second and third operand have different types, and
5958 // either has (cv) class type [...] an attempt is made to convert each of
5959 // those operands to the type of the other.
5960 if (!Context.hasSameType(LTy, RTy) &&
5961 (LTy->isRecordType() || RTy->isRecordType())) {
5962 // These return true if a single direction is already ambiguous.
5963 QualType L2RType, R2LType;
5964 bool HaveL2R, HaveR2L;
5965 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5967 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5970 // If both can be converted, [...] the program is ill-formed.
5971 if (HaveL2R && HaveR2L) {
5972 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5973 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5977 // If exactly one conversion is possible, that conversion is applied to
5978 // the chosen operand and the converted operands are used in place of the
5979 // original operands for the remainder of this section.
5981 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5983 LTy = LHS.get()->getType();
5984 } else if (HaveR2L) {
5985 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5987 RTy = RHS.get()->getType();
5991 // C++11 [expr.cond]p3
5992 // if both are glvalues of the same value category and the same type except
5993 // for cv-qualification, an attempt is made to convert each of those
5994 // operands to the type of the other.
5996 // Resolving a defect in P0012R1: we extend this to cover all cases where
5997 // one of the operands is reference-compatible with the other, in order
5998 // to support conditionals between functions differing in noexcept. This
5999 // will similarly cover difference in array bounds after P0388R4.
6000 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6002 ExprValueKind LVK = LHS.get()->getValueKind();
6003 ExprValueKind RVK = RHS.get()->getValueKind();
6004 if (!Context.hasSameType(LTy, RTy) &&
6005 LVK == RVK && LVK != VK_RValue) {
6006 // DerivedToBase was already handled by the class-specific case above.
6007 // FIXME: Should we allow ObjC conversions here?
6008 const ReferenceConversions AllowedConversions =
6009 ReferenceConversions::Qualification |
6010 ReferenceConversions::NestedQualification |
6011 ReferenceConversions::Function;
6013 ReferenceConversions RefConv;
6014 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6016 !(RefConv & ~AllowedConversions) &&
6017 // [...] subject to the constraint that the reference must bind
6019 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6020 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6021 RTy = RHS.get()->getType();
6022 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6024 !(RefConv & ~AllowedConversions) &&
6025 !LHS.get()->refersToBitField() &&
6026 !LHS.get()->refersToVectorElement()) {
6027 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6028 LTy = LHS.get()->getType();
6032 // C++11 [expr.cond]p4
6033 // If the second and third operands are glvalues of the same value
6034 // category and have the same type, the result is of that type and
6035 // value category and it is a bit-field if the second or the third
6036 // operand is a bit-field, or if both are bit-fields.
6037 // We only extend this to bitfields, not to the crazy other kinds of
6039 bool Same = Context.hasSameType(LTy, RTy);
6040 if (Same && LVK == RVK && LVK != VK_RValue &&
6041 LHS.get()->isOrdinaryOrBitFieldObject() &&
6042 RHS.get()->isOrdinaryOrBitFieldObject()) {
6043 VK = LHS.get()->getValueKind();
6044 if (LHS.get()->getObjectKind() == OK_BitField ||
6045 RHS.get()->getObjectKind() == OK_BitField)
6048 // If we have function pointer types, unify them anyway to unify their
6049 // exception specifications, if any.
6050 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6051 Qualifiers Qs = LTy.getQualifiers();
6052 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
6053 /*ConvertArgs*/false);
6054 LTy = Context.getQualifiedType(LTy, Qs);
6056 assert(!LTy.isNull() && "failed to find composite pointer type for "
6057 "canonically equivalent function ptr types");
6058 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
6064 // C++11 [expr.cond]p5
6065 // Otherwise, the result is a prvalue. If the second and third operands
6066 // do not have the same type, and either has (cv) class type, ...
6067 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6068 // ... overload resolution is used to determine the conversions (if any)
6069 // to be applied to the operands. If the overload resolution fails, the
6070 // program is ill-formed.
6071 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6075 // C++11 [expr.cond]p6
6076 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6077 // conversions are performed on the second and third operands.
6078 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6079 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6080 if (LHS.isInvalid() || RHS.isInvalid())
6082 LTy = LHS.get()->getType();
6083 RTy = RHS.get()->getType();
6085 // After those conversions, one of the following shall hold:
6086 // -- The second and third operands have the same type; the result
6087 // is of that type. If the operands have class type, the result
6088 // is a prvalue temporary of the result type, which is
6089 // copy-initialized from either the second operand or the third
6090 // operand depending on the value of the first operand.
6091 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
6092 if (LTy->isRecordType()) {
6093 // The operands have class type. Make a temporary copy.
6094 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
6096 ExprResult LHSCopy = PerformCopyInitialization(Entity,
6099 if (LHSCopy.isInvalid())
6102 ExprResult RHSCopy = PerformCopyInitialization(Entity,
6105 if (RHSCopy.isInvalid())
6112 // If we have function pointer types, unify them anyway to unify their
6113 // exception specifications, if any.
6114 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
6115 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
6116 assert(!LTy.isNull() && "failed to find composite pointer type for "
6117 "canonically equivalent function ptr types");
6123 // Extension: conditional operator involving vector types.
6124 if (LTy->isVectorType() || RTy->isVectorType())
6125 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6126 /*AllowBothBool*/true,
6127 /*AllowBoolConversions*/false);
6129 // -- The second and third operands have arithmetic or enumeration type;
6130 // the usual arithmetic conversions are performed to bring them to a
6131 // common type, and the result is of that type.
6132 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6134 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6135 if (LHS.isInvalid() || RHS.isInvalid())
6137 if (ResTy.isNull()) {
6139 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6140 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6144 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6145 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6150 // -- The second and third operands have pointer type, or one has pointer
6151 // type and the other is a null pointer constant, or both are null
6152 // pointer constants, at least one of which is non-integral; pointer
6153 // conversions and qualification conversions are performed to bring them
6154 // to their composite pointer type. The result is of the composite
6156 // -- The second and third operands have pointer to member type, or one has
6157 // pointer to member type and the other is a null pointer constant;
6158 // pointer to member conversions and qualification conversions are
6159 // performed to bring them to a common type, whose cv-qualification
6160 // shall match the cv-qualification of either the second or the third
6161 // operand. The result is of the common type.
6162 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6163 if (!Composite.isNull())
6166 // Similarly, attempt to find composite type of two objective-c pointers.
6167 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6168 if (!Composite.isNull())
6171 // Check if we are using a null with a non-pointer type.
6172 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6175 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6176 << LHS.get()->getType() << RHS.get()->getType()
6177 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6181 static FunctionProtoType::ExceptionSpecInfo
6182 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6183 FunctionProtoType::ExceptionSpecInfo ESI2,
6184 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6185 ExceptionSpecificationType EST1 = ESI1.Type;
6186 ExceptionSpecificationType EST2 = ESI2.Type;
6188 // If either of them can throw anything, that is the result.
6189 if (EST1 == EST_None) return ESI1;
6190 if (EST2 == EST_None) return ESI2;
6191 if (EST1 == EST_MSAny) return ESI1;
6192 if (EST2 == EST_MSAny) return ESI2;
6193 if (EST1 == EST_NoexceptFalse) return ESI1;
6194 if (EST2 == EST_NoexceptFalse) return ESI2;
6196 // If either of them is non-throwing, the result is the other.
6197 if (EST1 == EST_NoThrow) return ESI2;
6198 if (EST2 == EST_NoThrow) return ESI1;
6199 if (EST1 == EST_DynamicNone) return ESI2;
6200 if (EST2 == EST_DynamicNone) return ESI1;
6201 if (EST1 == EST_BasicNoexcept) return ESI2;
6202 if (EST2 == EST_BasicNoexcept) return ESI1;
6203 if (EST1 == EST_NoexceptTrue) return ESI2;
6204 if (EST2 == EST_NoexceptTrue) return ESI1;
6206 // If we're left with value-dependent computed noexcept expressions, we're
6207 // stuck. Before C++17, we can just drop the exception specification entirely,
6208 // since it's not actually part of the canonical type. And this should never
6209 // happen in C++17, because it would mean we were computing the composite
6210 // pointer type of dependent types, which should never happen.
6211 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
6212 assert(!S.getLangOpts().CPlusPlus17 &&
6213 "computing composite pointer type of dependent types");
6214 return FunctionProtoType::ExceptionSpecInfo();
6217 // Switch over the possibilities so that people adding new values know to
6218 // update this function.
6221 case EST_DynamicNone:
6223 case EST_BasicNoexcept:
6224 case EST_DependentNoexcept:
6225 case EST_NoexceptFalse:
6226 case EST_NoexceptTrue:
6228 llvm_unreachable("handled above");
6231 // This is the fun case: both exception specifications are dynamic. Form
6232 // the union of the two lists.
6233 assert(EST2 == EST_Dynamic && "other cases should already be handled");
6234 llvm::SmallPtrSet<QualType, 8> Found;
6235 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6236 for (QualType E : Exceptions)
6237 if (Found.insert(S.Context.getCanonicalType(E)).second)
6238 ExceptionTypeStorage.push_back(E);
6240 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6241 Result.Exceptions = ExceptionTypeStorage;
6245 case EST_Unevaluated:
6246 case EST_Uninstantiated:
6248 llvm_unreachable("shouldn't see unresolved exception specifications here");
6251 llvm_unreachable("invalid ExceptionSpecificationType");
6254 /// Find a merged pointer type and convert the two expressions to it.
6256 /// This finds the composite pointer type for \p E1 and \p E2 according to
6257 /// C++2a [expr.type]p3. It converts both expressions to this type and returns
6258 /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6261 /// \param Loc The location of the operator requiring these two expressions to
6262 /// be converted to the composite pointer type.
6264 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6265 QualType Sema::FindCompositePointerType(SourceLocation Loc,
6266 Expr *&E1, Expr *&E2,
6268 assert(getLangOpts().CPlusPlus && "This function assumes C++");
6271 // The composite pointer type of two operands p1 and p2 having types T1
6273 QualType T1 = E1->getType(), T2 = E2->getType();
6275 // where at least one is a pointer or pointer to member type or
6276 // std::nullptr_t is:
6277 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6278 T1->isNullPtrType();
6279 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6280 T2->isNullPtrType();
6281 if (!T1IsPointerLike && !T2IsPointerLike)
6284 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6285 // This can't actually happen, following the standard, but we also use this
6286 // to implement the end of [expr.conv], which hits this case.
6288 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6289 if (T1IsPointerLike &&
6290 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6292 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6293 ? CK_NullToMemberPointer
6294 : CK_NullToPointer).get();
6297 if (T2IsPointerLike &&
6298 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6300 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6301 ? CK_NullToMemberPointer
6302 : CK_NullToPointer).get();
6306 // Now both have to be pointers or member pointers.
6307 if (!T1IsPointerLike || !T2IsPointerLike)
6309 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
6310 "nullptr_t should be a null pointer constant");
6313 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6314 // Qualifiers to apply under the step kind.
6316 /// The class for a pointer-to-member; a constant array type with a bound
6317 /// (if any) for an array.
6318 const Type *ClassOrBound;
6320 Step(Kind K, const Type *ClassOrBound = nullptr)
6321 : K(K), Quals(), ClassOrBound(ClassOrBound) {}
6322 QualType rebuild(ASTContext &Ctx, QualType T) const {
6323 T = Ctx.getQualifiedType(T, Quals);
6326 return Ctx.getPointerType(T);
6328 return Ctx.getMemberPointerType(T, ClassOrBound);
6330 return Ctx.getObjCObjectPointerType(T);
6332 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6333 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6334 ArrayType::Normal, 0);
6336 return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
6338 llvm_unreachable("unknown step kind");
6342 SmallVector<Step, 8> Steps;
6344 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6345 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6346 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6348 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6349 // to member of C2 of type cv2 U2" for some non-function type U, where
6350 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6351 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6353 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6356 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6357 // and to prepare to form the cv-combined type if so.
6358 QualType Composite1 = T1;
6359 QualType Composite2 = T2;
6360 unsigned NeedConstBefore = 0;
6362 assert(!Composite1.isNull() && !Composite2.isNull());
6365 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6366 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6368 // Top-level qualifiers are ignored. Merge at all lower levels.
6369 if (!Steps.empty()) {
6370 // Find the qualifier union: (approximately) the unique minimal set of
6371 // qualifiers that is compatible with both types.
6372 Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
6373 Q2.getCVRUQualifiers());
6375 // Under one level of pointer or pointer-to-member, we can change to an
6376 // unambiguous compatible address space.
6377 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6378 Quals.setAddressSpace(Q1.getAddressSpace());
6379 } else if (Steps.size() == 1) {
6380 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
6381 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
6382 if (MaybeQ1 == MaybeQ2)
6383 return QualType(); // No unique best address space.
6384 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6385 : Q2.getAddressSpace());
6390 // FIXME: In C, we merge __strong and none to __strong at the top level.
6391 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6392 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6396 // Mismatched lifetime qualifiers never compatibly include each other.
6397 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6398 Quals.setObjCLifetime(Q1.getObjCLifetime());
6402 Steps.back().Quals = Quals;
6403 if (Q1 != Quals || Q2 != Quals)
6404 NeedConstBefore = Steps.size() - 1;
6407 // FIXME: Can we unify the following with UnwrapSimilarTypes?
6408 const PointerType *Ptr1, *Ptr2;
6409 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6410 (Ptr2 = Composite2->getAs<PointerType>())) {
6411 Composite1 = Ptr1->getPointeeType();
6412 Composite2 = Ptr2->getPointeeType();
6413 Steps.emplace_back(Step::Pointer);
6417 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6418 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6419 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6420 Composite1 = ObjPtr1->getPointeeType();
6421 Composite2 = ObjPtr2->getPointeeType();
6422 Steps.emplace_back(Step::ObjCPointer);
6426 const MemberPointerType *MemPtr1, *MemPtr2;
6427 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6428 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6429 Composite1 = MemPtr1->getPointeeType();
6430 Composite2 = MemPtr2->getPointeeType();
6432 // At the top level, we can perform a base-to-derived pointer-to-member
6435 // - [...] where C1 is reference-related to C2 or C2 is
6436 // reference-related to C1
6438 // (Note that the only kinds of reference-relatedness in scope here are
6439 // "same type or derived from".) At any other level, the class must
6441 const Type *Class = nullptr;
6442 QualType Cls1(MemPtr1->getClass(), 0);
6443 QualType Cls2(MemPtr2->getClass(), 0);
6444 if (Context.hasSameType(Cls1, Cls2))
6445 Class = MemPtr1->getClass();
6446 else if (Steps.empty())
6447 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
6448 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
6452 Steps.emplace_back(Step::MemberPointer, Class);
6456 // Special case: at the top level, we can decompose an Objective-C pointer
6457 // and a 'cv void *'. Unify the qualifiers.
6458 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
6459 Composite2->isObjCObjectPointerType()) ||
6460 (Composite1->isObjCObjectPointerType() &&
6461 Composite2->isVoidPointerType()))) {
6462 Composite1 = Composite1->getPointeeType();
6463 Composite2 = Composite2->getPointeeType();
6464 Steps.emplace_back(Step::Pointer);
6470 // FIXME: block pointer types?
6472 // Cannot unwrap any more types.
6476 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6477 // "pointer to function", where the function types are otherwise the same,
6478 // "pointer to function";
6479 // - if T1 or T2 is "pointer to member of C1 of type function", the other
6480 // type is "pointer to member of C2 of type noexcept function", and C1
6481 // is reference-related to C2 or C2 is reference-related to C1, where
6482 // the function types are otherwise the same, "pointer to member of C2 of
6483 // type function" or "pointer to member of C1 of type function",
6486 // We also support 'noreturn' here, so as a Clang extension we generalize the
6489 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6490 // "pointer to member function" and the pointee types can be unified
6491 // by a function pointer conversion, that conversion is applied
6492 // before checking the following rules.
6494 // We've already unwrapped down to the function types, and we want to merge
6495 // rather than just convert, so do this ourselves rather than calling
6496 // IsFunctionConversion.
6498 // FIXME: In order to match the standard wording as closely as possible, we
6499 // currently only do this under a single level of pointers. Ideally, we would
6500 // allow this in general, and set NeedConstBefore to the relevant depth on
6501 // the side(s) where we changed anything. If we permit that, we should also
6502 // consider this conversion when determining type similarity and model it as
6503 // a qualification conversion.
6504 if (Steps.size() == 1) {
6505 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6506 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6507 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6508 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6510 // The result is noreturn if both operands are.
6512 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6513 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6514 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6516 // The result is nothrow if both operands are.
6517 SmallVector<QualType, 8> ExceptionTypeStorage;
6518 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6519 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6520 ExceptionTypeStorage);
6522 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6523 FPT1->getParamTypes(), EPI1);
6524 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6525 FPT2->getParamTypes(), EPI2);
6530 // There are some more conversions we can perform under exactly one pointer.
6531 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
6532 !Context.hasSameType(Composite1, Composite2)) {
6533 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6534 // "pointer to cv2 T", where T is an object type or void,
6535 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
6536 if (Composite1->isVoidType() && Composite2->isObjectType())
6537 Composite2 = Composite1;
6538 else if (Composite2->isVoidType() && Composite1->isObjectType())
6539 Composite1 = Composite2;
6540 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6541 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6542 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
6543 // T1, respectively;
6545 // The "similar type" handling covers all of this except for the "T1 is a
6546 // base class of T2" case in the definition of reference-related.
6547 else if (IsDerivedFrom(Loc, Composite1, Composite2))
6548 Composite1 = Composite2;
6549 else if (IsDerivedFrom(Loc, Composite2, Composite1))
6550 Composite2 = Composite1;
6553 // At this point, either the inner types are the same or we have failed to
6554 // find a composite pointer type.
6555 if (!Context.hasSameType(Composite1, Composite2))
6558 // Per C++ [conv.qual]p3, add 'const' to every level before the last
6559 // differing qualifier.
6560 for (unsigned I = 0; I != NeedConstBefore; ++I)
6561 Steps[I].Quals.addConst();
6563 // Rebuild the composite type.
6564 QualType Composite = Composite1;
6565 for (auto &S : llvm::reverse(Steps))
6566 Composite = S.rebuild(Context, Composite);
6569 // Convert the expressions to the composite pointer type.
6570 InitializedEntity Entity =
6571 InitializedEntity::InitializeTemporary(Composite);
6572 InitializationKind Kind =
6573 InitializationKind::CreateCopy(Loc, SourceLocation());
6575 InitializationSequence E1ToC(*this, Entity, Kind, E1);
6579 InitializationSequence E2ToC(*this, Entity, Kind, E2);
6583 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
6584 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
6585 if (E1Result.isInvalid())
6587 E1 = E1Result.get();
6589 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
6590 if (E2Result.isInvalid())
6592 E2 = E2Result.get();
6598 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
6602 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
6604 // If the result is a glvalue, we shouldn't bind it.
6608 // In ARC, calls that return a retainable type can return retained,
6609 // in which case we have to insert a consuming cast.
6610 if (getLangOpts().ObjCAutoRefCount &&
6611 E->getType()->isObjCRetainableType()) {
6613 bool ReturnsRetained;
6615 // For actual calls, we compute this by examining the type of the
6617 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6618 Expr *Callee = Call->getCallee()->IgnoreParens();
6619 QualType T = Callee->getType();
6621 if (T == Context.BoundMemberTy) {
6622 // Handle pointer-to-members.
6623 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6624 T = BinOp->getRHS()->getType();
6625 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6626 T = Mem->getMemberDecl()->getType();
6629 if (const PointerType *Ptr = T->getAs<PointerType>())
6630 T = Ptr->getPointeeType();
6631 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6632 T = Ptr->getPointeeType();
6633 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6634 T = MemPtr->getPointeeType();
6636 const FunctionType *FTy = T->getAs<FunctionType>();
6637 assert(FTy && "call to value not of function type?");
6638 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6640 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6641 // type always produce a +1 object.
6642 } else if (isa<StmtExpr>(E)) {
6643 ReturnsRetained = true;
6645 // We hit this case with the lambda conversion-to-block optimization;
6646 // we don't want any extra casts here.
6647 } else if (isa<CastExpr>(E) &&
6648 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6651 // For message sends and property references, we try to find an
6652 // actual method. FIXME: we should infer retention by selector in
6653 // cases where we don't have an actual method.
6655 ObjCMethodDecl *D = nullptr;
6656 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6657 D = Send->getMethodDecl();
6658 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6659 D = BoxedExpr->getBoxingMethod();
6660 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6661 // Don't do reclaims if we're using the zero-element array
6663 if (ArrayLit->getNumElements() == 0 &&
6664 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6667 D = ArrayLit->getArrayWithObjectsMethod();
6668 } else if (ObjCDictionaryLiteral *DictLit
6669 = dyn_cast<ObjCDictionaryLiteral>(E)) {
6670 // Don't do reclaims if we're using the zero-element dictionary
6672 if (DictLit->getNumElements() == 0 &&
6673 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6676 D = DictLit->getDictWithObjectsMethod();
6679 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6681 // Don't do reclaims on performSelector calls; despite their
6682 // return type, the invoked method doesn't necessarily actually
6683 // return an object.
6684 if (!ReturnsRetained &&
6685 D && D->getMethodFamily() == OMF_performSelector)
6689 // Don't reclaim an object of Class type.
6690 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6693 Cleanup.setExprNeedsCleanups(true);
6695 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6696 : CK_ARCReclaimReturnedObject);
6697 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6701 if (!getLangOpts().CPlusPlus)
6704 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6705 // a fast path for the common case that the type is directly a RecordType.
6706 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6707 const RecordType *RT = nullptr;
6709 switch (T->getTypeClass()) {
6711 RT = cast<RecordType>(T);
6713 case Type::ConstantArray:
6714 case Type::IncompleteArray:
6715 case Type::VariableArray:
6716 case Type::DependentSizedArray:
6717 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6724 // That should be enough to guarantee that this type is complete, if we're
6725 // not processing a decltype expression.
6726 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6727 if (RD->isInvalidDecl() || RD->isDependentContext())
6730 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6731 ExpressionEvaluationContextRecord::EK_Decltype;
6732 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6735 MarkFunctionReferenced(E->getExprLoc(), Destructor);
6736 CheckDestructorAccess(E->getExprLoc(), Destructor,
6737 PDiag(diag::err_access_dtor_temp)
6739 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6742 // If destructor is trivial, we can avoid the extra copy.
6743 if (Destructor->isTrivial())
6746 // We need a cleanup, but we don't need to remember the temporary.
6747 Cleanup.setExprNeedsCleanups(true);
6750 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6751 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6754 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6760 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6761 if (SubExpr.isInvalid())
6764 return MaybeCreateExprWithCleanups(SubExpr.get());
6767 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6768 assert(SubExpr && "subexpression can't be null!");
6770 CleanupVarDeclMarking();
6772 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6773 assert(ExprCleanupObjects.size() >= FirstCleanup);
6774 assert(Cleanup.exprNeedsCleanups() ||
6775 ExprCleanupObjects.size() == FirstCleanup);
6776 if (!Cleanup.exprNeedsCleanups())
6779 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6780 ExprCleanupObjects.size() - FirstCleanup);
6782 auto *E = ExprWithCleanups::Create(
6783 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6784 DiscardCleanupsInEvaluationContext();
6789 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6790 assert(SubStmt && "sub-statement can't be null!");
6792 CleanupVarDeclMarking();
6794 if (!Cleanup.exprNeedsCleanups())
6797 // FIXME: In order to attach the temporaries, wrap the statement into
6798 // a StmtExpr; currently this is only used for asm statements.
6799 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6800 // a new AsmStmtWithTemporaries.
6801 CompoundStmt *CompStmt = CompoundStmt::Create(
6802 Context, SubStmt, SourceLocation(), SourceLocation());
6803 Expr *E = new (Context)
6804 StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
6805 /*FIXME TemplateDepth=*/0);
6806 return MaybeCreateExprWithCleanups(E);
6809 /// Process the expression contained within a decltype. For such expressions,
6810 /// certain semantic checks on temporaries are delayed until this point, and
6811 /// are omitted for the 'topmost' call in the decltype expression. If the
6812 /// topmost call bound a temporary, strip that temporary off the expression.
6813 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6814 assert(ExprEvalContexts.back().ExprContext ==
6815 ExpressionEvaluationContextRecord::EK_Decltype &&
6816 "not in a decltype expression");
6818 ExprResult Result = CheckPlaceholderExpr(E);
6819 if (Result.isInvalid())
6823 // C++11 [expr.call]p11:
6824 // If a function call is a prvalue of object type,
6825 // -- if the function call is either
6826 // -- the operand of a decltype-specifier, or
6827 // -- the right operand of a comma operator that is the operand of a
6828 // decltype-specifier,
6829 // a temporary object is not introduced for the prvalue.
6831 // Recursively rebuild ParenExprs and comma expressions to strip out the
6832 // outermost CXXBindTemporaryExpr, if any.
6833 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6834 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6835 if (SubExpr.isInvalid())
6837 if (SubExpr.get() == PE->getSubExpr())
6839 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6841 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6842 if (BO->getOpcode() == BO_Comma) {
6843 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6844 if (RHS.isInvalid())
6846 if (RHS.get() == BO->getRHS())
6848 return new (Context) BinaryOperator(
6849 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6850 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6854 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6855 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6862 // Disable the special decltype handling now.
6863 ExprEvalContexts.back().ExprContext =
6864 ExpressionEvaluationContextRecord::EK_Other;
6866 Result = CheckUnevaluatedOperand(E);
6867 if (Result.isInvalid())
6871 // In MS mode, don't perform any extra checking of call return types within a
6872 // decltype expression.
6873 if (getLangOpts().MSVCCompat)
6876 // Perform the semantic checks we delayed until this point.
6877 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6879 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6880 if (Call == TopCall)
6883 if (CheckCallReturnType(Call->getCallReturnType(Context),
6884 Call->getBeginLoc(), Call, Call->getDirectCallee()))
6888 // Now all relevant types are complete, check the destructors are accessible
6889 // and non-deleted, and annotate them on the temporaries.
6890 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6892 CXXBindTemporaryExpr *Bind =
6893 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6894 if (Bind == TopBind)
6897 CXXTemporary *Temp = Bind->getTemporary();
6900 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6901 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6902 Temp->setDestructor(Destructor);
6904 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6905 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6906 PDiag(diag::err_access_dtor_temp)
6907 << Bind->getType());
6908 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6911 // We need a cleanup, but we don't need to remember the temporary.
6912 Cleanup.setExprNeedsCleanups(true);
6915 // Possibly strip off the top CXXBindTemporaryExpr.
6919 /// Note a set of 'operator->' functions that were used for a member access.
6920 static void noteOperatorArrows(Sema &S,
6921 ArrayRef<FunctionDecl *> OperatorArrows) {
6922 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6923 // FIXME: Make this configurable?
6925 if (OperatorArrows.size() > Limit) {
6926 // Produce Limit-1 normal notes and one 'skipping' note.
6927 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6928 SkipCount = OperatorArrows.size() - (Limit - 1);
6931 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6932 if (I == SkipStart) {
6933 S.Diag(OperatorArrows[I]->getLocation(),
6934 diag::note_operator_arrows_suppressed)
6938 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6939 << OperatorArrows[I]->getCallResultType();
6945 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6946 SourceLocation OpLoc,
6947 tok::TokenKind OpKind,
6948 ParsedType &ObjectType,
6949 bool &MayBePseudoDestructor) {
6950 // Since this might be a postfix expression, get rid of ParenListExprs.
6951 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
6952 if (Result.isInvalid()) return ExprError();
6953 Base = Result.get();
6955 Result = CheckPlaceholderExpr(Base);
6956 if (Result.isInvalid()) return ExprError();
6957 Base = Result.get();
6959 QualType BaseType = Base->getType();
6960 MayBePseudoDestructor = false;
6961 if (BaseType->isDependentType()) {
6962 // If we have a pointer to a dependent type and are using the -> operator,
6963 // the object type is the type that the pointer points to. We might still
6964 // have enough information about that type to do something useful.
6965 if (OpKind == tok::arrow)
6966 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6967 BaseType = Ptr->getPointeeType();
6969 ObjectType = ParsedType::make(BaseType);
6970 MayBePseudoDestructor = true;
6974 // C++ [over.match.oper]p8:
6975 // [...] When operator->returns, the operator-> is applied to the value
6976 // returned, with the original second operand.
6977 if (OpKind == tok::arrow) {
6978 QualType StartingType = BaseType;
6979 bool NoArrowOperatorFound = false;
6980 bool FirstIteration = true;
6981 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6982 // The set of types we've considered so far.
6983 llvm::SmallPtrSet<CanQualType,8> CTypes;
6984 SmallVector<FunctionDecl*, 8> OperatorArrows;
6985 CTypes.insert(Context.getCanonicalType(BaseType));
6987 while (BaseType->isRecordType()) {
6988 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6989 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6990 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6991 noteOperatorArrows(*this, OperatorArrows);
6992 Diag(OpLoc, diag::note_operator_arrow_depth)
6993 << getLangOpts().ArrowDepth;
6997 Result = BuildOverloadedArrowExpr(
6999 // When in a template specialization and on the first loop iteration,
7000 // potentially give the default diagnostic (with the fixit in a
7001 // separate note) instead of having the error reported back to here
7002 // and giving a diagnostic with a fixit attached to the error itself.
7003 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7005 : &NoArrowOperatorFound);
7006 if (Result.isInvalid()) {
7007 if (NoArrowOperatorFound) {
7008 if (FirstIteration) {
7009 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7010 << BaseType << 1 << Base->getSourceRange()
7011 << FixItHint::CreateReplacement(OpLoc, ".");
7012 OpKind = tok::period;
7015 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7016 << BaseType << Base->getSourceRange();
7017 CallExpr *CE = dyn_cast<CallExpr>(Base);
7018 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7019 Diag(CD->getBeginLoc(),
7020 diag::note_member_reference_arrow_from_operator_arrow);
7025 Base = Result.get();
7026 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7027 OperatorArrows.push_back(OpCall->getDirectCallee());
7028 BaseType = Base->getType();
7029 CanQualType CBaseType = Context.getCanonicalType(BaseType);
7030 if (!CTypes.insert(CBaseType).second) {
7031 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7032 noteOperatorArrows(*this, OperatorArrows);
7035 FirstIteration = false;
7038 if (OpKind == tok::arrow) {
7039 if (BaseType->isPointerType())
7040 BaseType = BaseType->getPointeeType();
7041 else if (auto *AT = Context.getAsArrayType(BaseType))
7042 BaseType = AT->getElementType();
7046 // Objective-C properties allow "." access on Objective-C pointer types,
7047 // so adjust the base type to the object type itself.
7048 if (BaseType->isObjCObjectPointerType())
7049 BaseType = BaseType->getPointeeType();
7051 // C++ [basic.lookup.classref]p2:
7052 // [...] If the type of the object expression is of pointer to scalar
7053 // type, the unqualified-id is looked up in the context of the complete
7054 // postfix-expression.
7056 // This also indicates that we could be parsing a pseudo-destructor-name.
7057 // Note that Objective-C class and object types can be pseudo-destructor
7058 // expressions or normal member (ivar or property) access expressions, and
7059 // it's legal for the type to be incomplete if this is a pseudo-destructor
7060 // call. We'll do more incomplete-type checks later in the lookup process,
7061 // so just skip this check for ObjC types.
7062 if (!BaseType->isRecordType()) {
7063 ObjectType = ParsedType::make(BaseType);
7064 MayBePseudoDestructor = true;
7068 // The object type must be complete (or dependent), or
7069 // C++11 [expr.prim.general]p3:
7070 // Unlike the object expression in other contexts, *this is not required to
7071 // be of complete type for purposes of class member access (5.2.5) outside
7072 // the member function body.
7073 if (!BaseType->isDependentType() &&
7074 !isThisOutsideMemberFunctionBody(BaseType) &&
7075 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
7078 // C++ [basic.lookup.classref]p2:
7079 // If the id-expression in a class member access (5.2.5) is an
7080 // unqualified-id, and the type of the object expression is of a class
7081 // type C (or of pointer to a class type C), the unqualified-id is looked
7082 // up in the scope of class C. [...]
7083 ObjectType = ParsedType::make(BaseType);
7087 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
7088 tok::TokenKind& OpKind, SourceLocation OpLoc) {
7089 if (Base->hasPlaceholderType()) {
7090 ExprResult result = S.CheckPlaceholderExpr(Base);
7091 if (result.isInvalid()) return true;
7092 Base = result.get();
7094 ObjectType = Base->getType();
7096 // C++ [expr.pseudo]p2:
7097 // The left-hand side of the dot operator shall be of scalar type. The
7098 // left-hand side of the arrow operator shall be of pointer to scalar type.
7099 // This scalar type is the object type.
7100 // Note that this is rather different from the normal handling for the
7102 if (OpKind == tok::arrow) {
7103 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7104 ObjectType = Ptr->getPointeeType();
7105 } else if (!Base->isTypeDependent()) {
7106 // The user wrote "p->" when they probably meant "p."; fix it.
7107 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7108 << ObjectType << true
7109 << FixItHint::CreateReplacement(OpLoc, ".");
7110 if (S.isSFINAEContext())
7113 OpKind = tok::period;
7120 /// Check if it's ok to try and recover dot pseudo destructor calls on
7121 /// pointer objects.
7123 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7124 QualType DestructedType) {
7125 // If this is a record type, check if its destructor is callable.
7126 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7127 if (RD->hasDefinition())
7128 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7129 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7133 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7134 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7135 DestructedType->isVectorType();
7138 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
7139 SourceLocation OpLoc,
7140 tok::TokenKind OpKind,
7141 const CXXScopeSpec &SS,
7142 TypeSourceInfo *ScopeTypeInfo,
7143 SourceLocation CCLoc,
7144 SourceLocation TildeLoc,
7145 PseudoDestructorTypeStorage Destructed) {
7146 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7148 QualType ObjectType;
7149 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7152 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7153 !ObjectType->isVectorType()) {
7154 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7155 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7157 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7158 << ObjectType << Base->getSourceRange();
7163 // C++ [expr.pseudo]p2:
7164 // [...] The cv-unqualified versions of the object type and of the type
7165 // designated by the pseudo-destructor-name shall be the same type.
7166 if (DestructedTypeInfo) {
7167 QualType DestructedType = DestructedTypeInfo->getType();
7168 SourceLocation DestructedTypeStart
7169 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
7170 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7171 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7172 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7175 if (OpKind == tok::period && ObjectType->isPointerType() &&
7176 Context.hasSameUnqualifiedType(DestructedType,
7177 ObjectType->getPointeeType())) {
7179 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7180 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7182 // Issue a fixit only when the destructor is valid.
7183 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7184 *this, DestructedType))
7185 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7187 // Recover by setting the object type to the destructed type and the
7188 // operator to '->'.
7189 ObjectType = DestructedType;
7190 OpKind = tok::arrow;
7192 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7193 << ObjectType << DestructedType << Base->getSourceRange()
7194 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7196 // Recover by setting the destructed type to the object type.
7197 DestructedType = ObjectType;
7198 DestructedTypeInfo =
7199 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7200 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7202 } else if (DestructedType.getObjCLifetime() !=
7203 ObjectType.getObjCLifetime()) {
7205 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7206 // Okay: just pretend that the user provided the correctly-qualified
7209 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7210 << ObjectType << DestructedType << Base->getSourceRange()
7211 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
7214 // Recover by setting the destructed type to the object type.
7215 DestructedType = ObjectType;
7216 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7217 DestructedTypeStart);
7218 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7223 // C++ [expr.pseudo]p2:
7224 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7227 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7229 // shall designate the same scalar type.
7230 if (ScopeTypeInfo) {
7231 QualType ScopeType = ScopeTypeInfo->getType();
7232 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7233 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7235 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
7236 diag::err_pseudo_dtor_type_mismatch)
7237 << ObjectType << ScopeType << Base->getSourceRange()
7238 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
7240 ScopeType = QualType();
7241 ScopeTypeInfo = nullptr;
7246 = new (Context) CXXPseudoDestructorExpr(Context, Base,
7247 OpKind == tok::arrow, OpLoc,
7248 SS.getWithLocInContext(Context),
7257 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7258 SourceLocation OpLoc,
7259 tok::TokenKind OpKind,
7261 UnqualifiedId &FirstTypeName,
7262 SourceLocation CCLoc,
7263 SourceLocation TildeLoc,
7264 UnqualifiedId &SecondTypeName) {
7265 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7266 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7267 "Invalid first type name in pseudo-destructor");
7268 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7269 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&
7270 "Invalid second type name in pseudo-destructor");
7272 QualType ObjectType;
7273 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7276 // Compute the object type that we should use for name lookup purposes. Only
7277 // record types and dependent types matter.
7278 ParsedType ObjectTypePtrForLookup;
7280 if (ObjectType->isRecordType())
7281 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7282 else if (ObjectType->isDependentType())
7283 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7286 // Convert the name of the type being destructed (following the ~) into a
7287 // type (with source-location information).
7288 QualType DestructedType;
7289 TypeSourceInfo *DestructedTypeInfo = nullptr;
7290 PseudoDestructorTypeStorage Destructed;
7291 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7292 ParsedType T = getTypeName(*SecondTypeName.Identifier,
7293 SecondTypeName.StartLocation,
7294 S, &SS, true, false, ObjectTypePtrForLookup,
7295 /*IsCtorOrDtorName*/true);
7297 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7298 (!SS.isSet() && ObjectType->isDependentType()))) {
7299 // The name of the type being destroyed is a dependent name, and we
7300 // couldn't find anything useful in scope. Just store the identifier and
7301 // it's location, and we'll perform (qualified) name lookup again at
7302 // template instantiation time.
7303 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7304 SecondTypeName.StartLocation);
7306 Diag(SecondTypeName.StartLocation,
7307 diag::err_pseudo_dtor_destructor_non_type)
7308 << SecondTypeName.Identifier << ObjectType;
7309 if (isSFINAEContext())
7312 // Recover by assuming we had the right type all along.
7313 DestructedType = ObjectType;
7315 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7317 // Resolve the template-id to a type.
7318 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7319 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7320 TemplateId->NumArgs);
7321 TypeResult T = ActOnTemplateIdType(S,
7323 TemplateId->TemplateKWLoc,
7324 TemplateId->Template,
7326 TemplateId->TemplateNameLoc,
7327 TemplateId->LAngleLoc,
7329 TemplateId->RAngleLoc,
7330 /*IsCtorOrDtorName*/true);
7331 if (T.isInvalid() || !T.get()) {
7332 // Recover by assuming we had the right type all along.
7333 DestructedType = ObjectType;
7335 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7338 // If we've performed some kind of recovery, (re-)build the type source
7340 if (!DestructedType.isNull()) {
7341 if (!DestructedTypeInfo)
7342 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7343 SecondTypeName.StartLocation);
7344 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7347 // Convert the name of the scope type (the type prior to '::') into a type.
7348 TypeSourceInfo *ScopeTypeInfo = nullptr;
7350 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7351 FirstTypeName.Identifier) {
7352 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7353 ParsedType T = getTypeName(*FirstTypeName.Identifier,
7354 FirstTypeName.StartLocation,
7355 S, &SS, true, false, ObjectTypePtrForLookup,
7356 /*IsCtorOrDtorName*/true);
7358 Diag(FirstTypeName.StartLocation,
7359 diag::err_pseudo_dtor_destructor_non_type)
7360 << FirstTypeName.Identifier << ObjectType;
7362 if (isSFINAEContext())
7365 // Just drop this type. It's unnecessary anyway.
7366 ScopeType = QualType();
7368 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7370 // Resolve the template-id to a type.
7371 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7372 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7373 TemplateId->NumArgs);
7374 TypeResult T = ActOnTemplateIdType(S,
7376 TemplateId->TemplateKWLoc,
7377 TemplateId->Template,
7379 TemplateId->TemplateNameLoc,
7380 TemplateId->LAngleLoc,
7382 TemplateId->RAngleLoc,
7383 /*IsCtorOrDtorName*/true);
7384 if (T.isInvalid() || !T.get()) {
7385 // Recover by dropping this type.
7386 ScopeType = QualType();
7388 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7392 if (!ScopeType.isNull() && !ScopeTypeInfo)
7393 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7394 FirstTypeName.StartLocation);
7397 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7398 ScopeTypeInfo, CCLoc, TildeLoc,
7402 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7403 SourceLocation OpLoc,
7404 tok::TokenKind OpKind,
7405 SourceLocation TildeLoc,
7406 const DeclSpec& DS) {
7407 QualType ObjectType;
7408 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7411 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7415 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7416 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7417 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7418 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7420 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7421 nullptr, SourceLocation(), TildeLoc,
7425 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
7426 CXXConversionDecl *Method,
7427 bool HadMultipleCandidates) {
7428 // Convert the expression to match the conversion function's implicit object
7430 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7432 if (Exp.isInvalid())
7435 if (Method->getParent()->isLambda() &&
7436 Method->getConversionType()->isBlockPointerType()) {
7437 // This is a lambda conversion to block pointer; check if the argument
7438 // was a LambdaExpr.
7440 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7441 if (CE && CE->getCastKind() == CK_NoOp)
7442 SubE = CE->getSubExpr();
7443 SubE = SubE->IgnoreParens();
7444 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7445 SubE = BE->getSubExpr();
7446 if (isa<LambdaExpr>(SubE)) {
7447 // For the conversion to block pointer on a lambda expression, we
7448 // construct a special BlockLiteral instead; this doesn't really make
7449 // a difference in ARC, but outside of ARC the resulting block literal
7450 // follows the normal lifetime rules for block literals instead of being
7452 DiagnosticErrorTrap Trap(Diags);
7453 PushExpressionEvaluationContext(
7454 ExpressionEvaluationContext::PotentiallyEvaluated);
7455 ExprResult BlockExp = BuildBlockForLambdaConversion(
7456 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
7457 PopExpressionEvaluationContext();
7459 if (BlockExp.isInvalid())
7460 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7466 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
7467 NestedNameSpecifierLoc(), SourceLocation(), Method,
7468 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
7469 HadMultipleCandidates, DeclarationNameInfo(),
7470 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
7472 QualType ResultType = Method->getReturnType();
7473 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7474 ResultType = ResultType.getNonLValueExprType(Context);
7476 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7477 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
7479 if (CheckFunctionCall(Method, CE,
7480 Method->getType()->castAs<FunctionProtoType>()))
7486 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7487 SourceLocation RParen) {
7488 // If the operand is an unresolved lookup expression, the expression is ill-
7489 // formed per [over.over]p1, because overloaded function names cannot be used
7490 // without arguments except in explicit contexts.
7491 ExprResult R = CheckPlaceholderExpr(Operand);
7495 R = CheckUnevaluatedOperand(R.get());
7501 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
7502 // The expression operand for noexcept is in an unevaluated expression
7503 // context, so side effects could result in unintended consequences.
7504 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7507 CanThrowResult CanThrow = canThrow(Operand);
7508 return new (Context)
7509 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7512 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7513 Expr *Operand, SourceLocation RParen) {
7514 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7517 static bool IsSpecialDiscardedValue(Expr *E) {
7518 // In C++11, discarded-value expressions of a certain form are special,
7519 // according to [expr]p10:
7520 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7521 // expression is an lvalue of volatile-qualified type and it has
7522 // one of the following forms:
7523 E = E->IgnoreParens();
7525 // - id-expression (5.1.1),
7526 if (isa<DeclRefExpr>(E))
7529 // - subscripting (5.2.1),
7530 if (isa<ArraySubscriptExpr>(E))
7533 // - class member access (5.2.5),
7534 if (isa<MemberExpr>(E))
7537 // - indirection (5.3.1),
7538 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7539 if (UO->getOpcode() == UO_Deref)
7542 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7543 // - pointer-to-member operation (5.5),
7544 if (BO->isPtrMemOp())
7547 // - comma expression (5.18) where the right operand is one of the above.
7548 if (BO->getOpcode() == BO_Comma)
7549 return IsSpecialDiscardedValue(BO->getRHS());
7552 // - conditional expression (5.16) where both the second and the third
7553 // operands are one of the above, or
7554 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7555 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7556 IsSpecialDiscardedValue(CO->getFalseExpr());
7557 // The related edge case of "*x ?: *x".
7558 if (BinaryConditionalOperator *BCO =
7559 dyn_cast<BinaryConditionalOperator>(E)) {
7560 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7561 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7562 IsSpecialDiscardedValue(BCO->getFalseExpr());
7565 // Objective-C++ extensions to the rule.
7566 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7572 /// Perform the conversions required for an expression used in a
7573 /// context that ignores the result.
7574 ExprResult Sema::IgnoredValueConversions(Expr *E) {
7575 if (E->hasPlaceholderType()) {
7576 ExprResult result = CheckPlaceholderExpr(E);
7577 if (result.isInvalid()) return E;
7582 // [Except in specific positions,] an lvalue that does not have
7583 // array type is converted to the value stored in the
7584 // designated object (and is no longer an lvalue).
7585 if (E->isRValue()) {
7586 // In C, function designators (i.e. expressions of function type)
7587 // are r-values, but we still want to do function-to-pointer decay
7588 // on them. This is both technically correct and convenient for
7590 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7591 return DefaultFunctionArrayConversion(E);
7596 if (getLangOpts().CPlusPlus) {
7597 // The C++11 standard defines the notion of a discarded-value expression;
7598 // normally, we don't need to do anything to handle it, but if it is a
7599 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7601 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
7602 E->getType().isVolatileQualified()) {
7603 if (IsSpecialDiscardedValue(E)) {
7604 ExprResult Res = DefaultLvalueConversion(E);
7605 if (Res.isInvalid())
7609 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7610 // it occurs as a discarded-value expression.
7611 CheckUnusedVolatileAssignment(E);
7616 // If the expression is a prvalue after this optional conversion, the
7617 // temporary materialization conversion is applied.
7619 // We skip this step: IR generation is able to synthesize the storage for
7620 // itself in the aggregate case, and adding the extra node to the AST is
7622 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7623 // FIXME: Do any other AST consumers care about this?
7627 // GCC seems to also exclude expressions of incomplete enum type.
7628 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7629 if (!T->getDecl()->isComplete()) {
7630 // FIXME: stupid workaround for a codegen bug!
7631 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7636 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7637 if (Res.isInvalid())
7641 if (!E->getType()->isVoidType())
7642 RequireCompleteType(E->getExprLoc(), E->getType(),
7643 diag::err_incomplete_type);
7647 ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
7648 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
7649 // it occurs as an unevaluated operand.
7650 CheckUnusedVolatileAssignment(E);
7655 // If we can unambiguously determine whether Var can never be used
7656 // in a constant expression, return true.
7657 // - if the variable and its initializer are non-dependent, then
7658 // we can unambiguously check if the variable is a constant expression.
7659 // - if the initializer is not value dependent - we can determine whether
7660 // it can be used to initialize a constant expression. If Init can not
7661 // be used to initialize a constant expression we conclude that Var can
7662 // never be a constant expression.
7663 // - FXIME: if the initializer is dependent, we can still do some analysis and
7664 // identify certain cases unambiguously as non-const by using a Visitor:
7665 // - such as those that involve odr-use of a ParmVarDecl, involve a new
7666 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7667 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7668 ASTContext &Context) {
7669 if (isa<ParmVarDecl>(Var)) return true;
7670 const VarDecl *DefVD = nullptr;
7672 // If there is no initializer - this can not be a constant expression.
7673 if (!Var->getAnyInitializer(DefVD)) return true;
7675 if (DefVD->isWeak()) return false;
7676 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7678 Expr *Init = cast<Expr>(Eval->Value);
7680 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7681 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7682 // of value-dependent expressions, and use it here to determine whether the
7683 // initializer is a potential constant expression.
7687 return !Var->isUsableInConstantExpressions(Context);
7690 /// Check if the current lambda has any potential captures
7691 /// that must be captured by any of its enclosing lambdas that are ready to
7692 /// capture. If there is a lambda that can capture a nested
7693 /// potential-capture, go ahead and do so. Also, check to see if any
7694 /// variables are uncaptureable or do not involve an odr-use so do not
7695 /// need to be captured.
7697 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7698 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7700 assert(!S.isUnevaluatedContext());
7701 assert(S.CurContext->isDependentContext());
7703 DeclContext *DC = S.CurContext;
7704 while (DC && isa<CapturedDecl>(DC))
7705 DC = DC->getParent();
7707 CurrentLSI->CallOperator == DC &&
7708 "The current call operator must be synchronized with Sema's CurContext");
7711 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7713 // All the potentially captureable variables in the current nested
7714 // lambda (within a generic outer lambda), must be captured by an
7715 // outer lambda that is enclosed within a non-dependent context.
7716 CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
7717 // If the variable is clearly identified as non-odr-used and the full
7718 // expression is not instantiation dependent, only then do we not
7719 // need to check enclosing lambda's for speculative captures.
7721 // Even though 'x' is not odr-used, it should be captured.
7723 // const int x = 10;
7724 // auto L = [=](auto a) {
7728 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7729 !IsFullExprInstantiationDependent)
7732 // If we have a capture-capable lambda for the variable, go ahead and
7733 // capture the variable in that lambda (and all its enclosing lambdas).
7734 if (const Optional<unsigned> Index =
7735 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7736 S.FunctionScopes, Var, S))
7737 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
7739 const bool IsVarNeverAConstantExpression =
7740 VariableCanNeverBeAConstantExpression(Var, S.Context);
7741 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7742 // This full expression is not instantiation dependent or the variable
7743 // can not be used in a constant expression - which means
7744 // this variable must be odr-used here, so diagnose a
7745 // capture violation early, if the variable is un-captureable.
7746 // This is purely for diagnosing errors early. Otherwise, this
7747 // error would get diagnosed when the lambda becomes capture ready.
7748 QualType CaptureType, DeclRefType;
7749 SourceLocation ExprLoc = VarExpr->getExprLoc();
7750 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7751 /*EllipsisLoc*/ SourceLocation(),
7752 /*BuildAndDiagnose*/false, CaptureType,
7753 DeclRefType, nullptr)) {
7754 // We will never be able to capture this variable, and we need
7755 // to be able to in any and all instantiations, so diagnose it.
7756 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7757 /*EllipsisLoc*/ SourceLocation(),
7758 /*BuildAndDiagnose*/true, CaptureType,
7759 DeclRefType, nullptr);
7764 // Check if 'this' needs to be captured.
7765 if (CurrentLSI->hasPotentialThisCapture()) {
7766 // If we have a capture-capable lambda for 'this', go ahead and capture
7767 // 'this' in that lambda (and all its enclosing lambdas).
7768 if (const Optional<unsigned> Index =
7769 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7770 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
7771 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7772 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7773 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7774 &FunctionScopeIndexOfCapturableLambda);
7778 // Reset all the potential captures at the end of each full-expression.
7779 CurrentLSI->clearPotentialCaptures();
7782 static ExprResult attemptRecovery(Sema &SemaRef,
7783 const TypoCorrectionConsumer &Consumer,
7784 const TypoCorrection &TC) {
7785 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7786 Consumer.getLookupResult().getLookupKind());
7787 const CXXScopeSpec *SS = Consumer.getSS();
7790 // Use an approprate CXXScopeSpec for building the expr.
7791 if (auto *NNS = TC.getCorrectionSpecifier())
7792 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7793 else if (SS && !TC.WillReplaceSpecifier())
7796 if (auto *ND = TC.getFoundDecl()) {
7797 R.setLookupName(ND->getDeclName());
7799 if (ND->isCXXClassMember()) {
7800 // Figure out the correct naming class to add to the LookupResult.
7801 CXXRecordDecl *Record = nullptr;
7802 if (auto *NNS = TC.getCorrectionSpecifier())
7803 Record = NNS->getAsType()->getAsCXXRecordDecl();
7806 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7808 R.setNamingClass(Record);
7810 // Detect and handle the case where the decl might be an implicit
7812 bool MightBeImplicitMember;
7813 if (!Consumer.isAddressOfOperand())
7814 MightBeImplicitMember = true;
7815 else if (!NewSS.isEmpty())
7816 MightBeImplicitMember = false;
7817 else if (R.isOverloadedResult())
7818 MightBeImplicitMember = false;
7819 else if (R.isUnresolvableResult())
7820 MightBeImplicitMember = true;
7822 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7823 isa<IndirectFieldDecl>(ND) ||
7824 isa<MSPropertyDecl>(ND);
7826 if (MightBeImplicitMember)
7827 return SemaRef.BuildPossibleImplicitMemberExpr(
7828 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7829 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7830 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7831 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7832 Ivar->getIdentifier());
7836 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7837 /*AcceptInvalidDecl*/ true);
7841 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7842 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7845 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7846 : TypoExprs(TypoExprs) {}
7847 bool VisitTypoExpr(TypoExpr *TE) {
7848 TypoExprs.insert(TE);
7853 class TransformTypos : public TreeTransform<TransformTypos> {
7854 typedef TreeTransform<TransformTypos> BaseTransform;
7856 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7857 // process of being initialized.
7858 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7859 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7860 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7861 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7863 /// Emit diagnostics for all of the TypoExprs encountered.
7865 /// If the TypoExprs were successfully corrected, then the diagnostics should
7866 /// suggest the corrections. Otherwise the diagnostics will not suggest
7867 /// anything (having been passed an empty TypoCorrection).
7869 /// If we've failed to correct due to ambiguous corrections, we need to
7870 /// be sure to pass empty corrections and replacements. Otherwise it's
7871 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
7872 /// and we don't want to report those diagnostics.
7873 void EmitAllDiagnostics(bool IsAmbiguous) {
7874 for (TypoExpr *TE : TypoExprs) {
7875 auto &State = SemaRef.getTypoExprState(TE);
7876 if (State.DiagHandler) {
7877 TypoCorrection TC = IsAmbiguous
7878 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
7879 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
7881 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7882 // TypoCorrection, replacing the existing decls. This ensures the right
7883 // NamedDecl is used in diagnostics e.g. in the case where overload
7884 // resolution was used to select one from several possible decls that
7885 // had been stored in the TypoCorrection.
7886 if (auto *ND = getDeclFromExpr(
7887 Replacement.isInvalid() ? nullptr : Replacement.get()))
7888 TC.setCorrectionDecl(ND);
7890 State.DiagHandler(TC);
7892 SemaRef.clearDelayedTypo(TE);
7896 /// If corrections for the first TypoExpr have been exhausted for a
7897 /// given combination of the other TypoExprs, retry those corrections against
7898 /// the next combination of substitutions for the other TypoExprs by advancing
7899 /// to the next potential correction of the second TypoExpr. For the second
7900 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7901 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7902 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7903 /// TransformCache). Returns true if there is still any untried combinations
7905 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7906 for (auto TE : TypoExprs) {
7907 auto &State = SemaRef.getTypoExprState(TE);
7908 TransformCache.erase(TE);
7909 if (!State.Consumer->finished())
7911 State.Consumer->resetCorrectionStream();
7916 NamedDecl *getDeclFromExpr(Expr *E) {
7917 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7918 E = OverloadResolution[OE];
7922 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7923 return DRE->getFoundDecl();
7924 if (auto *ME = dyn_cast<MemberExpr>(E))
7925 return ME->getFoundDecl();
7926 // FIXME: Add any other expr types that could be be seen by the delayed typo
7927 // correction TreeTransform for which the corresponding TypoCorrection could
7928 // contain multiple decls.
7932 ExprResult TryTransform(Expr *E) {
7933 Sema::SFINAETrap Trap(SemaRef);
7934 ExprResult Res = TransformExpr(E);
7935 if (Trap.hasErrorOccurred() || Res.isInvalid())
7938 return ExprFilter(Res.get());
7941 // Since correcting typos may intoduce new TypoExprs, this function
7942 // checks for new TypoExprs and recurses if it finds any. Note that it will
7943 // only succeed if it is able to correct all typos in the given expression.
7944 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
7945 if (Res.isInvalid()) {
7948 // Check to see if any new TypoExprs were created. If so, we need to recurse
7949 // to check their validity.
7950 Expr *FixedExpr = Res.get();
7952 auto SavedTypoExprs = std::move(TypoExprs);
7953 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
7955 AmbiguousTypoExprs.clear();
7957 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
7958 if (!TypoExprs.empty()) {
7959 // Recurse to handle newly created TypoExprs. If we're not able to
7960 // handle them, discard these TypoExprs.
7961 ExprResult RecurResult =
7962 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
7963 if (RecurResult.isInvalid()) {
7965 // Recursive corrections didn't work, wipe them away and don't add
7966 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
7967 // since we don't want to clear them twice. Note: it's possible the
7968 // TypoExprs were created recursively and thus won't be in our
7969 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
7970 auto &SemaTypoExprs = SemaRef.TypoExprs;
7971 for (auto TE : TypoExprs) {
7972 TransformCache.erase(TE);
7973 SemaRef.clearDelayedTypo(TE);
7975 auto SI = find(SemaTypoExprs, TE);
7976 if (SI != SemaTypoExprs.end()) {
7977 SemaTypoExprs.erase(SI);
7981 // TypoExpr is valid: add newly created TypoExprs since we were
7982 // able to correct them.
7984 SavedTypoExprs.set_union(TypoExprs);
7988 TypoExprs = std::move(SavedTypoExprs);
7989 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
7994 // Try to transform the given expression, looping through the correction
7995 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
7997 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
7998 // true and this method immediately will return an `ExprError`.
7999 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8001 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8002 SemaRef.TypoExprs.clear();
8005 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8007 // Recursion encountered an ambiguous correction. This means that our
8008 // correction itself is ambiguous, so stop now.
8012 // If the transform is still valid after checking for any new typos,
8014 if (!Res.isInvalid())
8017 // The transform was invalid, see if we have any TypoExprs with untried
8018 // correction candidates.
8019 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8023 // If we found a valid result, double check to make sure it's not ambiguous.
8024 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8025 auto SavedTransformCache =
8026 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8028 // Ensure none of the TypoExprs have multiple typo correction candidates
8029 // with the same edit length that pass all the checks and filters.
8030 while (!AmbiguousTypoExprs.empty()) {
8031 auto TE = AmbiguousTypoExprs.back();
8033 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8034 // and invalidating our TypoExprState, so always fetch it instead of storing.
8035 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8037 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8038 TypoCorrection Next;
8040 // Fetch the next correction by erasing the typo from the cache and calling
8041 // `TryTransform` which will iterate through corrections in
8042 // `TransformTypoExpr`.
8043 TransformCache.erase(TE);
8044 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8046 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8047 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8048 SavedTransformCache.erase(TE);
8053 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8054 Next.getEditDistance(false) == TC.getEditDistance(false));
8059 AmbiguousTypoExprs.remove(TE);
8060 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8062 TransformCache = std::move(SavedTransformCache);
8065 // Wipe away any newly created TypoExprs that we don't know about. Since we
8066 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8067 // possible if a `TypoExpr` is created during a transformation but then
8068 // fails before we can discover it.
8069 auto &SemaTypoExprs = SemaRef.TypoExprs;
8070 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8071 auto TE = *Iterator;
8072 auto FI = find(TypoExprs, TE);
8073 if (FI != TypoExprs.end()) {
8077 SemaRef.clearDelayedTypo(TE);
8078 Iterator = SemaTypoExprs.erase(Iterator);
8080 SemaRef.TypoExprs = std::move(SavedTypoExprs);
8086 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8087 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8089 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8091 SourceLocation RParenLoc,
8092 Expr *ExecConfig = nullptr) {
8093 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8094 RParenLoc, ExecConfig);
8095 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8096 if (Result.isUsable()) {
8097 Expr *ResultCall = Result.get();
8098 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8099 ResultCall = BE->getSubExpr();
8100 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8101 OverloadResolution[OE] = CE->getCallee();
8107 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8109 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8111 ExprResult Transform(Expr *E) {
8112 bool IsAmbiguous = false;
8113 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8115 if (!Res.isUsable())
8116 FindTypoExprs(TypoExprs).TraverseStmt(E);
8118 EmitAllDiagnostics(IsAmbiguous);
8123 ExprResult TransformTypoExpr(TypoExpr *E) {
8124 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8125 // cached transformation result if there is one and the TypoExpr isn't the
8126 // first one that was encountered.
8127 auto &CacheEntry = TransformCache[E];
8128 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8132 auto &State = SemaRef.getTypoExprState(E);
8133 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
8135 // For the first TypoExpr and an uncached TypoExpr, find the next likely
8136 // typo correction and return it.
8137 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8138 if (InitDecl && TC.getFoundDecl() == InitDecl)
8140 // FIXME: If we would typo-correct to an invalid declaration, it's
8141 // probably best to just suppress all errors from this typo correction.
8142 ExprResult NE = State.RecoveryHandler ?
8143 State.RecoveryHandler(SemaRef, E, TC) :
8144 attemptRecovery(SemaRef, *State.Consumer, TC);
8145 if (!NE.isInvalid()) {
8146 // Check whether there may be a second viable correction with the same
8147 // edit distance; if so, remember this TypoExpr may have an ambiguous
8148 // correction so it can be more thoroughly vetted later.
8149 TypoCorrection Next;
8150 if ((Next = State.Consumer->peekNextCorrection()) &&
8151 Next.getEditDistance(false) == TC.getEditDistance(false)) {
8152 AmbiguousTypoExprs.insert(E);
8154 AmbiguousTypoExprs.remove(E);
8156 assert(!NE.isUnset() &&
8157 "Typo was transformed into a valid-but-null ExprResult");
8158 return CacheEntry = NE;
8161 return CacheEntry = ExprError();
8167 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
8168 llvm::function_ref<ExprResult(Expr *)> Filter) {
8169 // If the current evaluation context indicates there are uncorrected typos
8170 // and the current expression isn't guaranteed to not have typos, try to
8171 // resolve any TypoExpr nodes that might be in the expression.
8172 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
8173 (E->isTypeDependent() || E->isValueDependent() ||
8174 E->isInstantiationDependent())) {
8175 auto TyposResolved = DelayedTypos.size();
8176 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
8177 TyposResolved -= DelayedTypos.size();
8178 if (Result.isInvalid() || Result.get() != E) {
8179 ExprEvalContexts.back().NumTypos -= TyposResolved;
8182 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
8187 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
8188 bool DiscardedValue,
8190 ExprResult FullExpr = FE;
8192 if (!FullExpr.get())
8195 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
8198 if (DiscardedValue) {
8199 // Top-level expressions default to 'id' when we're in a debugger.
8200 if (getLangOpts().DebuggerCastResultToId &&
8201 FullExpr.get()->getType() == Context.UnknownAnyTy) {
8202 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8203 if (FullExpr.isInvalid())
8207 FullExpr = CheckPlaceholderExpr(FullExpr.get());
8208 if (FullExpr.isInvalid())
8211 FullExpr = IgnoredValueConversions(FullExpr.get());
8212 if (FullExpr.isInvalid())
8215 DiagnoseUnusedExprResult(FullExpr.get());
8218 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
8219 if (FullExpr.isInvalid())
8222 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
8224 // At the end of this full expression (which could be a deeply nested
8225 // lambda), if there is a potential capture within the nested lambda,
8226 // have the outer capture-able lambda try and capture it.
8227 // Consider the following code:
8228 // void f(int, int);
8229 // void f(const int&, double);
8231 // const int x = 10, y = 20;
8232 // auto L = [=](auto a) {
8233 // auto M = [=](auto b) {
8234 // f(x, b); <-- requires x to be captured by L and M
8235 // f(y, a); <-- requires y to be captured by L, but not all Ms
8240 // FIXME: Also consider what happens for something like this that involves
8241 // the gnu-extension statement-expressions or even lambda-init-captures:
8244 // auto L = [&](auto a) {
8245 // +n + ({ 0; a; });
8249 // Here, we see +n, and then the full-expression 0; ends, so we don't
8250 // capture n (and instead remove it from our list of potential captures),
8251 // and then the full-expression +n + ({ 0; }); ends, but it's too late
8252 // for us to see that we need to capture n after all.
8254 LambdaScopeInfo *const CurrentLSI =
8255 getCurLambda(/*IgnoreCapturedRegions=*/true);
8256 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
8257 // even if CurContext is not a lambda call operator. Refer to that Bug Report
8258 // for an example of the code that might cause this asynchrony.
8259 // By ensuring we are in the context of a lambda's call operator
8260 // we can fix the bug (we only need to check whether we need to capture
8261 // if we are within a lambda's body); but per the comments in that
8262 // PR, a proper fix would entail :
8263 // "Alternative suggestion:
8264 // - Add to Sema an integer holding the smallest (outermost) scope
8265 // index that we are *lexically* within, and save/restore/set to
8266 // FunctionScopes.size() in InstantiatingTemplate's
8267 // constructor/destructor.
8268 // - Teach the handful of places that iterate over FunctionScopes to
8269 // stop at the outermost enclosing lexical scope."
8270 DeclContext *DC = CurContext;
8271 while (DC && isa<CapturedDecl>(DC))
8272 DC = DC->getParent();
8273 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
8274 if (IsInLambdaDeclContext && CurrentLSI &&
8275 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
8276 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8278 return MaybeCreateExprWithCleanups(FullExpr);
8281 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8282 if (!FullStmt) return StmtError();
8284 return MaybeCreateStmtWithCleanups(FullStmt);
8287 Sema::IfExistsResult
8288 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8290 const DeclarationNameInfo &TargetNameInfo) {
8291 DeclarationName TargetName = TargetNameInfo.getName();
8293 return IER_DoesNotExist;
8295 // If the name itself is dependent, then the result is dependent.
8296 if (TargetName.isDependentName())
8297 return IER_Dependent;
8299 // Do the redeclaration lookup in the current scope.
8300 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8301 Sema::NotForRedeclaration);
8302 LookupParsedName(R, S, &SS);
8303 R.suppressDiagnostics();
8305 switch (R.getResultKind()) {
8306 case LookupResult::Found:
8307 case LookupResult::FoundOverloaded:
8308 case LookupResult::FoundUnresolvedValue:
8309 case LookupResult::Ambiguous:
8312 case LookupResult::NotFound:
8313 return IER_DoesNotExist;
8315 case LookupResult::NotFoundInCurrentInstantiation:
8316 return IER_Dependent;
8319 llvm_unreachable("Invalid LookupResult Kind!");
8322 Sema::IfExistsResult
8323 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8324 bool IsIfExists, CXXScopeSpec &SS,
8325 UnqualifiedId &Name) {
8326 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8328 // Check for an unexpanded parameter pack.
8329 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8330 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8331 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
8334 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8337 concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
8338 return BuildExprRequirement(E, /*IsSimple=*/true,
8339 /*NoexceptLoc=*/SourceLocation(),
8340 /*ReturnTypeRequirement=*/{});
8343 concepts::Requirement *
8344 Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
8345 SourceLocation NameLoc, IdentifierInfo *TypeName,
8346 TemplateIdAnnotation *TemplateId) {
8347 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&
8348 "Exactly one of TypeName and TemplateId must be specified.");
8349 TypeSourceInfo *TSI = nullptr;
8351 QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
8352 SS.getWithLocInContext(Context), *TypeName,
8353 NameLoc, &TSI, /*DeducedTypeContext=*/false);
8357 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
8358 TemplateId->NumArgs);
8359 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
8360 TemplateId->TemplateKWLoc,
8361 TemplateId->Template, TemplateId->Name,
8362 TemplateId->TemplateNameLoc,
8363 TemplateId->LAngleLoc, ArgsPtr,
8364 TemplateId->RAngleLoc);
8367 if (GetTypeFromParser(T.get(), &TSI).isNull())
8370 return BuildTypeRequirement(TSI);
8373 concepts::Requirement *
8374 Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
8375 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
8376 /*ReturnTypeRequirement=*/{});
8379 concepts::Requirement *
8380 Sema::ActOnCompoundRequirement(
8381 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8382 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
8383 // C++2a [expr.prim.req.compound] p1.3.3
8384 // [..] the expression is deduced against an invented function template
8385 // F [...] F is a void function template with a single type template
8386 // parameter T declared with the constrained-parameter. Form a new
8387 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
8388 // around the constrained-parameter. F has a single parameter whose
8389 // type-specifier is cv T followed by the abstract-declarator. [...]
8391 // The cv part is done in the calling function - we get the concept with
8392 // arguments and the abstract declarator with the correct CV qualification and
8393 // have to synthesize T and the single parameter of F.
8394 auto &II = Context.Idents.get("expr-type");
8395 auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
8397 SourceLocation(), Depth,
8400 /*ParameterPack=*/false,
8401 /*HasTypeConstraint=*/true);
8403 if (ActOnTypeConstraint(SS, TypeConstraint, TParam,
8404 /*EllpsisLoc=*/SourceLocation()))
8405 // Just produce a requirement with no type requirements.
8406 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
8408 auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
8410 ArrayRef<NamedDecl *>(TParam),
8412 /*RequiresClause=*/nullptr);
8413 return BuildExprRequirement(
8414 E, /*IsSimple=*/false, NoexceptLoc,
8415 concepts::ExprRequirement::ReturnTypeRequirement(TPL));
8418 concepts::ExprRequirement *
8419 Sema::BuildExprRequirement(
8420 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
8421 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8422 auto Status = concepts::ExprRequirement::SS_Satisfied;
8423 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
8424 if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
8425 Status = concepts::ExprRequirement::SS_Dependent;
8426 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
8427 Status = concepts::ExprRequirement::SS_NoexceptNotMet;
8428 else if (ReturnTypeRequirement.isSubstitutionFailure())
8429 Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
8430 else if (ReturnTypeRequirement.isTypeConstraint()) {
8431 // C++2a [expr.prim.req]p1.3.3
8432 // The immediately-declared constraint ([temp]) of decltype((E)) shall
8434 TemplateParameterList *TPL =
8435 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
8436 QualType MatchedType =
8437 BuildDecltypeType(E, E->getBeginLoc()).getCanonicalType();
8438 llvm::SmallVector<TemplateArgument, 1> Args;
8439 Args.push_back(TemplateArgument(MatchedType));
8440 TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
8441 MultiLevelTemplateArgumentList MLTAL(TAL);
8442 for (unsigned I = 0; I < TPL->getDepth(); ++I)
8443 MLTAL.addOuterRetainedLevel();
8445 cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint()
8446 ->getImmediatelyDeclaredConstraint();
8447 ExprResult Constraint = SubstExpr(IDC, MLTAL);
8448 assert(!Constraint.isInvalid() &&
8449 "Substitution cannot fail as it is simply putting a type template "
8450 "argument into a concept specialization expression's parameter.");
8452 SubstitutedConstraintExpr =
8453 cast<ConceptSpecializationExpr>(Constraint.get());
8454 if (!SubstitutedConstraintExpr->isSatisfied())
8455 Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
8457 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
8458 ReturnTypeRequirement, Status,
8459 SubstitutedConstraintExpr);
8462 concepts::ExprRequirement *
8463 Sema::BuildExprRequirement(
8464 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
8465 bool IsSimple, SourceLocation NoexceptLoc,
8466 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
8467 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
8468 IsSimple, NoexceptLoc,
8469 ReturnTypeRequirement);
8472 concepts::TypeRequirement *
8473 Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
8474 return new (Context) concepts::TypeRequirement(Type);
8477 concepts::TypeRequirement *
8478 Sema::BuildTypeRequirement(
8479 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8480 return new (Context) concepts::TypeRequirement(SubstDiag);
8483 concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
8484 return BuildNestedRequirement(Constraint);
8487 concepts::NestedRequirement *
8488 Sema::BuildNestedRequirement(Expr *Constraint) {
8489 ConstraintSatisfaction Satisfaction;
8490 if (!Constraint->isInstantiationDependent() &&
8491 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
8492 Constraint->getSourceRange(), Satisfaction))
8494 return new (Context) concepts::NestedRequirement(Context, Constraint,
8498 concepts::NestedRequirement *
8499 Sema::BuildNestedRequirement(
8500 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
8501 return new (Context) concepts::NestedRequirement(SubstDiag);
8504 RequiresExprBodyDecl *
8505 Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8506 ArrayRef<ParmVarDecl *> LocalParameters,
8510 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
8513 PushDeclContext(BodyScope, Body);
8515 for (ParmVarDecl *Param : LocalParameters) {
8516 if (Param->hasDefaultArg())
8517 // C++2a [expr.prim.req] p4
8518 // [...] A local parameter of a requires-expression shall not have a
8519 // default argument. [...]
8520 Diag(Param->getDefaultArgRange().getBegin(),
8521 diag::err_requires_expr_local_parameter_default_argument);
8522 // Ignore default argument and move on
8524 Param->setDeclContext(Body);
8525 // If this has an identifier, add it to the scope stack.
8526 if (Param->getIdentifier()) {
8527 CheckShadow(BodyScope, Param);
8528 PushOnScopeChains(Param, BodyScope);
8534 void Sema::ActOnFinishRequiresExpr() {
8535 assert(CurContext && "DeclContext imbalance!");
8536 CurContext = CurContext->getLexicalParent();
8537 assert(CurContext && "Popped translation unit!");
8541 Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8542 RequiresExprBodyDecl *Body,
8543 ArrayRef<ParmVarDecl *> LocalParameters,
8544 ArrayRef<concepts::Requirement *> Requirements,
8545 SourceLocation ClosingBraceLoc) {
8546 return RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
8547 Requirements, ClosingBraceLoc);