1 //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// \brief Implements semantic analysis for C++ expressions.
13 //===----------------------------------------------------------------------===//
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/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaLambda.h"
37 #include "clang/Sema/TemplateDeduction.h"
38 #include "llvm/ADT/APInt.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 using namespace clang;
44 /// \brief Handle the result of the special case name lookup for inheriting
45 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46 /// constructor names in member using declarations, even if 'X' is not the
47 /// name of the corresponding type.
48 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
53 // Convert the nested-name-specifier into a type.
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
69 case NestedNameSpecifier::Global:
70 case NestedNameSpecifier::Super:
71 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
82 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
84 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
88 // Determine where to perform name lookup.
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
98 // template <typename T> struct S {
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
107 // See also PR6358 and PR6359.
108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
111 DeclContext *LookupCtx = nullptr;
112 bool isDependent = false;
113 bool LookInScope = false;
118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
122 SearchType = GetTypeFromParser(ObjectTypePtr);
125 NestedNameSpecifier *NNS = SS.getScopeRep();
127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
129 // C++11 [basic.lookup.qual]p6:
130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
131 // the type-names are looked up as types in the scope designated by the
132 // nested-name-specifier. Similarly, in a qualified-id of the form:
134 // nested-name-specifier[opt] class-name :: ~ class-name
136 // the second class-name is looked up in the same scope as the first.
138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
145 } else if (DC && isa<CXXRecordDecl>(DC)) {
146 LookAtPrefix = false;
150 // The second case from the C++03 rules quoted further above.
151 NestedNameSpecifier *Prefix = nullptr;
152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
159 } else if (ObjectTypePtr) {
160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
163 LookupCtx = computeDeclContext(SS, EnteringContext);
164 isDependent = LookupCtx && LookupCtx->isDependentContext();
166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
176 assert((isDependent || !SearchType->isIncompleteType()) &&
177 "Caller should have completed object type");
181 // Perform lookup into the current scope (only).
185 TypeDecl *NonMatchingTypeDecl = nullptr;
186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
189 // have one) and, if that fails to find a match, in the scope (if
190 // we're allowed to look there).
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
194 else if (Step == 1 && LookInScope && S)
195 LookupName(Found, S);
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
224 // issue 399, for which there isn't even an obvious direction.
225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
237 if (MemberOfType.isNull())
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
248 return CreateParsedType(
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
265 // The class template we found is the same template being
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
269 return CreateParsedType(
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
278 if (DependentTemplateName *DepTemplate
279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
282 return CreateParsedType(
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
293 // We didn't find our type, but that's okay: it's dependent
296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
300 return ParsedType::make(T);
303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
316 const DeclContext *Ctx = S->getEntity();
317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
326 ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
327 ParsedType ObjectType) {
328 if (DS.getTypeSpecType() == DeclSpec::TST_error)
331 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
332 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
336 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&
337 "unexpected type in getDestructorType");
338 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
340 // If we know the type of the object, check that the correct destructor
341 // type was named now; we can give better diagnostics this way.
342 QualType SearchType = GetTypeFromParser(ObjectType);
343 if (!SearchType.isNull() && !SearchType->isDependentType() &&
344 !Context.hasSameUnqualifiedType(T, SearchType)) {
345 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
350 return ParsedType::make(T);
353 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
354 const UnqualifiedId &Name) {
355 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
360 switch (SS.getScopeRep()->getKind()) {
361 case NestedNameSpecifier::Identifier:
362 case NestedNameSpecifier::TypeSpec:
363 case NestedNameSpecifier::TypeSpecWithTemplate:
364 // Per C++11 [over.literal]p2, literal operators can only be declared at
365 // namespace scope. Therefore, this unqualified-id cannot name anything.
366 // Reject it early, because we have no AST representation for this in the
367 // case where the scope is dependent.
368 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
372 case NestedNameSpecifier::Global:
373 case NestedNameSpecifier::Super:
374 case NestedNameSpecifier::Namespace:
375 case NestedNameSpecifier::NamespaceAlias:
379 llvm_unreachable("unknown nested name specifier kind");
382 /// \brief Build a C++ typeid expression with a type operand.
383 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
384 SourceLocation TypeidLoc,
385 TypeSourceInfo *Operand,
386 SourceLocation RParenLoc) {
387 // C++ [expr.typeid]p4:
388 // The top-level cv-qualifiers of the lvalue expression or the type-id
389 // that is the operand of typeid are always ignored.
390 // If the type of the type-id is a class type or a reference to a class
391 // type, the class shall be completely-defined.
394 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
396 if (T->getAs<RecordType>() &&
397 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
400 if (T->isVariablyModifiedType())
401 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
403 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
404 SourceRange(TypeidLoc, RParenLoc));
407 /// \brief Build a C++ typeid expression with an expression operand.
408 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
409 SourceLocation TypeidLoc,
411 SourceLocation RParenLoc) {
412 bool WasEvaluated = false;
413 if (E && !E->isTypeDependent()) {
414 if (E->getType()->isPlaceholderType()) {
415 ExprResult result = CheckPlaceholderExpr(E);
416 if (result.isInvalid()) return ExprError();
420 QualType T = E->getType();
421 if (const RecordType *RecordT = T->getAs<RecordType>()) {
422 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
423 // C++ [expr.typeid]p3:
424 // [...] If the type of the expression is a class type, the class
425 // shall be completely-defined.
426 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
429 // C++ [expr.typeid]p3:
430 // When typeid is applied to an expression other than an glvalue of a
431 // polymorphic class type [...] [the] expression is an unevaluated
433 if (RecordD->isPolymorphic() && E->isGLValue()) {
434 // The subexpression is potentially evaluated; switch the context
435 // and recheck the subexpression.
436 ExprResult Result = TransformToPotentiallyEvaluated(E);
437 if (Result.isInvalid()) return ExprError();
440 // We require a vtable to query the type at run time.
441 MarkVTableUsed(TypeidLoc, RecordD);
446 // C++ [expr.typeid]p4:
447 // [...] If the type of the type-id is a reference to a possibly
448 // cv-qualified type, the result of the typeid expression refers to a
449 // std::type_info object representing the cv-unqualified referenced
452 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
453 if (!Context.hasSameType(T, UnqualT)) {
455 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
459 if (E->getType()->isVariablyModifiedType())
460 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
462 else if (!inTemplateInstantiation() &&
463 E->HasSideEffects(Context, WasEvaluated)) {
464 // The expression operand for typeid is in an unevaluated expression
465 // context, so side effects could result in unintended consequences.
466 Diag(E->getExprLoc(), WasEvaluated
467 ? diag::warn_side_effects_typeid
468 : diag::warn_side_effects_unevaluated_context);
471 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
472 SourceRange(TypeidLoc, RParenLoc));
475 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
477 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
478 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
479 // Find the std::type_info type.
480 if (!getStdNamespace())
481 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
483 if (!CXXTypeInfoDecl) {
484 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
485 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
486 LookupQualifiedName(R, getStdNamespace());
487 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
488 // Microsoft's typeinfo doesn't have type_info in std but in the global
489 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
490 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
491 LookupQualifiedName(R, Context.getTranslationUnitDecl());
492 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
494 if (!CXXTypeInfoDecl)
495 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
498 if (!getLangOpts().RTTI) {
499 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
502 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
505 // The operand is a type; handle it as such.
506 TypeSourceInfo *TInfo = nullptr;
507 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
513 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
515 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
518 // The operand is an expression.
519 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
522 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
525 getUuidAttrOfType(Sema &SemaRef, QualType QT,
526 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
527 // Optionally remove one level of pointer, reference or array indirection.
528 const Type *Ty = QT.getTypePtr();
529 if (QT->isPointerType() || QT->isReferenceType())
530 Ty = QT->getPointeeType().getTypePtr();
531 else if (QT->isArrayType())
532 Ty = Ty->getBaseElementTypeUnsafe();
534 const auto *TD = Ty->getAsTagDecl();
538 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
539 UuidAttrs.insert(Uuid);
543 // __uuidof can grab UUIDs from template arguments.
544 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
545 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
546 for (const TemplateArgument &TA : TAL.asArray()) {
547 const UuidAttr *UuidForTA = nullptr;
548 if (TA.getKind() == TemplateArgument::Type)
549 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
550 else if (TA.getKind() == TemplateArgument::Declaration)
551 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
554 UuidAttrs.insert(UuidForTA);
559 /// \brief Build a Microsoft __uuidof expression with a type operand.
560 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
561 SourceLocation TypeidLoc,
562 TypeSourceInfo *Operand,
563 SourceLocation RParenLoc) {
565 if (!Operand->getType()->isDependentType()) {
566 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
567 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
568 if (UuidAttrs.empty())
569 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
570 if (UuidAttrs.size() > 1)
571 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
572 UuidStr = UuidAttrs.back()->getGuid();
575 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
576 SourceRange(TypeidLoc, RParenLoc));
579 /// \brief Build a Microsoft __uuidof expression with an expression operand.
580 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
581 SourceLocation TypeidLoc,
583 SourceLocation RParenLoc) {
585 if (!E->getType()->isDependentType()) {
586 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
587 UuidStr = "00000000-0000-0000-0000-000000000000";
589 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
590 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
591 if (UuidAttrs.empty())
592 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
593 if (UuidAttrs.size() > 1)
594 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
595 UuidStr = UuidAttrs.back()->getGuid();
599 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
600 SourceRange(TypeidLoc, RParenLoc));
603 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
605 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
606 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
607 // If MSVCGuidDecl has not been cached, do the lookup.
609 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
610 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
611 LookupQualifiedName(R, Context.getTranslationUnitDecl());
612 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
614 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
617 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
620 // The operand is a type; handle it as such.
621 TypeSourceInfo *TInfo = nullptr;
622 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
628 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
630 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
633 // The operand is an expression.
634 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
637 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
639 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
640 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
641 "Unknown C++ Boolean value!");
643 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
646 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
648 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
649 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
652 /// ActOnCXXThrow - Parse throw expressions.
654 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
655 bool IsThrownVarInScope = false;
657 // C++0x [class.copymove]p31:
658 // When certain criteria are met, an implementation is allowed to omit the
659 // copy/move construction of a class object [...]
661 // - in a throw-expression, when the operand is the name of a
662 // non-volatile automatic object (other than a function or catch-
663 // clause parameter) whose scope does not extend beyond the end of the
664 // innermost enclosing try-block (if there is one), the copy/move
665 // operation from the operand to the exception object (15.1) can be
666 // omitted by constructing the automatic object directly into the
668 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
669 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
670 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
671 for( ; S; S = S->getParent()) {
672 if (S->isDeclScope(Var)) {
673 IsThrownVarInScope = true;
678 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
679 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
687 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
690 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
691 bool IsThrownVarInScope) {
692 // Don't report an error if 'throw' is used in system headers.
693 if (!getLangOpts().CXXExceptions &&
694 !getSourceManager().isInSystemHeader(OpLoc))
695 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
697 // Exceptions aren't allowed in CUDA device code.
698 if (getLangOpts().CUDA)
699 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
700 << "throw" << CurrentCUDATarget();
702 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
703 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
705 if (Ex && !Ex->isTypeDependent()) {
706 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
707 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
710 // Initialize the exception result. This implicitly weeds out
711 // abstract types or types with inaccessible copy constructors.
713 // C++0x [class.copymove]p31:
714 // When certain criteria are met, an implementation is allowed to omit the
715 // copy/move construction of a class object [...]
717 // - in a throw-expression, when the operand is the name of a
718 // non-volatile automatic object (other than a function or
720 // parameter) whose scope does not extend beyond the end of the
721 // innermost enclosing try-block (if there is one), the copy/move
722 // operation from the operand to the exception object (15.1) can be
723 // omitted by constructing the automatic object directly into the
725 const VarDecl *NRVOVariable = nullptr;
726 if (IsThrownVarInScope)
727 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
729 InitializedEntity Entity = InitializedEntity::InitializeException(
730 OpLoc, ExceptionObjectTy,
731 /*NRVO=*/NRVOVariable != nullptr);
732 ExprResult Res = PerformMoveOrCopyInitialization(
733 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
740 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
744 collectPublicBases(CXXRecordDecl *RD,
745 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
746 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
747 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
748 bool ParentIsPublic) {
749 for (const CXXBaseSpecifier &BS : RD->bases()) {
750 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
752 // Virtual bases constitute the same subobject. Non-virtual bases are
753 // always distinct subobjects.
755 NewSubobject = VBases.insert(BaseDecl).second;
760 ++SubobjectsSeen[BaseDecl];
762 // Only add subobjects which have public access throughout the entire chain.
763 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
765 PublicSubobjectsSeen.insert(BaseDecl);
767 // Recurse on to each base subobject.
768 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
773 static void getUnambiguousPublicSubobjects(
774 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
775 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
776 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
777 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
778 SubobjectsSeen[RD] = 1;
779 PublicSubobjectsSeen.insert(RD);
780 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
781 /*ParentIsPublic=*/true);
783 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
784 // Skip ambiguous objects.
785 if (SubobjectsSeen[PublicSubobject] > 1)
788 Objects.push_back(PublicSubobject);
792 /// CheckCXXThrowOperand - Validate the operand of a throw.
793 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
794 QualType ExceptionObjectTy, Expr *E) {
795 // If the type of the exception would be an incomplete type or a pointer
796 // to an incomplete type other than (cv) void the program is ill-formed.
797 QualType Ty = ExceptionObjectTy;
798 bool isPointer = false;
799 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
800 Ty = Ptr->getPointeeType();
803 if (!isPointer || !Ty->isVoidType()) {
804 if (RequireCompleteType(ThrowLoc, Ty,
805 isPointer ? diag::err_throw_incomplete_ptr
806 : diag::err_throw_incomplete,
807 E->getSourceRange()))
810 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
811 diag::err_throw_abstract_type, E))
815 // If the exception has class type, we need additional handling.
816 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
820 // If we are throwing a polymorphic class type or pointer thereof,
821 // exception handling will make use of the vtable.
822 MarkVTableUsed(ThrowLoc, RD);
824 // If a pointer is thrown, the referenced object will not be destroyed.
828 // If the class has a destructor, we must be able to call it.
829 if (!RD->hasIrrelevantDestructor()) {
830 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
831 MarkFunctionReferenced(E->getExprLoc(), Destructor);
832 CheckDestructorAccess(E->getExprLoc(), Destructor,
833 PDiag(diag::err_access_dtor_exception) << Ty);
834 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
839 // The MSVC ABI creates a list of all types which can catch the exception
840 // object. This list also references the appropriate copy constructor to call
841 // if the object is caught by value and has a non-trivial copy constructor.
842 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
843 // We are only interested in the public, unambiguous bases contained within
844 // the exception object. Bases which are ambiguous or otherwise
845 // inaccessible are not catchable types.
846 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
847 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
849 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
850 // Attempt to lookup the copy constructor. Various pieces of machinery
851 // will spring into action, like template instantiation, which means this
852 // cannot be a simple walk of the class's decls. Instead, we must perform
853 // lookup and overload resolution.
854 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
858 // Mark the constructor referenced as it is used by this throw expression.
859 MarkFunctionReferenced(E->getExprLoc(), CD);
861 // Skip this copy constructor if it is trivial, we don't need to record it
862 // in the catchable type data.
866 // The copy constructor is non-trivial, create a mapping from this class
867 // type to this constructor.
868 // N.B. The selection of copy constructor is not sensitive to this
869 // particular throw-site. Lookup will be performed at the catch-site to
870 // ensure that the copy constructor is, in fact, accessible (via
871 // friendship or any other means).
872 Context.addCopyConstructorForExceptionObject(Subobject, CD);
874 // We don't keep the instantiated default argument expressions around so
875 // we must rebuild them here.
876 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
877 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
886 static QualType adjustCVQualifiersForCXXThisWithinLambda(
887 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
888 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
890 QualType ClassType = ThisTy->getPointeeType();
891 LambdaScopeInfo *CurLSI = nullptr;
892 DeclContext *CurDC = CurSemaContext;
894 // Iterate through the stack of lambdas starting from the innermost lambda to
895 // the outermost lambda, checking if '*this' is ever captured by copy - since
896 // that could change the cv-qualifiers of the '*this' object.
897 // The object referred to by '*this' starts out with the cv-qualifiers of its
898 // member function. We then start with the innermost lambda and iterate
899 // outward checking to see if any lambda performs a by-copy capture of '*this'
900 // - and if so, any nested lambda must respect the 'constness' of that
901 // capturing lamdbda's call operator.
904 // Since the FunctionScopeInfo stack is representative of the lexical
905 // nesting of the lambda expressions during initial parsing (and is the best
906 // place for querying information about captures about lambdas that are
907 // partially processed) and perhaps during instantiation of function templates
908 // that contain lambda expressions that need to be transformed BUT not
909 // necessarily during instantiation of a nested generic lambda's function call
910 // operator (which might even be instantiated at the end of the TU) - at which
911 // time the DeclContext tree is mature enough to query capture information
912 // reliably - we use a two pronged approach to walk through all the lexically
913 // enclosing lambda expressions:
915 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
916 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
917 // enclosed by the call-operator of the LSI below it on the stack (while
918 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
919 // the stack represents the innermost lambda.
921 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
922 // represents a lambda's call operator. If it does, we must be instantiating
923 // a generic lambda's call operator (represented by the Current LSI, and
924 // should be the only scenario where an inconsistency between the LSI and the
925 // DeclContext should occur), so climb out the DeclContexts if they
926 // represent lambdas, while querying the corresponding closure types
927 // regarding capture information.
929 // 1) Climb down the function scope info stack.
930 for (int I = FunctionScopes.size();
931 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
932 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
933 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
934 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
935 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
937 if (!CurLSI->isCXXThisCaptured())
940 auto C = CurLSI->getCXXThisCapture();
942 if (C.isCopyCapture()) {
943 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
944 if (CurLSI->CallOperator->isConst())
945 ClassType.addConst();
946 return ASTCtx.getPointerType(ClassType);
950 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
951 // happen during instantiation of its nested generic lambda call operator)
952 if (isLambdaCallOperator(CurDC)) {
953 assert(CurLSI && "While computing 'this' capture-type for a generic "
954 "lambda, we must have a corresponding LambdaScopeInfo");
955 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&
956 "While computing 'this' capture-type for a generic lambda, when we "
957 "run out of enclosing LSI's, yet the enclosing DC is a "
958 "lambda-call-operator we must be (i.e. Current LSI) in a generic "
959 "lambda call oeprator");
960 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
962 auto IsThisCaptured =
963 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
966 for (auto &&C : Closure->captures()) {
967 if (C.capturesThis()) {
968 if (C.getCaptureKind() == LCK_StarThis)
970 if (Closure->getLambdaCallOperator()->isConst())
978 bool IsByCopyCapture = false;
979 bool IsConstCapture = false;
980 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
982 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
983 if (IsByCopyCapture) {
984 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
986 ClassType.addConst();
987 return ASTCtx.getPointerType(ClassType);
989 Closure = isLambdaCallOperator(Closure->getParent())
990 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
994 return ASTCtx.getPointerType(ClassType);
997 QualType Sema::getCurrentThisType() {
998 DeclContext *DC = getFunctionLevelDeclContext();
999 QualType ThisTy = CXXThisTypeOverride;
1001 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1002 if (method && method->isInstance())
1003 ThisTy = method->getThisType(Context);
1006 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1007 inTemplateInstantiation()) {
1009 assert(isa<CXXRecordDecl>(DC) &&
1010 "Trying to get 'this' type from static method?");
1012 // This is a lambda call operator that is being instantiated as a default
1013 // initializer. DC must point to the enclosing class type, so we can recover
1014 // the 'this' type from it.
1016 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1017 // There are no cv-qualifiers for 'this' within default initializers,
1018 // per [expr.prim.general]p4.
1019 ThisTy = Context.getPointerType(ClassTy);
1022 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1023 // might need to be adjusted if the lambda or any of its enclosing lambda's
1024 // captures '*this' by copy.
1025 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1026 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1027 CurContext, Context);
1031 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1033 unsigned CXXThisTypeQuals,
1035 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1037 if (!Enabled || !ContextDecl)
1040 CXXRecordDecl *Record = nullptr;
1041 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1042 Record = Template->getTemplatedDecl();
1044 Record = cast<CXXRecordDecl>(ContextDecl);
1046 // We care only for CVR qualifiers here, so cut everything else.
1047 CXXThisTypeQuals &= Qualifiers::FastMask;
1048 S.CXXThisTypeOverride
1049 = S.Context.getPointerType(
1050 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1052 this->Enabled = true;
1056 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1058 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1062 static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1063 QualType ThisTy, SourceLocation Loc,
1064 const bool ByCopy) {
1066 QualType AdjustedThisTy = ThisTy;
1067 // The type of the corresponding data member (not a 'this' pointer if 'by
1069 QualType CaptureThisFieldTy = ThisTy;
1071 // If we are capturing the object referred to by '*this' by copy, ignore any
1072 // cv qualifiers inherited from the type of the member function for the type
1073 // of the closure-type's corresponding data member and any use of 'this'.
1074 CaptureThisFieldTy = ThisTy->getPointeeType();
1075 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1076 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1079 FieldDecl *Field = FieldDecl::Create(
1080 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1081 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1084 Field->setImplicit(true);
1085 Field->setAccess(AS_private);
1088 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1090 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1093 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1094 nullptr, CaptureThisFieldTy, Loc);
1095 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1096 InitializationSequence Init(S, Entity, InitKind, StarThis);
1097 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1098 if (ER.isInvalid()) return nullptr;
1104 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1105 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1106 const bool ByCopy) {
1107 // We don't need to capture this in an unevaluated context.
1108 if (isUnevaluatedContext() && !Explicit)
1111 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1113 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
1114 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
1116 // Check that we can capture the *enclosing object* (referred to by '*this')
1117 // by the capturing-entity/closure (lambda/block/etc) at
1118 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1120 // Note: The *enclosing object* can only be captured by-value by a
1121 // closure that is a lambda, using the explicit notation:
1123 // Every other capture of the *enclosing object* results in its by-reference
1126 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1127 // stack), we can capture the *enclosing object* only if:
1128 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1129 // - or, 'L' has an implicit capture.
1131 // -- there is no enclosing closure
1132 // -- or, there is some enclosing closure 'E' that has already captured the
1133 // *enclosing object*, and every intervening closure (if any) between 'E'
1134 // and 'L' can implicitly capture the *enclosing object*.
1135 // -- or, every enclosing closure can implicitly capture the
1136 // *enclosing object*
1139 unsigned NumCapturingClosures = 0;
1140 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
1141 if (CapturingScopeInfo *CSI =
1142 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1143 if (CSI->CXXThisCaptureIndex != 0) {
1144 // 'this' is already being captured; there isn't anything more to do.
1145 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1148 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1149 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1150 // This context can't implicitly capture 'this'; fail out.
1151 if (BuildAndDiagnose)
1152 Diag(Loc, diag::err_this_capture)
1153 << (Explicit && idx == MaxFunctionScopesIndex);
1156 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1157 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1158 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1159 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1160 (Explicit && idx == MaxFunctionScopesIndex)) {
1161 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1162 // iteration through can be an explicit capture, all enclosing closures,
1163 // if any, must perform implicit captures.
1165 // This closure can capture 'this'; continue looking upwards.
1166 NumCapturingClosures++;
1169 // This context can't implicitly capture 'this'; fail out.
1170 if (BuildAndDiagnose)
1171 Diag(Loc, diag::err_this_capture)
1172 << (Explicit && idx == MaxFunctionScopesIndex);
1177 if (!BuildAndDiagnose) return false;
1179 // If we got here, then the closure at MaxFunctionScopesIndex on the
1180 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1181 // (including implicit by-reference captures in any enclosing closures).
1183 // In the loop below, respect the ByCopy flag only for the closure requesting
1184 // the capture (i.e. first iteration through the loop below). Ignore it for
1185 // all enclosing closure's up to NumCapturingClosures (since they must be
1186 // implicitly capturing the *enclosing object* by reference (see loop
1189 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1190 "Only a lambda can capture the enclosing object (referred to by "
1192 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1194 QualType ThisTy = getCurrentThisType();
1195 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
1196 --idx, --NumCapturingClosures) {
1197 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1198 Expr *ThisExpr = nullptr;
1200 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1201 // For lambda expressions, build a field and an initializing expression,
1202 // and capture the *enclosing object* by copy only if this is the first
1204 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1205 ByCopy && idx == MaxFunctionScopesIndex);
1207 } else if (CapturedRegionScopeInfo *RSI
1208 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1210 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1213 bool isNested = NumCapturingClosures > 1;
1214 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1219 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1220 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1221 /// is a non-lvalue expression whose value is the address of the object for
1222 /// which the function is called.
1224 QualType ThisTy = getCurrentThisType();
1225 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1227 CheckCXXThisCapture(Loc);
1228 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1231 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1232 // If we're outside the body of a member function, then we'll have a specified
1234 if (CXXThisTypeOverride.isNull())
1237 // Determine whether we're looking into a class that's currently being
1239 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1240 return Class && Class->isBeingDefined();
1244 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1245 SourceLocation LParenLoc,
1247 SourceLocation RParenLoc) {
1251 TypeSourceInfo *TInfo;
1252 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1254 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1256 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1257 // Avoid creating a non-type-dependent expression that contains typos.
1258 // Non-type-dependent expressions are liable to be discarded without
1259 // checking for embedded typos.
1260 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1261 !Result.get()->isTypeDependent())
1262 Result = CorrectDelayedTyposInExpr(Result.get());
1266 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1267 /// Can be interpreted either as function-style casting ("int(x)")
1268 /// or class type construction ("ClassType(x,y,z)")
1269 /// or creation of a value-initialized type ("int()").
1271 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1272 SourceLocation LParenLoc,
1274 SourceLocation RParenLoc) {
1275 QualType Ty = TInfo->getType();
1276 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1278 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1279 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1283 bool ListInitialization = LParenLoc.isInvalid();
1284 assert((!ListInitialization ||
1285 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&
1286 "List initialization must have initializer list as expression.");
1287 SourceRange FullRange = SourceRange(TyBeginLoc,
1288 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1290 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1291 InitializationKind Kind =
1293 ? ListInitialization
1294 ? InitializationKind::CreateDirectList(TyBeginLoc)
1295 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc,
1297 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1299 // C++1z [expr.type.conv]p1:
1300 // If the type is a placeholder for a deduced class type, [...perform class
1301 // template argument deduction...]
1302 DeducedType *Deduced = Ty->getContainedDeducedType();
1303 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1304 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1308 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1311 // C++ [expr.type.conv]p1:
1312 // If the expression list is a parenthesized single expression, the type
1313 // conversion expression is equivalent (in definedness, and if defined in
1314 // meaning) to the corresponding cast expression.
1315 if (Exprs.size() == 1 && !ListInitialization &&
1316 !isa<InitListExpr>(Exprs[0])) {
1317 Expr *Arg = Exprs[0];
1318 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenLoc, Arg, RParenLoc);
1321 // For an expression of the form T(), T shall not be an array type.
1322 QualType ElemTy = Ty;
1323 if (Ty->isArrayType()) {
1324 if (!ListInitialization)
1325 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1327 ElemTy = Context.getBaseElementType(Ty);
1330 // There doesn't seem to be an explicit rule against this but sanity demands
1331 // we only construct objects with object types.
1332 if (Ty->isFunctionType())
1333 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1334 << Ty << FullRange);
1336 // C++17 [expr.type.conv]p2:
1337 // If the type is cv void and the initializer is (), the expression is a
1338 // prvalue of the specified type that performs no initialization.
1339 if (!Ty->isVoidType() &&
1340 RequireCompleteType(TyBeginLoc, ElemTy,
1341 diag::err_invalid_incomplete_type_use, FullRange))
1344 // Otherwise, the expression is a prvalue of the specified type whose
1345 // result object is direct-initialized (11.6) with the initializer.
1346 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1347 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1349 if (Result.isInvalid())
1352 Expr *Inner = Result.get();
1353 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1354 Inner = BTE->getSubExpr();
1355 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1356 !isa<CXXScalarValueInitExpr>(Inner)) {
1357 // If we created a CXXTemporaryObjectExpr, that node also represents the
1358 // functional cast. Otherwise, create an explicit cast to represent
1359 // the syntactic form of a functional-style cast that was used here.
1361 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1362 // would give a more consistent AST representation than using a
1363 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1364 // is sometimes handled by initialization and sometimes not.
1365 QualType ResultType = Result.get()->getType();
1366 Result = CXXFunctionalCastExpr::Create(
1367 Context, ResultType, Expr::getValueKindForType(Ty), TInfo,
1368 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
1374 /// \brief Determine whether the given function is a non-placement
1375 /// deallocation function.
1376 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1377 if (FD->isInvalidDecl())
1380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1381 return Method->isUsualDeallocationFunction();
1383 if (FD->getOverloadedOperator() != OO_Delete &&
1384 FD->getOverloadedOperator() != OO_Array_Delete)
1387 unsigned UsualParams = 1;
1389 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1390 S.Context.hasSameUnqualifiedType(
1391 FD->getParamDecl(UsualParams)->getType(),
1392 S.Context.getSizeType()))
1395 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1396 S.Context.hasSameUnqualifiedType(
1397 FD->getParamDecl(UsualParams)->getType(),
1398 S.Context.getTypeDeclType(S.getStdAlignValT())))
1401 return UsualParams == FD->getNumParams();
1405 struct UsualDeallocFnInfo {
1406 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1407 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1408 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1409 HasSizeT(false), HasAlignValT(false), CUDAPref(Sema::CFP_Native) {
1410 // A function template declaration is never a usual deallocation function.
1413 if (FD->getNumParams() == 3)
1414 HasAlignValT = HasSizeT = true;
1415 else if (FD->getNumParams() == 2) {
1416 HasSizeT = FD->getParamDecl(1)->getType()->isIntegerType();
1417 HasAlignValT = !HasSizeT;
1420 // In CUDA, determine how much we'd like / dislike to call this.
1421 if (S.getLangOpts().CUDA)
1422 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1423 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1426 operator bool() const { return FD; }
1428 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1429 bool WantAlign) const {
1430 // C++17 [expr.delete]p10:
1431 // If the type has new-extended alignment, a function with a parameter
1432 // of type std::align_val_t is preferred; otherwise a function without
1433 // such a parameter is preferred
1434 if (HasAlignValT != Other.HasAlignValT)
1435 return HasAlignValT == WantAlign;
1437 if (HasSizeT != Other.HasSizeT)
1438 return HasSizeT == WantSize;
1440 // Use CUDA call preference as a tiebreaker.
1441 return CUDAPref > Other.CUDAPref;
1444 DeclAccessPair Found;
1446 bool HasSizeT, HasAlignValT;
1447 Sema::CUDAFunctionPreference CUDAPref;
1451 /// Determine whether a type has new-extended alignment. This may be called when
1452 /// the type is incomplete (for a delete-expression with an incomplete pointee
1453 /// type), in which case it will conservatively return false if the alignment is
1455 static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1456 return S.getLangOpts().AlignedAllocation &&
1457 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1458 S.getASTContext().getTargetInfo().getNewAlign();
1461 /// Select the correct "usual" deallocation function to use from a selection of
1462 /// deallocation functions (either global or class-scope).
1463 static UsualDeallocFnInfo resolveDeallocationOverload(
1464 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1465 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1466 UsualDeallocFnInfo Best;
1468 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1469 UsualDeallocFnInfo Info(S, I.getPair());
1470 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1471 Info.CUDAPref == Sema::CFP_Never)
1477 BestFns->push_back(Info);
1481 if (Best.isBetterThan(Info, WantSize, WantAlign))
1484 // If more than one preferred function is found, all non-preferred
1485 // functions are eliminated from further consideration.
1486 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1491 BestFns->push_back(Info);
1497 /// Determine whether a given type is a class for which 'delete[]' would call
1498 /// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1499 /// we need to store the array size (even if the type is
1500 /// trivially-destructible).
1501 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1502 QualType allocType) {
1503 const RecordType *record =
1504 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1505 if (!record) return false;
1507 // Try to find an operator delete[] in class scope.
1509 DeclarationName deleteName =
1510 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1511 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1512 S.LookupQualifiedName(ops, record->getDecl());
1514 // We're just doing this for information.
1515 ops.suppressDiagnostics();
1517 // Very likely: there's no operator delete[].
1518 if (ops.empty()) return false;
1520 // If it's ambiguous, it should be illegal to call operator delete[]
1521 // on this thing, so it doesn't matter if we allocate extra space or not.
1522 if (ops.isAmbiguous()) return false;
1524 // C++17 [expr.delete]p10:
1525 // If the deallocation functions have class scope, the one without a
1526 // parameter of type std::size_t is selected.
1527 auto Best = resolveDeallocationOverload(
1528 S, ops, /*WantSize*/false,
1529 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1530 return Best && Best.HasSizeT;
1533 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1536 /// @code new (memory) int[size][4] @endcode
1538 /// @code ::new Foo(23, "hello") @endcode
1540 /// \param StartLoc The first location of the expression.
1541 /// \param UseGlobal True if 'new' was prefixed with '::'.
1542 /// \param PlacementLParen Opening paren of the placement arguments.
1543 /// \param PlacementArgs Placement new arguments.
1544 /// \param PlacementRParen Closing paren of the placement arguments.
1545 /// \param TypeIdParens If the type is in parens, the source range.
1546 /// \param D The type to be allocated, as well as array dimensions.
1547 /// \param Initializer The initializing expression or initializer-list, or null
1548 /// if there is none.
1550 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1551 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1552 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1553 Declarator &D, Expr *Initializer) {
1554 Expr *ArraySize = nullptr;
1555 // If the specified type is an array, unwrap it and save the expression.
1556 if (D.getNumTypeObjects() > 0 &&
1557 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1558 DeclaratorChunk &Chunk = D.getTypeObject(0);
1559 if (D.getDeclSpec().hasAutoTypeSpec())
1560 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1561 << D.getSourceRange());
1562 if (Chunk.Arr.hasStatic)
1563 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1564 << D.getSourceRange());
1565 if (!Chunk.Arr.NumElts)
1566 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1567 << D.getSourceRange());
1569 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1570 D.DropFirstTypeObject();
1573 // Every dimension shall be of constant size.
1575 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1576 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1579 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1580 if (Expr *NumElts = (Expr *)Array.NumElts) {
1581 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1582 if (getLangOpts().CPlusPlus14) {
1583 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1584 // shall be a converted constant expression (5.19) of type std::size_t
1585 // and shall evaluate to a strictly positive value.
1586 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1587 assert(IntWidth && "Builtin type of size 0?");
1588 llvm::APSInt Value(IntWidth);
1590 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1595 = VerifyIntegerConstantExpression(NumElts, nullptr,
1596 diag::err_new_array_nonconst)
1606 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1607 QualType AllocType = TInfo->getType();
1608 if (D.isInvalidType())
1611 SourceRange DirectInitRange;
1612 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1613 DirectInitRange = List->getSourceRange();
1615 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1627 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1631 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1632 return PLE->getNumExprs() == 0;
1633 if (isa<ImplicitValueInitExpr>(Init))
1635 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1636 return !CCE->isListInitialization() &&
1637 CCE->getConstructor()->isDefaultConstructor();
1638 else if (Style == CXXNewExpr::ListInit) {
1639 assert(isa<InitListExpr>(Init) &&
1640 "Shouldn't create list CXXConstructExprs for arrays.");
1647 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1648 SourceLocation PlacementLParen,
1649 MultiExprArg PlacementArgs,
1650 SourceLocation PlacementRParen,
1651 SourceRange TypeIdParens,
1653 TypeSourceInfo *AllocTypeInfo,
1655 SourceRange DirectInitRange,
1656 Expr *Initializer) {
1657 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1658 SourceLocation StartLoc = Range.getBegin();
1660 CXXNewExpr::InitializationStyle initStyle;
1661 if (DirectInitRange.isValid()) {
1662 assert(Initializer && "Have parens but no initializer.");
1663 initStyle = CXXNewExpr::CallInit;
1664 } else if (Initializer && isa<InitListExpr>(Initializer))
1665 initStyle = CXXNewExpr::ListInit;
1667 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1668 isa<CXXConstructExpr>(Initializer)) &&
1669 "Initializer expression that cannot have been implicitly created.");
1670 initStyle = CXXNewExpr::NoInit;
1673 Expr **Inits = &Initializer;
1674 unsigned NumInits = Initializer ? 1 : 0;
1675 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1676 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1677 Inits = List->getExprs();
1678 NumInits = List->getNumExprs();
1681 // C++11 [expr.new]p15:
1682 // A new-expression that creates an object of type T initializes that
1683 // object as follows:
1684 InitializationKind Kind
1685 // - If the new-initializer is omitted, the object is default-
1686 // initialized (8.5); if no initialization is performed,
1687 // the object has indeterminate value
1688 = initStyle == CXXNewExpr::NoInit
1689 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1690 // - Otherwise, the new-initializer is interpreted according to the
1691 // initialization rules of 8.5 for direct-initialization.
1692 : initStyle == CXXNewExpr::ListInit
1693 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1694 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1695 DirectInitRange.getBegin(),
1696 DirectInitRange.getEnd());
1698 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1699 auto *Deduced = AllocType->getContainedDeducedType();
1700 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1702 return ExprError(Diag(ArraySize->getExprLoc(),
1703 diag::err_deduced_class_template_compound_type)
1704 << /*array*/ 2 << ArraySize->getSourceRange());
1706 InitializedEntity Entity
1707 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1708 AllocType = DeduceTemplateSpecializationFromInitializer(
1709 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1710 if (AllocType.isNull())
1712 } else if (Deduced) {
1713 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1714 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1715 << AllocType << TypeRange);
1716 if (initStyle == CXXNewExpr::ListInit ||
1717 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
1718 return ExprError(Diag(Inits[0]->getLocStart(),
1719 diag::err_auto_new_list_init)
1720 << AllocType << TypeRange);
1722 Expr *FirstBad = Inits[1];
1723 return ExprError(Diag(FirstBad->getLocStart(),
1724 diag::err_auto_new_ctor_multiple_expressions)
1725 << AllocType << TypeRange);
1727 Expr *Deduce = Inits[0];
1728 QualType DeducedType;
1729 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1730 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1731 << AllocType << Deduce->getType()
1732 << TypeRange << Deduce->getSourceRange());
1733 if (DeducedType.isNull())
1735 AllocType = DeducedType;
1738 // Per C++0x [expr.new]p5, the type being constructed may be a
1739 // typedef of an array type.
1741 if (const ConstantArrayType *Array
1742 = Context.getAsConstantArrayType(AllocType)) {
1743 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1744 Context.getSizeType(),
1745 TypeRange.getEnd());
1746 AllocType = Array->getElementType();
1750 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1753 if (initStyle == CXXNewExpr::ListInit &&
1754 isStdInitializerList(AllocType, nullptr)) {
1755 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1756 diag::warn_dangling_std_initializer_list)
1757 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1760 // In ARC, infer 'retaining' for the allocated
1761 if (getLangOpts().ObjCAutoRefCount &&
1762 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1763 AllocType->isObjCLifetimeType()) {
1764 AllocType = Context.getLifetimeQualifiedType(AllocType,
1765 AllocType->getObjCARCImplicitLifetime());
1768 QualType ResultType = Context.getPointerType(AllocType);
1770 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1771 ExprResult result = CheckPlaceholderExpr(ArraySize);
1772 if (result.isInvalid()) return ExprError();
1773 ArraySize = result.get();
1775 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1776 // integral or enumeration type with a non-negative value."
1777 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1778 // enumeration type, or a class type for which a single non-explicit
1779 // conversion function to integral or unscoped enumeration type exists.
1780 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1782 llvm::Optional<uint64_t> KnownArraySize;
1783 if (ArraySize && !ArraySize->isTypeDependent()) {
1784 ExprResult ConvertedSize;
1785 if (getLangOpts().CPlusPlus14) {
1786 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1788 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1791 if (!ConvertedSize.isInvalid() &&
1792 ArraySize->getType()->getAs<RecordType>())
1793 // Diagnose the compatibility of this conversion.
1794 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1795 << ArraySize->getType() << 0 << "'size_t'";
1797 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1802 SizeConvertDiagnoser(Expr *ArraySize)
1803 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1804 ArraySize(ArraySize) {}
1806 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1807 QualType T) override {
1808 return S.Diag(Loc, diag::err_array_size_not_integral)
1809 << S.getLangOpts().CPlusPlus11 << T;
1812 SemaDiagnosticBuilder diagnoseIncomplete(
1813 Sema &S, SourceLocation Loc, QualType T) override {
1814 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1815 << T << ArraySize->getSourceRange();
1818 SemaDiagnosticBuilder diagnoseExplicitConv(
1819 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1820 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1823 SemaDiagnosticBuilder noteExplicitConv(
1824 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1825 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1826 << ConvTy->isEnumeralType() << ConvTy;
1829 SemaDiagnosticBuilder diagnoseAmbiguous(
1830 Sema &S, SourceLocation Loc, QualType T) override {
1831 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1834 SemaDiagnosticBuilder noteAmbiguous(
1835 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1836 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1837 << ConvTy->isEnumeralType() << ConvTy;
1840 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1842 QualType ConvTy) override {
1844 S.getLangOpts().CPlusPlus11
1845 ? diag::warn_cxx98_compat_array_size_conversion
1846 : diag::ext_array_size_conversion)
1847 << T << ConvTy->isEnumeralType() << ConvTy;
1849 } SizeDiagnoser(ArraySize);
1851 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1854 if (ConvertedSize.isInvalid())
1857 ArraySize = ConvertedSize.get();
1858 QualType SizeType = ArraySize->getType();
1860 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1863 // C++98 [expr.new]p7:
1864 // The expression in a direct-new-declarator shall have integral type
1865 // with a non-negative value.
1867 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1868 // per CWG1464. Otherwise, if it's not a constant, we must have an
1869 // unparenthesized array type.
1870 if (!ArraySize->isValueDependent()) {
1872 // We've already performed any required implicit conversion to integer or
1873 // unscoped enumeration type.
1874 // FIXME: Per CWG1464, we are required to check the value prior to
1875 // converting to size_t. This will never find a negative array size in
1876 // C++14 onwards, because Value is always unsigned here!
1877 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1878 if (Value.isSigned() && Value.isNegative()) {
1879 return ExprError(Diag(ArraySize->getLocStart(),
1880 diag::err_typecheck_negative_array_size)
1881 << ArraySize->getSourceRange());
1884 if (!AllocType->isDependentType()) {
1885 unsigned ActiveSizeBits =
1886 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1887 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1888 return ExprError(Diag(ArraySize->getLocStart(),
1889 diag::err_array_too_large)
1890 << Value.toString(10)
1891 << ArraySize->getSourceRange());
1894 KnownArraySize = Value.getZExtValue();
1895 } else if (TypeIdParens.isValid()) {
1896 // Can't have dynamic array size when the type-id is in parentheses.
1897 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1898 << ArraySize->getSourceRange()
1899 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1900 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1902 TypeIdParens = SourceRange();
1906 // Note that we do *not* convert the argument in any way. It can
1907 // be signed, larger than size_t, whatever.
1910 FunctionDecl *OperatorNew = nullptr;
1911 FunctionDecl *OperatorDelete = nullptr;
1912 unsigned Alignment =
1913 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
1914 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
1915 bool PassAlignment = getLangOpts().AlignedAllocation &&
1916 Alignment > NewAlignment;
1918 if (!AllocType->isDependentType() &&
1919 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1920 FindAllocationFunctions(StartLoc,
1921 SourceRange(PlacementLParen, PlacementRParen),
1922 UseGlobal, AllocType, ArraySize, PassAlignment,
1923 PlacementArgs, OperatorNew, OperatorDelete))
1926 // If this is an array allocation, compute whether the usual array
1927 // deallocation function for the type has a size_t parameter.
1928 bool UsualArrayDeleteWantsSize = false;
1929 if (ArraySize && !AllocType->isDependentType())
1930 UsualArrayDeleteWantsSize =
1931 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1933 SmallVector<Expr *, 8> AllPlaceArgs;
1935 const FunctionProtoType *Proto =
1936 OperatorNew->getType()->getAs<FunctionProtoType>();
1937 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1938 : VariadicDoesNotApply;
1940 // We've already converted the placement args, just fill in any default
1941 // arguments. Skip the first parameter because we don't have a corresponding
1942 // argument. Skip the second parameter too if we're passing in the
1943 // alignment; we've already filled it in.
1944 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
1945 PassAlignment ? 2 : 1, PlacementArgs,
1946 AllPlaceArgs, CallType))
1949 if (!AllPlaceArgs.empty())
1950 PlacementArgs = AllPlaceArgs;
1952 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
1953 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1955 // FIXME: Missing call to CheckFunctionCall or equivalent
1957 // Warn if the type is over-aligned and is being allocated by (unaligned)
1958 // global operator new.
1959 if (PlacementArgs.empty() && !PassAlignment &&
1960 (OperatorNew->isImplicit() ||
1961 (OperatorNew->getLocStart().isValid() &&
1962 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1963 if (Alignment > NewAlignment)
1964 Diag(StartLoc, diag::warn_overaligned_type)
1966 << unsigned(Alignment / Context.getCharWidth())
1967 << unsigned(NewAlignment / Context.getCharWidth());
1971 // Array 'new' can't have any initializers except empty parentheses.
1972 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1973 // dialect distinction.
1974 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
1975 SourceRange InitRange(Inits[0]->getLocStart(),
1976 Inits[NumInits - 1]->getLocEnd());
1977 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1981 // If we can perform the initialization, and we've not already done so,
1983 if (!AllocType->isDependentType() &&
1984 !Expr::hasAnyTypeDependentArguments(
1985 llvm::makeArrayRef(Inits, NumInits))) {
1986 // The type we initialize is the complete type, including the array bound.
1989 InitType = Context.getConstantArrayType(
1990 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
1992 ArrayType::Normal, 0);
1995 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
1997 InitType = AllocType;
1999 InitializedEntity Entity
2000 = InitializedEntity::InitializeNew(StartLoc, InitType);
2001 InitializationSequence InitSeq(*this, Entity, Kind,
2002 MultiExprArg(Inits, NumInits));
2003 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2004 MultiExprArg(Inits, NumInits));
2005 if (FullInit.isInvalid())
2008 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2009 // we don't want the initialized object to be destructed.
2010 // FIXME: We should not create these in the first place.
2011 if (CXXBindTemporaryExpr *Binder =
2012 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2013 FullInit = Binder->getSubExpr();
2015 Initializer = FullInit.get();
2018 // Mark the new and delete operators as referenced.
2020 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2022 MarkFunctionReferenced(StartLoc, OperatorNew);
2024 if (OperatorDelete) {
2025 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2027 MarkFunctionReferenced(StartLoc, OperatorDelete);
2030 // C++0x [expr.new]p17:
2031 // If the new expression creates an array of objects of class type,
2032 // access and ambiguity control are done for the destructor.
2033 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2034 if (ArraySize && !BaseAllocType->isDependentType()) {
2035 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2036 if (CXXDestructorDecl *dtor = LookupDestructor(
2037 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2038 MarkFunctionReferenced(StartLoc, dtor);
2039 CheckDestructorAccess(StartLoc, dtor,
2040 PDiag(diag::err_access_dtor)
2042 if (DiagnoseUseOfDecl(dtor, StartLoc))
2048 return new (Context)
2049 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2050 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2051 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2052 Range, DirectInitRange);
2055 /// \brief Checks that a type is suitable as the allocated type
2056 /// in a new-expression.
2057 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2059 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2060 // abstract class type or array thereof.
2061 if (AllocType->isFunctionType())
2062 return Diag(Loc, diag::err_bad_new_type)
2063 << AllocType << 0 << R;
2064 else if (AllocType->isReferenceType())
2065 return Diag(Loc, diag::err_bad_new_type)
2066 << AllocType << 1 << R;
2067 else if (!AllocType->isDependentType() &&
2068 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2070 else if (RequireNonAbstractType(Loc, AllocType,
2071 diag::err_allocation_of_abstract_type))
2073 else if (AllocType->isVariablyModifiedType())
2074 return Diag(Loc, diag::err_variably_modified_new_type)
2076 else if (AllocType.getAddressSpace())
2077 return Diag(Loc, diag::err_address_space_qualified_new)
2078 << AllocType.getUnqualifiedType()
2079 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2080 else if (getLangOpts().ObjCAutoRefCount) {
2081 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2082 QualType BaseAllocType = Context.getBaseElementType(AT);
2083 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2084 BaseAllocType->isObjCLifetimeType())
2085 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2094 resolveAllocationOverload(Sema &S, LookupResult &R, SourceRange Range,
2095 SmallVectorImpl<Expr *> &Args, bool &PassAlignment,
2096 FunctionDecl *&Operator,
2097 OverloadCandidateSet *AlignedCandidates = nullptr,
2098 Expr *AlignArg = nullptr) {
2099 OverloadCandidateSet Candidates(R.getNameLoc(),
2100 OverloadCandidateSet::CSK_Normal);
2101 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2102 Alloc != AllocEnd; ++Alloc) {
2103 // Even member operator new/delete are implicitly treated as
2104 // static, so don't use AddMemberCandidate.
2105 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2107 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2108 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2109 /*ExplicitTemplateArgs=*/nullptr, Args,
2111 /*SuppressUserConversions=*/false);
2115 FunctionDecl *Fn = cast<FunctionDecl>(D);
2116 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2117 /*SuppressUserConversions=*/false);
2120 // Do the resolution.
2121 OverloadCandidateSet::iterator Best;
2122 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2125 FunctionDecl *FnDecl = Best->Function;
2126 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2127 Best->FoundDecl) == Sema::AR_inaccessible)
2134 case OR_No_Viable_Function:
2135 // C++17 [expr.new]p13:
2136 // If no matching function is found and the allocated object type has
2137 // new-extended alignment, the alignment argument is removed from the
2138 // argument list, and overload resolution is performed again.
2139 if (PassAlignment) {
2140 PassAlignment = false;
2142 Args.erase(Args.begin() + 1);
2143 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2144 Operator, &Candidates, AlignArg);
2147 // MSVC will fall back on trying to find a matching global operator new
2148 // if operator new[] cannot be found. Also, MSVC will leak by not
2149 // generating a call to operator delete or operator delete[], but we
2150 // will not replicate that bug.
2151 // FIXME: Find out how this interacts with the std::align_val_t fallback
2152 // once MSVC implements it.
2153 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2154 S.Context.getLangOpts().MSVCCompat) {
2156 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2157 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2158 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2159 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2163 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2164 << R.getLookupName() << Range;
2166 // If we have aligned candidates, only note the align_val_t candidates
2167 // from AlignedCandidates and the non-align_val_t candidates from
2169 if (AlignedCandidates) {
2170 auto IsAligned = [](OverloadCandidate &C) {
2171 return C.Function->getNumParams() > 1 &&
2172 C.Function->getParamDecl(1)->getType()->isAlignValT();
2174 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2176 // This was an overaligned allocation, so list the aligned candidates
2178 Args.insert(Args.begin() + 1, AlignArg);
2179 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2180 R.getNameLoc(), IsAligned);
2181 Args.erase(Args.begin() + 1);
2182 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2185 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2190 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2191 << R.getLookupName() << Range;
2192 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2196 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2197 << Best->Function->isDeleted()
2198 << R.getLookupName()
2199 << S.getDeletedOrUnavailableSuffix(Best->Function)
2201 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2205 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2209 /// FindAllocationFunctions - Finds the overloads of operator new and delete
2210 /// that are appropriate for the allocation.
2211 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2212 bool UseGlobal, QualType AllocType,
2213 bool IsArray, bool &PassAlignment,
2214 MultiExprArg PlaceArgs,
2215 FunctionDecl *&OperatorNew,
2216 FunctionDecl *&OperatorDelete) {
2217 // --- Choosing an allocation function ---
2218 // C++ 5.3.4p8 - 14 & 18
2219 // 1) If UseGlobal is true, only look in the global scope. Else, also look
2220 // in the scope of the allocated class.
2221 // 2) If an array size is given, look for operator new[], else look for
2223 // 3) The first argument is always size_t. Append the arguments from the
2226 SmallVector<Expr*, 8> AllocArgs;
2227 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2229 // We don't care about the actual value of these arguments.
2230 // FIXME: Should the Sema create the expression and embed it in the syntax
2231 // tree? Or should the consumer just recalculate the value?
2232 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2233 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2234 Context.getTargetInfo().getPointerWidth(0)),
2235 Context.getSizeType(),
2237 AllocArgs.push_back(&Size);
2239 QualType AlignValT = Context.VoidTy;
2240 if (PassAlignment) {
2241 DeclareGlobalNewDelete();
2242 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2244 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2246 AllocArgs.push_back(&Align);
2248 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2250 // C++ [expr.new]p8:
2251 // If the allocated type is a non-array type, the allocation
2252 // function's name is operator new and the deallocation function's
2253 // name is operator delete. If the allocated type is an array
2254 // type, the allocation function's name is operator new[] and the
2255 // deallocation function's name is operator delete[].
2256 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2257 IsArray ? OO_Array_New : OO_New);
2259 QualType AllocElemType = Context.getBaseElementType(AllocType);
2261 // Find the allocation function.
2263 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2265 // C++1z [expr.new]p9:
2266 // If the new-expression begins with a unary :: operator, the allocation
2267 // function's name is looked up in the global scope. Otherwise, if the
2268 // allocated type is a class type T or array thereof, the allocation
2269 // function's name is looked up in the scope of T.
2270 if (AllocElemType->isRecordType() && !UseGlobal)
2271 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2273 // We can see ambiguity here if the allocation function is found in
2274 // multiple base classes.
2275 if (R.isAmbiguous())
2278 // If this lookup fails to find the name, or if the allocated type is not
2279 // a class type, the allocation function's name is looked up in the
2282 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2284 assert(!R.empty() && "implicitly declared allocation functions not found");
2285 assert(!R.isAmbiguous() && "global allocation functions are ambiguous");
2287 // We do our own custom access checks below.
2288 R.suppressDiagnostics();
2290 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2295 // We don't need an operator delete if we're running under -fno-exceptions.
2296 if (!getLangOpts().Exceptions) {
2297 OperatorDelete = nullptr;
2301 // Note, the name of OperatorNew might have been changed from array to
2302 // non-array by resolveAllocationOverload.
2303 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2304 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2308 // C++ [expr.new]p19:
2310 // If the new-expression begins with a unary :: operator, the
2311 // deallocation function's name is looked up in the global
2312 // scope. Otherwise, if the allocated type is a class type T or an
2313 // array thereof, the deallocation function's name is looked up in
2314 // the scope of T. If this lookup fails to find the name, or if
2315 // the allocated type is not a class type or array thereof, the
2316 // deallocation function's name is looked up in the global scope.
2317 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2318 if (AllocElemType->isRecordType() && !UseGlobal) {
2320 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2321 LookupQualifiedName(FoundDelete, RD);
2323 if (FoundDelete.isAmbiguous())
2324 return true; // FIXME: clean up expressions?
2326 bool FoundGlobalDelete = FoundDelete.empty();
2327 if (FoundDelete.empty()) {
2328 DeclareGlobalNewDelete();
2329 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2332 FoundDelete.suppressDiagnostics();
2334 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2336 // Whether we're looking for a placement operator delete is dictated
2337 // by whether we selected a placement operator new, not by whether
2338 // we had explicit placement arguments. This matters for things like
2339 // struct A { void *operator new(size_t, int = 0); ... };
2342 // We don't have any definition for what a "placement allocation function"
2343 // is, but we assume it's any allocation function whose
2344 // parameter-declaration-clause is anything other than (size_t).
2346 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2347 // This affects whether an exception from the constructor of an overaligned
2348 // type uses the sized or non-sized form of aligned operator delete.
2349 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2350 OperatorNew->isVariadic();
2352 if (isPlacementNew) {
2353 // C++ [expr.new]p20:
2354 // A declaration of a placement deallocation function matches the
2355 // declaration of a placement allocation function if it has the
2356 // same number of parameters and, after parameter transformations
2357 // (8.3.5), all parameter types except the first are
2360 // To perform this comparison, we compute the function type that
2361 // the deallocation function should have, and use that type both
2362 // for template argument deduction and for comparison purposes.
2363 QualType ExpectedFunctionType;
2365 const FunctionProtoType *Proto
2366 = OperatorNew->getType()->getAs<FunctionProtoType>();
2368 SmallVector<QualType, 4> ArgTypes;
2369 ArgTypes.push_back(Context.VoidPtrTy);
2370 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2371 ArgTypes.push_back(Proto->getParamType(I));
2373 FunctionProtoType::ExtProtoInfo EPI;
2374 // FIXME: This is not part of the standard's rule.
2375 EPI.Variadic = Proto->isVariadic();
2377 ExpectedFunctionType
2378 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2381 for (LookupResult::iterator D = FoundDelete.begin(),
2382 DEnd = FoundDelete.end();
2384 FunctionDecl *Fn = nullptr;
2385 if (FunctionTemplateDecl *FnTmpl =
2386 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2387 // Perform template argument deduction to try to match the
2388 // expected function type.
2389 TemplateDeductionInfo Info(StartLoc);
2390 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2394 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2396 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2397 ExpectedFunctionType,
2398 /*AdjustExcpetionSpec*/true),
2399 ExpectedFunctionType))
2400 Matches.push_back(std::make_pair(D.getPair(), Fn));
2403 if (getLangOpts().CUDA)
2404 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2406 // C++1y [expr.new]p22:
2407 // For a non-placement allocation function, the normal deallocation
2408 // function lookup is used
2410 // Per [expr.delete]p10, this lookup prefers a member operator delete
2411 // without a size_t argument, but prefers a non-member operator delete
2412 // with a size_t where possible (which it always is in this case).
2413 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2414 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2415 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2416 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2419 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2421 // If we failed to select an operator, all remaining functions are viable
2423 for (auto Fn : BestDeallocFns)
2424 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2428 // C++ [expr.new]p20:
2429 // [...] If the lookup finds a single matching deallocation
2430 // function, that function will be called; otherwise, no
2431 // deallocation function will be called.
2432 if (Matches.size() == 1) {
2433 OperatorDelete = Matches[0].second;
2435 // C++1z [expr.new]p23:
2436 // If the lookup finds a usual deallocation function (3.7.4.2)
2437 // with a parameter of type std::size_t and that function, considered
2438 // as a placement deallocation function, would have been
2439 // selected as a match for the allocation function, the program
2441 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2442 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2443 UsualDeallocFnInfo Info(*this,
2444 DeclAccessPair::make(OperatorDelete, AS_public));
2445 // Core issue, per mail to core reflector, 2016-10-09:
2446 // If this is a member operator delete, and there is a corresponding
2447 // non-sized member operator delete, this isn't /really/ a sized
2448 // deallocation function, it just happens to have a size_t parameter.
2449 bool IsSizedDelete = Info.HasSizeT;
2450 if (IsSizedDelete && !FoundGlobalDelete) {
2451 auto NonSizedDelete =
2452 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2453 /*WantAlign*/Info.HasAlignValT);
2454 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2455 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2456 IsSizedDelete = false;
2459 if (IsSizedDelete) {
2460 SourceRange R = PlaceArgs.empty()
2462 : SourceRange(PlaceArgs.front()->getLocStart(),
2463 PlaceArgs.back()->getLocEnd());
2464 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2465 if (!OperatorDelete->isImplicit())
2466 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2471 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2473 } else if (!Matches.empty()) {
2474 // We found multiple suitable operators. Per [expr.new]p20, that means we
2475 // call no 'operator delete' function, but we should at least warn the user.
2476 // FIXME: Suppress this warning if the construction cannot throw.
2477 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2478 << DeleteName << AllocElemType;
2480 for (auto &Match : Matches)
2481 Diag(Match.second->getLocation(),
2482 diag::note_member_declared_here) << DeleteName;
2488 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2489 /// delete. These are:
2492 /// void* operator new(std::size_t) throw(std::bad_alloc);
2493 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2494 /// void operator delete(void *) throw();
2495 /// void operator delete[](void *) throw();
2497 /// void* operator new(std::size_t);
2498 /// void* operator new[](std::size_t);
2499 /// void operator delete(void *) noexcept;
2500 /// void operator delete[](void *) noexcept;
2502 /// void* operator new(std::size_t);
2503 /// void* operator new[](std::size_t);
2504 /// void operator delete(void *) noexcept;
2505 /// void operator delete[](void *) noexcept;
2506 /// void operator delete(void *, std::size_t) noexcept;
2507 /// void operator delete[](void *, std::size_t) noexcept;
2509 /// Note that the placement and nothrow forms of new are *not* implicitly
2510 /// declared. Their use requires including \<new\>.
2511 void Sema::DeclareGlobalNewDelete() {
2512 if (GlobalNewDeleteDeclared)
2515 // C++ [basic.std.dynamic]p2:
2516 // [...] The following allocation and deallocation functions (18.4) are
2517 // implicitly declared in global scope in each translation unit of a
2521 // void* operator new(std::size_t) throw(std::bad_alloc);
2522 // void* operator new[](std::size_t) throw(std::bad_alloc);
2523 // void operator delete(void*) throw();
2524 // void operator delete[](void*) throw();
2526 // void* operator new(std::size_t);
2527 // void* operator new[](std::size_t);
2528 // void operator delete(void*) noexcept;
2529 // void operator delete[](void*) noexcept;
2531 // void* operator new(std::size_t);
2532 // void* operator new[](std::size_t);
2533 // void operator delete(void*) noexcept;
2534 // void operator delete[](void*) noexcept;
2535 // void operator delete(void*, std::size_t) noexcept;
2536 // void operator delete[](void*, std::size_t) noexcept;
2538 // These implicit declarations introduce only the function names operator
2539 // new, operator new[], operator delete, operator delete[].
2541 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2542 // "std" or "bad_alloc" as necessary to form the exception specification.
2543 // However, we do not make these implicit declarations visible to name
2545 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2546 // The "std::bad_alloc" class has not yet been declared, so build it
2548 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2549 getOrCreateStdNamespace(),
2550 SourceLocation(), SourceLocation(),
2551 &PP.getIdentifierTable().get("bad_alloc"),
2553 getStdBadAlloc()->setImplicit(true);
2555 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2556 // The "std::align_val_t" enum class has not yet been declared, so build it
2558 auto *AlignValT = EnumDecl::Create(
2559 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2560 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2561 AlignValT->setIntegerType(Context.getSizeType());
2562 AlignValT->setPromotionType(Context.getSizeType());
2563 AlignValT->setImplicit(true);
2564 StdAlignValT = AlignValT;
2567 GlobalNewDeleteDeclared = true;
2569 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2570 QualType SizeT = Context.getSizeType();
2572 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2573 QualType Return, QualType Param) {
2574 llvm::SmallVector<QualType, 3> Params;
2575 Params.push_back(Param);
2577 // Create up to four variants of the function (sized/aligned).
2578 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2579 (Kind == OO_Delete || Kind == OO_Array_Delete);
2580 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2582 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2583 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2584 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2586 Params.push_back(SizeT);
2588 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2590 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2592 DeclareGlobalAllocationFunction(
2593 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2601 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2602 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2603 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2604 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2607 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2608 /// allocation function if it doesn't already exist.
2609 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2611 ArrayRef<QualType> Params) {
2612 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2614 // Check if this function is already declared.
2615 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2616 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2617 Alloc != AllocEnd; ++Alloc) {
2618 // Only look at non-template functions, as it is the predefined,
2619 // non-templated allocation function we are trying to declare here.
2620 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2621 if (Func->getNumParams() == Params.size()) {
2622 llvm::SmallVector<QualType, 3> FuncParams;
2623 for (auto *P : Func->parameters())
2624 FuncParams.push_back(
2625 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2626 if (llvm::makeArrayRef(FuncParams) == Params) {
2627 // Make the function visible to name lookup, even if we found it in
2628 // an unimported module. It either is an implicitly-declared global
2629 // allocation function, or is suppressing that function.
2630 Func->setHidden(false);
2637 FunctionProtoType::ExtProtoInfo EPI;
2639 QualType BadAllocType;
2640 bool HasBadAllocExceptionSpec
2641 = (Name.getCXXOverloadedOperator() == OO_New ||
2642 Name.getCXXOverloadedOperator() == OO_Array_New);
2643 if (HasBadAllocExceptionSpec) {
2644 if (!getLangOpts().CPlusPlus11) {
2645 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2646 assert(StdBadAlloc && "Must have std::bad_alloc declared");
2647 EPI.ExceptionSpec.Type = EST_Dynamic;
2648 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2652 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2655 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2656 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2657 FunctionDecl *Alloc = FunctionDecl::Create(
2658 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2659 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2660 Alloc->setImplicit();
2661 // Global allocation functions should always be visible.
2662 Alloc->setHidden(false);
2664 // Implicit sized deallocation functions always have default visibility.
2666 VisibilityAttr::CreateImplicit(Context, VisibilityAttr::Default));
2668 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2669 for (QualType T : Params) {
2670 ParamDecls.push_back(ParmVarDecl::Create(
2671 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2672 /*TInfo=*/nullptr, SC_None, nullptr));
2673 ParamDecls.back()->setImplicit();
2675 Alloc->setParams(ParamDecls);
2677 Alloc->addAttr(ExtraAttr);
2678 Context.getTranslationUnitDecl()->addDecl(Alloc);
2679 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2683 CreateAllocationFunctionDecl(nullptr);
2685 // Host and device get their own declaration so each can be
2686 // defined or re-declared independently.
2687 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2688 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2692 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2693 bool CanProvideSize,
2695 DeclarationName Name) {
2696 DeclareGlobalNewDelete();
2698 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2699 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2701 // FIXME: It's possible for this to result in ambiguity, through a
2702 // user-declared variadic operator delete or the enable_if attribute. We
2703 // should probably not consider those cases to be usual deallocation
2704 // functions. But for now we just make an arbitrary choice in that case.
2705 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2707 assert(Result.FD && "operator delete missing from global scope?");
2711 FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2712 CXXRecordDecl *RD) {
2713 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2715 FunctionDecl *OperatorDelete = nullptr;
2716 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2719 return OperatorDelete;
2721 // If there's no class-specific operator delete, look up the global
2722 // non-array delete.
2723 return FindUsualDeallocationFunction(
2724 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2728 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2729 DeclarationName Name,
2730 FunctionDecl *&Operator, bool Diagnose) {
2731 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2732 // Try to find operator delete/operator delete[] in class scope.
2733 LookupQualifiedName(Found, RD);
2735 if (Found.isAmbiguous())
2738 Found.suppressDiagnostics();
2740 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2742 // C++17 [expr.delete]p10:
2743 // If the deallocation functions have class scope, the one without a
2744 // parameter of type std::size_t is selected.
2745 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2746 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2747 /*WantAlign*/ Overaligned, &Matches);
2749 // If we could find an overload, use it.
2750 if (Matches.size() == 1) {
2751 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2753 // FIXME: DiagnoseUseOfDecl?
2754 if (Operator->isDeleted()) {
2756 Diag(StartLoc, diag::err_deleted_function_use);
2757 NoteDeletedFunction(Operator);
2762 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2763 Matches[0].Found, Diagnose) == AR_inaccessible)
2769 // We found multiple suitable operators; complain about the ambiguity.
2770 // FIXME: The standard doesn't say to do this; it appears that the intent
2771 // is that this should never happen.
2772 if (!Matches.empty()) {
2774 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2776 for (auto &Match : Matches)
2777 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2782 // We did find operator delete/operator delete[] declarations, but
2783 // none of them were suitable.
2784 if (!Found.empty()) {
2786 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2789 for (NamedDecl *D : Found)
2790 Diag(D->getUnderlyingDecl()->getLocation(),
2791 diag::note_member_declared_here) << Name;
2801 /// \brief Checks whether delete-expression, and new-expression used for
2802 /// initializing deletee have the same array form.
2803 class MismatchingNewDeleteDetector {
2805 enum MismatchResult {
2806 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2808 /// Indicates that variable is initialized with mismatching form of \a new.
2810 /// Indicates that member is initialized with mismatching form of \a new.
2811 MemberInitMismatches,
2812 /// Indicates that 1 or more constructors' definitions could not been
2813 /// analyzed, and they will be checked again at the end of translation unit.
2817 /// \param EndOfTU True, if this is the final analysis at the end of
2818 /// translation unit. False, if this is the initial analysis at the point
2819 /// delete-expression was encountered.
2820 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2821 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2822 HasUndefinedConstructors(false) {}
2824 /// \brief Checks whether pointee of a delete-expression is initialized with
2825 /// matching form of new-expression.
2827 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2828 /// point where delete-expression is encountered, then a warning will be
2829 /// issued immediately. If return value is \c AnalyzeLater at the point where
2830 /// delete-expression is seen, then member will be analyzed at the end of
2831 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2832 /// couldn't be analyzed. If at least one constructor initializes the member
2833 /// with matching type of new, the return value is \c NoMismatch.
2834 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2835 /// \brief Analyzes a class member.
2836 /// \param Field Class member to analyze.
2837 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2838 /// for deleting the \p Field.
2839 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2841 /// List of mismatching new-expressions used for initialization of the pointee
2842 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2843 /// Indicates whether delete-expression was in array form.
2848 /// \brief Indicates that there is at least one constructor without body.
2849 bool HasUndefinedConstructors;
2850 /// \brief Returns \c CXXNewExpr from given initialization expression.
2851 /// \param E Expression used for initializing pointee in delete-expression.
2852 /// E can be a single-element \c InitListExpr consisting of new-expression.
2853 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2854 /// \brief Returns whether member is initialized with mismatching form of
2855 /// \c new either by the member initializer or in-class initialization.
2857 /// If bodies of all constructors are not visible at the end of translation
2858 /// unit or at least one constructor initializes member with the matching
2859 /// form of \c new, mismatch cannot be proven, and this function will return
2861 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2862 /// \brief Returns whether variable is initialized with mismatching form of
2865 /// If variable is initialized with matching form of \c new or variable is not
2866 /// initialized with a \c new expression, this function will return true.
2867 /// If variable is initialized with mismatching form of \c new, returns false.
2868 /// \param D Variable to analyze.
2869 bool hasMatchingVarInit(const DeclRefExpr *D);
2870 /// \brief Checks whether the constructor initializes pointee with mismatching
2873 /// Returns true, if member is initialized with matching form of \c new in
2874 /// member initializer list. Returns false, if member is initialized with the
2875 /// matching form of \c new in this constructor's initializer or given
2876 /// constructor isn't defined at the point where delete-expression is seen, or
2877 /// member isn't initialized by the constructor.
2878 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2879 /// \brief Checks whether member is initialized with matching form of
2880 /// \c new in member initializer list.
2881 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2882 /// Checks whether member is initialized with mismatching form of \c new by
2883 /// in-class initializer.
2884 MismatchResult analyzeInClassInitializer();
2888 MismatchingNewDeleteDetector::MismatchResult
2889 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2891 assert(DE && "Expected delete-expression");
2892 IsArrayForm = DE->isArrayForm();
2893 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2894 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2895 return analyzeMemberExpr(ME);
2896 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2897 if (!hasMatchingVarInit(D))
2898 return VarInitMismatches;
2904 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2905 assert(E != nullptr && "Expected a valid initializer expression");
2906 E = E->IgnoreParenImpCasts();
2907 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2908 if (ILE->getNumInits() == 1)
2909 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2912 return dyn_cast_or_null<const CXXNewExpr>(E);
2915 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2916 const CXXCtorInitializer *CI) {
2917 const CXXNewExpr *NE = nullptr;
2918 if (Field == CI->getMember() &&
2919 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2920 if (NE->isArray() == IsArrayForm)
2923 NewExprs.push_back(NE);
2928 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2929 const CXXConstructorDecl *CD) {
2930 if (CD->isImplicit())
2932 const FunctionDecl *Definition = CD;
2933 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2934 HasUndefinedConstructors = true;
2937 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2938 if (hasMatchingNewInCtorInit(CI))
2944 MismatchingNewDeleteDetector::MismatchResult
2945 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2946 assert(Field != nullptr && "This should be called only for members");
2947 const Expr *InitExpr = Field->getInClassInitializer();
2949 return EndOfTU ? NoMismatch : AnalyzeLater;
2950 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
2951 if (NE->isArray() != IsArrayForm) {
2952 NewExprs.push_back(NE);
2953 return MemberInitMismatches;
2959 MismatchingNewDeleteDetector::MismatchResult
2960 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2961 bool DeleteWasArrayForm) {
2962 assert(Field != nullptr && "Analysis requires a valid class member.");
2963 this->Field = Field;
2964 IsArrayForm = DeleteWasArrayForm;
2965 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2966 for (const auto *CD : RD->ctors()) {
2967 if (hasMatchingNewInCtor(CD))
2970 if (HasUndefinedConstructors)
2971 return EndOfTU ? NoMismatch : AnalyzeLater;
2972 if (!NewExprs.empty())
2973 return MemberInitMismatches;
2974 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2978 MismatchingNewDeleteDetector::MismatchResult
2979 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2980 assert(ME != nullptr && "Expected a member expression");
2981 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2982 return analyzeField(F, IsArrayForm);
2986 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2987 const CXXNewExpr *NE = nullptr;
2988 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2989 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2990 NE->isArray() != IsArrayForm) {
2991 NewExprs.push_back(NE);
2994 return NewExprs.empty();
2998 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2999 const MismatchingNewDeleteDetector &Detector) {
3000 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3002 if (!Detector.IsArrayForm)
3003 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3005 SourceLocation RSquare = Lexer::findLocationAfterToken(
3006 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3007 SemaRef.getLangOpts(), true);
3008 if (RSquare.isValid())
3009 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3011 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3012 << Detector.IsArrayForm << H;
3014 for (const auto *NE : Detector.NewExprs)
3015 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3016 << Detector.IsArrayForm;
3019 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3020 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3022 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3023 switch (Detector.analyzeDeleteExpr(DE)) {
3024 case MismatchingNewDeleteDetector::VarInitMismatches:
3025 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3026 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
3029 case MismatchingNewDeleteDetector::AnalyzeLater: {
3030 DeleteExprs[Detector.Field].push_back(
3031 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
3034 case MismatchingNewDeleteDetector::NoMismatch:
3039 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3040 bool DeleteWasArrayForm) {
3041 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3042 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3043 case MismatchingNewDeleteDetector::VarInitMismatches:
3044 llvm_unreachable("This analysis should have been done for class members.");
3045 case MismatchingNewDeleteDetector::AnalyzeLater:
3046 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
3047 "translation unit.");
3048 case MismatchingNewDeleteDetector::MemberInitMismatches:
3049 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3051 case MismatchingNewDeleteDetector::NoMismatch:
3056 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3057 /// @code ::delete ptr; @endcode
3059 /// @code delete [] ptr; @endcode
3061 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3062 bool ArrayForm, Expr *ExE) {
3063 // C++ [expr.delete]p1:
3064 // The operand shall have a pointer type, or a class type having a single
3065 // non-explicit conversion function to a pointer type. The result has type
3068 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3070 ExprResult Ex = ExE;
3071 FunctionDecl *OperatorDelete = nullptr;
3072 bool ArrayFormAsWritten = ArrayForm;
3073 bool UsualArrayDeleteWantsSize = false;
3075 if (!Ex.get()->isTypeDependent()) {
3076 // Perform lvalue-to-rvalue cast, if needed.
3077 Ex = DefaultLvalueConversion(Ex.get());
3081 QualType Type = Ex.get()->getType();
3083 class DeleteConverter : public ContextualImplicitConverter {
3085 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3087 bool match(QualType ConvType) override {
3088 // FIXME: If we have an operator T* and an operator void*, we must pick
3090 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3091 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3096 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3097 QualType T) override {
3098 return S.Diag(Loc, diag::err_delete_operand) << T;
3101 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3102 QualType T) override {
3103 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3106 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3108 QualType ConvTy) override {
3109 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3112 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3113 QualType ConvTy) override {
3114 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3118 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3119 QualType T) override {
3120 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3123 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3124 QualType ConvTy) override {
3125 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3129 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3131 QualType ConvTy) override {
3132 llvm_unreachable("conversion functions are permitted");
3136 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3139 Type = Ex.get()->getType();
3140 if (!Converter.match(Type))
3141 // FIXME: PerformContextualImplicitConversion should return ExprError
3142 // itself in this case.
3145 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3146 QualType PointeeElem = Context.getBaseElementType(Pointee);
3148 if (Pointee.getAddressSpace())
3149 return Diag(Ex.get()->getLocStart(),
3150 diag::err_address_space_qualified_delete)
3151 << Pointee.getUnqualifiedType()
3152 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3154 CXXRecordDecl *PointeeRD = nullptr;
3155 if (Pointee->isVoidType() && !isSFINAEContext()) {
3156 // The C++ standard bans deleting a pointer to a non-object type, which
3157 // effectively bans deletion of "void*". However, most compilers support
3158 // this, so we treat it as a warning unless we're in a SFINAE context.
3159 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3160 << Type << Ex.get()->getSourceRange();
3161 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3162 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3163 << Type << Ex.get()->getSourceRange());
3164 } else if (!Pointee->isDependentType()) {
3165 // FIXME: This can result in errors if the definition was imported from a
3166 // module but is hidden.
3167 if (!RequireCompleteType(StartLoc, Pointee,
3168 diag::warn_delete_incomplete, Ex.get())) {
3169 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3170 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3174 if (Pointee->isArrayType() && !ArrayForm) {
3175 Diag(StartLoc, diag::warn_delete_array_type)
3176 << Type << Ex.get()->getSourceRange()
3177 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3181 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3182 ArrayForm ? OO_Array_Delete : OO_Delete);
3186 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3190 // If we're allocating an array of records, check whether the
3191 // usual operator delete[] has a size_t parameter.
3193 // If the user specifically asked to use the global allocator,
3194 // we'll need to do the lookup into the class.
3196 UsualArrayDeleteWantsSize =
3197 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3199 // Otherwise, the usual operator delete[] should be the
3200 // function we just found.
3201 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3202 UsualArrayDeleteWantsSize =
3203 UsualDeallocFnInfo(*this,
3204 DeclAccessPair::make(OperatorDelete, AS_public))
3208 if (!PointeeRD->hasIrrelevantDestructor())
3209 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3210 MarkFunctionReferenced(StartLoc,
3211 const_cast<CXXDestructorDecl*>(Dtor));
3212 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3216 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3217 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3218 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3222 if (!OperatorDelete) {
3223 bool IsComplete = isCompleteType(StartLoc, Pointee);
3224 bool CanProvideSize =
3225 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3226 Pointee.isDestructedType());
3227 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3229 // Look for a global declaration.
3230 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3231 Overaligned, DeleteName);
3234 MarkFunctionReferenced(StartLoc, OperatorDelete);
3236 // Check access and ambiguity of operator delete and destructor.
3238 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3239 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3240 PDiag(diag::err_access_dtor) << PointeeElem);
3245 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3246 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3247 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3248 AnalyzeDeleteExprMismatch(Result);
3252 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3253 bool IsDelete, bool CallCanBeVirtual,
3254 bool WarnOnNonAbstractTypes,
3255 SourceLocation DtorLoc) {
3256 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3259 // C++ [expr.delete]p3:
3260 // In the first alternative (delete object), if the static type of the
3261 // object to be deleted is different from its dynamic type, the static
3262 // type shall be a base class of the dynamic type of the object to be
3263 // deleted and the static type shall have a virtual destructor or the
3264 // behavior is undefined.
3266 const CXXRecordDecl *PointeeRD = dtor->getParent();
3267 // Note: a final class cannot be derived from, no issue there
3268 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3271 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3272 if (PointeeRD->isAbstract()) {
3273 // If the class is abstract, we warn by default, because we're
3274 // sure the code has undefined behavior.
3275 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3277 } else if (WarnOnNonAbstractTypes) {
3278 // Otherwise, if this is not an array delete, it's a bit suspect,
3279 // but not necessarily wrong.
3280 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3284 std::string TypeStr;
3285 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3286 Diag(DtorLoc, diag::note_delete_non_virtual)
3287 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3291 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3292 SourceLocation StmtLoc,
3295 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3297 return ConditionError();
3298 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3299 CK == ConditionKind::ConstexprIf);
3302 /// \brief Check the use of the given variable as a C++ condition in an if,
3303 /// while, do-while, or switch statement.
3304 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3305 SourceLocation StmtLoc,
3307 if (ConditionVar->isInvalidDecl())
3310 QualType T = ConditionVar->getType();
3312 // C++ [stmt.select]p2:
3313 // The declarator shall not specify a function or an array.
3314 if (T->isFunctionType())
3315 return ExprError(Diag(ConditionVar->getLocation(),
3316 diag::err_invalid_use_of_function_type)
3317 << ConditionVar->getSourceRange());
3318 else if (T->isArrayType())
3319 return ExprError(Diag(ConditionVar->getLocation(),
3320 diag::err_invalid_use_of_array_type)
3321 << ConditionVar->getSourceRange());
3323 ExprResult Condition = DeclRefExpr::Create(
3324 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3325 /*enclosing*/ false, ConditionVar->getLocation(),
3326 ConditionVar->getType().getNonReferenceType(), VK_LValue);
3328 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3331 case ConditionKind::Boolean:
3332 return CheckBooleanCondition(StmtLoc, Condition.get());
3334 case ConditionKind::ConstexprIf:
3335 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3337 case ConditionKind::Switch:
3338 return CheckSwitchCondition(StmtLoc, Condition.get());
3341 llvm_unreachable("unexpected condition kind");
3344 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3345 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3347 // The value of a condition that is an initialized declaration in a statement
3348 // other than a switch statement is the value of the declared variable
3349 // implicitly converted to type bool. If that conversion is ill-formed, the
3350 // program is ill-formed.
3351 // The value of a condition that is an expression is the value of the
3352 // expression, implicitly converted to bool.
3354 // FIXME: Return this value to the caller so they don't need to recompute it.
3355 llvm::APSInt Value(/*BitWidth*/1);
3356 return (IsConstexpr && !CondExpr->isValueDependent())
3357 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3359 : PerformContextuallyConvertToBool(CondExpr);
3362 /// Helper function to determine whether this is the (deprecated) C++
3363 /// conversion from a string literal to a pointer to non-const char or
3364 /// non-const wchar_t (for narrow and wide string literals,
3367 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3368 // Look inside the implicit cast, if it exists.
3369 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3370 From = Cast->getSubExpr();
3372 // A string literal (2.13.4) that is not a wide string literal can
3373 // be converted to an rvalue of type "pointer to char"; a wide
3374 // string literal can be converted to an rvalue of type "pointer
3375 // to wchar_t" (C++ 4.2p2).
3376 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3377 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3378 if (const BuiltinType *ToPointeeType
3379 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3380 // This conversion is considered only when there is an
3381 // explicit appropriate pointer target type (C++ 4.2p2).
3382 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3383 switch (StrLit->getKind()) {
3384 case StringLiteral::UTF8:
3385 case StringLiteral::UTF16:
3386 case StringLiteral::UTF32:
3387 // We don't allow UTF literals to be implicitly converted
3389 case StringLiteral::Ascii:
3390 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3391 ToPointeeType->getKind() == BuiltinType::Char_S);
3392 case StringLiteral::Wide:
3393 return Context.typesAreCompatible(Context.getWideCharType(),
3394 QualType(ToPointeeType, 0));
3402 static ExprResult BuildCXXCastArgument(Sema &S,
3403 SourceLocation CastLoc,
3406 CXXMethodDecl *Method,
3407 DeclAccessPair FoundDecl,
3408 bool HadMultipleCandidates,
3411 default: llvm_unreachable("Unhandled cast kind!");
3412 case CK_ConstructorConversion: {
3413 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3414 SmallVector<Expr*, 8> ConstructorArgs;
3416 if (S.RequireNonAbstractType(CastLoc, Ty,
3417 diag::err_allocation_of_abstract_type))
3420 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3423 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3424 InitializedEntity::InitializeTemporary(Ty));
3425 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3428 ExprResult Result = S.BuildCXXConstructExpr(
3429 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3430 ConstructorArgs, HadMultipleCandidates,
3431 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3432 CXXConstructExpr::CK_Complete, SourceRange());
3433 if (Result.isInvalid())
3436 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3439 case CK_UserDefinedConversion: {
3440 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3442 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3443 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3446 // Create an implicit call expr that calls it.
3447 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3448 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3449 HadMultipleCandidates);
3450 if (Result.isInvalid())
3452 // Record usage of conversion in an implicit cast.
3453 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3454 CK_UserDefinedConversion, Result.get(),
3455 nullptr, Result.get()->getValueKind());
3457 return S.MaybeBindToTemporary(Result.get());
3462 /// PerformImplicitConversion - Perform an implicit conversion of the
3463 /// expression From to the type ToType using the pre-computed implicit
3464 /// conversion sequence ICS. Returns the converted
3465 /// expression. Action is the kind of conversion we're performing,
3466 /// used in the error message.
3468 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3469 const ImplicitConversionSequence &ICS,
3470 AssignmentAction Action,
3471 CheckedConversionKind CCK) {
3472 switch (ICS.getKind()) {
3473 case ImplicitConversionSequence::StandardConversion: {
3474 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3476 if (Res.isInvalid())
3482 case ImplicitConversionSequence::UserDefinedConversion: {
3484 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3486 QualType BeforeToType;
3487 assert(FD && "no conversion function for user-defined conversion seq");
3488 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3489 CastKind = CK_UserDefinedConversion;
3491 // If the user-defined conversion is specified by a conversion function,
3492 // the initial standard conversion sequence converts the source type to
3493 // the implicit object parameter of the conversion function.
3494 BeforeToType = Context.getTagDeclType(Conv->getParent());
3496 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3497 CastKind = CK_ConstructorConversion;
3498 // Do no conversion if dealing with ... for the first conversion.
3499 if (!ICS.UserDefined.EllipsisConversion) {
3500 // If the user-defined conversion is specified by a constructor, the
3501 // initial standard conversion sequence converts the source type to
3502 // the type required by the argument of the constructor
3503 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3506 // Watch out for ellipsis conversion.
3507 if (!ICS.UserDefined.EllipsisConversion) {
3509 PerformImplicitConversion(From, BeforeToType,
3510 ICS.UserDefined.Before, AA_Converting,
3512 if (Res.isInvalid())
3518 = BuildCXXCastArgument(*this,
3519 From->getLocStart(),
3520 ToType.getNonReferenceType(),
3521 CastKind, cast<CXXMethodDecl>(FD),
3522 ICS.UserDefined.FoundConversionFunction,
3523 ICS.UserDefined.HadMultipleCandidates,
3526 if (CastArg.isInvalid())
3529 From = CastArg.get();
3531 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3532 AA_Converting, CCK);
3535 case ImplicitConversionSequence::AmbiguousConversion:
3536 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3537 PDiag(diag::err_typecheck_ambiguous_condition)
3538 << From->getSourceRange());
3541 case ImplicitConversionSequence::EllipsisConversion:
3542 llvm_unreachable("Cannot perform an ellipsis conversion");
3544 case ImplicitConversionSequence::BadConversion:
3546 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3547 From->getType(), From, Action);
3548 assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed;
3552 // Everything went well.
3556 /// PerformImplicitConversion - Perform an implicit conversion of the
3557 /// expression From to the type ToType by following the standard
3558 /// conversion sequence SCS. Returns the converted
3559 /// expression. Flavor is the context in which we're performing this
3560 /// conversion, for use in error messages.
3562 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3563 const StandardConversionSequence& SCS,
3564 AssignmentAction Action,
3565 CheckedConversionKind CCK) {
3566 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3568 // Overall FIXME: we are recomputing too many types here and doing far too
3569 // much extra work. What this means is that we need to keep track of more
3570 // information that is computed when we try the implicit conversion initially,
3571 // so that we don't need to recompute anything here.
3572 QualType FromType = From->getType();
3574 if (SCS.CopyConstructor) {
3575 // FIXME: When can ToType be a reference type?
3576 assert(!ToType->isReferenceType());
3577 if (SCS.Second == ICK_Derived_To_Base) {
3578 SmallVector<Expr*, 8> ConstructorArgs;
3579 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3580 From, /*FIXME:ConstructLoc*/SourceLocation(),
3583 return BuildCXXConstructExpr(
3584 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3585 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3586 ConstructorArgs, /*HadMultipleCandidates*/ false,
3587 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3588 CXXConstructExpr::CK_Complete, SourceRange());
3590 return BuildCXXConstructExpr(
3591 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3592 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3593 From, /*HadMultipleCandidates*/ false,
3594 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3595 CXXConstructExpr::CK_Complete, SourceRange());
3598 // Resolve overloaded function references.
3599 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3600 DeclAccessPair Found;
3601 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3606 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
3609 From = FixOverloadedFunctionReference(From, Found, Fn);
3610 FromType = From->getType();
3613 // If we're converting to an atomic type, first convert to the corresponding
3615 QualType ToAtomicType;
3616 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3617 ToAtomicType = ToType;
3618 ToType = ToAtomic->getValueType();
3621 QualType InitialFromType = FromType;
3622 // Perform the first implicit conversion.
3623 switch (SCS.First) {
3625 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3626 FromType = FromAtomic->getValueType().getUnqualifiedType();
3627 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3628 From, /*BasePath=*/nullptr, VK_RValue);
3632 case ICK_Lvalue_To_Rvalue: {
3633 assert(From->getObjectKind() != OK_ObjCProperty);
3634 ExprResult FromRes = DefaultLvalueConversion(From);
3635 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
3636 From = FromRes.get();
3637 FromType = From->getType();
3641 case ICK_Array_To_Pointer:
3642 FromType = Context.getArrayDecayedType(FromType);
3643 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3644 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3647 case ICK_Function_To_Pointer:
3648 FromType = Context.getPointerType(FromType);
3649 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3650 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3654 llvm_unreachable("Improper first standard conversion");
3657 // Perform the second implicit conversion
3658 switch (SCS.Second) {
3660 // C++ [except.spec]p5:
3661 // [For] assignment to and initialization of pointers to functions,
3662 // pointers to member functions, and references to functions: the
3663 // target entity shall allow at least the exceptions allowed by the
3664 // source value in the assignment or initialization.
3667 case AA_Initializing:
3668 // Note, function argument passing and returning are initialization.
3672 case AA_Passing_CFAudited:
3673 if (CheckExceptionSpecCompatibility(From, ToType))
3679 // Casts and implicit conversions are not initialization, so are not
3680 // checked for exception specification mismatches.
3683 // Nothing else to do.
3686 case ICK_Integral_Promotion:
3687 case ICK_Integral_Conversion:
3688 if (ToType->isBooleanType()) {
3689 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3690 SCS.Second == ICK_Integral_Promotion &&
3691 "only enums with fixed underlying type can promote to bool");
3692 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
3693 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3695 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
3696 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3700 case ICK_Floating_Promotion:
3701 case ICK_Floating_Conversion:
3702 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
3703 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3706 case ICK_Complex_Promotion:
3707 case ICK_Complex_Conversion: {
3708 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3709 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3711 if (FromEl->isRealFloatingType()) {
3712 if (ToEl->isRealFloatingType())
3713 CK = CK_FloatingComplexCast;
3715 CK = CK_FloatingComplexToIntegralComplex;
3716 } else if (ToEl->isRealFloatingType()) {
3717 CK = CK_IntegralComplexToFloatingComplex;
3719 CK = CK_IntegralComplexCast;
3721 From = ImpCastExprToType(From, ToType, CK,
3722 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3726 case ICK_Floating_Integral:
3727 if (ToType->isRealFloatingType())
3728 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
3729 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3731 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
3732 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3735 case ICK_Compatible_Conversion:
3736 From = ImpCastExprToType(From, ToType, CK_NoOp,
3737 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3740 case ICK_Writeback_Conversion:
3741 case ICK_Pointer_Conversion: {
3742 if (SCS.IncompatibleObjC && Action != AA_Casting) {
3743 // Diagnose incompatible Objective-C conversions
3744 if (Action == AA_Initializing || Action == AA_Assigning)
3745 Diag(From->getLocStart(),
3746 diag::ext_typecheck_convert_incompatible_pointer)
3747 << ToType << From->getType() << Action
3748 << From->getSourceRange() << 0;
3750 Diag(From->getLocStart(),
3751 diag::ext_typecheck_convert_incompatible_pointer)
3752 << From->getType() << ToType << Action
3753 << From->getSourceRange() << 0;
3755 if (From->getType()->isObjCObjectPointerType() &&
3756 ToType->isObjCObjectPointerType())
3757 EmitRelatedResultTypeNote(From);
3758 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
3759 !CheckObjCARCUnavailableWeakConversion(ToType,
3761 if (Action == AA_Initializing)
3762 Diag(From->getLocStart(),
3763 diag::err_arc_weak_unavailable_assign);
3765 Diag(From->getLocStart(),
3766 diag::err_arc_convesion_of_weak_unavailable)
3767 << (Action == AA_Casting) << From->getType() << ToType
3768 << From->getSourceRange();
3771 CastKind Kind = CK_Invalid;
3772 CXXCastPath BasePath;
3773 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
3776 // Make sure we extend blocks if necessary.
3777 // FIXME: doing this here is really ugly.
3778 if (Kind == CK_BlockPointerToObjCPointerCast) {
3779 ExprResult E = From;
3780 (void) PrepareCastToObjCObjectPointer(E);
3783 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
3784 CheckObjCConversion(SourceRange(), ToType, From, CCK);
3785 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3790 case ICK_Pointer_Member: {
3791 CastKind Kind = CK_Invalid;
3792 CXXCastPath BasePath;
3793 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
3795 if (CheckExceptionSpecCompatibility(From, ToType))
3798 // We may not have been able to figure out what this member pointer resolved
3799 // to up until this exact point. Attempt to lock-in it's inheritance model.
3800 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3801 (void)isCompleteType(From->getExprLoc(), From->getType());
3802 (void)isCompleteType(From->getExprLoc(), ToType);
3805 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3810 case ICK_Boolean_Conversion:
3811 // Perform half-to-boolean conversion via float.
3812 if (From->getType()->isHalfType()) {
3813 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
3814 FromType = Context.FloatTy;
3817 From = ImpCastExprToType(From, Context.BoolTy,
3818 ScalarTypeToBooleanCastKind(FromType),
3819 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3822 case ICK_Derived_To_Base: {
3823 CXXCastPath BasePath;
3824 if (CheckDerivedToBaseConversion(From->getType(),
3825 ToType.getNonReferenceType(),
3826 From->getLocStart(),
3827 From->getSourceRange(),
3832 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3833 CK_DerivedToBase, From->getValueKind(),
3834 &BasePath, CCK).get();
3838 case ICK_Vector_Conversion:
3839 From = ImpCastExprToType(From, ToType, CK_BitCast,
3840 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3843 case ICK_Vector_Splat: {
3844 // Vector splat from any arithmetic type to a vector.
3845 Expr *Elem = prepareVectorSplat(ToType, From).get();
3846 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3847 /*BasePath=*/nullptr, CCK).get();
3851 case ICK_Complex_Real:
3852 // Case 1. x -> _Complex y
3853 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3854 QualType ElType = ToComplex->getElementType();
3855 bool isFloatingComplex = ElType->isRealFloatingType();
3858 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3860 } else if (From->getType()->isRealFloatingType()) {
3861 From = ImpCastExprToType(From, ElType,
3862 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
3864 assert(From->getType()->isIntegerType());
3865 From = ImpCastExprToType(From, ElType,
3866 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
3869 From = ImpCastExprToType(From, ToType,
3870 isFloatingComplex ? CK_FloatingRealToComplex
3871 : CK_IntegralRealToComplex).get();
3873 // Case 2. _Complex x -> y
3875 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3876 assert(FromComplex);
3878 QualType ElType = FromComplex->getElementType();
3879 bool isFloatingComplex = ElType->isRealFloatingType();
3882 From = ImpCastExprToType(From, ElType,
3883 isFloatingComplex ? CK_FloatingComplexToReal
3884 : CK_IntegralComplexToReal,
3885 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3888 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3890 } else if (ToType->isRealFloatingType()) {
3891 From = ImpCastExprToType(From, ToType,
3892 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
3893 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3895 assert(ToType->isIntegerType());
3896 From = ImpCastExprToType(From, ToType,
3897 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3898 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3903 case ICK_Block_Pointer_Conversion: {
3904 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3905 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3909 case ICK_TransparentUnionConversion: {
3910 ExprResult FromRes = From;
3911 Sema::AssignConvertType ConvTy =
3912 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3913 if (FromRes.isInvalid())
3915 From = FromRes.get();
3916 assert ((ConvTy == Sema::Compatible) &&
3917 "Improper transparent union conversion");
3922 case ICK_Zero_Event_Conversion:
3923 From = ImpCastExprToType(From, ToType,
3925 From->getValueKind()).get();
3928 case ICK_Zero_Queue_Conversion:
3929 From = ImpCastExprToType(From, ToType,
3931 From->getValueKind()).get();
3934 case ICK_Lvalue_To_Rvalue:
3935 case ICK_Array_To_Pointer:
3936 case ICK_Function_To_Pointer:
3937 case ICK_Function_Conversion:
3938 case ICK_Qualification:
3939 case ICK_Num_Conversion_Kinds:
3940 case ICK_C_Only_Conversion:
3941 case ICK_Incompatible_Pointer_Conversion:
3942 llvm_unreachable("Improper second standard conversion");
3945 switch (SCS.Third) {
3950 case ICK_Function_Conversion:
3951 // If both sides are functions (or pointers/references to them), there could
3952 // be incompatible exception declarations.
3953 if (CheckExceptionSpecCompatibility(From, ToType))
3956 From = ImpCastExprToType(From, ToType, CK_NoOp,
3957 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3960 case ICK_Qualification: {
3961 // The qualification keeps the category of the inner expression, unless the
3962 // target type isn't a reference.
3963 ExprValueKind VK = ToType->isReferenceType() ?
3964 From->getValueKind() : VK_RValue;
3965 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3966 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
3968 if (SCS.DeprecatedStringLiteralToCharPtr &&
3969 !getLangOpts().WritableStrings) {
3970 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3971 ? diag::ext_deprecated_string_literal_conversion
3972 : diag::warn_deprecated_string_literal_conversion)
3973 << ToType.getNonReferenceType();
3980 llvm_unreachable("Improper third standard conversion");
3983 // If this conversion sequence involved a scalar -> atomic conversion, perform
3984 // that conversion now.
3985 if (!ToAtomicType.isNull()) {
3986 assert(Context.hasSameType(
3987 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3988 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3989 VK_RValue, nullptr, CCK).get();
3992 // If this conversion sequence succeeded and involved implicitly converting a
3993 // _Nullable type to a _Nonnull one, complain.
3994 if (CCK == CCK_ImplicitConversion)
3995 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3996 From->getLocStart());
4001 /// \brief Check the completeness of a type in a unary type trait.
4003 /// If the particular type trait requires a complete type, tries to complete
4004 /// it. If completing the type fails, a diagnostic is emitted and false
4005 /// returned. If completing the type succeeds or no completion was required,
4007 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4010 // C++0x [meta.unary.prop]p3:
4011 // For all of the class templates X declared in this Clause, instantiating
4012 // that template with a template argument that is a class template
4013 // specialization may result in the implicit instantiation of the template
4014 // argument if and only if the semantics of X require that the argument
4015 // must be a complete type.
4016 // We apply this rule to all the type trait expressions used to implement
4017 // these class templates. We also try to follow any GCC documented behavior
4018 // in these expressions to ensure portability of standard libraries.
4020 default: llvm_unreachable("not a UTT");
4021 // is_complete_type somewhat obviously cannot require a complete type.
4022 case UTT_IsCompleteType:
4025 // These traits are modeled on the type predicates in C++0x
4026 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4027 // requiring a complete type, as whether or not they return true cannot be
4028 // impacted by the completeness of the type.
4030 case UTT_IsIntegral:
4031 case UTT_IsFloatingPoint:
4034 case UTT_IsLvalueReference:
4035 case UTT_IsRvalueReference:
4036 case UTT_IsMemberFunctionPointer:
4037 case UTT_IsMemberObjectPointer:
4041 case UTT_IsFunction:
4042 case UTT_IsReference:
4043 case UTT_IsArithmetic:
4044 case UTT_IsFundamental:
4047 case UTT_IsCompound:
4048 case UTT_IsMemberPointer:
4051 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4052 // which requires some of its traits to have the complete type. However,
4053 // the completeness of the type cannot impact these traits' semantics, and
4054 // so they don't require it. This matches the comments on these traits in
4057 case UTT_IsVolatile:
4059 case UTT_IsUnsigned:
4061 // This type trait always returns false, checking the type is moot.
4062 case UTT_IsInterfaceClass:
4065 // C++14 [meta.unary.prop]:
4066 // If T is a non-union class type, T shall be a complete type.
4068 case UTT_IsPolymorphic:
4069 case UTT_IsAbstract:
4070 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4072 return !S.RequireCompleteType(
4073 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4076 // C++14 [meta.unary.prop]:
4077 // If T is a class type, T shall be a complete type.
4080 if (ArgTy->getAsCXXRecordDecl())
4081 return !S.RequireCompleteType(
4082 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4085 // C++1z [meta.unary.prop]:
4086 // remove_all_extents_t<T> shall be a complete type or cv void.
4087 case UTT_IsAggregate:
4089 case UTT_IsTriviallyCopyable:
4090 case UTT_IsStandardLayout:
4093 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4096 // C++1z [meta.unary.prop]:
4097 // T shall be a complete type, cv void, or an array of unknown bound.
4098 case UTT_IsDestructible:
4099 case UTT_IsNothrowDestructible:
4100 case UTT_IsTriviallyDestructible:
4101 // Per the GCC type traits documentation, the same constraints apply to these.
4102 case UTT_HasNothrowAssign:
4103 case UTT_HasNothrowMoveAssign:
4104 case UTT_HasNothrowConstructor:
4105 case UTT_HasNothrowCopy:
4106 case UTT_HasTrivialAssign:
4107 case UTT_HasTrivialMoveAssign:
4108 case UTT_HasTrivialDefaultConstructor:
4109 case UTT_HasTrivialMoveConstructor:
4110 case UTT_HasTrivialCopy:
4111 case UTT_HasTrivialDestructor:
4112 case UTT_HasVirtualDestructor:
4113 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4116 return !S.RequireCompleteType(
4117 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4121 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4122 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4123 bool (CXXRecordDecl::*HasTrivial)() const,
4124 bool (CXXRecordDecl::*HasNonTrivial)() const,
4125 bool (CXXMethodDecl::*IsDesiredOp)() const)
4127 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4128 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4131 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4132 DeclarationNameInfo NameInfo(Name, KeyLoc);
4133 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4134 if (Self.LookupQualifiedName(Res, RD)) {
4135 bool FoundOperator = false;
4136 Res.suppressDiagnostics();
4137 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4138 Op != OpEnd; ++Op) {
4139 if (isa<FunctionTemplateDecl>(*Op))
4142 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4143 if((Operator->*IsDesiredOp)()) {
4144 FoundOperator = true;
4145 const FunctionProtoType *CPT =
4146 Operator->getType()->getAs<FunctionProtoType>();
4147 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4148 if (!CPT || !CPT->isNothrow(C))
4152 return FoundOperator;
4157 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4158 SourceLocation KeyLoc, QualType T) {
4159 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4161 ASTContext &C = Self.Context;
4163 default: llvm_unreachable("not a UTT");
4164 // Type trait expressions corresponding to the primary type category
4165 // predicates in C++0x [meta.unary.cat].
4167 return T->isVoidType();
4168 case UTT_IsIntegral:
4169 return T->isIntegralType(C);
4170 case UTT_IsFloatingPoint:
4171 return T->isFloatingType();
4173 return T->isArrayType();
4175 return T->isPointerType();
4176 case UTT_IsLvalueReference:
4177 return T->isLValueReferenceType();
4178 case UTT_IsRvalueReference:
4179 return T->isRValueReferenceType();
4180 case UTT_IsMemberFunctionPointer:
4181 return T->isMemberFunctionPointerType();
4182 case UTT_IsMemberObjectPointer:
4183 return T->isMemberDataPointerType();
4185 return T->isEnumeralType();
4187 return T->isUnionType();
4189 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4190 case UTT_IsFunction:
4191 return T->isFunctionType();
4193 // Type trait expressions which correspond to the convenient composition
4194 // predicates in C++0x [meta.unary.comp].
4195 case UTT_IsReference:
4196 return T->isReferenceType();
4197 case UTT_IsArithmetic:
4198 return T->isArithmeticType() && !T->isEnumeralType();
4199 case UTT_IsFundamental:
4200 return T->isFundamentalType();
4202 return T->isObjectType();
4204 // Note: semantic analysis depends on Objective-C lifetime types to be
4205 // considered scalar types. However, such types do not actually behave
4206 // like scalar types at run time (since they may require retain/release
4207 // operations), so we report them as non-scalar.
4208 if (T->isObjCLifetimeType()) {
4209 switch (T.getObjCLifetime()) {
4210 case Qualifiers::OCL_None:
4211 case Qualifiers::OCL_ExplicitNone:
4214 case Qualifiers::OCL_Strong:
4215 case Qualifiers::OCL_Weak:
4216 case Qualifiers::OCL_Autoreleasing:
4221 return T->isScalarType();
4222 case UTT_IsCompound:
4223 return T->isCompoundType();
4224 case UTT_IsMemberPointer:
4225 return T->isMemberPointerType();
4227 // Type trait expressions which correspond to the type property predicates
4228 // in C++0x [meta.unary.prop].
4230 return T.isConstQualified();
4231 case UTT_IsVolatile:
4232 return T.isVolatileQualified();
4234 return T.isTrivialType(C);
4235 case UTT_IsTriviallyCopyable:
4236 return T.isTriviallyCopyableType(C);
4237 case UTT_IsStandardLayout:
4238 return T->isStandardLayoutType();
4240 return T.isPODType(C);
4242 return T->isLiteralType(C);
4244 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4245 return !RD->isUnion() && RD->isEmpty();
4247 case UTT_IsPolymorphic:
4248 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4249 return !RD->isUnion() && RD->isPolymorphic();
4251 case UTT_IsAbstract:
4252 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4253 return !RD->isUnion() && RD->isAbstract();
4255 case UTT_IsAggregate:
4256 // Report vector extensions and complex types as aggregates because they
4257 // support aggregate initialization. GCC mirrors this behavior for vectors
4258 // but not _Complex.
4259 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4260 T->isAnyComplexType();
4261 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4262 // even then only when it is used with the 'interface struct ...' syntax
4263 // Clang doesn't support /CLR which makes this type trait moot.
4264 case UTT_IsInterfaceClass:
4268 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4269 return RD->hasAttr<FinalAttr>();
4272 return T->isSignedIntegerType();
4273 case UTT_IsUnsigned:
4274 return T->isUnsignedIntegerType();
4276 // Type trait expressions which query classes regarding their construction,
4277 // destruction, and copying. Rather than being based directly on the
4278 // related type predicates in the standard, they are specified by both
4279 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4282 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4283 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4285 // Note that these builtins do not behave as documented in g++: if a class
4286 // has both a trivial and a non-trivial special member of a particular kind,
4287 // they return false! For now, we emulate this behavior.
4288 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4289 // does not correctly compute triviality in the presence of multiple special
4290 // members of the same kind. Revisit this once the g++ bug is fixed.
4291 case UTT_HasTrivialDefaultConstructor:
4292 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4293 // If __is_pod (type) is true then the trait is true, else if type is
4294 // a cv class or union type (or array thereof) with a trivial default
4295 // constructor ([class.ctor]) then the trait is true, else it is false.
4298 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4299 return RD->hasTrivialDefaultConstructor() &&
4300 !RD->hasNonTrivialDefaultConstructor();
4302 case UTT_HasTrivialMoveConstructor:
4303 // This trait is implemented by MSVC 2012 and needed to parse the
4304 // standard library headers. Specifically this is used as the logic
4305 // behind std::is_trivially_move_constructible (20.9.4.3).
4308 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4309 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4311 case UTT_HasTrivialCopy:
4312 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4313 // If __is_pod (type) is true or type is a reference type then
4314 // the trait is true, else if type is a cv class or union type
4315 // with a trivial copy constructor ([class.copy]) then the trait
4316 // is true, else it is false.
4317 if (T.isPODType(C) || T->isReferenceType())
4319 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4320 return RD->hasTrivialCopyConstructor() &&
4321 !RD->hasNonTrivialCopyConstructor();
4323 case UTT_HasTrivialMoveAssign:
4324 // This trait is implemented by MSVC 2012 and needed to parse the
4325 // standard library headers. Specifically it is used as the logic
4326 // behind std::is_trivially_move_assignable (20.9.4.3)
4329 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4330 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4332 case UTT_HasTrivialAssign:
4333 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4334 // If type is const qualified or is a reference type then the
4335 // trait is false. Otherwise if __is_pod (type) is true then the
4336 // trait is true, else if type is a cv class or union type with
4337 // a trivial copy assignment ([class.copy]) then the trait is
4338 // true, else it is false.
4339 // Note: the const and reference restrictions are interesting,
4340 // given that const and reference members don't prevent a class
4341 // from having a trivial copy assignment operator (but do cause
4342 // errors if the copy assignment operator is actually used, q.v.
4343 // [class.copy]p12).
4345 if (T.isConstQualified())
4349 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4350 return RD->hasTrivialCopyAssignment() &&
4351 !RD->hasNonTrivialCopyAssignment();
4353 case UTT_IsDestructible:
4354 case UTT_IsTriviallyDestructible:
4355 case UTT_IsNothrowDestructible:
4356 // C++14 [meta.unary.prop]:
4357 // For reference types, is_destructible<T>::value is true.
4358 if (T->isReferenceType())
4361 // Objective-C++ ARC: autorelease types don't require destruction.
4362 if (T->isObjCLifetimeType() &&
4363 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4366 // C++14 [meta.unary.prop]:
4367 // For incomplete types and function types, is_destructible<T>::value is
4369 if (T->isIncompleteType() || T->isFunctionType())
4372 // A type that requires destruction (via a non-trivial destructor or ARC
4373 // lifetime semantics) is not trivially-destructible.
4374 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4377 // C++14 [meta.unary.prop]:
4378 // For object types and given U equal to remove_all_extents_t<T>, if the
4379 // expression std::declval<U&>().~U() is well-formed when treated as an
4380 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4381 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4382 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4385 // C++14 [dcl.fct.def.delete]p2:
4386 // A program that refers to a deleted function implicitly or
4387 // explicitly, other than to declare it, is ill-formed.
4388 if (Destructor->isDeleted())
4390 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4392 if (UTT == UTT_IsNothrowDestructible) {
4393 const FunctionProtoType *CPT =
4394 Destructor->getType()->getAs<FunctionProtoType>();
4395 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4396 if (!CPT || !CPT->isNothrow(C))
4402 case UTT_HasTrivialDestructor:
4403 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4404 // If __is_pod (type) is true or type is a reference type
4405 // then the trait is true, else if type is a cv class or union
4406 // type (or array thereof) with a trivial destructor
4407 // ([class.dtor]) then the trait is true, else it is
4409 if (T.isPODType(C) || T->isReferenceType())
4412 // Objective-C++ ARC: autorelease types don't require destruction.
4413 if (T->isObjCLifetimeType() &&
4414 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4417 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4418 return RD->hasTrivialDestructor();
4420 // TODO: Propagate nothrowness for implicitly declared special members.
4421 case UTT_HasNothrowAssign:
4422 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4423 // If type is const qualified or is a reference type then the
4424 // trait is false. Otherwise if __has_trivial_assign (type)
4425 // is true then the trait is true, else if type is a cv class
4426 // or union type with copy assignment operators that are known
4427 // not to throw an exception then the trait is true, else it is
4429 if (C.getBaseElementType(T).isConstQualified())
4431 if (T->isReferenceType())
4433 if (T.isPODType(C) || T->isObjCLifetimeType())
4436 if (const RecordType *RT = T->getAs<RecordType>())
4437 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4438 &CXXRecordDecl::hasTrivialCopyAssignment,
4439 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4440 &CXXMethodDecl::isCopyAssignmentOperator);
4442 case UTT_HasNothrowMoveAssign:
4443 // This trait is implemented by MSVC 2012 and needed to parse the
4444 // standard library headers. Specifically this is used as the logic
4445 // behind std::is_nothrow_move_assignable (20.9.4.3).
4449 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4450 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4451 &CXXRecordDecl::hasTrivialMoveAssignment,
4452 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4453 &CXXMethodDecl::isMoveAssignmentOperator);
4455 case UTT_HasNothrowCopy:
4456 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4457 // If __has_trivial_copy (type) is true then the trait is true, else
4458 // if type is a cv class or union type with copy constructors that are
4459 // known not to throw an exception then the trait is true, else it is
4461 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4463 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4464 if (RD->hasTrivialCopyConstructor() &&
4465 !RD->hasNonTrivialCopyConstructor())
4468 bool FoundConstructor = false;
4470 for (const auto *ND : Self.LookupConstructors(RD)) {
4471 // A template constructor is never a copy constructor.
4472 // FIXME: However, it may actually be selected at the actual overload
4473 // resolution point.
4474 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4476 // UsingDecl itself is not a constructor
4477 if (isa<UsingDecl>(ND))
4479 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4480 if (Constructor->isCopyConstructor(FoundTQs)) {
4481 FoundConstructor = true;
4482 const FunctionProtoType *CPT
4483 = Constructor->getType()->getAs<FunctionProtoType>();
4484 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4487 // TODO: check whether evaluating default arguments can throw.
4488 // For now, we'll be conservative and assume that they can throw.
4489 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
4494 return FoundConstructor;
4497 case UTT_HasNothrowConstructor:
4498 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4499 // If __has_trivial_constructor (type) is true then the trait is
4500 // true, else if type is a cv class or union type (or array
4501 // thereof) with a default constructor that is known not to
4502 // throw an exception then the trait is true, else it is false.
4503 if (T.isPODType(C) || T->isObjCLifetimeType())
4505 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4506 if (RD->hasTrivialDefaultConstructor() &&
4507 !RD->hasNonTrivialDefaultConstructor())
4510 bool FoundConstructor = false;
4511 for (const auto *ND : Self.LookupConstructors(RD)) {
4512 // FIXME: In C++0x, a constructor template can be a default constructor.
4513 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4515 // UsingDecl itself is not a constructor
4516 if (isa<UsingDecl>(ND))
4518 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4519 if (Constructor->isDefaultConstructor()) {
4520 FoundConstructor = true;
4521 const FunctionProtoType *CPT
4522 = Constructor->getType()->getAs<FunctionProtoType>();
4523 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4526 // FIXME: check whether evaluating default arguments can throw.
4527 // For now, we'll be conservative and assume that they can throw.
4528 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
4532 return FoundConstructor;
4535 case UTT_HasVirtualDestructor:
4536 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4537 // If type is a class type with a virtual destructor ([class.dtor])
4538 // then the trait is true, else it is false.
4539 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4540 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4541 return Destructor->isVirtual();
4544 // These type trait expressions are modeled on the specifications for the
4545 // Embarcadero C++0x type trait functions:
4546 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4547 case UTT_IsCompleteType:
4548 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4549 // Returns True if and only if T is a complete type at the point of the
4551 return !T->isIncompleteType();
4555 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4556 QualType RhsT, SourceLocation KeyLoc);
4558 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4559 ArrayRef<TypeSourceInfo *> Args,
4560 SourceLocation RParenLoc) {
4561 if (Kind <= UTT_Last)
4562 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4564 if (Kind <= BTT_Last)
4565 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4566 Args[1]->getType(), RParenLoc);
4569 case clang::TT_IsConstructible:
4570 case clang::TT_IsNothrowConstructible:
4571 case clang::TT_IsTriviallyConstructible: {
4572 // C++11 [meta.unary.prop]:
4573 // is_trivially_constructible is defined as:
4575 // is_constructible<T, Args...>::value is true and the variable
4576 // definition for is_constructible, as defined below, is known to call
4577 // no operation that is not trivial.
4579 // The predicate condition for a template specialization
4580 // is_constructible<T, Args...> shall be satisfied if and only if the
4581 // following variable definition would be well-formed for some invented
4584 // T t(create<Args>()...);
4585 assert(!Args.empty());
4587 // Precondition: T and all types in the parameter pack Args shall be
4588 // complete types, (possibly cv-qualified) void, or arrays of
4590 for (const auto *TSI : Args) {
4591 QualType ArgTy = TSI->getType();
4592 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4595 if (S.RequireCompleteType(KWLoc, ArgTy,
4596 diag::err_incomplete_type_used_in_type_trait_expr))
4600 // Make sure the first argument is not incomplete nor a function type.
4601 QualType T = Args[0]->getType();
4602 if (T->isIncompleteType() || T->isFunctionType())
4605 // Make sure the first argument is not an abstract type.
4606 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4607 if (RD && RD->isAbstract())
4610 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4611 SmallVector<Expr *, 2> ArgExprs;
4612 ArgExprs.reserve(Args.size() - 1);
4613 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4614 QualType ArgTy = Args[I]->getType();
4615 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4616 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4617 OpaqueArgExprs.push_back(
4618 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4619 ArgTy.getNonLValueExprType(S.Context),
4620 Expr::getValueKindForType(ArgTy)));
4622 for (Expr &E : OpaqueArgExprs)
4623 ArgExprs.push_back(&E);
4625 // Perform the initialization in an unevaluated context within a SFINAE
4626 // trap at translation unit scope.
4627 EnterExpressionEvaluationContext Unevaluated(
4628 S, Sema::ExpressionEvaluationContext::Unevaluated);
4629 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4630 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4631 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4632 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4634 InitializationSequence Init(S, To, InitKind, ArgExprs);
4638 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4639 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4642 if (Kind == clang::TT_IsConstructible)
4645 if (Kind == clang::TT_IsNothrowConstructible)
4646 return S.canThrow(Result.get()) == CT_Cannot;
4648 if (Kind == clang::TT_IsTriviallyConstructible) {
4649 // Under Objective-C ARC and Weak, if the destination has non-trivial
4650 // Objective-C lifetime, this is a non-trivial construction.
4651 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
4654 // The initialization succeeded; now make sure there are no non-trivial
4656 return !Result.get()->hasNonTrivialCall(S.Context);
4659 llvm_unreachable("unhandled type trait");
4662 default: llvm_unreachable("not a TT");
4668 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4669 ArrayRef<TypeSourceInfo *> Args,
4670 SourceLocation RParenLoc) {
4671 QualType ResultType = Context.getLogicalOperationType();
4673 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4674 *this, Kind, KWLoc, Args[0]->getType()))
4677 bool Dependent = false;
4678 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4679 if (Args[I]->getType()->isDependentType()) {
4685 bool Result = false;
4687 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4689 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4693 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4694 ArrayRef<ParsedType> Args,
4695 SourceLocation RParenLoc) {
4696 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
4697 ConvertedArgs.reserve(Args.size());
4699 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4700 TypeSourceInfo *TInfo;
4701 QualType T = GetTypeFromParser(Args[I], &TInfo);
4703 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4705 ConvertedArgs.push_back(TInfo);
4708 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4711 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4712 QualType RhsT, SourceLocation KeyLoc) {
4713 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4714 "Cannot evaluate traits of dependent types");
4717 case BTT_IsBaseOf: {
4718 // C++0x [meta.rel]p2
4719 // Base is a base class of Derived without regard to cv-qualifiers or
4720 // Base and Derived are not unions and name the same class type without
4721 // regard to cv-qualifiers.
4723 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4724 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4725 if (!rhsRecord || !lhsRecord) {
4726 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
4727 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
4728 if (!LHSObjTy || !RHSObjTy)
4731 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
4732 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
4733 if (!BaseInterface || !DerivedInterface)
4736 if (Self.RequireCompleteType(
4737 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
4740 return BaseInterface->isSuperClassOf(DerivedInterface);
4743 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4744 == (lhsRecord == rhsRecord));
4746 if (lhsRecord == rhsRecord)
4747 return !lhsRecord->getDecl()->isUnion();
4749 // C++0x [meta.rel]p2:
4750 // If Base and Derived are class types and are different types
4751 // (ignoring possible cv-qualifiers) then Derived shall be a
4753 if (Self.RequireCompleteType(KeyLoc, RhsT,
4754 diag::err_incomplete_type_used_in_type_trait_expr))
4757 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4758 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4761 return Self.Context.hasSameType(LhsT, RhsT);
4762 case BTT_TypeCompatible:
4763 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4764 RhsT.getUnqualifiedType());
4765 case BTT_IsConvertible:
4766 case BTT_IsConvertibleTo: {
4767 // C++0x [meta.rel]p4:
4768 // Given the following function prototype:
4770 // template <class T>
4771 // typename add_rvalue_reference<T>::type create();
4773 // the predicate condition for a template specialization
4774 // is_convertible<From, To> shall be satisfied if and only if
4775 // the return expression in the following code would be
4776 // well-formed, including any implicit conversions to the return
4777 // type of the function:
4780 // return create<From>();
4783 // Access checking is performed as if in a context unrelated to To and
4784 // From. Only the validity of the immediate context of the expression
4785 // of the return-statement (including conversions to the return type)
4788 // We model the initialization as a copy-initialization of a temporary
4789 // of the appropriate type, which for this expression is identical to the
4790 // return statement (since NRVO doesn't apply).
4792 // Functions aren't allowed to return function or array types.
4793 if (RhsT->isFunctionType() || RhsT->isArrayType())
4796 // A return statement in a void function must have void type.
4797 if (RhsT->isVoidType())
4798 return LhsT->isVoidType();
4800 // A function definition requires a complete, non-abstract return type.
4801 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
4804 // Compute the result of add_rvalue_reference.
4805 if (LhsT->isObjectType() || LhsT->isFunctionType())
4806 LhsT = Self.Context.getRValueReferenceType(LhsT);
4808 // Build a fake source and destination for initialization.
4809 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
4810 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4811 Expr::getValueKindForType(LhsT));
4812 Expr *FromPtr = &From;
4813 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
4816 // Perform the initialization in an unevaluated context within a SFINAE
4817 // trap at translation unit scope.
4818 EnterExpressionEvaluationContext Unevaluated(
4819 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4820 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4821 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4822 InitializationSequence Init(Self, To, Kind, FromPtr);
4826 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
4827 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4830 case BTT_IsAssignable:
4831 case BTT_IsNothrowAssignable:
4832 case BTT_IsTriviallyAssignable: {
4833 // C++11 [meta.unary.prop]p3:
4834 // is_trivially_assignable is defined as:
4835 // is_assignable<T, U>::value is true and the assignment, as defined by
4836 // is_assignable, is known to call no operation that is not trivial
4838 // is_assignable is defined as:
4839 // The expression declval<T>() = declval<U>() is well-formed when
4840 // treated as an unevaluated operand (Clause 5).
4842 // For both, T and U shall be complete types, (possibly cv-qualified)
4843 // void, or arrays of unknown bound.
4844 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4845 Self.RequireCompleteType(KeyLoc, LhsT,
4846 diag::err_incomplete_type_used_in_type_trait_expr))
4848 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4849 Self.RequireCompleteType(KeyLoc, RhsT,
4850 diag::err_incomplete_type_used_in_type_trait_expr))
4853 // cv void is never assignable.
4854 if (LhsT->isVoidType() || RhsT->isVoidType())
4857 // Build expressions that emulate the effect of declval<T>() and
4859 if (LhsT->isObjectType() || LhsT->isFunctionType())
4860 LhsT = Self.Context.getRValueReferenceType(LhsT);
4861 if (RhsT->isObjectType() || RhsT->isFunctionType())
4862 RhsT = Self.Context.getRValueReferenceType(RhsT);
4863 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4864 Expr::getValueKindForType(LhsT));
4865 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4866 Expr::getValueKindForType(RhsT));
4868 // Attempt the assignment in an unevaluated context within a SFINAE
4869 // trap at translation unit scope.
4870 EnterExpressionEvaluationContext Unevaluated(
4871 Self, Sema::ExpressionEvaluationContext::Unevaluated);
4872 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4873 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4874 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4876 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4879 if (BTT == BTT_IsAssignable)
4882 if (BTT == BTT_IsNothrowAssignable)
4883 return Self.canThrow(Result.get()) == CT_Cannot;
4885 if (BTT == BTT_IsTriviallyAssignable) {
4886 // Under Objective-C ARC and Weak, if the destination has non-trivial
4887 // Objective-C lifetime, this is a non-trivial assignment.
4888 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
4891 return !Result.get()->hasNonTrivialCall(Self.Context);
4894 llvm_unreachable("unhandled type trait");
4897 default: llvm_unreachable("not a BTT");
4899 llvm_unreachable("Unknown type trait or not implemented");
4902 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4903 SourceLocation KWLoc,
4906 SourceLocation RParen) {
4907 TypeSourceInfo *TSInfo;
4908 QualType T = GetTypeFromParser(Ty, &TSInfo);
4910 TSInfo = Context.getTrivialTypeSourceInfo(T);
4912 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4915 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4916 QualType T, Expr *DimExpr,
4917 SourceLocation KeyLoc) {
4918 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4922 if (T->isArrayType()) {
4924 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4926 T = AT->getElementType();
4932 case ATT_ArrayExtent: {
4935 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
4936 diag::err_dimension_expr_not_constant_integer,
4939 if (Value.isSigned() && Value.isNegative()) {
4940 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4941 << DimExpr->getSourceRange();
4944 Dim = Value.getLimitedValue();
4946 if (T->isArrayType()) {
4948 bool Matched = false;
4949 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4955 T = AT->getElementType();
4958 if (Matched && T->isArrayType()) {
4959 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4960 return CAT->getSize().getLimitedValue();
4966 llvm_unreachable("Unknown type trait or not implemented");
4969 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4970 SourceLocation KWLoc,
4971 TypeSourceInfo *TSInfo,
4973 SourceLocation RParen) {
4974 QualType T = TSInfo->getType();
4976 // FIXME: This should likely be tracked as an APInt to remove any host
4977 // assumptions about the width of size_t on the target.
4979 if (!T->isDependentType())
4980 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4982 // While the specification for these traits from the Embarcadero C++
4983 // compiler's documentation says the return type is 'unsigned int', Clang
4984 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4985 // compiler, there is no difference. On several other platforms this is an
4986 // important distinction.
4987 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4988 RParen, Context.getSizeType());
4991 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4992 SourceLocation KWLoc,
4994 SourceLocation RParen) {
4995 // If error parsing the expression, ignore.
4999 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5004 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5006 case ET_IsLValueExpr: return E->isLValue();
5007 case ET_IsRValueExpr: return E->isRValue();
5009 llvm_unreachable("Expression trait not covered by switch");
5012 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5013 SourceLocation KWLoc,
5015 SourceLocation RParen) {
5016 if (Queried->isTypeDependent()) {
5017 // Delay type-checking for type-dependent expressions.
5018 } else if (Queried->getType()->isPlaceholderType()) {
5019 ExprResult PE = CheckPlaceholderExpr(Queried);
5020 if (PE.isInvalid()) return ExprError();
5021 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5024 bool Value = EvaluateExpressionTrait(ET, Queried);
5026 return new (Context)
5027 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5030 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5034 assert(!LHS.get()->getType()->isPlaceholderType() &&
5035 !RHS.get()->getType()->isPlaceholderType() &&
5036 "placeholders should have been weeded out by now");
5038 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5039 // temporary materialization conversion otherwise.
5041 LHS = DefaultLvalueConversion(LHS.get());
5042 else if (LHS.get()->isRValue())
5043 LHS = TemporaryMaterializationConversion(LHS.get());
5044 if (LHS.isInvalid())
5047 // The RHS always undergoes lvalue conversions.
5048 RHS = DefaultLvalueConversion(RHS.get());
5049 if (RHS.isInvalid()) return QualType();
5051 const char *OpSpelling = isIndirect ? "->*" : ".*";
5053 // The binary operator .* [p3: ->*] binds its second operand, which shall
5054 // be of type "pointer to member of T" (where T is a completely-defined
5055 // class type) [...]
5056 QualType RHSType = RHS.get()->getType();
5057 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5059 Diag(Loc, diag::err_bad_memptr_rhs)
5060 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5064 QualType Class(MemPtr->getClass(), 0);
5066 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5067 // member pointer points must be completely-defined. However, there is no
5068 // reason for this semantic distinction, and the rule is not enforced by
5069 // other compilers. Therefore, we do not check this property, as it is
5070 // likely to be considered a defect.
5073 // [...] to its first operand, which shall be of class T or of a class of
5074 // which T is an unambiguous and accessible base class. [p3: a pointer to
5076 QualType LHSType = LHS.get()->getType();
5078 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5079 LHSType = Ptr->getPointeeType();
5081 Diag(Loc, diag::err_bad_memptr_lhs)
5082 << OpSpelling << 1 << LHSType
5083 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5088 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5089 // If we want to check the hierarchy, we need a complete type.
5090 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5091 OpSpelling, (int)isIndirect)) {
5095 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5096 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5097 << (int)isIndirect << LHS.get()->getType();
5101 CXXCastPath BasePath;
5102 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
5103 SourceRange(LHS.get()->getLocStart(),
5104 RHS.get()->getLocEnd()),
5108 // Cast LHS to type of use.
5109 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5111 UseType = Context.getPointerType(UseType);
5112 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5113 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5117 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5118 // Diagnose use of pointer-to-member type which when used as
5119 // the functional cast in a pointer-to-member expression.
5120 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5125 // The result is an object or a function of the type specified by the
5127 // The cv qualifiers are the union of those in the pointer and the left side,
5128 // in accordance with 5.5p5 and 5.2.5.
5129 QualType Result = MemPtr->getPointeeType();
5130 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5132 // C++0x [expr.mptr.oper]p6:
5133 // In a .* expression whose object expression is an rvalue, the program is
5134 // ill-formed if the second operand is a pointer to member function with
5135 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5136 // expression is an lvalue, the program is ill-formed if the second operand
5137 // is a pointer to member function with ref-qualifier &&.
5138 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5139 switch (Proto->getRefQualifier()) {
5145 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
5146 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5147 << RHSType << 1 << LHS.get()->getSourceRange();
5151 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5152 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5153 << RHSType << 0 << LHS.get()->getSourceRange();
5158 // C++ [expr.mptr.oper]p6:
5159 // The result of a .* expression whose second operand is a pointer
5160 // to a data member is of the same value category as its
5161 // first operand. The result of a .* expression whose second
5162 // operand is a pointer to a member function is a prvalue. The
5163 // result of an ->* expression is an lvalue if its second operand
5164 // is a pointer to data member and a prvalue otherwise.
5165 if (Result->isFunctionType()) {
5167 return Context.BoundMemberTy;
5168 } else if (isIndirect) {
5171 VK = LHS.get()->getValueKind();
5177 /// \brief Try to convert a type to another according to C++11 5.16p3.
5179 /// This is part of the parameter validation for the ? operator. If either
5180 /// value operand is a class type, the two operands are attempted to be
5181 /// converted to each other. This function does the conversion in one direction.
5182 /// It returns true if the program is ill-formed and has already been diagnosed
5184 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5185 SourceLocation QuestionLoc,
5186 bool &HaveConversion,
5188 HaveConversion = false;
5189 ToType = To->getType();
5191 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
5194 // The process for determining whether an operand expression E1 of type T1
5195 // can be converted to match an operand expression E2 of type T2 is defined
5197 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5198 // implicitly converted to type "lvalue reference to T2", subject to the
5199 // constraint that in the conversion the reference must bind directly to
5201 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5202 // implicitly conveted to the type "rvalue reference to R2", subject to
5203 // the constraint that the reference must bind directly.
5204 if (To->isLValue() || To->isXValue()) {
5205 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5206 : Self.Context.getRValueReferenceType(ToType);
5208 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5210 InitializationSequence InitSeq(Self, Entity, Kind, From);
5211 if (InitSeq.isDirectReferenceBinding()) {
5213 HaveConversion = true;
5217 if (InitSeq.isAmbiguous())
5218 return InitSeq.Diagnose(Self, Entity, Kind, From);
5221 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5222 // -- if E1 and E2 have class type, and the underlying class types are
5223 // the same or one is a base class of the other:
5224 QualType FTy = From->getType();
5225 QualType TTy = To->getType();
5226 const RecordType *FRec = FTy->getAs<RecordType>();
5227 const RecordType *TRec = TTy->getAs<RecordType>();
5228 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5229 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5230 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5231 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5232 // E1 can be converted to match E2 if the class of T2 is the
5233 // same type as, or a base class of, the class of T1, and
5235 if (FRec == TRec || FDerivedFromT) {
5236 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5237 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5238 InitializationSequence InitSeq(Self, Entity, Kind, From);
5240 HaveConversion = true;
5244 if (InitSeq.isAmbiguous())
5245 return InitSeq.Diagnose(Self, Entity, Kind, From);
5252 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5253 // implicitly converted to the type that expression E2 would have
5254 // if E2 were converted to an rvalue (or the type it has, if E2 is
5257 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5258 // to the array-to-pointer or function-to-pointer conversions.
5259 TTy = TTy.getNonLValueExprType(Self.Context);
5261 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5262 InitializationSequence InitSeq(Self, Entity, Kind, From);
5263 HaveConversion = !InitSeq.Failed();
5265 if (InitSeq.isAmbiguous())
5266 return InitSeq.Diagnose(Self, Entity, Kind, From);
5271 /// \brief Try to find a common type for two according to C++0x 5.16p5.
5273 /// This is part of the parameter validation for the ? operator. If either
5274 /// value operand is a class type, overload resolution is used to find a
5275 /// conversion to a common type.
5276 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5277 SourceLocation QuestionLoc) {
5278 Expr *Args[2] = { LHS.get(), RHS.get() };
5279 OverloadCandidateSet CandidateSet(QuestionLoc,
5280 OverloadCandidateSet::CSK_Operator);
5281 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5284 OverloadCandidateSet::iterator Best;
5285 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5287 // We found a match. Perform the conversions on the arguments and move on.
5288 ExprResult LHSRes = Self.PerformImplicitConversion(
5289 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5290 Sema::AA_Converting);
5291 if (LHSRes.isInvalid())
5295 ExprResult RHSRes = Self.PerformImplicitConversion(
5296 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5297 Sema::AA_Converting);
5298 if (RHSRes.isInvalid())
5302 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5306 case OR_No_Viable_Function:
5308 // Emit a better diagnostic if one of the expressions is a null pointer
5309 // constant and the other is a pointer type. In this case, the user most
5310 // likely forgot to take the address of the other expression.
5311 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5314 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5315 << LHS.get()->getType() << RHS.get()->getType()
5316 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5320 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5321 << LHS.get()->getType() << RHS.get()->getType()
5322 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5323 // FIXME: Print the possible common types by printing the return types of
5324 // the viable candidates.
5328 llvm_unreachable("Conditional operator has only built-in overloads");
5333 /// \brief Perform an "extended" implicit conversion as returned by
5334 /// TryClassUnification.
5335 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5336 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5337 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
5339 Expr *Arg = E.get();
5340 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5341 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5342 if (Result.isInvalid())
5349 /// \brief Check the operands of ?: under C++ semantics.
5351 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5352 /// extension. In this case, LHS == Cond. (But they're not aliases.)
5353 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5354 ExprResult &RHS, ExprValueKind &VK,
5356 SourceLocation QuestionLoc) {
5357 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5358 // interface pointers.
5360 // C++11 [expr.cond]p1
5361 // The first expression is contextually converted to bool.
5363 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5364 // a is that of a integer vector with the same number of elements and
5365 // size as the vectors of b and c. If one of either b or c is a scalar
5366 // it is implicitly converted to match the type of the vector.
5367 // Otherwise the expression is ill-formed. If both b and c are scalars,
5368 // then b and c are checked and converted to the type of a if possible.
5369 // Unlike the OpenCL ?: operator, the expression is evaluated as
5370 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5371 if (!Cond.get()->isTypeDependent()) {
5372 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5373 if (CondRes.isInvalid())
5382 // Either of the arguments dependent?
5383 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5384 return Context.DependentTy;
5386 // C++11 [expr.cond]p2
5387 // If either the second or the third operand has type (cv) void, ...
5388 QualType LTy = LHS.get()->getType();
5389 QualType RTy = RHS.get()->getType();
5390 bool LVoid = LTy->isVoidType();
5391 bool RVoid = RTy->isVoidType();
5392 if (LVoid || RVoid) {
5393 // ... one of the following shall hold:
5394 // -- The second or the third operand (but not both) is a (possibly
5395 // parenthesized) throw-expression; the result is of the type
5396 // and value category of the other.
5397 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5398 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5399 if (LThrow != RThrow) {
5400 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5401 VK = NonThrow->getValueKind();
5402 // DR (no number yet): the result is a bit-field if the
5403 // non-throw-expression operand is a bit-field.
5404 OK = NonThrow->getObjectKind();
5405 return NonThrow->getType();
5408 // -- Both the second and third operands have type void; the result is of
5409 // type void and is a prvalue.
5411 return Context.VoidTy;
5413 // Neither holds, error.
5414 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5415 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5416 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5422 // C++11 [expr.cond]p3
5423 // Otherwise, if the second and third operand have different types, and
5424 // either has (cv) class type [...] an attempt is made to convert each of
5425 // those operands to the type of the other.
5426 if (!Context.hasSameType(LTy, RTy) &&
5427 (LTy->isRecordType() || RTy->isRecordType())) {
5428 // These return true if a single direction is already ambiguous.
5429 QualType L2RType, R2LType;
5430 bool HaveL2R, HaveR2L;
5431 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5433 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5436 // If both can be converted, [...] the program is ill-formed.
5437 if (HaveL2R && HaveR2L) {
5438 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5439 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5443 // If exactly one conversion is possible, that conversion is applied to
5444 // the chosen operand and the converted operands are used in place of the
5445 // original operands for the remainder of this section.
5447 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5449 LTy = LHS.get()->getType();
5450 } else if (HaveR2L) {
5451 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5453 RTy = RHS.get()->getType();
5457 // C++11 [expr.cond]p3
5458 // if both are glvalues of the same value category and the same type except
5459 // for cv-qualification, an attempt is made to convert each of those
5460 // operands to the type of the other.
5462 // Resolving a defect in P0012R1: we extend this to cover all cases where
5463 // one of the operands is reference-compatible with the other, in order
5464 // to support conditionals between functions differing in noexcept.
5465 ExprValueKind LVK = LHS.get()->getValueKind();
5466 ExprValueKind RVK = RHS.get()->getValueKind();
5467 if (!Context.hasSameType(LTy, RTy) &&
5468 LVK == RVK && LVK != VK_RValue) {
5469 // DerivedToBase was already handled by the class-specific case above.
5470 // FIXME: Should we allow ObjC conversions here?
5471 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5472 if (CompareReferenceRelationship(
5473 QuestionLoc, LTy, RTy, DerivedToBase,
5474 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5475 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5476 // [...] subject to the constraint that the reference must bind
5478 !RHS.get()->refersToBitField() &&
5479 !RHS.get()->refersToVectorElement()) {
5480 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5481 RTy = RHS.get()->getType();
5482 } else if (CompareReferenceRelationship(
5483 QuestionLoc, RTy, LTy, DerivedToBase,
5484 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5485 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5486 !LHS.get()->refersToBitField() &&
5487 !LHS.get()->refersToVectorElement()) {
5488 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5489 LTy = LHS.get()->getType();
5493 // C++11 [expr.cond]p4
5494 // If the second and third operands are glvalues of the same value
5495 // category and have the same type, the result is of that type and
5496 // value category and it is a bit-field if the second or the third
5497 // operand is a bit-field, or if both are bit-fields.
5498 // We only extend this to bitfields, not to the crazy other kinds of
5500 bool Same = Context.hasSameType(LTy, RTy);
5501 if (Same && LVK == RVK && LVK != VK_RValue &&
5502 LHS.get()->isOrdinaryOrBitFieldObject() &&
5503 RHS.get()->isOrdinaryOrBitFieldObject()) {
5504 VK = LHS.get()->getValueKind();
5505 if (LHS.get()->getObjectKind() == OK_BitField ||
5506 RHS.get()->getObjectKind() == OK_BitField)
5509 // If we have function pointer types, unify them anyway to unify their
5510 // exception specifications, if any.
5511 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5512 Qualifiers Qs = LTy.getQualifiers();
5513 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
5514 /*ConvertArgs*/false);
5515 LTy = Context.getQualifiedType(LTy, Qs);
5517 assert(!LTy.isNull() && "failed to find composite pointer type for "
5518 "canonically equivalent function ptr types");
5519 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type");
5525 // C++11 [expr.cond]p5
5526 // Otherwise, the result is a prvalue. If the second and third operands
5527 // do not have the same type, and either has (cv) class type, ...
5528 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5529 // ... overload resolution is used to determine the conversions (if any)
5530 // to be applied to the operands. If the overload resolution fails, the
5531 // program is ill-formed.
5532 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5536 // C++11 [expr.cond]p6
5537 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5538 // conversions are performed on the second and third operands.
5539 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5540 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5541 if (LHS.isInvalid() || RHS.isInvalid())
5543 LTy = LHS.get()->getType();
5544 RTy = RHS.get()->getType();
5546 // After those conversions, one of the following shall hold:
5547 // -- The second and third operands have the same type; the result
5548 // is of that type. If the operands have class type, the result
5549 // is a prvalue temporary of the result type, which is
5550 // copy-initialized from either the second operand or the third
5551 // operand depending on the value of the first operand.
5552 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5553 if (LTy->isRecordType()) {
5554 // The operands have class type. Make a temporary copy.
5555 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5557 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5560 if (LHSCopy.isInvalid())
5563 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5566 if (RHSCopy.isInvalid())
5573 // If we have function pointer types, unify them anyway to unify their
5574 // exception specifications, if any.
5575 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5576 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5577 assert(!LTy.isNull() && "failed to find composite pointer type for "
5578 "canonically equivalent function ptr types");
5584 // Extension: conditional operator involving vector types.
5585 if (LTy->isVectorType() || RTy->isVectorType())
5586 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5587 /*AllowBothBool*/true,
5588 /*AllowBoolConversions*/false);
5590 // -- The second and third operands have arithmetic or enumeration type;
5591 // the usual arithmetic conversions are performed to bring them to a
5592 // common type, and the result is of that type.
5593 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5594 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5595 if (LHS.isInvalid() || RHS.isInvalid())
5597 if (ResTy.isNull()) {
5599 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5600 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5604 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5605 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5610 // -- The second and third operands have pointer type, or one has pointer
5611 // type and the other is a null pointer constant, or both are null
5612 // pointer constants, at least one of which is non-integral; pointer
5613 // conversions and qualification conversions are performed to bring them
5614 // to their composite pointer type. The result is of the composite
5616 // -- The second and third operands have pointer to member type, or one has
5617 // pointer to member type and the other is a null pointer constant;
5618 // pointer to member conversions and qualification conversions are
5619 // performed to bring them to a common type, whose cv-qualification
5620 // shall match the cv-qualification of either the second or the third
5621 // operand. The result is of the common type.
5622 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5623 if (!Composite.isNull())
5626 // Similarly, attempt to find composite type of two objective-c pointers.
5627 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5628 if (!Composite.isNull())
5631 // Check if we are using a null with a non-pointer type.
5632 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5635 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5636 << LHS.get()->getType() << RHS.get()->getType()
5637 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5641 static FunctionProtoType::ExceptionSpecInfo
5642 mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
5643 FunctionProtoType::ExceptionSpecInfo ESI2,
5644 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
5645 ExceptionSpecificationType EST1 = ESI1.Type;
5646 ExceptionSpecificationType EST2 = ESI2.Type;
5648 // If either of them can throw anything, that is the result.
5649 if (EST1 == EST_None) return ESI1;
5650 if (EST2 == EST_None) return ESI2;
5651 if (EST1 == EST_MSAny) return ESI1;
5652 if (EST2 == EST_MSAny) return ESI2;
5654 // If either of them is non-throwing, the result is the other.
5655 if (EST1 == EST_DynamicNone) return ESI2;
5656 if (EST2 == EST_DynamicNone) return ESI1;
5657 if (EST1 == EST_BasicNoexcept) return ESI2;
5658 if (EST2 == EST_BasicNoexcept) return ESI1;
5660 // If either of them is a non-value-dependent computed noexcept, that
5661 // determines the result.
5662 if (EST2 == EST_ComputedNoexcept && ESI2.NoexceptExpr &&
5663 !ESI2.NoexceptExpr->isValueDependent())
5664 return !ESI2.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI2 : ESI1;
5665 if (EST1 == EST_ComputedNoexcept && ESI1.NoexceptExpr &&
5666 !ESI1.NoexceptExpr->isValueDependent())
5667 return !ESI1.NoexceptExpr->EvaluateKnownConstInt(S.Context) ? ESI1 : ESI2;
5668 // If we're left with value-dependent computed noexcept expressions, we're
5669 // stuck. Before C++17, we can just drop the exception specification entirely,
5670 // since it's not actually part of the canonical type. And this should never
5671 // happen in C++17, because it would mean we were computing the composite
5672 // pointer type of dependent types, which should never happen.
5673 if (EST1 == EST_ComputedNoexcept || EST2 == EST_ComputedNoexcept) {
5674 assert(!S.getLangOpts().CPlusPlus1z &&
5675 "computing composite pointer type of dependent types");
5676 return FunctionProtoType::ExceptionSpecInfo();
5679 // Switch over the possibilities so that people adding new values know to
5680 // update this function.
5683 case EST_DynamicNone:
5685 case EST_BasicNoexcept:
5686 case EST_ComputedNoexcept:
5687 llvm_unreachable("handled above");
5690 // This is the fun case: both exception specifications are dynamic. Form
5691 // the union of the two lists.
5692 assert(EST2 == EST_Dynamic && "other cases should already be handled");
5693 llvm::SmallPtrSet<QualType, 8> Found;
5694 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
5695 for (QualType E : Exceptions)
5696 if (Found.insert(S.Context.getCanonicalType(E)).second)
5697 ExceptionTypeStorage.push_back(E);
5699 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
5700 Result.Exceptions = ExceptionTypeStorage;
5704 case EST_Unevaluated:
5705 case EST_Uninstantiated:
5707 llvm_unreachable("shouldn't see unresolved exception specifications here");
5710 llvm_unreachable("invalid ExceptionSpecificationType");
5713 /// \brief Find a merged pointer type and convert the two expressions to it.
5715 /// This finds the composite pointer type (or member pointer type) for @p E1
5716 /// and @p E2 according to C++1z 5p14. It converts both expressions to this
5717 /// type and returns it.
5718 /// It does not emit diagnostics.
5720 /// \param Loc The location of the operator requiring these two expressions to
5721 /// be converted to the composite pointer type.
5723 /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
5724 QualType Sema::FindCompositePointerType(SourceLocation Loc,
5725 Expr *&E1, Expr *&E2,
5727 assert(getLangOpts().CPlusPlus && "This function assumes C++");
5730 // The composite pointer type of two operands p1 and p2 having types T1
5732 QualType T1 = E1->getType(), T2 = E2->getType();
5734 // where at least one is a pointer or pointer to member type or
5735 // std::nullptr_t is:
5736 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
5737 T1->isNullPtrType();
5738 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
5739 T2->isNullPtrType();
5740 if (!T1IsPointerLike && !T2IsPointerLike)
5743 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
5744 // This can't actually happen, following the standard, but we also use this
5745 // to implement the end of [expr.conv], which hits this case.
5747 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
5748 if (T1IsPointerLike &&
5749 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5751 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
5752 ? CK_NullToMemberPointer
5753 : CK_NullToPointer).get();
5756 if (T2IsPointerLike &&
5757 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5759 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
5760 ? CK_NullToMemberPointer
5761 : CK_NullToPointer).get();
5765 // Now both have to be pointers or member pointers.
5766 if (!T1IsPointerLike || !T2IsPointerLike)
5768 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&
5769 "nullptr_t should be a null pointer constant");
5771 // - if T1 or T2 is "pointer to cv1 void" and the other type is
5772 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
5773 // the union of cv1 and cv2;
5774 // - if T1 or T2 is "pointer to noexcept function" and the other type is
5775 // "pointer to function", where the function types are otherwise the same,
5776 // "pointer to function";
5777 // FIXME: This rule is defective: it should also permit removing noexcept
5778 // from a pointer to member function. As a Clang extension, we also
5779 // permit removing 'noreturn', so we generalize this rule to;
5780 // - [Clang] If T1 and T2 are both of type "pointer to function" or
5781 // "pointer to member function" and the pointee types can be unified
5782 // by a function pointer conversion, that conversion is applied
5783 // before checking the following rules.
5784 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
5785 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
5786 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
5788 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
5789 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
5790 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
5791 // T1 or the cv-combined type of T1 and T2, respectively;
5792 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
5795 // If looked at in the right way, these bullets all do the same thing.
5796 // What we do here is, we build the two possible cv-combined types, and try
5797 // the conversions in both directions. If only one works, or if the two
5798 // composite types are the same, we have succeeded.
5799 // FIXME: extended qualifiers?
5801 // Note that this will fail to find a composite pointer type for "pointer
5802 // to void" and "pointer to function". We can't actually perform the final
5803 // conversion in this case, even though a composite pointer type formally
5805 SmallVector<unsigned, 4> QualifierUnion;
5806 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
5807 QualType Composite1 = T1;
5808 QualType Composite2 = T2;
5809 unsigned NeedConstBefore = 0;
5811 const PointerType *Ptr1, *Ptr2;
5812 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5813 (Ptr2 = Composite2->getAs<PointerType>())) {
5814 Composite1 = Ptr1->getPointeeType();
5815 Composite2 = Ptr2->getPointeeType();
5817 // If we're allowed to create a non-standard composite type, keep track
5818 // of where we need to fill in additional 'const' qualifiers.
5819 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5820 NeedConstBefore = QualifierUnion.size();
5822 QualifierUnion.push_back(
5823 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5824 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
5828 const MemberPointerType *MemPtr1, *MemPtr2;
5829 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5830 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5831 Composite1 = MemPtr1->getPointeeType();
5832 Composite2 = MemPtr2->getPointeeType();
5834 // If we're allowed to create a non-standard composite type, keep track
5835 // of where we need to fill in additional 'const' qualifiers.
5836 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5837 NeedConstBefore = QualifierUnion.size();
5839 QualifierUnion.push_back(
5840 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5841 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5842 MemPtr2->getClass()));
5846 // FIXME: block pointer types?
5848 // Cannot unwrap any more types.
5852 // Apply the function pointer conversion to unify the types. We've already
5853 // unwrapped down to the function types, and we want to merge rather than
5854 // just convert, so do this ourselves rather than calling
5855 // IsFunctionConversion.
5857 // FIXME: In order to match the standard wording as closely as possible, we
5858 // currently only do this under a single level of pointers. Ideally, we would
5859 // allow this in general, and set NeedConstBefore to the relevant depth on
5860 // the side(s) where we changed anything.
5861 if (QualifierUnion.size() == 1) {
5862 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
5863 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
5864 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
5865 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
5867 // The result is noreturn if both operands are.
5869 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
5870 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
5871 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
5873 // The result is nothrow if both operands are.
5874 SmallVector<QualType, 8> ExceptionTypeStorage;
5875 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
5876 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
5877 ExceptionTypeStorage);
5879 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
5880 FPT1->getParamTypes(), EPI1);
5881 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
5882 FPT2->getParamTypes(), EPI2);
5887 if (NeedConstBefore) {
5888 // Extension: Add 'const' to qualifiers that come before the first qualifier
5889 // mismatch, so that our (non-standard!) composite type meets the
5890 // requirements of C++ [conv.qual]p4 bullet 3.
5891 for (unsigned I = 0; I != NeedConstBefore; ++I)
5892 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
5893 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5896 // Rewrap the composites as pointers or member pointers with the union CVRs.
5897 auto MOC = MemberOfClass.rbegin();
5898 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
5899 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
5900 auto Classes = *MOC++;
5901 if (Classes.first && Classes.second) {
5902 // Rebuild member pointer type
5903 Composite1 = Context.getMemberPointerType(
5904 Context.getQualifiedType(Composite1, Quals), Classes.first);
5905 Composite2 = Context.getMemberPointerType(
5906 Context.getQualifiedType(Composite2, Quals), Classes.second);
5908 // Rebuild pointer type
5910 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5912 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
5920 InitializedEntity Entity;
5921 InitializationKind Kind;
5922 InitializationSequence E1ToC, E2ToC;
5925 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
5927 : S(S), E1(E1), E2(E2), Composite(Composite),
5928 Entity(InitializedEntity::InitializeTemporary(Composite)),
5929 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
5930 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
5931 Viable(E1ToC && E2ToC) {}
5934 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
5935 if (E1Result.isInvalid())
5937 E1 = E1Result.getAs<Expr>();
5939 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
5940 if (E2Result.isInvalid())
5942 E2 = E2Result.getAs<Expr>();
5948 // Try to convert to each composite pointer type.
5949 Conversion C1(*this, Loc, E1, E2, Composite1);
5950 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
5951 if (ConvertArgs && C1.perform())
5953 return C1.Composite;
5955 Conversion C2(*this, Loc, E1, E2, Composite2);
5957 if (C1.Viable == C2.Viable) {
5958 // Either Composite1 and Composite2 are viable and are different, or
5959 // neither is viable.
5960 // FIXME: How both be viable and different?
5964 // Convert to the chosen type.
5965 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
5968 return C1.Viable ? C1.Composite : C2.Composite;
5971 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
5975 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5977 // If the result is a glvalue, we shouldn't bind it.
5981 // In ARC, calls that return a retainable type can return retained,
5982 // in which case we have to insert a consuming cast.
5983 if (getLangOpts().ObjCAutoRefCount &&
5984 E->getType()->isObjCRetainableType()) {
5986 bool ReturnsRetained;
5988 // For actual calls, we compute this by examining the type of the
5990 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5991 Expr *Callee = Call->getCallee()->IgnoreParens();
5992 QualType T = Callee->getType();
5994 if (T == Context.BoundMemberTy) {
5995 // Handle pointer-to-members.
5996 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5997 T = BinOp->getRHS()->getType();
5998 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5999 T = Mem->getMemberDecl()->getType();
6002 if (const PointerType *Ptr = T->getAs<PointerType>())
6003 T = Ptr->getPointeeType();
6004 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6005 T = Ptr->getPointeeType();
6006 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6007 T = MemPtr->getPointeeType();
6009 const FunctionType *FTy = T->getAs<FunctionType>();
6010 assert(FTy && "call to value not of function type?");
6011 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6013 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6014 // type always produce a +1 object.
6015 } else if (isa<StmtExpr>(E)) {
6016 ReturnsRetained = true;
6018 // We hit this case with the lambda conversion-to-block optimization;
6019 // we don't want any extra casts here.
6020 } else if (isa<CastExpr>(E) &&
6021 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6024 // For message sends and property references, we try to find an
6025 // actual method. FIXME: we should infer retention by selector in
6026 // cases where we don't have an actual method.
6028 ObjCMethodDecl *D = nullptr;
6029 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6030 D = Send->getMethodDecl();
6031 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6032 D = BoxedExpr->getBoxingMethod();
6033 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6034 // Don't do reclaims if we're using the zero-element array
6036 if (ArrayLit->getNumElements() == 0 &&
6037 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6040 D = ArrayLit->getArrayWithObjectsMethod();
6041 } else if (ObjCDictionaryLiteral *DictLit
6042 = dyn_cast<ObjCDictionaryLiteral>(E)) {
6043 // Don't do reclaims if we're using the zero-element dictionary
6045 if (DictLit->getNumElements() == 0 &&
6046 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6049 D = DictLit->getDictWithObjectsMethod();
6052 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6054 // Don't do reclaims on performSelector calls; despite their
6055 // return type, the invoked method doesn't necessarily actually
6056 // return an object.
6057 if (!ReturnsRetained &&
6058 D && D->getMethodFamily() == OMF_performSelector)
6062 // Don't reclaim an object of Class type.
6063 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6066 Cleanup.setExprNeedsCleanups(true);
6068 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6069 : CK_ARCReclaimReturnedObject);
6070 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6074 if (!getLangOpts().CPlusPlus)
6077 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6078 // a fast path for the common case that the type is directly a RecordType.
6079 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6080 const RecordType *RT = nullptr;
6082 switch (T->getTypeClass()) {
6084 RT = cast<RecordType>(T);
6086 case Type::ConstantArray:
6087 case Type::IncompleteArray:
6088 case Type::VariableArray:
6089 case Type::DependentSizedArray:
6090 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6097 // That should be enough to guarantee that this type is complete, if we're
6098 // not processing a decltype expression.
6099 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6100 if (RD->isInvalidDecl() || RD->isDependentContext())
6103 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
6104 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6107 MarkFunctionReferenced(E->getExprLoc(), Destructor);
6108 CheckDestructorAccess(E->getExprLoc(), Destructor,
6109 PDiag(diag::err_access_dtor_temp)
6111 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6114 // If destructor is trivial, we can avoid the extra copy.
6115 if (Destructor->isTrivial())
6118 // We need a cleanup, but we don't need to remember the temporary.
6119 Cleanup.setExprNeedsCleanups(true);
6122 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6123 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6126 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6132 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6133 if (SubExpr.isInvalid())
6136 return MaybeCreateExprWithCleanups(SubExpr.get());
6139 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6140 assert(SubExpr && "subexpression can't be null!");
6142 CleanupVarDeclMarking();
6144 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6145 assert(ExprCleanupObjects.size() >= FirstCleanup);
6146 assert(Cleanup.exprNeedsCleanups() ||
6147 ExprCleanupObjects.size() == FirstCleanup);
6148 if (!Cleanup.exprNeedsCleanups())
6151 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6152 ExprCleanupObjects.size() - FirstCleanup);
6154 auto *E = ExprWithCleanups::Create(
6155 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6156 DiscardCleanupsInEvaluationContext();
6161 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6162 assert(SubStmt && "sub-statement can't be null!");
6164 CleanupVarDeclMarking();
6166 if (!Cleanup.exprNeedsCleanups())
6169 // FIXME: In order to attach the temporaries, wrap the statement into
6170 // a StmtExpr; currently this is only used for asm statements.
6171 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6172 // a new AsmStmtWithTemporaries.
6173 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
6176 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6178 return MaybeCreateExprWithCleanups(E);
6181 /// Process the expression contained within a decltype. For such expressions,
6182 /// certain semantic checks on temporaries are delayed until this point, and
6183 /// are omitted for the 'topmost' call in the decltype expression. If the
6184 /// topmost call bound a temporary, strip that temporary off the expression.
6185 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6186 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
6188 // C++11 [expr.call]p11:
6189 // If a function call is a prvalue of object type,
6190 // -- if the function call is either
6191 // -- the operand of a decltype-specifier, or
6192 // -- the right operand of a comma operator that is the operand of a
6193 // decltype-specifier,
6194 // a temporary object is not introduced for the prvalue.
6196 // Recursively rebuild ParenExprs and comma expressions to strip out the
6197 // outermost CXXBindTemporaryExpr, if any.
6198 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6199 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6200 if (SubExpr.isInvalid())
6202 if (SubExpr.get() == PE->getSubExpr())
6204 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6206 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6207 if (BO->getOpcode() == BO_Comma) {
6208 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6209 if (RHS.isInvalid())
6211 if (RHS.get() == BO->getRHS())
6213 return new (Context) BinaryOperator(
6214 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6215 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6219 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6220 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6227 // Disable the special decltype handling now.
6228 ExprEvalContexts.back().IsDecltype = false;
6230 // In MS mode, don't perform any extra checking of call return types within a
6231 // decltype expression.
6232 if (getLangOpts().MSVCCompat)
6235 // Perform the semantic checks we delayed until this point.
6236 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6238 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6239 if (Call == TopCall)
6242 if (CheckCallReturnType(Call->getCallReturnType(Context),
6243 Call->getLocStart(),
6244 Call, Call->getDirectCallee()))
6248 // Now all relevant types are complete, check the destructors are accessible
6249 // and non-deleted, and annotate them on the temporaries.
6250 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6252 CXXBindTemporaryExpr *Bind =
6253 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6254 if (Bind == TopBind)
6257 CXXTemporary *Temp = Bind->getTemporary();
6260 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6261 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6262 Temp->setDestructor(Destructor);
6264 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6265 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6266 PDiag(diag::err_access_dtor_temp)
6267 << Bind->getType());
6268 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6271 // We need a cleanup, but we don't need to remember the temporary.
6272 Cleanup.setExprNeedsCleanups(true);
6275 // Possibly strip off the top CXXBindTemporaryExpr.
6279 /// Note a set of 'operator->' functions that were used for a member access.
6280 static void noteOperatorArrows(Sema &S,
6281 ArrayRef<FunctionDecl *> OperatorArrows) {
6282 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6283 // FIXME: Make this configurable?
6285 if (OperatorArrows.size() > Limit) {
6286 // Produce Limit-1 normal notes and one 'skipping' note.
6287 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6288 SkipCount = OperatorArrows.size() - (Limit - 1);
6291 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6292 if (I == SkipStart) {
6293 S.Diag(OperatorArrows[I]->getLocation(),
6294 diag::note_operator_arrows_suppressed)
6298 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6299 << OperatorArrows[I]->getCallResultType();
6305 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6306 SourceLocation OpLoc,
6307 tok::TokenKind OpKind,
6308 ParsedType &ObjectType,
6309 bool &MayBePseudoDestructor) {
6310 // Since this might be a postfix expression, get rid of ParenListExprs.
6311 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
6312 if (Result.isInvalid()) return ExprError();
6313 Base = Result.get();
6315 Result = CheckPlaceholderExpr(Base);
6316 if (Result.isInvalid()) return ExprError();
6317 Base = Result.get();
6319 QualType BaseType = Base->getType();
6320 MayBePseudoDestructor = false;
6321 if (BaseType->isDependentType()) {
6322 // If we have a pointer to a dependent type and are using the -> operator,
6323 // the object type is the type that the pointer points to. We might still
6324 // have enough information about that type to do something useful.
6325 if (OpKind == tok::arrow)
6326 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6327 BaseType = Ptr->getPointeeType();
6329 ObjectType = ParsedType::make(BaseType);
6330 MayBePseudoDestructor = true;
6334 // C++ [over.match.oper]p8:
6335 // [...] When operator->returns, the operator-> is applied to the value
6336 // returned, with the original second operand.
6337 if (OpKind == tok::arrow) {
6338 QualType StartingType = BaseType;
6339 bool NoArrowOperatorFound = false;
6340 bool FirstIteration = true;
6341 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6342 // The set of types we've considered so far.
6343 llvm::SmallPtrSet<CanQualType,8> CTypes;
6344 SmallVector<FunctionDecl*, 8> OperatorArrows;
6345 CTypes.insert(Context.getCanonicalType(BaseType));
6347 while (BaseType->isRecordType()) {
6348 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6349 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6350 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6351 noteOperatorArrows(*this, OperatorArrows);
6352 Diag(OpLoc, diag::note_operator_arrow_depth)
6353 << getLangOpts().ArrowDepth;
6357 Result = BuildOverloadedArrowExpr(
6359 // When in a template specialization and on the first loop iteration,
6360 // potentially give the default diagnostic (with the fixit in a
6361 // separate note) instead of having the error reported back to here
6362 // and giving a diagnostic with a fixit attached to the error itself.
6363 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6365 : &NoArrowOperatorFound);
6366 if (Result.isInvalid()) {
6367 if (NoArrowOperatorFound) {
6368 if (FirstIteration) {
6369 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6370 << BaseType << 1 << Base->getSourceRange()
6371 << FixItHint::CreateReplacement(OpLoc, ".");
6372 OpKind = tok::period;
6375 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6376 << BaseType << Base->getSourceRange();
6377 CallExpr *CE = dyn_cast<CallExpr>(Base);
6378 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
6379 Diag(CD->getLocStart(),
6380 diag::note_member_reference_arrow_from_operator_arrow);
6385 Base = Result.get();
6386 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
6387 OperatorArrows.push_back(OpCall->getDirectCallee());
6388 BaseType = Base->getType();
6389 CanQualType CBaseType = Context.getCanonicalType(BaseType);
6390 if (!CTypes.insert(CBaseType).second) {
6391 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6392 noteOperatorArrows(*this, OperatorArrows);
6395 FirstIteration = false;
6398 if (OpKind == tok::arrow &&
6399 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6400 BaseType = BaseType->getPointeeType();
6403 // Objective-C properties allow "." access on Objective-C pointer types,
6404 // so adjust the base type to the object type itself.
6405 if (BaseType->isObjCObjectPointerType())
6406 BaseType = BaseType->getPointeeType();
6408 // C++ [basic.lookup.classref]p2:
6409 // [...] If the type of the object expression is of pointer to scalar
6410 // type, the unqualified-id is looked up in the context of the complete
6411 // postfix-expression.
6413 // This also indicates that we could be parsing a pseudo-destructor-name.
6414 // Note that Objective-C class and object types can be pseudo-destructor
6415 // expressions or normal member (ivar or property) access expressions, and
6416 // it's legal for the type to be incomplete if this is a pseudo-destructor
6417 // call. We'll do more incomplete-type checks later in the lookup process,
6418 // so just skip this check for ObjC types.
6419 if (BaseType->isObjCObjectOrInterfaceType()) {
6420 ObjectType = ParsedType::make(BaseType);
6421 MayBePseudoDestructor = true;
6423 } else if (!BaseType->isRecordType()) {
6424 ObjectType = nullptr;
6425 MayBePseudoDestructor = true;
6429 // The object type must be complete (or dependent), or
6430 // C++11 [expr.prim.general]p3:
6431 // Unlike the object expression in other contexts, *this is not required to
6432 // be of complete type for purposes of class member access (5.2.5) outside
6433 // the member function body.
6434 if (!BaseType->isDependentType() &&
6435 !isThisOutsideMemberFunctionBody(BaseType) &&
6436 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6439 // C++ [basic.lookup.classref]p2:
6440 // If the id-expression in a class member access (5.2.5) is an
6441 // unqualified-id, and the type of the object expression is of a class
6442 // type C (or of pointer to a class type C), the unqualified-id is looked
6443 // up in the scope of class C. [...]
6444 ObjectType = ParsedType::make(BaseType);
6448 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6449 tok::TokenKind& OpKind, SourceLocation OpLoc) {
6450 if (Base->hasPlaceholderType()) {
6451 ExprResult result = S.CheckPlaceholderExpr(Base);
6452 if (result.isInvalid()) return true;
6453 Base = result.get();
6455 ObjectType = Base->getType();
6457 // C++ [expr.pseudo]p2:
6458 // The left-hand side of the dot operator shall be of scalar type. The
6459 // left-hand side of the arrow operator shall be of pointer to scalar type.
6460 // This scalar type is the object type.
6461 // Note that this is rather different from the normal handling for the
6463 if (OpKind == tok::arrow) {
6464 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6465 ObjectType = Ptr->getPointeeType();
6466 } else if (!Base->isTypeDependent()) {
6467 // The user wrote "p->" when they probably meant "p."; fix it.
6468 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6469 << ObjectType << true
6470 << FixItHint::CreateReplacement(OpLoc, ".");
6471 if (S.isSFINAEContext())
6474 OpKind = tok::period;
6481 /// \brief Check if it's ok to try and recover dot pseudo destructor calls on
6482 /// pointer objects.
6484 canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6485 QualType DestructedType) {
6486 // If this is a record type, check if its destructor is callable.
6487 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6488 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6489 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6493 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6494 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6495 DestructedType->isVectorType();
6498 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6499 SourceLocation OpLoc,
6500 tok::TokenKind OpKind,
6501 const CXXScopeSpec &SS,
6502 TypeSourceInfo *ScopeTypeInfo,
6503 SourceLocation CCLoc,
6504 SourceLocation TildeLoc,
6505 PseudoDestructorTypeStorage Destructed) {
6506 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6508 QualType ObjectType;
6509 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6512 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6513 !ObjectType->isVectorType()) {
6514 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6515 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6517 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6518 << ObjectType << Base->getSourceRange();
6523 // C++ [expr.pseudo]p2:
6524 // [...] The cv-unqualified versions of the object type and of the type
6525 // designated by the pseudo-destructor-name shall be the same type.
6526 if (DestructedTypeInfo) {
6527 QualType DestructedType = DestructedTypeInfo->getType();
6528 SourceLocation DestructedTypeStart
6529 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6530 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6531 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6532 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6535 if (OpKind == tok::period && ObjectType->isPointerType() &&
6536 Context.hasSameUnqualifiedType(DestructedType,
6537 ObjectType->getPointeeType())) {
6539 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6540 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
6542 // Issue a fixit only when the destructor is valid.
6543 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6544 *this, DestructedType))
6545 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6547 // Recover by setting the object type to the destructed type and the
6548 // operator to '->'.
6549 ObjectType = DestructedType;
6550 OpKind = tok::arrow;
6552 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6553 << ObjectType << DestructedType << Base->getSourceRange()
6554 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6556 // Recover by setting the destructed type to the object type.
6557 DestructedType = ObjectType;
6558 DestructedTypeInfo =
6559 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6560 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6562 } else if (DestructedType.getObjCLifetime() !=
6563 ObjectType.getObjCLifetime()) {
6565 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6566 // Okay: just pretend that the user provided the correctly-qualified
6569 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6570 << ObjectType << DestructedType << Base->getSourceRange()
6571 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6574 // Recover by setting the destructed type to the object type.
6575 DestructedType = ObjectType;
6576 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6577 DestructedTypeStart);
6578 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6583 // C++ [expr.pseudo]p2:
6584 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6587 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6589 // shall designate the same scalar type.
6590 if (ScopeTypeInfo) {
6591 QualType ScopeType = ScopeTypeInfo->getType();
6592 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6593 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6595 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6596 diag::err_pseudo_dtor_type_mismatch)
6597 << ObjectType << ScopeType << Base->getSourceRange()
6598 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6600 ScopeType = QualType();
6601 ScopeTypeInfo = nullptr;
6606 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6607 OpKind == tok::arrow, OpLoc,
6608 SS.getWithLocInContext(Context),
6617 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6618 SourceLocation OpLoc,
6619 tok::TokenKind OpKind,
6621 UnqualifiedId &FirstTypeName,
6622 SourceLocation CCLoc,
6623 SourceLocation TildeLoc,
6624 UnqualifiedId &SecondTypeName) {
6625 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6626 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6627 "Invalid first type name in pseudo-destructor");
6628 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6629 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6630 "Invalid second type name in pseudo-destructor");
6632 QualType ObjectType;
6633 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6636 // Compute the object type that we should use for name lookup purposes. Only
6637 // record types and dependent types matter.
6638 ParsedType ObjectTypePtrForLookup;
6640 if (ObjectType->isRecordType())
6641 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
6642 else if (ObjectType->isDependentType())
6643 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
6646 // Convert the name of the type being destructed (following the ~) into a
6647 // type (with source-location information).
6648 QualType DestructedType;
6649 TypeSourceInfo *DestructedTypeInfo = nullptr;
6650 PseudoDestructorTypeStorage Destructed;
6651 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6652 ParsedType T = getTypeName(*SecondTypeName.Identifier,
6653 SecondTypeName.StartLocation,
6654 S, &SS, true, false, ObjectTypePtrForLookup,
6655 /*IsCtorOrDtorName*/true);
6657 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6658 (!SS.isSet() && ObjectType->isDependentType()))) {
6659 // The name of the type being destroyed is a dependent name, and we
6660 // couldn't find anything useful in scope. Just store the identifier and
6661 // it's location, and we'll perform (qualified) name lookup again at
6662 // template instantiation time.
6663 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6664 SecondTypeName.StartLocation);
6666 Diag(SecondTypeName.StartLocation,
6667 diag::err_pseudo_dtor_destructor_non_type)
6668 << SecondTypeName.Identifier << ObjectType;
6669 if (isSFINAEContext())
6672 // Recover by assuming we had the right type all along.
6673 DestructedType = ObjectType;
6675 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
6677 // Resolve the template-id to a type.
6678 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
6679 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6680 TemplateId->NumArgs);
6681 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6682 TemplateId->TemplateKWLoc,
6683 TemplateId->Template,
6685 TemplateId->TemplateNameLoc,
6686 TemplateId->LAngleLoc,
6688 TemplateId->RAngleLoc,
6689 /*IsCtorOrDtorName*/true);
6690 if (T.isInvalid() || !T.get()) {
6691 // Recover by assuming we had the right type all along.
6692 DestructedType = ObjectType;
6694 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
6697 // If we've performed some kind of recovery, (re-)build the type source
6699 if (!DestructedType.isNull()) {
6700 if (!DestructedTypeInfo)
6701 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
6702 SecondTypeName.StartLocation);
6703 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6706 // Convert the name of the scope type (the type prior to '::') into a type.
6707 TypeSourceInfo *ScopeTypeInfo = nullptr;
6709 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6710 FirstTypeName.Identifier) {
6711 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6712 ParsedType T = getTypeName(*FirstTypeName.Identifier,
6713 FirstTypeName.StartLocation,
6714 S, &SS, true, false, ObjectTypePtrForLookup,
6715 /*IsCtorOrDtorName*/true);
6717 Diag(FirstTypeName.StartLocation,
6718 diag::err_pseudo_dtor_destructor_non_type)
6719 << FirstTypeName.Identifier << ObjectType;
6721 if (isSFINAEContext())
6724 // Just drop this type. It's unnecessary anyway.
6725 ScopeType = QualType();
6727 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
6729 // Resolve the template-id to a type.
6730 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
6731 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6732 TemplateId->NumArgs);
6733 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6734 TemplateId->TemplateKWLoc,
6735 TemplateId->Template,
6737 TemplateId->TemplateNameLoc,
6738 TemplateId->LAngleLoc,
6740 TemplateId->RAngleLoc,
6741 /*IsCtorOrDtorName*/true);
6742 if (T.isInvalid() || !T.get()) {
6743 // Recover by dropping this type.
6744 ScopeType = QualType();
6746 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
6750 if (!ScopeType.isNull() && !ScopeTypeInfo)
6751 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6752 FirstTypeName.StartLocation);
6755 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
6756 ScopeTypeInfo, CCLoc, TildeLoc,
6760 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6761 SourceLocation OpLoc,
6762 tok::TokenKind OpKind,
6763 SourceLocation TildeLoc,
6764 const DeclSpec& DS) {
6765 QualType ObjectType;
6766 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6769 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6773 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6774 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6775 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6776 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6778 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
6779 nullptr, SourceLocation(), TildeLoc,
6783 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
6784 CXXConversionDecl *Method,
6785 bool HadMultipleCandidates) {
6786 if (Method->getParent()->isLambda() &&
6787 Method->getConversionType()->isBlockPointerType()) {
6788 // This is a lambda coversion to block pointer; check if the argument
6791 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6792 if (CE && CE->getCastKind() == CK_NoOp)
6793 SubE = CE->getSubExpr();
6794 SubE = SubE->IgnoreParens();
6795 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6796 SubE = BE->getSubExpr();
6797 if (isa<LambdaExpr>(SubE)) {
6798 // For the conversion to block pointer on a lambda expression, we
6799 // construct a special BlockLiteral instead; this doesn't really make
6800 // a difference in ARC, but outside of ARC the resulting block literal
6801 // follows the normal lifetime rules for block literals instead of being
6803 DiagnosticErrorTrap Trap(Diags);
6804 PushExpressionEvaluationContext(
6805 ExpressionEvaluationContext::PotentiallyEvaluated);
6806 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6809 PopExpressionEvaluationContext();
6811 if (Exp.isInvalid())
6812 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6817 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
6819 if (Exp.isInvalid())
6822 MemberExpr *ME = new (Context) MemberExpr(
6823 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6824 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
6825 if (HadMultipleCandidates)
6826 ME->setHadMultipleCandidates(true);
6827 MarkMemberReferenced(ME);
6829 QualType ResultType = Method->getReturnType();
6830 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6831 ResultType = ResultType.getNonLValueExprType(Context);
6833 CXXMemberCallExpr *CE =
6834 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
6835 Exp.get()->getLocEnd());
6837 if (CheckFunctionCall(Method, CE,
6838 Method->getType()->castAs<FunctionProtoType>()))
6844 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6845 SourceLocation RParen) {
6846 // If the operand is an unresolved lookup expression, the expression is ill-
6847 // formed per [over.over]p1, because overloaded function names cannot be used
6848 // without arguments except in explicit contexts.
6849 ExprResult R = CheckPlaceholderExpr(Operand);
6853 // The operand may have been modified when checking the placeholder type.
6856 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
6857 // The expression operand for noexcept is in an unevaluated expression
6858 // context, so side effects could result in unintended consequences.
6859 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6862 CanThrowResult CanThrow = canThrow(Operand);
6863 return new (Context)
6864 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
6867 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6868 Expr *Operand, SourceLocation RParen) {
6869 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
6872 static bool IsSpecialDiscardedValue(Expr *E) {
6873 // In C++11, discarded-value expressions of a certain form are special,
6874 // according to [expr]p10:
6875 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6876 // expression is an lvalue of volatile-qualified type and it has
6877 // one of the following forms:
6878 E = E->IgnoreParens();
6880 // - id-expression (5.1.1),
6881 if (isa<DeclRefExpr>(E))
6884 // - subscripting (5.2.1),
6885 if (isa<ArraySubscriptExpr>(E))
6888 // - class member access (5.2.5),
6889 if (isa<MemberExpr>(E))
6892 // - indirection (5.3.1),
6893 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6894 if (UO->getOpcode() == UO_Deref)
6897 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6898 // - pointer-to-member operation (5.5),
6899 if (BO->isPtrMemOp())
6902 // - comma expression (5.18) where the right operand is one of the above.
6903 if (BO->getOpcode() == BO_Comma)
6904 return IsSpecialDiscardedValue(BO->getRHS());
6907 // - conditional expression (5.16) where both the second and the third
6908 // operands are one of the above, or
6909 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6910 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6911 IsSpecialDiscardedValue(CO->getFalseExpr());
6912 // The related edge case of "*x ?: *x".
6913 if (BinaryConditionalOperator *BCO =
6914 dyn_cast<BinaryConditionalOperator>(E)) {
6915 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6916 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6917 IsSpecialDiscardedValue(BCO->getFalseExpr());
6920 // Objective-C++ extensions to the rule.
6921 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6927 /// Perform the conversions required for an expression used in a
6928 /// context that ignores the result.
6929 ExprResult Sema::IgnoredValueConversions(Expr *E) {
6930 if (E->hasPlaceholderType()) {
6931 ExprResult result = CheckPlaceholderExpr(E);
6932 if (result.isInvalid()) return E;
6937 // [Except in specific positions,] an lvalue that does not have
6938 // array type is converted to the value stored in the
6939 // designated object (and is no longer an lvalue).
6940 if (E->isRValue()) {
6941 // In C, function designators (i.e. expressions of function type)
6942 // are r-values, but we still want to do function-to-pointer decay
6943 // on them. This is both technically correct and convenient for
6945 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
6946 return DefaultFunctionArrayConversion(E);
6951 if (getLangOpts().CPlusPlus) {
6952 // The C++11 standard defines the notion of a discarded-value expression;
6953 // normally, we don't need to do anything to handle it, but if it is a
6954 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6956 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
6957 E->getType().isVolatileQualified() &&
6958 IsSpecialDiscardedValue(E)) {
6959 ExprResult Res = DefaultLvalueConversion(E);
6960 if (Res.isInvalid())
6966 // If the expression is a prvalue after this optional conversion, the
6967 // temporary materialization conversion is applied.
6969 // We skip this step: IR generation is able to synthesize the storage for
6970 // itself in the aggregate case, and adding the extra node to the AST is
6972 // FIXME: We don't emit lifetime markers for the temporaries due to this.
6973 // FIXME: Do any other AST consumers care about this?
6977 // GCC seems to also exclude expressions of incomplete enum type.
6978 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6979 if (!T->getDecl()->isComplete()) {
6980 // FIXME: stupid workaround for a codegen bug!
6981 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
6986 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6987 if (Res.isInvalid())
6991 if (!E->getType()->isVoidType())
6992 RequireCompleteType(E->getExprLoc(), E->getType(),
6993 diag::err_incomplete_type);
6997 // If we can unambiguously determine whether Var can never be used
6998 // in a constant expression, return true.
6999 // - if the variable and its initializer are non-dependent, then
7000 // we can unambiguously check if the variable is a constant expression.
7001 // - if the initializer is not value dependent - we can determine whether
7002 // it can be used to initialize a constant expression. If Init can not
7003 // be used to initialize a constant expression we conclude that Var can
7004 // never be a constant expression.
7005 // - FXIME: if the initializer is dependent, we can still do some analysis and
7006 // identify certain cases unambiguously as non-const by using a Visitor:
7007 // - such as those that involve odr-use of a ParmVarDecl, involve a new
7008 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7009 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7010 ASTContext &Context) {
7011 if (isa<ParmVarDecl>(Var)) return true;
7012 const VarDecl *DefVD = nullptr;
7014 // If there is no initializer - this can not be a constant expression.
7015 if (!Var->getAnyInitializer(DefVD)) return true;
7017 if (DefVD->isWeak()) return false;
7018 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7020 Expr *Init = cast<Expr>(Eval->Value);
7022 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7023 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7024 // of value-dependent expressions, and use it here to determine whether the
7025 // initializer is a potential constant expression.
7029 return !IsVariableAConstantExpression(Var, Context);
7032 /// \brief Check if the current lambda has any potential captures
7033 /// that must be captured by any of its enclosing lambdas that are ready to
7034 /// capture. If there is a lambda that can capture a nested
7035 /// potential-capture, go ahead and do so. Also, check to see if any
7036 /// variables are uncaptureable or do not involve an odr-use so do not
7037 /// need to be captured.
7039 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7040 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7042 assert(!S.isUnevaluatedContext());
7043 assert(S.CurContext->isDependentContext());
7045 DeclContext *DC = S.CurContext;
7046 while (DC && isa<CapturedDecl>(DC))
7047 DC = DC->getParent();
7049 CurrentLSI->CallOperator == DC &&
7050 "The current call operator must be synchronized with Sema's CurContext");
7053 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7055 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
7056 S.FunctionScopes.data(), S.FunctionScopes.size());
7058 // All the potentially captureable variables in the current nested
7059 // lambda (within a generic outer lambda), must be captured by an
7060 // outer lambda that is enclosed within a non-dependent context.
7061 const unsigned NumPotentialCaptures =
7062 CurrentLSI->getNumPotentialVariableCaptures();
7063 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
7064 Expr *VarExpr = nullptr;
7065 VarDecl *Var = nullptr;
7066 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
7067 // If the variable is clearly identified as non-odr-used and the full
7068 // expression is not instantiation dependent, only then do we not
7069 // need to check enclosing lambda's for speculative captures.
7071 // Even though 'x' is not odr-used, it should be captured.
7073 // const int x = 10;
7074 // auto L = [=](auto a) {
7078 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7079 !IsFullExprInstantiationDependent)
7082 // If we have a capture-capable lambda for the variable, go ahead and
7083 // capture the variable in that lambda (and all its enclosing lambdas).
7084 if (const Optional<unsigned> Index =
7085 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7086 FunctionScopesArrayRef, Var, S)) {
7087 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7088 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
7089 &FunctionScopeIndexOfCapturableLambda);
7091 const bool IsVarNeverAConstantExpression =
7092 VariableCanNeverBeAConstantExpression(Var, S.Context);
7093 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7094 // This full expression is not instantiation dependent or the variable
7095 // can not be used in a constant expression - which means
7096 // this variable must be odr-used here, so diagnose a
7097 // capture violation early, if the variable is un-captureable.
7098 // This is purely for diagnosing errors early. Otherwise, this
7099 // error would get diagnosed when the lambda becomes capture ready.
7100 QualType CaptureType, DeclRefType;
7101 SourceLocation ExprLoc = VarExpr->getExprLoc();
7102 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7103 /*EllipsisLoc*/ SourceLocation(),
7104 /*BuildAndDiagnose*/false, CaptureType,
7105 DeclRefType, nullptr)) {
7106 // We will never be able to capture this variable, and we need
7107 // to be able to in any and all instantiations, so diagnose it.
7108 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7109 /*EllipsisLoc*/ SourceLocation(),
7110 /*BuildAndDiagnose*/true, CaptureType,
7111 DeclRefType, nullptr);
7116 // Check if 'this' needs to be captured.
7117 if (CurrentLSI->hasPotentialThisCapture()) {
7118 // If we have a capture-capable lambda for 'this', go ahead and capture
7119 // 'this' in that lambda (and all its enclosing lambdas).
7120 if (const Optional<unsigned> Index =
7121 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7122 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
7123 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7124 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7125 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7126 &FunctionScopeIndexOfCapturableLambda);
7130 // Reset all the potential captures at the end of each full-expression.
7131 CurrentLSI->clearPotentialCaptures();
7134 static ExprResult attemptRecovery(Sema &SemaRef,
7135 const TypoCorrectionConsumer &Consumer,
7136 const TypoCorrection &TC) {
7137 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7138 Consumer.getLookupResult().getLookupKind());
7139 const CXXScopeSpec *SS = Consumer.getSS();
7142 // Use an approprate CXXScopeSpec for building the expr.
7143 if (auto *NNS = TC.getCorrectionSpecifier())
7144 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7145 else if (SS && !TC.WillReplaceSpecifier())
7148 if (auto *ND = TC.getFoundDecl()) {
7149 R.setLookupName(ND->getDeclName());
7151 if (ND->isCXXClassMember()) {
7152 // Figure out the correct naming class to add to the LookupResult.
7153 CXXRecordDecl *Record = nullptr;
7154 if (auto *NNS = TC.getCorrectionSpecifier())
7155 Record = NNS->getAsType()->getAsCXXRecordDecl();
7158 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7160 R.setNamingClass(Record);
7162 // Detect and handle the case where the decl might be an implicit
7164 bool MightBeImplicitMember;
7165 if (!Consumer.isAddressOfOperand())
7166 MightBeImplicitMember = true;
7167 else if (!NewSS.isEmpty())
7168 MightBeImplicitMember = false;
7169 else if (R.isOverloadedResult())
7170 MightBeImplicitMember = false;
7171 else if (R.isUnresolvableResult())
7172 MightBeImplicitMember = true;
7174 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7175 isa<IndirectFieldDecl>(ND) ||
7176 isa<MSPropertyDecl>(ND);
7178 if (MightBeImplicitMember)
7179 return SemaRef.BuildPossibleImplicitMemberExpr(
7180 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7181 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7182 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7183 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7184 Ivar->getIdentifier());
7188 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7189 /*AcceptInvalidDecl*/ true);
7193 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7194 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7197 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7198 : TypoExprs(TypoExprs) {}
7199 bool VisitTypoExpr(TypoExpr *TE) {
7200 TypoExprs.insert(TE);
7205 class TransformTypos : public TreeTransform<TransformTypos> {
7206 typedef TreeTransform<TransformTypos> BaseTransform;
7208 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7209 // process of being initialized.
7210 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7211 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7212 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7213 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7215 /// \brief Emit diagnostics for all of the TypoExprs encountered.
7216 /// If the TypoExprs were successfully corrected, then the diagnostics should
7217 /// suggest the corrections. Otherwise the diagnostics will not suggest
7218 /// anything (having been passed an empty TypoCorrection).
7219 void EmitAllDiagnostics() {
7220 for (auto E : TypoExprs) {
7221 TypoExpr *TE = cast<TypoExpr>(E);
7222 auto &State = SemaRef.getTypoExprState(TE);
7223 if (State.DiagHandler) {
7224 TypoCorrection TC = State.Consumer->getCurrentCorrection();
7225 ExprResult Replacement = TransformCache[TE];
7227 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7228 // TypoCorrection, replacing the existing decls. This ensures the right
7229 // NamedDecl is used in diagnostics e.g. in the case where overload
7230 // resolution was used to select one from several possible decls that
7231 // had been stored in the TypoCorrection.
7232 if (auto *ND = getDeclFromExpr(
7233 Replacement.isInvalid() ? nullptr : Replacement.get()))
7234 TC.setCorrectionDecl(ND);
7236 State.DiagHandler(TC);
7238 SemaRef.clearDelayedTypo(TE);
7242 /// \brief If corrections for the first TypoExpr have been exhausted for a
7243 /// given combination of the other TypoExprs, retry those corrections against
7244 /// the next combination of substitutions for the other TypoExprs by advancing
7245 /// to the next potential correction of the second TypoExpr. For the second
7246 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7247 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7248 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7249 /// TransformCache). Returns true if there is still any untried combinations
7251 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7252 for (auto TE : TypoExprs) {
7253 auto &State = SemaRef.getTypoExprState(TE);
7254 TransformCache.erase(TE);
7255 if (!State.Consumer->finished())
7257 State.Consumer->resetCorrectionStream();
7262 NamedDecl *getDeclFromExpr(Expr *E) {
7263 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7264 E = OverloadResolution[OE];
7268 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7269 return DRE->getFoundDecl();
7270 if (auto *ME = dyn_cast<MemberExpr>(E))
7271 return ME->getFoundDecl();
7272 // FIXME: Add any other expr types that could be be seen by the delayed typo
7273 // correction TreeTransform for which the corresponding TypoCorrection could
7274 // contain multiple decls.
7278 ExprResult TryTransform(Expr *E) {
7279 Sema::SFINAETrap Trap(SemaRef);
7280 ExprResult Res = TransformExpr(E);
7281 if (Trap.hasErrorOccurred() || Res.isInvalid())
7284 return ExprFilter(Res.get());
7288 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7289 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
7291 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7293 SourceLocation RParenLoc,
7294 Expr *ExecConfig = nullptr) {
7295 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7296 RParenLoc, ExecConfig);
7297 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
7298 if (Result.isUsable()) {
7299 Expr *ResultCall = Result.get();
7300 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7301 ResultCall = BE->getSubExpr();
7302 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7303 OverloadResolution[OE] = CE->getCallee();
7309 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7311 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7313 ExprResult Transform(Expr *E) {
7316 Res = TryTransform(E);
7318 // Exit if either the transform was valid or if there were no TypoExprs
7319 // to transform that still have any untried correction candidates..
7320 if (!Res.isInvalid() ||
7321 !CheckAndAdvanceTypoExprCorrectionStreams())
7325 // Ensure none of the TypoExprs have multiple typo correction candidates
7326 // with the same edit length that pass all the checks and filters.
7327 // TODO: Properly handle various permutations of possible corrections when
7328 // there is more than one potentially ambiguous typo correction.
7329 // Also, disable typo correction while attempting the transform when
7330 // handling potentially ambiguous typo corrections as any new TypoExprs will
7331 // have been introduced by the application of one of the correction
7332 // candidates and add little to no value if corrected.
7333 SemaRef.DisableTypoCorrection = true;
7334 while (!AmbiguousTypoExprs.empty()) {
7335 auto TE = AmbiguousTypoExprs.back();
7336 auto Cached = TransformCache[TE];
7337 auto &State = SemaRef.getTypoExprState(TE);
7338 State.Consumer->saveCurrentPosition();
7339 TransformCache.erase(TE);
7340 if (!TryTransform(E).isInvalid()) {
7341 State.Consumer->resetCorrectionStream();
7342 TransformCache.erase(TE);
7346 AmbiguousTypoExprs.remove(TE);
7347 State.Consumer->restoreSavedPosition();
7348 TransformCache[TE] = Cached;
7350 SemaRef.DisableTypoCorrection = false;
7352 // Ensure that all of the TypoExprs within the current Expr have been found.
7353 if (!Res.isUsable())
7354 FindTypoExprs(TypoExprs).TraverseStmt(E);
7356 EmitAllDiagnostics();
7361 ExprResult TransformTypoExpr(TypoExpr *E) {
7362 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7363 // cached transformation result if there is one and the TypoExpr isn't the
7364 // first one that was encountered.
7365 auto &CacheEntry = TransformCache[E];
7366 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7370 auto &State = SemaRef.getTypoExprState(E);
7371 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
7373 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7374 // typo correction and return it.
7375 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
7376 if (InitDecl && TC.getFoundDecl() == InitDecl)
7378 // FIXME: If we would typo-correct to an invalid declaration, it's
7379 // probably best to just suppress all errors from this typo correction.
7380 ExprResult NE = State.RecoveryHandler ?
7381 State.RecoveryHandler(SemaRef, E, TC) :
7382 attemptRecovery(SemaRef, *State.Consumer, TC);
7383 if (!NE.isInvalid()) {
7384 // Check whether there may be a second viable correction with the same
7385 // edit distance; if so, remember this TypoExpr may have an ambiguous
7386 // correction so it can be more thoroughly vetted later.
7387 TypoCorrection Next;
7388 if ((Next = State.Consumer->peekNextCorrection()) &&
7389 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7390 AmbiguousTypoExprs.insert(E);
7392 AmbiguousTypoExprs.remove(E);
7394 assert(!NE.isUnset() &&
7395 "Typo was transformed into a valid-but-null ExprResult");
7396 return CacheEntry = NE;
7399 return CacheEntry = ExprError();
7405 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7406 llvm::function_ref<ExprResult(Expr *)> Filter) {
7407 // If the current evaluation context indicates there are uncorrected typos
7408 // and the current expression isn't guaranteed to not have typos, try to
7409 // resolve any TypoExpr nodes that might be in the expression.
7410 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
7411 (E->isTypeDependent() || E->isValueDependent() ||
7412 E->isInstantiationDependent())) {
7413 auto TyposInContext = ExprEvalContexts.back().NumTypos;
7414 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
7415 ExprEvalContexts.back().NumTypos = ~0U;
7416 auto TyposResolved = DelayedTypos.size();
7417 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
7418 ExprEvalContexts.back().NumTypos = TyposInContext;
7419 TyposResolved -= DelayedTypos.size();
7420 if (Result.isInvalid() || Result.get() != E) {
7421 ExprEvalContexts.back().NumTypos -= TyposResolved;
7424 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
7429 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
7430 bool DiscardedValue,
7432 bool IsLambdaInitCaptureInitializer) {
7433 ExprResult FullExpr = FE;
7435 if (!FullExpr.get())
7438 // If we are an init-expression in a lambdas init-capture, we should not
7439 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
7440 // containing full-expression is done).
7441 // template<class ... Ts> void test(Ts ... t) {
7442 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
7446 // FIXME: This is a hack. It would be better if we pushed the lambda scope
7447 // when we parse the lambda introducer, and teach capturing (but not
7448 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
7449 // corresponding class yet (that is, have LambdaScopeInfo either represent a
7450 // lambda where we've entered the introducer but not the body, or represent a
7451 // lambda where we've entered the body, depending on where the
7452 // parser/instantiation has got to).
7453 if (!IsLambdaInitCaptureInitializer &&
7454 DiagnoseUnexpandedParameterPack(FullExpr.get()))
7457 // Top-level expressions default to 'id' when we're in a debugger.
7458 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
7459 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7460 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7461 if (FullExpr.isInvalid())
7465 if (DiscardedValue) {
7466 FullExpr = CheckPlaceholderExpr(FullExpr.get());
7467 if (FullExpr.isInvalid())
7470 FullExpr = IgnoredValueConversions(FullExpr.get());
7471 if (FullExpr.isInvalid())
7475 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7476 if (FullExpr.isInvalid())
7479 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7481 // At the end of this full expression (which could be a deeply nested
7482 // lambda), if there is a potential capture within the nested lambda,
7483 // have the outer capture-able lambda try and capture it.
7484 // Consider the following code:
7485 // void f(int, int);
7486 // void f(const int&, double);
7488 // const int x = 10, y = 20;
7489 // auto L = [=](auto a) {
7490 // auto M = [=](auto b) {
7491 // f(x, b); <-- requires x to be captured by L and M
7492 // f(y, a); <-- requires y to be captured by L, but not all Ms
7497 // FIXME: Also consider what happens for something like this that involves
7498 // the gnu-extension statement-expressions or even lambda-init-captures:
7501 // auto L = [&](auto a) {
7502 // +n + ({ 0; a; });
7506 // Here, we see +n, and then the full-expression 0; ends, so we don't
7507 // capture n (and instead remove it from our list of potential captures),
7508 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7509 // for us to see that we need to capture n after all.
7511 LambdaScopeInfo *const CurrentLSI =
7512 getCurLambda(/*IgnoreCapturedRegions=*/true);
7513 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7514 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7515 // for an example of the code that might cause this asynchrony.
7516 // By ensuring we are in the context of a lambda's call operator
7517 // we can fix the bug (we only need to check whether we need to capture
7518 // if we are within a lambda's body); but per the comments in that
7519 // PR, a proper fix would entail :
7520 // "Alternative suggestion:
7521 // - Add to Sema an integer holding the smallest (outermost) scope
7522 // index that we are *lexically* within, and save/restore/set to
7523 // FunctionScopes.size() in InstantiatingTemplate's
7524 // constructor/destructor.
7525 // - Teach the handful of places that iterate over FunctionScopes to
7526 // stop at the outermost enclosing lexical scope."
7527 DeclContext *DC = CurContext;
7528 while (DC && isa<CapturedDecl>(DC))
7529 DC = DC->getParent();
7530 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7531 if (IsInLambdaDeclContext && CurrentLSI &&
7532 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7533 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7535 return MaybeCreateExprWithCleanups(FullExpr);
7538 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7539 if (!FullStmt) return StmtError();
7541 return MaybeCreateStmtWithCleanups(FullStmt);
7544 Sema::IfExistsResult
7545 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7547 const DeclarationNameInfo &TargetNameInfo) {
7548 DeclarationName TargetName = TargetNameInfo.getName();
7550 return IER_DoesNotExist;
7552 // If the name itself is dependent, then the result is dependent.
7553 if (TargetName.isDependentName())
7554 return IER_Dependent;
7556 // Do the redeclaration lookup in the current scope.
7557 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7558 Sema::NotForRedeclaration);
7559 LookupParsedName(R, S, &SS);
7560 R.suppressDiagnostics();
7562 switch (R.getResultKind()) {
7563 case LookupResult::Found:
7564 case LookupResult::FoundOverloaded:
7565 case LookupResult::FoundUnresolvedValue:
7566 case LookupResult::Ambiguous:
7569 case LookupResult::NotFound:
7570 return IER_DoesNotExist;
7572 case LookupResult::NotFoundInCurrentInstantiation:
7573 return IER_Dependent;
7576 llvm_unreachable("Invalid LookupResult Kind!");
7579 Sema::IfExistsResult
7580 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7581 bool IsIfExists, CXXScopeSpec &SS,
7582 UnqualifiedId &Name) {
7583 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7585 // Check for an unexpanded parameter pack.
7586 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
7587 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
7588 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
7591 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);