10b57cec5SDimitry Andric //===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric /// 90b57cec5SDimitry Andric /// \file 100b57cec5SDimitry Andric /// Implements semantic analysis for C++ expressions. 110b57cec5SDimitry Andric /// 120b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 130b57cec5SDimitry Andric 1455e4f9d5SDimitry Andric #include "clang/Sema/Template.h" 150b57cec5SDimitry Andric #include "clang/Sema/SemaInternal.h" 160b57cec5SDimitry Andric #include "TreeTransform.h" 170b57cec5SDimitry Andric #include "TypeLocBuilder.h" 180b57cec5SDimitry Andric #include "clang/AST/ASTContext.h" 190b57cec5SDimitry Andric #include "clang/AST/ASTLambda.h" 200b57cec5SDimitry Andric #include "clang/AST/CXXInheritance.h" 210b57cec5SDimitry Andric #include "clang/AST/CharUnits.h" 220b57cec5SDimitry Andric #include "clang/AST/DeclObjC.h" 230b57cec5SDimitry Andric #include "clang/AST/ExprCXX.h" 240b57cec5SDimitry Andric #include "clang/AST/ExprObjC.h" 250b57cec5SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h" 260b57cec5SDimitry Andric #include "clang/AST/TypeLoc.h" 270b57cec5SDimitry Andric #include "clang/Basic/AlignedAllocation.h" 280b57cec5SDimitry Andric #include "clang/Basic/PartialDiagnostic.h" 290b57cec5SDimitry Andric #include "clang/Basic/TargetInfo.h" 300b57cec5SDimitry Andric #include "clang/Lex/Preprocessor.h" 310b57cec5SDimitry Andric #include "clang/Sema/DeclSpec.h" 320b57cec5SDimitry Andric #include "clang/Sema/Initialization.h" 330b57cec5SDimitry Andric #include "clang/Sema/Lookup.h" 340b57cec5SDimitry Andric #include "clang/Sema/ParsedTemplate.h" 350b57cec5SDimitry Andric #include "clang/Sema/Scope.h" 360b57cec5SDimitry Andric #include "clang/Sema/ScopeInfo.h" 370b57cec5SDimitry Andric #include "clang/Sema/SemaLambda.h" 380b57cec5SDimitry Andric #include "clang/Sema/TemplateDeduction.h" 390b57cec5SDimitry Andric #include "llvm/ADT/APInt.h" 400b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h" 410b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h" 420b57cec5SDimitry Andric using namespace clang; 430b57cec5SDimitry Andric using namespace sema; 440b57cec5SDimitry Andric 450b57cec5SDimitry Andric /// Handle the result of the special case name lookup for inheriting 460b57cec5SDimitry Andric /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as 470b57cec5SDimitry Andric /// constructor names in member using declarations, even if 'X' is not the 480b57cec5SDimitry Andric /// name of the corresponding type. 490b57cec5SDimitry Andric ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, 500b57cec5SDimitry Andric SourceLocation NameLoc, 510b57cec5SDimitry Andric IdentifierInfo &Name) { 520b57cec5SDimitry Andric NestedNameSpecifier *NNS = SS.getScopeRep(); 530b57cec5SDimitry Andric 540b57cec5SDimitry Andric // Convert the nested-name-specifier into a type. 550b57cec5SDimitry Andric QualType Type; 560b57cec5SDimitry Andric switch (NNS->getKind()) { 570b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpec: 580b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpecWithTemplate: 590b57cec5SDimitry Andric Type = QualType(NNS->getAsType(), 0); 600b57cec5SDimitry Andric break; 610b57cec5SDimitry Andric 620b57cec5SDimitry Andric case NestedNameSpecifier::Identifier: 630b57cec5SDimitry Andric // Strip off the last layer of the nested-name-specifier and build a 640b57cec5SDimitry Andric // typename type for it. 650b57cec5SDimitry Andric assert(NNS->getAsIdentifier() == &Name && "not a constructor name"); 660b57cec5SDimitry Andric Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(), 670b57cec5SDimitry Andric NNS->getAsIdentifier()); 680b57cec5SDimitry Andric break; 690b57cec5SDimitry Andric 700b57cec5SDimitry Andric case NestedNameSpecifier::Global: 710b57cec5SDimitry Andric case NestedNameSpecifier::Super: 720b57cec5SDimitry Andric case NestedNameSpecifier::Namespace: 730b57cec5SDimitry Andric case NestedNameSpecifier::NamespaceAlias: 740b57cec5SDimitry Andric llvm_unreachable("Nested name specifier is not a type for inheriting ctor"); 750b57cec5SDimitry Andric } 760b57cec5SDimitry Andric 770b57cec5SDimitry Andric // This reference to the type is located entirely at the location of the 780b57cec5SDimitry Andric // final identifier in the qualified-id. 790b57cec5SDimitry Andric return CreateParsedType(Type, 800b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(Type, NameLoc)); 810b57cec5SDimitry Andric } 820b57cec5SDimitry Andric 830b57cec5SDimitry Andric ParsedType Sema::getConstructorName(IdentifierInfo &II, 840b57cec5SDimitry Andric SourceLocation NameLoc, 850b57cec5SDimitry Andric Scope *S, CXXScopeSpec &SS, 860b57cec5SDimitry Andric bool EnteringContext) { 870b57cec5SDimitry Andric CXXRecordDecl *CurClass = getCurrentClass(S, &SS); 880b57cec5SDimitry Andric assert(CurClass && &II == CurClass->getIdentifier() && 890b57cec5SDimitry Andric "not a constructor name"); 900b57cec5SDimitry Andric 910b57cec5SDimitry Andric // When naming a constructor as a member of a dependent context (eg, in a 920b57cec5SDimitry Andric // friend declaration or an inherited constructor declaration), form an 930b57cec5SDimitry Andric // unresolved "typename" type. 940b57cec5SDimitry Andric if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { 950b57cec5SDimitry Andric QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II); 960b57cec5SDimitry Andric return ParsedType::make(T); 970b57cec5SDimitry Andric } 980b57cec5SDimitry Andric 990b57cec5SDimitry Andric if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) 1000b57cec5SDimitry Andric return ParsedType(); 1010b57cec5SDimitry Andric 1020b57cec5SDimitry Andric // Find the injected-class-name declaration. Note that we make no attempt to 1030b57cec5SDimitry Andric // diagnose cases where the injected-class-name is shadowed: the only 1040b57cec5SDimitry Andric // declaration that can validly shadow the injected-class-name is a 1050b57cec5SDimitry Andric // non-static data member, and if the class contains both a non-static data 1060b57cec5SDimitry Andric // member and a constructor then it is ill-formed (we check that in 1070b57cec5SDimitry Andric // CheckCompletedCXXClass). 1080b57cec5SDimitry Andric CXXRecordDecl *InjectedClassName = nullptr; 1090b57cec5SDimitry Andric for (NamedDecl *ND : CurClass->lookup(&II)) { 1100b57cec5SDimitry Andric auto *RD = dyn_cast<CXXRecordDecl>(ND); 1110b57cec5SDimitry Andric if (RD && RD->isInjectedClassName()) { 1120b57cec5SDimitry Andric InjectedClassName = RD; 1130b57cec5SDimitry Andric break; 1140b57cec5SDimitry Andric } 1150b57cec5SDimitry Andric } 1160b57cec5SDimitry Andric if (!InjectedClassName) { 1170b57cec5SDimitry Andric if (!CurClass->isInvalidDecl()) { 1180b57cec5SDimitry Andric // FIXME: RequireCompleteDeclContext doesn't check dependent contexts 1190b57cec5SDimitry Andric // properly. Work around it here for now. 1200b57cec5SDimitry Andric Diag(SS.getLastQualifierNameLoc(), 1210b57cec5SDimitry Andric diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); 1220b57cec5SDimitry Andric } 1230b57cec5SDimitry Andric return ParsedType(); 1240b57cec5SDimitry Andric } 1250b57cec5SDimitry Andric 1260b57cec5SDimitry Andric QualType T = Context.getTypeDeclType(InjectedClassName); 1270b57cec5SDimitry Andric DiagnoseUseOfDecl(InjectedClassName, NameLoc); 1280b57cec5SDimitry Andric MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false); 1290b57cec5SDimitry Andric 1300b57cec5SDimitry Andric return ParsedType::make(T); 1310b57cec5SDimitry Andric } 1320b57cec5SDimitry Andric 1330b57cec5SDimitry Andric ParsedType Sema::getDestructorName(SourceLocation TildeLoc, 1340b57cec5SDimitry Andric IdentifierInfo &II, 1350b57cec5SDimitry Andric SourceLocation NameLoc, 1360b57cec5SDimitry Andric Scope *S, CXXScopeSpec &SS, 1370b57cec5SDimitry Andric ParsedType ObjectTypePtr, 1380b57cec5SDimitry Andric bool EnteringContext) { 1390b57cec5SDimitry Andric // Determine where to perform name lookup. 1400b57cec5SDimitry Andric 1410b57cec5SDimitry Andric // FIXME: This area of the standard is very messy, and the current 1420b57cec5SDimitry Andric // wording is rather unclear about which scopes we search for the 1430b57cec5SDimitry Andric // destructor name; see core issues 399 and 555. Issue 399 in 1440b57cec5SDimitry Andric // particular shows where the current description of destructor name 1450b57cec5SDimitry Andric // lookup is completely out of line with existing practice, e.g., 1460b57cec5SDimitry Andric // this appears to be ill-formed: 1470b57cec5SDimitry Andric // 1480b57cec5SDimitry Andric // namespace N { 1490b57cec5SDimitry Andric // template <typename T> struct S { 1500b57cec5SDimitry Andric // ~S(); 1510b57cec5SDimitry Andric // }; 1520b57cec5SDimitry Andric // } 1530b57cec5SDimitry Andric // 1540b57cec5SDimitry Andric // void f(N::S<int>* s) { 1550b57cec5SDimitry Andric // s->N::S<int>::~S(); 1560b57cec5SDimitry Andric // } 1570b57cec5SDimitry Andric // 1580b57cec5SDimitry Andric // See also PR6358 and PR6359. 1590b57cec5SDimitry Andric // For this reason, we're currently only doing the C++03 version of this 1600b57cec5SDimitry Andric // code; the C++0x version has to wait until we get a proper spec. 1610b57cec5SDimitry Andric QualType SearchType; 1620b57cec5SDimitry Andric DeclContext *LookupCtx = nullptr; 1630b57cec5SDimitry Andric bool isDependent = false; 1640b57cec5SDimitry Andric bool LookInScope = false; 1650b57cec5SDimitry Andric 1660b57cec5SDimitry Andric if (SS.isInvalid()) 1670b57cec5SDimitry Andric return nullptr; 1680b57cec5SDimitry Andric 1690b57cec5SDimitry Andric // If we have an object type, it's because we are in a 1700b57cec5SDimitry Andric // pseudo-destructor-expression or a member access expression, and 1710b57cec5SDimitry Andric // we know what type we're looking for. 1720b57cec5SDimitry Andric if (ObjectTypePtr) 1730b57cec5SDimitry Andric SearchType = GetTypeFromParser(ObjectTypePtr); 1740b57cec5SDimitry Andric 1750b57cec5SDimitry Andric if (SS.isSet()) { 1760b57cec5SDimitry Andric NestedNameSpecifier *NNS = SS.getScopeRep(); 1770b57cec5SDimitry Andric 1780b57cec5SDimitry Andric bool AlreadySearched = false; 1790b57cec5SDimitry Andric bool LookAtPrefix = true; 1800b57cec5SDimitry Andric // C++11 [basic.lookup.qual]p6: 1810b57cec5SDimitry Andric // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier, 1820b57cec5SDimitry Andric // the type-names are looked up as types in the scope designated by the 1830b57cec5SDimitry Andric // nested-name-specifier. Similarly, in a qualified-id of the form: 1840b57cec5SDimitry Andric // 1850b57cec5SDimitry Andric // nested-name-specifier[opt] class-name :: ~ class-name 1860b57cec5SDimitry Andric // 1870b57cec5SDimitry Andric // the second class-name is looked up in the same scope as the first. 1880b57cec5SDimitry Andric // 1890b57cec5SDimitry Andric // Here, we determine whether the code below is permitted to look at the 1900b57cec5SDimitry Andric // prefix of the nested-name-specifier. 1910b57cec5SDimitry Andric DeclContext *DC = computeDeclContext(SS, EnteringContext); 1920b57cec5SDimitry Andric if (DC && DC->isFileContext()) { 1930b57cec5SDimitry Andric AlreadySearched = true; 1940b57cec5SDimitry Andric LookupCtx = DC; 1950b57cec5SDimitry Andric isDependent = false; 1960b57cec5SDimitry Andric } else if (DC && isa<CXXRecordDecl>(DC)) { 1970b57cec5SDimitry Andric LookAtPrefix = false; 1980b57cec5SDimitry Andric LookInScope = true; 1990b57cec5SDimitry Andric } 2000b57cec5SDimitry Andric 2010b57cec5SDimitry Andric // The second case from the C++03 rules quoted further above. 2020b57cec5SDimitry Andric NestedNameSpecifier *Prefix = nullptr; 2030b57cec5SDimitry Andric if (AlreadySearched) { 2040b57cec5SDimitry Andric // Nothing left to do. 2050b57cec5SDimitry Andric } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) { 2060b57cec5SDimitry Andric CXXScopeSpec PrefixSS; 2070b57cec5SDimitry Andric PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 2080b57cec5SDimitry Andric LookupCtx = computeDeclContext(PrefixSS, EnteringContext); 2090b57cec5SDimitry Andric isDependent = isDependentScopeSpecifier(PrefixSS); 2100b57cec5SDimitry Andric } else if (ObjectTypePtr) { 2110b57cec5SDimitry Andric LookupCtx = computeDeclContext(SearchType); 2120b57cec5SDimitry Andric isDependent = SearchType->isDependentType(); 2130b57cec5SDimitry Andric } else { 2140b57cec5SDimitry Andric LookupCtx = computeDeclContext(SS, EnteringContext); 2150b57cec5SDimitry Andric isDependent = LookupCtx && LookupCtx->isDependentContext(); 2160b57cec5SDimitry Andric } 2170b57cec5SDimitry Andric } else if (ObjectTypePtr) { 2180b57cec5SDimitry Andric // C++ [basic.lookup.classref]p3: 2190b57cec5SDimitry Andric // If the unqualified-id is ~type-name, the type-name is looked up 2200b57cec5SDimitry Andric // in the context of the entire postfix-expression. If the type T 2210b57cec5SDimitry Andric // of the object expression is of a class type C, the type-name is 2220b57cec5SDimitry Andric // also looked up in the scope of class C. At least one of the 2230b57cec5SDimitry Andric // lookups shall find a name that refers to (possibly 2240b57cec5SDimitry Andric // cv-qualified) T. 2250b57cec5SDimitry Andric LookupCtx = computeDeclContext(SearchType); 2260b57cec5SDimitry Andric isDependent = SearchType->isDependentType(); 2270b57cec5SDimitry Andric assert((isDependent || !SearchType->isIncompleteType()) && 2280b57cec5SDimitry Andric "Caller should have completed object type"); 2290b57cec5SDimitry Andric 2300b57cec5SDimitry Andric LookInScope = true; 2310b57cec5SDimitry Andric } else { 2320b57cec5SDimitry Andric // Perform lookup into the current scope (only). 2330b57cec5SDimitry Andric LookInScope = true; 2340b57cec5SDimitry Andric } 2350b57cec5SDimitry Andric 2360b57cec5SDimitry Andric TypeDecl *NonMatchingTypeDecl = nullptr; 2370b57cec5SDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName); 2380b57cec5SDimitry Andric for (unsigned Step = 0; Step != 2; ++Step) { 2390b57cec5SDimitry Andric // Look for the name first in the computed lookup context (if we 2400b57cec5SDimitry Andric // have one) and, if that fails to find a match, in the scope (if 2410b57cec5SDimitry Andric // we're allowed to look there). 2420b57cec5SDimitry Andric Found.clear(); 2430b57cec5SDimitry Andric if (Step == 0 && LookupCtx) { 2440b57cec5SDimitry Andric if (RequireCompleteDeclContext(SS, LookupCtx)) 2450b57cec5SDimitry Andric return nullptr; 2460b57cec5SDimitry Andric LookupQualifiedName(Found, LookupCtx); 2470b57cec5SDimitry Andric } else if (Step == 1 && LookInScope && S) { 2480b57cec5SDimitry Andric LookupName(Found, S); 2490b57cec5SDimitry Andric } else { 2500b57cec5SDimitry Andric continue; 2510b57cec5SDimitry Andric } 2520b57cec5SDimitry Andric 2530b57cec5SDimitry Andric // FIXME: Should we be suppressing ambiguities here? 2540b57cec5SDimitry Andric if (Found.isAmbiguous()) 2550b57cec5SDimitry Andric return nullptr; 2560b57cec5SDimitry Andric 2570b57cec5SDimitry Andric if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 2580b57cec5SDimitry Andric QualType T = Context.getTypeDeclType(Type); 2590b57cec5SDimitry Andric MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 2600b57cec5SDimitry Andric 2610b57cec5SDimitry Andric if (SearchType.isNull() || SearchType->isDependentType() || 2620b57cec5SDimitry Andric Context.hasSameUnqualifiedType(T, SearchType)) { 2630b57cec5SDimitry Andric // We found our type! 2640b57cec5SDimitry Andric 2650b57cec5SDimitry Andric return CreateParsedType(T, 2660b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(T, NameLoc)); 2670b57cec5SDimitry Andric } 2680b57cec5SDimitry Andric 2690b57cec5SDimitry Andric if (!SearchType.isNull()) 2700b57cec5SDimitry Andric NonMatchingTypeDecl = Type; 2710b57cec5SDimitry Andric } 2720b57cec5SDimitry Andric 2730b57cec5SDimitry Andric // If the name that we found is a class template name, and it is 2740b57cec5SDimitry Andric // the same name as the template name in the last part of the 2750b57cec5SDimitry Andric // nested-name-specifier (if present) or the object type, then 2760b57cec5SDimitry Andric // this is the destructor for that class. 2770b57cec5SDimitry Andric // FIXME: This is a workaround until we get real drafting for core 2780b57cec5SDimitry Andric // issue 399, for which there isn't even an obvious direction. 2790b57cec5SDimitry Andric if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) { 2800b57cec5SDimitry Andric QualType MemberOfType; 2810b57cec5SDimitry Andric if (SS.isSet()) { 2820b57cec5SDimitry Andric if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) { 2830b57cec5SDimitry Andric // Figure out the type of the context, if it has one. 2840b57cec5SDimitry Andric if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) 2850b57cec5SDimitry Andric MemberOfType = Context.getTypeDeclType(Record); 2860b57cec5SDimitry Andric } 2870b57cec5SDimitry Andric } 2880b57cec5SDimitry Andric if (MemberOfType.isNull()) 2890b57cec5SDimitry Andric MemberOfType = SearchType; 2900b57cec5SDimitry Andric 2910b57cec5SDimitry Andric if (MemberOfType.isNull()) 2920b57cec5SDimitry Andric continue; 2930b57cec5SDimitry Andric 2940b57cec5SDimitry Andric // We're referring into a class template specialization. If the 2950b57cec5SDimitry Andric // class template we found is the same as the template being 2960b57cec5SDimitry Andric // specialized, we found what we are looking for. 2970b57cec5SDimitry Andric if (const RecordType *Record = MemberOfType->getAs<RecordType>()) { 2980b57cec5SDimitry Andric if (ClassTemplateSpecializationDecl *Spec 2990b57cec5SDimitry Andric = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 3000b57cec5SDimitry Andric if (Spec->getSpecializedTemplate()->getCanonicalDecl() == 3010b57cec5SDimitry Andric Template->getCanonicalDecl()) 3020b57cec5SDimitry Andric return CreateParsedType( 3030b57cec5SDimitry Andric MemberOfType, 3040b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc)); 3050b57cec5SDimitry Andric } 3060b57cec5SDimitry Andric 3070b57cec5SDimitry Andric continue; 3080b57cec5SDimitry Andric } 3090b57cec5SDimitry Andric 3100b57cec5SDimitry Andric // We're referring to an unresolved class template 3110b57cec5SDimitry Andric // specialization. Determine whether we class template we found 3120b57cec5SDimitry Andric // is the same as the template being specialized or, if we don't 3130b57cec5SDimitry Andric // know which template is being specialized, that it at least 3140b57cec5SDimitry Andric // has the same name. 3150b57cec5SDimitry Andric if (const TemplateSpecializationType *SpecType 3160b57cec5SDimitry Andric = MemberOfType->getAs<TemplateSpecializationType>()) { 3170b57cec5SDimitry Andric TemplateName SpecName = SpecType->getTemplateName(); 3180b57cec5SDimitry Andric 3190b57cec5SDimitry Andric // The class template we found is the same template being 3200b57cec5SDimitry Andric // specialized. 3210b57cec5SDimitry Andric if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) { 3220b57cec5SDimitry Andric if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl()) 3230b57cec5SDimitry Andric return CreateParsedType( 3240b57cec5SDimitry Andric MemberOfType, 3250b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc)); 3260b57cec5SDimitry Andric 3270b57cec5SDimitry Andric continue; 3280b57cec5SDimitry Andric } 3290b57cec5SDimitry Andric 3300b57cec5SDimitry Andric // The class template we found has the same name as the 3310b57cec5SDimitry Andric // (dependent) template name being specialized. 3320b57cec5SDimitry Andric if (DependentTemplateName *DepTemplate 3330b57cec5SDimitry Andric = SpecName.getAsDependentTemplateName()) { 3340b57cec5SDimitry Andric if (DepTemplate->isIdentifier() && 3350b57cec5SDimitry Andric DepTemplate->getIdentifier() == Template->getIdentifier()) 3360b57cec5SDimitry Andric return CreateParsedType( 3370b57cec5SDimitry Andric MemberOfType, 3380b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc)); 3390b57cec5SDimitry Andric 3400b57cec5SDimitry Andric continue; 3410b57cec5SDimitry Andric } 3420b57cec5SDimitry Andric } 3430b57cec5SDimitry Andric } 3440b57cec5SDimitry Andric } 3450b57cec5SDimitry Andric 3460b57cec5SDimitry Andric if (isDependent) { 3470b57cec5SDimitry Andric // We didn't find our type, but that's okay: it's dependent 3480b57cec5SDimitry Andric // anyway. 3490b57cec5SDimitry Andric 3500b57cec5SDimitry Andric // FIXME: What if we have no nested-name-specifier? 3510b57cec5SDimitry Andric QualType T = CheckTypenameType(ETK_None, SourceLocation(), 3520b57cec5SDimitry Andric SS.getWithLocInContext(Context), 3530b57cec5SDimitry Andric II, NameLoc); 3540b57cec5SDimitry Andric return ParsedType::make(T); 3550b57cec5SDimitry Andric } 3560b57cec5SDimitry Andric 3570b57cec5SDimitry Andric if (NonMatchingTypeDecl) { 3580b57cec5SDimitry Andric QualType T = Context.getTypeDeclType(NonMatchingTypeDecl); 3590b57cec5SDimitry Andric Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 3600b57cec5SDimitry Andric << T << SearchType; 3610b57cec5SDimitry Andric Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here) 3620b57cec5SDimitry Andric << T; 3630b57cec5SDimitry Andric } else if (ObjectTypePtr) 3640b57cec5SDimitry Andric Diag(NameLoc, diag::err_ident_in_dtor_not_a_type) 3650b57cec5SDimitry Andric << &II; 3660b57cec5SDimitry Andric else { 3670b57cec5SDimitry Andric SemaDiagnosticBuilder DtorDiag = Diag(NameLoc, 3680b57cec5SDimitry Andric diag::err_destructor_class_name); 3690b57cec5SDimitry Andric if (S) { 3700b57cec5SDimitry Andric const DeclContext *Ctx = S->getEntity(); 3710b57cec5SDimitry Andric if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx)) 3720b57cec5SDimitry Andric DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc), 3730b57cec5SDimitry Andric Class->getNameAsString()); 3740b57cec5SDimitry Andric } 3750b57cec5SDimitry Andric } 3760b57cec5SDimitry Andric 3770b57cec5SDimitry Andric return nullptr; 3780b57cec5SDimitry Andric } 3790b57cec5SDimitry Andric 3800b57cec5SDimitry Andric ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, 3810b57cec5SDimitry Andric ParsedType ObjectType) { 3820b57cec5SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_error) 3830b57cec5SDimitry Andric return nullptr; 3840b57cec5SDimitry Andric 3850b57cec5SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { 3860b57cec5SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 3870b57cec5SDimitry Andric return nullptr; 3880b57cec5SDimitry Andric } 3890b57cec5SDimitry Andric 3900b57cec5SDimitry Andric assert(DS.getTypeSpecType() == DeclSpec::TST_decltype && 3910b57cec5SDimitry Andric "unexpected type in getDestructorType"); 3920b57cec5SDimitry Andric QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc()); 3930b57cec5SDimitry Andric 3940b57cec5SDimitry Andric // If we know the type of the object, check that the correct destructor 3950b57cec5SDimitry Andric // type was named now; we can give better diagnostics this way. 3960b57cec5SDimitry Andric QualType SearchType = GetTypeFromParser(ObjectType); 3970b57cec5SDimitry Andric if (!SearchType.isNull() && !SearchType->isDependentType() && 3980b57cec5SDimitry Andric !Context.hasSameUnqualifiedType(T, SearchType)) { 3990b57cec5SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) 4000b57cec5SDimitry Andric << T << SearchType; 4010b57cec5SDimitry Andric return nullptr; 4020b57cec5SDimitry Andric } 4030b57cec5SDimitry Andric 4040b57cec5SDimitry Andric return ParsedType::make(T); 4050b57cec5SDimitry Andric } 4060b57cec5SDimitry Andric 4070b57cec5SDimitry Andric bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, 4080b57cec5SDimitry Andric const UnqualifiedId &Name) { 4090b57cec5SDimitry Andric assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId); 4100b57cec5SDimitry Andric 4110b57cec5SDimitry Andric if (!SS.isValid()) 4120b57cec5SDimitry Andric return false; 4130b57cec5SDimitry Andric 4140b57cec5SDimitry Andric switch (SS.getScopeRep()->getKind()) { 4150b57cec5SDimitry Andric case NestedNameSpecifier::Identifier: 4160b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpec: 4170b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpecWithTemplate: 4180b57cec5SDimitry Andric // Per C++11 [over.literal]p2, literal operators can only be declared at 4190b57cec5SDimitry Andric // namespace scope. Therefore, this unqualified-id cannot name anything. 4200b57cec5SDimitry Andric // Reject it early, because we have no AST representation for this in the 4210b57cec5SDimitry Andric // case where the scope is dependent. 4220b57cec5SDimitry Andric Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) 4230b57cec5SDimitry Andric << SS.getScopeRep(); 4240b57cec5SDimitry Andric return true; 4250b57cec5SDimitry Andric 4260b57cec5SDimitry Andric case NestedNameSpecifier::Global: 4270b57cec5SDimitry Andric case NestedNameSpecifier::Super: 4280b57cec5SDimitry Andric case NestedNameSpecifier::Namespace: 4290b57cec5SDimitry Andric case NestedNameSpecifier::NamespaceAlias: 4300b57cec5SDimitry Andric return false; 4310b57cec5SDimitry Andric } 4320b57cec5SDimitry Andric 4330b57cec5SDimitry Andric llvm_unreachable("unknown nested name specifier kind"); 4340b57cec5SDimitry Andric } 4350b57cec5SDimitry Andric 4360b57cec5SDimitry Andric /// Build a C++ typeid expression with a type operand. 4370b57cec5SDimitry Andric ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 4380b57cec5SDimitry Andric SourceLocation TypeidLoc, 4390b57cec5SDimitry Andric TypeSourceInfo *Operand, 4400b57cec5SDimitry Andric SourceLocation RParenLoc) { 4410b57cec5SDimitry Andric // C++ [expr.typeid]p4: 4420b57cec5SDimitry Andric // The top-level cv-qualifiers of the lvalue expression or the type-id 4430b57cec5SDimitry Andric // that is the operand of typeid are always ignored. 4440b57cec5SDimitry Andric // If the type of the type-id is a class type or a reference to a class 4450b57cec5SDimitry Andric // type, the class shall be completely-defined. 4460b57cec5SDimitry Andric Qualifiers Quals; 4470b57cec5SDimitry Andric QualType T 4480b57cec5SDimitry Andric = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 4490b57cec5SDimitry Andric Quals); 4500b57cec5SDimitry Andric if (T->getAs<RecordType>() && 4510b57cec5SDimitry Andric RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 4520b57cec5SDimitry Andric return ExprError(); 4530b57cec5SDimitry Andric 4540b57cec5SDimitry Andric if (T->isVariablyModifiedType()) 4550b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); 4560b57cec5SDimitry Andric 457a7dea167SDimitry Andric if (CheckQualifiedFunctionForTypeId(T, TypeidLoc)) 458a7dea167SDimitry Andric return ExprError(); 459a7dea167SDimitry Andric 4600b57cec5SDimitry Andric return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, 4610b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 4620b57cec5SDimitry Andric } 4630b57cec5SDimitry Andric 4640b57cec5SDimitry Andric /// Build a C++ typeid expression with an expression operand. 4650b57cec5SDimitry Andric ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 4660b57cec5SDimitry Andric SourceLocation TypeidLoc, 4670b57cec5SDimitry Andric Expr *E, 4680b57cec5SDimitry Andric SourceLocation RParenLoc) { 4690b57cec5SDimitry Andric bool WasEvaluated = false; 4700b57cec5SDimitry Andric if (E && !E->isTypeDependent()) { 4710b57cec5SDimitry Andric if (E->getType()->isPlaceholderType()) { 4720b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(E); 4730b57cec5SDimitry Andric if (result.isInvalid()) return ExprError(); 4740b57cec5SDimitry Andric E = result.get(); 4750b57cec5SDimitry Andric } 4760b57cec5SDimitry Andric 4770b57cec5SDimitry Andric QualType T = E->getType(); 4780b57cec5SDimitry Andric if (const RecordType *RecordT = T->getAs<RecordType>()) { 4790b57cec5SDimitry Andric CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 4800b57cec5SDimitry Andric // C++ [expr.typeid]p3: 4810b57cec5SDimitry Andric // [...] If the type of the expression is a class type, the class 4820b57cec5SDimitry Andric // shall be completely-defined. 4830b57cec5SDimitry Andric if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 4840b57cec5SDimitry Andric return ExprError(); 4850b57cec5SDimitry Andric 4860b57cec5SDimitry Andric // C++ [expr.typeid]p3: 4870b57cec5SDimitry Andric // When typeid is applied to an expression other than an glvalue of a 4880b57cec5SDimitry Andric // polymorphic class type [...] [the] expression is an unevaluated 4890b57cec5SDimitry Andric // operand. [...] 4900b57cec5SDimitry Andric if (RecordD->isPolymorphic() && E->isGLValue()) { 4910b57cec5SDimitry Andric // The subexpression is potentially evaluated; switch the context 4920b57cec5SDimitry Andric // and recheck the subexpression. 4930b57cec5SDimitry Andric ExprResult Result = TransformToPotentiallyEvaluated(E); 4940b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 4950b57cec5SDimitry Andric E = Result.get(); 4960b57cec5SDimitry Andric 4970b57cec5SDimitry Andric // We require a vtable to query the type at run time. 4980b57cec5SDimitry Andric MarkVTableUsed(TypeidLoc, RecordD); 4990b57cec5SDimitry Andric WasEvaluated = true; 5000b57cec5SDimitry Andric } 5010b57cec5SDimitry Andric } 5020b57cec5SDimitry Andric 503a7dea167SDimitry Andric ExprResult Result = CheckUnevaluatedOperand(E); 504a7dea167SDimitry Andric if (Result.isInvalid()) 505a7dea167SDimitry Andric return ExprError(); 506a7dea167SDimitry Andric E = Result.get(); 507a7dea167SDimitry Andric 5080b57cec5SDimitry Andric // C++ [expr.typeid]p4: 5090b57cec5SDimitry Andric // [...] If the type of the type-id is a reference to a possibly 5100b57cec5SDimitry Andric // cv-qualified type, the result of the typeid expression refers to a 5110b57cec5SDimitry Andric // std::type_info object representing the cv-unqualified referenced 5120b57cec5SDimitry Andric // type. 5130b57cec5SDimitry Andric Qualifiers Quals; 5140b57cec5SDimitry Andric QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 5150b57cec5SDimitry Andric if (!Context.hasSameType(T, UnqualT)) { 5160b57cec5SDimitry Andric T = UnqualT; 5170b57cec5SDimitry Andric E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); 5180b57cec5SDimitry Andric } 5190b57cec5SDimitry Andric } 5200b57cec5SDimitry Andric 5210b57cec5SDimitry Andric if (E->getType()->isVariablyModifiedType()) 5220b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) 5230b57cec5SDimitry Andric << E->getType()); 5240b57cec5SDimitry Andric else if (!inTemplateInstantiation() && 5250b57cec5SDimitry Andric E->HasSideEffects(Context, WasEvaluated)) { 5260b57cec5SDimitry Andric // The expression operand for typeid is in an unevaluated expression 5270b57cec5SDimitry Andric // context, so side effects could result in unintended consequences. 5280b57cec5SDimitry Andric Diag(E->getExprLoc(), WasEvaluated 5290b57cec5SDimitry Andric ? diag::warn_side_effects_typeid 5300b57cec5SDimitry Andric : diag::warn_side_effects_unevaluated_context); 5310b57cec5SDimitry Andric } 5320b57cec5SDimitry Andric 5330b57cec5SDimitry Andric return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, 5340b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 5350b57cec5SDimitry Andric } 5360b57cec5SDimitry Andric 5370b57cec5SDimitry Andric /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 5380b57cec5SDimitry Andric ExprResult 5390b57cec5SDimitry Andric Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 5400b57cec5SDimitry Andric bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 5410b57cec5SDimitry Andric // typeid is not supported in OpenCL. 5420b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) { 5430b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) 5440b57cec5SDimitry Andric << "typeid"); 5450b57cec5SDimitry Andric } 5460b57cec5SDimitry Andric 5470b57cec5SDimitry Andric // Find the std::type_info type. 5480b57cec5SDimitry Andric if (!getStdNamespace()) 5490b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 5500b57cec5SDimitry Andric 5510b57cec5SDimitry Andric if (!CXXTypeInfoDecl) { 5520b57cec5SDimitry Andric IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 5530b57cec5SDimitry Andric LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 5540b57cec5SDimitry Andric LookupQualifiedName(R, getStdNamespace()); 5550b57cec5SDimitry Andric CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 5560b57cec5SDimitry Andric // Microsoft's typeinfo doesn't have type_info in std but in the global 5570b57cec5SDimitry Andric // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. 5580b57cec5SDimitry Andric if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { 5590b57cec5SDimitry Andric LookupQualifiedName(R, Context.getTranslationUnitDecl()); 5600b57cec5SDimitry Andric CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 5610b57cec5SDimitry Andric } 5620b57cec5SDimitry Andric if (!CXXTypeInfoDecl) 5630b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 5640b57cec5SDimitry Andric } 5650b57cec5SDimitry Andric 5660b57cec5SDimitry Andric if (!getLangOpts().RTTI) { 5670b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); 5680b57cec5SDimitry Andric } 5690b57cec5SDimitry Andric 5700b57cec5SDimitry Andric QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 5710b57cec5SDimitry Andric 5720b57cec5SDimitry Andric if (isType) { 5730b57cec5SDimitry Andric // The operand is a type; handle it as such. 5740b57cec5SDimitry Andric TypeSourceInfo *TInfo = nullptr; 5750b57cec5SDimitry Andric QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 5760b57cec5SDimitry Andric &TInfo); 5770b57cec5SDimitry Andric if (T.isNull()) 5780b57cec5SDimitry Andric return ExprError(); 5790b57cec5SDimitry Andric 5800b57cec5SDimitry Andric if (!TInfo) 5810b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 5820b57cec5SDimitry Andric 5830b57cec5SDimitry Andric return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 5840b57cec5SDimitry Andric } 5850b57cec5SDimitry Andric 5860b57cec5SDimitry Andric // The operand is an expression. 5870b57cec5SDimitry Andric return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 5880b57cec5SDimitry Andric } 5890b57cec5SDimitry Andric 5900b57cec5SDimitry Andric /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to 5910b57cec5SDimitry Andric /// a single GUID. 5920b57cec5SDimitry Andric static void 5930b57cec5SDimitry Andric getUuidAttrOfType(Sema &SemaRef, QualType QT, 5940b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { 5950b57cec5SDimitry Andric // Optionally remove one level of pointer, reference or array indirection. 5960b57cec5SDimitry Andric const Type *Ty = QT.getTypePtr(); 5970b57cec5SDimitry Andric if (QT->isPointerType() || QT->isReferenceType()) 5980b57cec5SDimitry Andric Ty = QT->getPointeeType().getTypePtr(); 5990b57cec5SDimitry Andric else if (QT->isArrayType()) 6000b57cec5SDimitry Andric Ty = Ty->getBaseElementTypeUnsafe(); 6010b57cec5SDimitry Andric 6020b57cec5SDimitry Andric const auto *TD = Ty->getAsTagDecl(); 6030b57cec5SDimitry Andric if (!TD) 6040b57cec5SDimitry Andric return; 6050b57cec5SDimitry Andric 6060b57cec5SDimitry Andric if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { 6070b57cec5SDimitry Andric UuidAttrs.insert(Uuid); 6080b57cec5SDimitry Andric return; 6090b57cec5SDimitry Andric } 6100b57cec5SDimitry Andric 6110b57cec5SDimitry Andric // __uuidof can grab UUIDs from template arguments. 6120b57cec5SDimitry Andric if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) { 6130b57cec5SDimitry Andric const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 6140b57cec5SDimitry Andric for (const TemplateArgument &TA : TAL.asArray()) { 6150b57cec5SDimitry Andric const UuidAttr *UuidForTA = nullptr; 6160b57cec5SDimitry Andric if (TA.getKind() == TemplateArgument::Type) 6170b57cec5SDimitry Andric getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); 6180b57cec5SDimitry Andric else if (TA.getKind() == TemplateArgument::Declaration) 6190b57cec5SDimitry Andric getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); 6200b57cec5SDimitry Andric 6210b57cec5SDimitry Andric if (UuidForTA) 6220b57cec5SDimitry Andric UuidAttrs.insert(UuidForTA); 6230b57cec5SDimitry Andric } 6240b57cec5SDimitry Andric } 6250b57cec5SDimitry Andric } 6260b57cec5SDimitry Andric 6270b57cec5SDimitry Andric /// Build a Microsoft __uuidof expression with a type operand. 6280b57cec5SDimitry Andric ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 6290b57cec5SDimitry Andric SourceLocation TypeidLoc, 6300b57cec5SDimitry Andric TypeSourceInfo *Operand, 6310b57cec5SDimitry Andric SourceLocation RParenLoc) { 6320b57cec5SDimitry Andric StringRef UuidStr; 6330b57cec5SDimitry Andric if (!Operand->getType()->isDependentType()) { 6340b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 6350b57cec5SDimitry Andric getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); 6360b57cec5SDimitry Andric if (UuidAttrs.empty()) 6370b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 6380b57cec5SDimitry Andric if (UuidAttrs.size() > 1) 6390b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 6400b57cec5SDimitry Andric UuidStr = UuidAttrs.back()->getGuid(); 6410b57cec5SDimitry Andric } 6420b57cec5SDimitry Andric 6430b57cec5SDimitry Andric return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr, 6440b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 6450b57cec5SDimitry Andric } 6460b57cec5SDimitry Andric 6470b57cec5SDimitry Andric /// Build a Microsoft __uuidof expression with an expression operand. 6480b57cec5SDimitry Andric ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType, 6490b57cec5SDimitry Andric SourceLocation TypeidLoc, 6500b57cec5SDimitry Andric Expr *E, 6510b57cec5SDimitry Andric SourceLocation RParenLoc) { 6520b57cec5SDimitry Andric StringRef UuidStr; 6530b57cec5SDimitry Andric if (!E->getType()->isDependentType()) { 6540b57cec5SDimitry Andric if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 6550b57cec5SDimitry Andric UuidStr = "00000000-0000-0000-0000-000000000000"; 6560b57cec5SDimitry Andric } else { 6570b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 6580b57cec5SDimitry Andric getUuidAttrOfType(*this, E->getType(), UuidAttrs); 6590b57cec5SDimitry Andric if (UuidAttrs.empty()) 6600b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 6610b57cec5SDimitry Andric if (UuidAttrs.size() > 1) 6620b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 6630b57cec5SDimitry Andric UuidStr = UuidAttrs.back()->getGuid(); 6640b57cec5SDimitry Andric } 6650b57cec5SDimitry Andric } 6660b57cec5SDimitry Andric 6670b57cec5SDimitry Andric return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr, 6680b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 6690b57cec5SDimitry Andric } 6700b57cec5SDimitry Andric 6710b57cec5SDimitry Andric /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 6720b57cec5SDimitry Andric ExprResult 6730b57cec5SDimitry Andric Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 6740b57cec5SDimitry Andric bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 6750b57cec5SDimitry Andric // If MSVCGuidDecl has not been cached, do the lookup. 6760b57cec5SDimitry Andric if (!MSVCGuidDecl) { 6770b57cec5SDimitry Andric IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID"); 6780b57cec5SDimitry Andric LookupResult R(*this, GuidII, SourceLocation(), LookupTagName); 6790b57cec5SDimitry Andric LookupQualifiedName(R, Context.getTranslationUnitDecl()); 6800b57cec5SDimitry Andric MSVCGuidDecl = R.getAsSingle<RecordDecl>(); 6810b57cec5SDimitry Andric if (!MSVCGuidDecl) 6820b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof)); 6830b57cec5SDimitry Andric } 6840b57cec5SDimitry Andric 6850b57cec5SDimitry Andric QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl); 6860b57cec5SDimitry Andric 6870b57cec5SDimitry Andric if (isType) { 6880b57cec5SDimitry Andric // The operand is a type; handle it as such. 6890b57cec5SDimitry Andric TypeSourceInfo *TInfo = nullptr; 6900b57cec5SDimitry Andric QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 6910b57cec5SDimitry Andric &TInfo); 6920b57cec5SDimitry Andric if (T.isNull()) 6930b57cec5SDimitry Andric return ExprError(); 6940b57cec5SDimitry Andric 6950b57cec5SDimitry Andric if (!TInfo) 6960b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 6970b57cec5SDimitry Andric 6980b57cec5SDimitry Andric return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 6990b57cec5SDimitry Andric } 7000b57cec5SDimitry Andric 7010b57cec5SDimitry Andric // The operand is an expression. 7020b57cec5SDimitry Andric return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 7030b57cec5SDimitry Andric } 7040b57cec5SDimitry Andric 7050b57cec5SDimitry Andric /// ActOnCXXBoolLiteral - Parse {true,false} literals. 7060b57cec5SDimitry Andric ExprResult 7070b57cec5SDimitry Andric Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 7080b57cec5SDimitry Andric assert((Kind == tok::kw_true || Kind == tok::kw_false) && 7090b57cec5SDimitry Andric "Unknown C++ Boolean value!"); 7100b57cec5SDimitry Andric return new (Context) 7110b57cec5SDimitry Andric CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 7120b57cec5SDimitry Andric } 7130b57cec5SDimitry Andric 7140b57cec5SDimitry Andric /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 7150b57cec5SDimitry Andric ExprResult 7160b57cec5SDimitry Andric Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 7170b57cec5SDimitry Andric return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 7180b57cec5SDimitry Andric } 7190b57cec5SDimitry Andric 7200b57cec5SDimitry Andric /// ActOnCXXThrow - Parse throw expressions. 7210b57cec5SDimitry Andric ExprResult 7220b57cec5SDimitry Andric Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { 7230b57cec5SDimitry Andric bool IsThrownVarInScope = false; 7240b57cec5SDimitry Andric if (Ex) { 7250b57cec5SDimitry Andric // C++0x [class.copymove]p31: 7260b57cec5SDimitry Andric // When certain criteria are met, an implementation is allowed to omit the 7270b57cec5SDimitry Andric // copy/move construction of a class object [...] 7280b57cec5SDimitry Andric // 7290b57cec5SDimitry Andric // - in a throw-expression, when the operand is the name of a 7300b57cec5SDimitry Andric // non-volatile automatic object (other than a function or catch- 7310b57cec5SDimitry Andric // clause parameter) whose scope does not extend beyond the end of the 7320b57cec5SDimitry Andric // innermost enclosing try-block (if there is one), the copy/move 7330b57cec5SDimitry Andric // operation from the operand to the exception object (15.1) can be 7340b57cec5SDimitry Andric // omitted by constructing the automatic object directly into the 7350b57cec5SDimitry Andric // exception object 7360b57cec5SDimitry Andric if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) 7370b57cec5SDimitry Andric if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 7380b57cec5SDimitry Andric if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { 7390b57cec5SDimitry Andric for( ; S; S = S->getParent()) { 7400b57cec5SDimitry Andric if (S->isDeclScope(Var)) { 7410b57cec5SDimitry Andric IsThrownVarInScope = true; 7420b57cec5SDimitry Andric break; 7430b57cec5SDimitry Andric } 7440b57cec5SDimitry Andric 7450b57cec5SDimitry Andric if (S->getFlags() & 7460b57cec5SDimitry Andric (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | 7470b57cec5SDimitry Andric Scope::FunctionPrototypeScope | Scope::ObjCMethodScope | 7480b57cec5SDimitry Andric Scope::TryScope)) 7490b57cec5SDimitry Andric break; 7500b57cec5SDimitry Andric } 7510b57cec5SDimitry Andric } 7520b57cec5SDimitry Andric } 7530b57cec5SDimitry Andric } 7540b57cec5SDimitry Andric 7550b57cec5SDimitry Andric return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); 7560b57cec5SDimitry Andric } 7570b57cec5SDimitry Andric 7580b57cec5SDimitry Andric ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 7590b57cec5SDimitry Andric bool IsThrownVarInScope) { 7600b57cec5SDimitry Andric // Don't report an error if 'throw' is used in system headers. 7610b57cec5SDimitry Andric if (!getLangOpts().CXXExceptions && 7620b57cec5SDimitry Andric !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) { 7630b57cec5SDimitry Andric // Delay error emission for the OpenMP device code. 7640b57cec5SDimitry Andric targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw"; 7650b57cec5SDimitry Andric } 7660b57cec5SDimitry Andric 7670b57cec5SDimitry Andric // Exceptions aren't allowed in CUDA device code. 7680b57cec5SDimitry Andric if (getLangOpts().CUDA) 7690b57cec5SDimitry Andric CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) 7700b57cec5SDimitry Andric << "throw" << CurrentCUDATarget(); 7710b57cec5SDimitry Andric 7720b57cec5SDimitry Andric if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) 7730b57cec5SDimitry Andric Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; 7740b57cec5SDimitry Andric 7750b57cec5SDimitry Andric if (Ex && !Ex->isTypeDependent()) { 7760b57cec5SDimitry Andric QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); 7770b57cec5SDimitry Andric if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) 7780b57cec5SDimitry Andric return ExprError(); 7790b57cec5SDimitry Andric 7800b57cec5SDimitry Andric // Initialize the exception result. This implicitly weeds out 7810b57cec5SDimitry Andric // abstract types or types with inaccessible copy constructors. 7820b57cec5SDimitry Andric 7830b57cec5SDimitry Andric // C++0x [class.copymove]p31: 7840b57cec5SDimitry Andric // When certain criteria are met, an implementation is allowed to omit the 7850b57cec5SDimitry Andric // copy/move construction of a class object [...] 7860b57cec5SDimitry Andric // 7870b57cec5SDimitry Andric // - in a throw-expression, when the operand is the name of a 7880b57cec5SDimitry Andric // non-volatile automatic object (other than a function or 7890b57cec5SDimitry Andric // catch-clause 7900b57cec5SDimitry Andric // parameter) whose scope does not extend beyond the end of the 7910b57cec5SDimitry Andric // innermost enclosing try-block (if there is one), the copy/move 7920b57cec5SDimitry Andric // operation from the operand to the exception object (15.1) can be 7930b57cec5SDimitry Andric // omitted by constructing the automatic object directly into the 7940b57cec5SDimitry Andric // exception object 7950b57cec5SDimitry Andric const VarDecl *NRVOVariable = nullptr; 7960b57cec5SDimitry Andric if (IsThrownVarInScope) 7970b57cec5SDimitry Andric NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict); 7980b57cec5SDimitry Andric 7990b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeException( 8000b57cec5SDimitry Andric OpLoc, ExceptionObjectTy, 8010b57cec5SDimitry Andric /*NRVO=*/NRVOVariable != nullptr); 8020b57cec5SDimitry Andric ExprResult Res = PerformMoveOrCopyInitialization( 8030b57cec5SDimitry Andric Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope); 8040b57cec5SDimitry Andric if (Res.isInvalid()) 8050b57cec5SDimitry Andric return ExprError(); 8060b57cec5SDimitry Andric Ex = Res.get(); 8070b57cec5SDimitry Andric } 8080b57cec5SDimitry Andric 8090b57cec5SDimitry Andric return new (Context) 8100b57cec5SDimitry Andric CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); 8110b57cec5SDimitry Andric } 8120b57cec5SDimitry Andric 8130b57cec5SDimitry Andric static void 8140b57cec5SDimitry Andric collectPublicBases(CXXRecordDecl *RD, 8150b57cec5SDimitry Andric llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, 8160b57cec5SDimitry Andric llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, 8170b57cec5SDimitry Andric llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, 8180b57cec5SDimitry Andric bool ParentIsPublic) { 8190b57cec5SDimitry Andric for (const CXXBaseSpecifier &BS : RD->bases()) { 8200b57cec5SDimitry Andric CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 8210b57cec5SDimitry Andric bool NewSubobject; 8220b57cec5SDimitry Andric // Virtual bases constitute the same subobject. Non-virtual bases are 8230b57cec5SDimitry Andric // always distinct subobjects. 8240b57cec5SDimitry Andric if (BS.isVirtual()) 8250b57cec5SDimitry Andric NewSubobject = VBases.insert(BaseDecl).second; 8260b57cec5SDimitry Andric else 8270b57cec5SDimitry Andric NewSubobject = true; 8280b57cec5SDimitry Andric 8290b57cec5SDimitry Andric if (NewSubobject) 8300b57cec5SDimitry Andric ++SubobjectsSeen[BaseDecl]; 8310b57cec5SDimitry Andric 8320b57cec5SDimitry Andric // Only add subobjects which have public access throughout the entire chain. 8330b57cec5SDimitry Andric bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; 8340b57cec5SDimitry Andric if (PublicPath) 8350b57cec5SDimitry Andric PublicSubobjectsSeen.insert(BaseDecl); 8360b57cec5SDimitry Andric 8370b57cec5SDimitry Andric // Recurse on to each base subobject. 8380b57cec5SDimitry Andric collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, 8390b57cec5SDimitry Andric PublicPath); 8400b57cec5SDimitry Andric } 8410b57cec5SDimitry Andric } 8420b57cec5SDimitry Andric 8430b57cec5SDimitry Andric static void getUnambiguousPublicSubobjects( 8440b57cec5SDimitry Andric CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { 8450b57cec5SDimitry Andric llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; 8460b57cec5SDimitry Andric llvm::SmallSet<CXXRecordDecl *, 2> VBases; 8470b57cec5SDimitry Andric llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; 8480b57cec5SDimitry Andric SubobjectsSeen[RD] = 1; 8490b57cec5SDimitry Andric PublicSubobjectsSeen.insert(RD); 8500b57cec5SDimitry Andric collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, 8510b57cec5SDimitry Andric /*ParentIsPublic=*/true); 8520b57cec5SDimitry Andric 8530b57cec5SDimitry Andric for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { 8540b57cec5SDimitry Andric // Skip ambiguous objects. 8550b57cec5SDimitry Andric if (SubobjectsSeen[PublicSubobject] > 1) 8560b57cec5SDimitry Andric continue; 8570b57cec5SDimitry Andric 8580b57cec5SDimitry Andric Objects.push_back(PublicSubobject); 8590b57cec5SDimitry Andric } 8600b57cec5SDimitry Andric } 8610b57cec5SDimitry Andric 8620b57cec5SDimitry Andric /// CheckCXXThrowOperand - Validate the operand of a throw. 8630b57cec5SDimitry Andric bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, 8640b57cec5SDimitry Andric QualType ExceptionObjectTy, Expr *E) { 8650b57cec5SDimitry Andric // If the type of the exception would be an incomplete type or a pointer 8660b57cec5SDimitry Andric // to an incomplete type other than (cv) void the program is ill-formed. 8670b57cec5SDimitry Andric QualType Ty = ExceptionObjectTy; 8680b57cec5SDimitry Andric bool isPointer = false; 8690b57cec5SDimitry Andric if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 8700b57cec5SDimitry Andric Ty = Ptr->getPointeeType(); 8710b57cec5SDimitry Andric isPointer = true; 8720b57cec5SDimitry Andric } 8730b57cec5SDimitry Andric if (!isPointer || !Ty->isVoidType()) { 8740b57cec5SDimitry Andric if (RequireCompleteType(ThrowLoc, Ty, 8750b57cec5SDimitry Andric isPointer ? diag::err_throw_incomplete_ptr 8760b57cec5SDimitry Andric : diag::err_throw_incomplete, 8770b57cec5SDimitry Andric E->getSourceRange())) 8780b57cec5SDimitry Andric return true; 8790b57cec5SDimitry Andric 8800b57cec5SDimitry Andric if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, 8810b57cec5SDimitry Andric diag::err_throw_abstract_type, E)) 8820b57cec5SDimitry Andric return true; 8830b57cec5SDimitry Andric } 8840b57cec5SDimitry Andric 8850b57cec5SDimitry Andric // If the exception has class type, we need additional handling. 8860b57cec5SDimitry Andric CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 8870b57cec5SDimitry Andric if (!RD) 8880b57cec5SDimitry Andric return false; 8890b57cec5SDimitry Andric 8900b57cec5SDimitry Andric // If we are throwing a polymorphic class type or pointer thereof, 8910b57cec5SDimitry Andric // exception handling will make use of the vtable. 8920b57cec5SDimitry Andric MarkVTableUsed(ThrowLoc, RD); 8930b57cec5SDimitry Andric 8940b57cec5SDimitry Andric // If a pointer is thrown, the referenced object will not be destroyed. 8950b57cec5SDimitry Andric if (isPointer) 8960b57cec5SDimitry Andric return false; 8970b57cec5SDimitry Andric 8980b57cec5SDimitry Andric // If the class has a destructor, we must be able to call it. 8990b57cec5SDimitry Andric if (!RD->hasIrrelevantDestructor()) { 9000b57cec5SDimitry Andric if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 9010b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), Destructor); 9020b57cec5SDimitry Andric CheckDestructorAccess(E->getExprLoc(), Destructor, 9030b57cec5SDimitry Andric PDiag(diag::err_access_dtor_exception) << Ty); 9040b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 9050b57cec5SDimitry Andric return true; 9060b57cec5SDimitry Andric } 9070b57cec5SDimitry Andric } 9080b57cec5SDimitry Andric 9090b57cec5SDimitry Andric // The MSVC ABI creates a list of all types which can catch the exception 9100b57cec5SDimitry Andric // object. This list also references the appropriate copy constructor to call 9110b57cec5SDimitry Andric // if the object is caught by value and has a non-trivial copy constructor. 9120b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 9130b57cec5SDimitry Andric // We are only interested in the public, unambiguous bases contained within 9140b57cec5SDimitry Andric // the exception object. Bases which are ambiguous or otherwise 9150b57cec5SDimitry Andric // inaccessible are not catchable types. 9160b57cec5SDimitry Andric llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; 9170b57cec5SDimitry Andric getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); 9180b57cec5SDimitry Andric 9190b57cec5SDimitry Andric for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { 9200b57cec5SDimitry Andric // Attempt to lookup the copy constructor. Various pieces of machinery 9210b57cec5SDimitry Andric // will spring into action, like template instantiation, which means this 9220b57cec5SDimitry Andric // cannot be a simple walk of the class's decls. Instead, we must perform 9230b57cec5SDimitry Andric // lookup and overload resolution. 9240b57cec5SDimitry Andric CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); 925480093f4SDimitry Andric if (!CD || CD->isDeleted()) 9260b57cec5SDimitry Andric continue; 9270b57cec5SDimitry Andric 9280b57cec5SDimitry Andric // Mark the constructor referenced as it is used by this throw expression. 9290b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), CD); 9300b57cec5SDimitry Andric 9310b57cec5SDimitry Andric // Skip this copy constructor if it is trivial, we don't need to record it 9320b57cec5SDimitry Andric // in the catchable type data. 9330b57cec5SDimitry Andric if (CD->isTrivial()) 9340b57cec5SDimitry Andric continue; 9350b57cec5SDimitry Andric 9360b57cec5SDimitry Andric // The copy constructor is non-trivial, create a mapping from this class 9370b57cec5SDimitry Andric // type to this constructor. 9380b57cec5SDimitry Andric // N.B. The selection of copy constructor is not sensitive to this 9390b57cec5SDimitry Andric // particular throw-site. Lookup will be performed at the catch-site to 9400b57cec5SDimitry Andric // ensure that the copy constructor is, in fact, accessible (via 9410b57cec5SDimitry Andric // friendship or any other means). 9420b57cec5SDimitry Andric Context.addCopyConstructorForExceptionObject(Subobject, CD); 9430b57cec5SDimitry Andric 9440b57cec5SDimitry Andric // We don't keep the instantiated default argument expressions around so 9450b57cec5SDimitry Andric // we must rebuild them here. 9460b57cec5SDimitry Andric for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { 9470b57cec5SDimitry Andric if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I))) 9480b57cec5SDimitry Andric return true; 9490b57cec5SDimitry Andric } 9500b57cec5SDimitry Andric } 9510b57cec5SDimitry Andric } 9520b57cec5SDimitry Andric 9530b57cec5SDimitry Andric // Under the Itanium C++ ABI, memory for the exception object is allocated by 9540b57cec5SDimitry Andric // the runtime with no ability for the compiler to request additional 9550b57cec5SDimitry Andric // alignment. Warn if the exception type requires alignment beyond the minimum 9560b57cec5SDimitry Andric // guaranteed by the target C++ runtime. 9570b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { 9580b57cec5SDimitry Andric CharUnits TypeAlign = Context.getTypeAlignInChars(Ty); 9590b57cec5SDimitry Andric CharUnits ExnObjAlign = Context.getExnObjectAlignment(); 9600b57cec5SDimitry Andric if (ExnObjAlign < TypeAlign) { 9610b57cec5SDimitry Andric Diag(ThrowLoc, diag::warn_throw_underaligned_obj); 9620b57cec5SDimitry Andric Diag(ThrowLoc, diag::note_throw_underaligned_obj) 9630b57cec5SDimitry Andric << Ty << (unsigned)TypeAlign.getQuantity() 9640b57cec5SDimitry Andric << (unsigned)ExnObjAlign.getQuantity(); 9650b57cec5SDimitry Andric } 9660b57cec5SDimitry Andric } 9670b57cec5SDimitry Andric 9680b57cec5SDimitry Andric return false; 9690b57cec5SDimitry Andric } 9700b57cec5SDimitry Andric 9710b57cec5SDimitry Andric static QualType adjustCVQualifiersForCXXThisWithinLambda( 9720b57cec5SDimitry Andric ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, 9730b57cec5SDimitry Andric DeclContext *CurSemaContext, ASTContext &ASTCtx) { 9740b57cec5SDimitry Andric 9750b57cec5SDimitry Andric QualType ClassType = ThisTy->getPointeeType(); 9760b57cec5SDimitry Andric LambdaScopeInfo *CurLSI = nullptr; 9770b57cec5SDimitry Andric DeclContext *CurDC = CurSemaContext; 9780b57cec5SDimitry Andric 9790b57cec5SDimitry Andric // Iterate through the stack of lambdas starting from the innermost lambda to 9800b57cec5SDimitry Andric // the outermost lambda, checking if '*this' is ever captured by copy - since 9810b57cec5SDimitry Andric // that could change the cv-qualifiers of the '*this' object. 9820b57cec5SDimitry Andric // The object referred to by '*this' starts out with the cv-qualifiers of its 9830b57cec5SDimitry Andric // member function. We then start with the innermost lambda and iterate 9840b57cec5SDimitry Andric // outward checking to see if any lambda performs a by-copy capture of '*this' 9850b57cec5SDimitry Andric // - and if so, any nested lambda must respect the 'constness' of that 9860b57cec5SDimitry Andric // capturing lamdbda's call operator. 9870b57cec5SDimitry Andric // 9880b57cec5SDimitry Andric 9890b57cec5SDimitry Andric // Since the FunctionScopeInfo stack is representative of the lexical 9900b57cec5SDimitry Andric // nesting of the lambda expressions during initial parsing (and is the best 9910b57cec5SDimitry Andric // place for querying information about captures about lambdas that are 9920b57cec5SDimitry Andric // partially processed) and perhaps during instantiation of function templates 9930b57cec5SDimitry Andric // that contain lambda expressions that need to be transformed BUT not 9940b57cec5SDimitry Andric // necessarily during instantiation of a nested generic lambda's function call 9950b57cec5SDimitry Andric // operator (which might even be instantiated at the end of the TU) - at which 9960b57cec5SDimitry Andric // time the DeclContext tree is mature enough to query capture information 9970b57cec5SDimitry Andric // reliably - we use a two pronged approach to walk through all the lexically 9980b57cec5SDimitry Andric // enclosing lambda expressions: 9990b57cec5SDimitry Andric // 10000b57cec5SDimitry Andric // 1) Climb down the FunctionScopeInfo stack as long as each item represents 10010b57cec5SDimitry Andric // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically 10020b57cec5SDimitry Andric // enclosed by the call-operator of the LSI below it on the stack (while 10030b57cec5SDimitry Andric // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on 10040b57cec5SDimitry Andric // the stack represents the innermost lambda. 10050b57cec5SDimitry Andric // 10060b57cec5SDimitry Andric // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext 10070b57cec5SDimitry Andric // represents a lambda's call operator. If it does, we must be instantiating 10080b57cec5SDimitry Andric // a generic lambda's call operator (represented by the Current LSI, and 10090b57cec5SDimitry Andric // should be the only scenario where an inconsistency between the LSI and the 10100b57cec5SDimitry Andric // DeclContext should occur), so climb out the DeclContexts if they 10110b57cec5SDimitry Andric // represent lambdas, while querying the corresponding closure types 10120b57cec5SDimitry Andric // regarding capture information. 10130b57cec5SDimitry Andric 10140b57cec5SDimitry Andric // 1) Climb down the function scope info stack. 10150b57cec5SDimitry Andric for (int I = FunctionScopes.size(); 10160b57cec5SDimitry Andric I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) && 10170b57cec5SDimitry Andric (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == 10180b57cec5SDimitry Andric cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator); 10190b57cec5SDimitry Andric CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { 10200b57cec5SDimitry Andric CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); 10210b57cec5SDimitry Andric 10220b57cec5SDimitry Andric if (!CurLSI->isCXXThisCaptured()) 10230b57cec5SDimitry Andric continue; 10240b57cec5SDimitry Andric 10250b57cec5SDimitry Andric auto C = CurLSI->getCXXThisCapture(); 10260b57cec5SDimitry Andric 10270b57cec5SDimitry Andric if (C.isCopyCapture()) { 10280b57cec5SDimitry Andric ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 10290b57cec5SDimitry Andric if (CurLSI->CallOperator->isConst()) 10300b57cec5SDimitry Andric ClassType.addConst(); 10310b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 10320b57cec5SDimitry Andric } 10330b57cec5SDimitry Andric } 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can 10360b57cec5SDimitry Andric // happen during instantiation of its nested generic lambda call operator) 10370b57cec5SDimitry Andric if (isLambdaCallOperator(CurDC)) { 10380b57cec5SDimitry Andric assert(CurLSI && "While computing 'this' capture-type for a generic " 10390b57cec5SDimitry Andric "lambda, we must have a corresponding LambdaScopeInfo"); 10400b57cec5SDimitry Andric assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && 10410b57cec5SDimitry Andric "While computing 'this' capture-type for a generic lambda, when we " 10420b57cec5SDimitry Andric "run out of enclosing LSI's, yet the enclosing DC is a " 10430b57cec5SDimitry Andric "lambda-call-operator we must be (i.e. Current LSI) in a generic " 10440b57cec5SDimitry Andric "lambda call oeprator"); 10450b57cec5SDimitry Andric assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); 10460b57cec5SDimitry Andric 10470b57cec5SDimitry Andric auto IsThisCaptured = 10480b57cec5SDimitry Andric [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { 10490b57cec5SDimitry Andric IsConst = false; 10500b57cec5SDimitry Andric IsByCopy = false; 10510b57cec5SDimitry Andric for (auto &&C : Closure->captures()) { 10520b57cec5SDimitry Andric if (C.capturesThis()) { 10530b57cec5SDimitry Andric if (C.getCaptureKind() == LCK_StarThis) 10540b57cec5SDimitry Andric IsByCopy = true; 10550b57cec5SDimitry Andric if (Closure->getLambdaCallOperator()->isConst()) 10560b57cec5SDimitry Andric IsConst = true; 10570b57cec5SDimitry Andric return true; 10580b57cec5SDimitry Andric } 10590b57cec5SDimitry Andric } 10600b57cec5SDimitry Andric return false; 10610b57cec5SDimitry Andric }; 10620b57cec5SDimitry Andric 10630b57cec5SDimitry Andric bool IsByCopyCapture = false; 10640b57cec5SDimitry Andric bool IsConstCapture = false; 10650b57cec5SDimitry Andric CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); 10660b57cec5SDimitry Andric while (Closure && 10670b57cec5SDimitry Andric IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { 10680b57cec5SDimitry Andric if (IsByCopyCapture) { 10690b57cec5SDimitry Andric ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 10700b57cec5SDimitry Andric if (IsConstCapture) 10710b57cec5SDimitry Andric ClassType.addConst(); 10720b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 10730b57cec5SDimitry Andric } 10740b57cec5SDimitry Andric Closure = isLambdaCallOperator(Closure->getParent()) 10750b57cec5SDimitry Andric ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) 10760b57cec5SDimitry Andric : nullptr; 10770b57cec5SDimitry Andric } 10780b57cec5SDimitry Andric } 10790b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 10800b57cec5SDimitry Andric } 10810b57cec5SDimitry Andric 10820b57cec5SDimitry Andric QualType Sema::getCurrentThisType() { 10830b57cec5SDimitry Andric DeclContext *DC = getFunctionLevelDeclContext(); 10840b57cec5SDimitry Andric QualType ThisTy = CXXThisTypeOverride; 10850b57cec5SDimitry Andric 10860b57cec5SDimitry Andric if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { 10870b57cec5SDimitry Andric if (method && method->isInstance()) 10880b57cec5SDimitry Andric ThisTy = method->getThisType(); 10890b57cec5SDimitry Andric } 10900b57cec5SDimitry Andric 10910b57cec5SDimitry Andric if (ThisTy.isNull() && isLambdaCallOperator(CurContext) && 10920b57cec5SDimitry Andric inTemplateInstantiation()) { 10930b57cec5SDimitry Andric 10940b57cec5SDimitry Andric assert(isa<CXXRecordDecl>(DC) && 10950b57cec5SDimitry Andric "Trying to get 'this' type from static method?"); 10960b57cec5SDimitry Andric 10970b57cec5SDimitry Andric // This is a lambda call operator that is being instantiated as a default 10980b57cec5SDimitry Andric // initializer. DC must point to the enclosing class type, so we can recover 10990b57cec5SDimitry Andric // the 'this' type from it. 11000b57cec5SDimitry Andric 11010b57cec5SDimitry Andric QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); 11020b57cec5SDimitry Andric // There are no cv-qualifiers for 'this' within default initializers, 11030b57cec5SDimitry Andric // per [expr.prim.general]p4. 11040b57cec5SDimitry Andric ThisTy = Context.getPointerType(ClassTy); 11050b57cec5SDimitry Andric } 11060b57cec5SDimitry Andric 11070b57cec5SDimitry Andric // If we are within a lambda's call operator, the cv-qualifiers of 'this' 11080b57cec5SDimitry Andric // might need to be adjusted if the lambda or any of its enclosing lambda's 11090b57cec5SDimitry Andric // captures '*this' by copy. 11100b57cec5SDimitry Andric if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) 11110b57cec5SDimitry Andric return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, 11120b57cec5SDimitry Andric CurContext, Context); 11130b57cec5SDimitry Andric return ThisTy; 11140b57cec5SDimitry Andric } 11150b57cec5SDimitry Andric 11160b57cec5SDimitry Andric Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 11170b57cec5SDimitry Andric Decl *ContextDecl, 11180b57cec5SDimitry Andric Qualifiers CXXThisTypeQuals, 11190b57cec5SDimitry Andric bool Enabled) 11200b57cec5SDimitry Andric : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) 11210b57cec5SDimitry Andric { 11220b57cec5SDimitry Andric if (!Enabled || !ContextDecl) 11230b57cec5SDimitry Andric return; 11240b57cec5SDimitry Andric 11250b57cec5SDimitry Andric CXXRecordDecl *Record = nullptr; 11260b57cec5SDimitry Andric if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) 11270b57cec5SDimitry Andric Record = Template->getTemplatedDecl(); 11280b57cec5SDimitry Andric else 11290b57cec5SDimitry Andric Record = cast<CXXRecordDecl>(ContextDecl); 11300b57cec5SDimitry Andric 11310b57cec5SDimitry Andric QualType T = S.Context.getRecordType(Record); 11320b57cec5SDimitry Andric T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals); 11330b57cec5SDimitry Andric 11340b57cec5SDimitry Andric S.CXXThisTypeOverride = S.Context.getPointerType(T); 11350b57cec5SDimitry Andric 11360b57cec5SDimitry Andric this->Enabled = true; 11370b57cec5SDimitry Andric } 11380b57cec5SDimitry Andric 11390b57cec5SDimitry Andric 11400b57cec5SDimitry Andric Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { 11410b57cec5SDimitry Andric if (Enabled) { 11420b57cec5SDimitry Andric S.CXXThisTypeOverride = OldCXXThisTypeOverride; 11430b57cec5SDimitry Andric } 11440b57cec5SDimitry Andric } 11450b57cec5SDimitry Andric 11460b57cec5SDimitry Andric bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, 11470b57cec5SDimitry Andric bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, 11480b57cec5SDimitry Andric const bool ByCopy) { 11490b57cec5SDimitry Andric // We don't need to capture this in an unevaluated context. 11500b57cec5SDimitry Andric if (isUnevaluatedContext() && !Explicit) 11510b57cec5SDimitry Andric return true; 11520b57cec5SDimitry Andric 11530b57cec5SDimitry Andric assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value"); 11540b57cec5SDimitry Andric 11550b57cec5SDimitry Andric const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 11560b57cec5SDimitry Andric ? *FunctionScopeIndexToStopAt 11570b57cec5SDimitry Andric : FunctionScopes.size() - 1; 11580b57cec5SDimitry Andric 11590b57cec5SDimitry Andric // Check that we can capture the *enclosing object* (referred to by '*this') 11600b57cec5SDimitry Andric // by the capturing-entity/closure (lambda/block/etc) at 11610b57cec5SDimitry Andric // MaxFunctionScopesIndex-deep on the FunctionScopes stack. 11620b57cec5SDimitry Andric 11630b57cec5SDimitry Andric // Note: The *enclosing object* can only be captured by-value by a 11640b57cec5SDimitry Andric // closure that is a lambda, using the explicit notation: 11650b57cec5SDimitry Andric // [*this] { ... }. 11660b57cec5SDimitry Andric // Every other capture of the *enclosing object* results in its by-reference 11670b57cec5SDimitry Andric // capture. 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes 11700b57cec5SDimitry Andric // stack), we can capture the *enclosing object* only if: 11710b57cec5SDimitry Andric // - 'L' has an explicit byref or byval capture of the *enclosing object* 11720b57cec5SDimitry Andric // - or, 'L' has an implicit capture. 11730b57cec5SDimitry Andric // AND 11740b57cec5SDimitry Andric // -- there is no enclosing closure 11750b57cec5SDimitry Andric // -- or, there is some enclosing closure 'E' that has already captured the 11760b57cec5SDimitry Andric // *enclosing object*, and every intervening closure (if any) between 'E' 11770b57cec5SDimitry Andric // and 'L' can implicitly capture the *enclosing object*. 11780b57cec5SDimitry Andric // -- or, every enclosing closure can implicitly capture the 11790b57cec5SDimitry Andric // *enclosing object* 11800b57cec5SDimitry Andric 11810b57cec5SDimitry Andric 11820b57cec5SDimitry Andric unsigned NumCapturingClosures = 0; 11830b57cec5SDimitry Andric for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { 11840b57cec5SDimitry Andric if (CapturingScopeInfo *CSI = 11850b57cec5SDimitry Andric dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { 11860b57cec5SDimitry Andric if (CSI->CXXThisCaptureIndex != 0) { 11870b57cec5SDimitry Andric // 'this' is already being captured; there isn't anything more to do. 11880b57cec5SDimitry Andric CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); 11890b57cec5SDimitry Andric break; 11900b57cec5SDimitry Andric } 11910b57cec5SDimitry Andric LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); 11920b57cec5SDimitry Andric if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { 11930b57cec5SDimitry Andric // This context can't implicitly capture 'this'; fail out. 11940b57cec5SDimitry Andric if (BuildAndDiagnose) 11950b57cec5SDimitry Andric Diag(Loc, diag::err_this_capture) 11960b57cec5SDimitry Andric << (Explicit && idx == MaxFunctionScopesIndex); 11970b57cec5SDimitry Andric return true; 11980b57cec5SDimitry Andric } 11990b57cec5SDimitry Andric if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || 12000b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || 12010b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || 12020b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || 12030b57cec5SDimitry Andric (Explicit && idx == MaxFunctionScopesIndex)) { 12040b57cec5SDimitry Andric // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first 12050b57cec5SDimitry Andric // iteration through can be an explicit capture, all enclosing closures, 12060b57cec5SDimitry Andric // if any, must perform implicit captures. 12070b57cec5SDimitry Andric 12080b57cec5SDimitry Andric // This closure can capture 'this'; continue looking upwards. 12090b57cec5SDimitry Andric NumCapturingClosures++; 12100b57cec5SDimitry Andric continue; 12110b57cec5SDimitry Andric } 12120b57cec5SDimitry Andric // This context can't implicitly capture 'this'; fail out. 12130b57cec5SDimitry Andric if (BuildAndDiagnose) 12140b57cec5SDimitry Andric Diag(Loc, diag::err_this_capture) 12150b57cec5SDimitry Andric << (Explicit && idx == MaxFunctionScopesIndex); 12160b57cec5SDimitry Andric return true; 12170b57cec5SDimitry Andric } 12180b57cec5SDimitry Andric break; 12190b57cec5SDimitry Andric } 12200b57cec5SDimitry Andric if (!BuildAndDiagnose) return false; 12210b57cec5SDimitry Andric 12220b57cec5SDimitry Andric // If we got here, then the closure at MaxFunctionScopesIndex on the 12230b57cec5SDimitry Andric // FunctionScopes stack, can capture the *enclosing object*, so capture it 12240b57cec5SDimitry Andric // (including implicit by-reference captures in any enclosing closures). 12250b57cec5SDimitry Andric 12260b57cec5SDimitry Andric // In the loop below, respect the ByCopy flag only for the closure requesting 12270b57cec5SDimitry Andric // the capture (i.e. first iteration through the loop below). Ignore it for 12280b57cec5SDimitry Andric // all enclosing closure's up to NumCapturingClosures (since they must be 12290b57cec5SDimitry Andric // implicitly capturing the *enclosing object* by reference (see loop 12300b57cec5SDimitry Andric // above)). 12310b57cec5SDimitry Andric assert((!ByCopy || 12320b57cec5SDimitry Andric dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && 12330b57cec5SDimitry Andric "Only a lambda can capture the enclosing object (referred to by " 12340b57cec5SDimitry Andric "*this) by copy"); 12350b57cec5SDimitry Andric QualType ThisTy = getCurrentThisType(); 12360b57cec5SDimitry Andric for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; 12370b57cec5SDimitry Andric --idx, --NumCapturingClosures) { 12380b57cec5SDimitry Andric CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 12390b57cec5SDimitry Andric 12400b57cec5SDimitry Andric // The type of the corresponding data member (not a 'this' pointer if 'by 12410b57cec5SDimitry Andric // copy'). 12420b57cec5SDimitry Andric QualType CaptureType = ThisTy; 12430b57cec5SDimitry Andric if (ByCopy) { 12440b57cec5SDimitry Andric // If we are capturing the object referred to by '*this' by copy, ignore 12450b57cec5SDimitry Andric // any cv qualifiers inherited from the type of the member function for 12460b57cec5SDimitry Andric // the type of the closure-type's corresponding data member and any use 12470b57cec5SDimitry Andric // of 'this'. 12480b57cec5SDimitry Andric CaptureType = ThisTy->getPointeeType(); 12490b57cec5SDimitry Andric CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 12500b57cec5SDimitry Andric } 12510b57cec5SDimitry Andric 12520b57cec5SDimitry Andric bool isNested = NumCapturingClosures > 1; 12530b57cec5SDimitry Andric CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); 12540b57cec5SDimitry Andric } 12550b57cec5SDimitry Andric return false; 12560b57cec5SDimitry Andric } 12570b57cec5SDimitry Andric 12580b57cec5SDimitry Andric ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 12590b57cec5SDimitry Andric /// C++ 9.3.2: In the body of a non-static member function, the keyword this 12600b57cec5SDimitry Andric /// is a non-lvalue expression whose value is the address of the object for 12610b57cec5SDimitry Andric /// which the function is called. 12620b57cec5SDimitry Andric 12630b57cec5SDimitry Andric QualType ThisTy = getCurrentThisType(); 12640b57cec5SDimitry Andric if (ThisTy.isNull()) 12650b57cec5SDimitry Andric return Diag(Loc, diag::err_invalid_this_use); 12660b57cec5SDimitry Andric return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); 12670b57cec5SDimitry Andric } 12680b57cec5SDimitry Andric 12690b57cec5SDimitry Andric Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, 12700b57cec5SDimitry Andric bool IsImplicit) { 12710b57cec5SDimitry Andric auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit); 12720b57cec5SDimitry Andric MarkThisReferenced(This); 12730b57cec5SDimitry Andric return This; 12740b57cec5SDimitry Andric } 12750b57cec5SDimitry Andric 12760b57cec5SDimitry Andric void Sema::MarkThisReferenced(CXXThisExpr *This) { 12770b57cec5SDimitry Andric CheckCXXThisCapture(This->getExprLoc()); 12780b57cec5SDimitry Andric } 12790b57cec5SDimitry Andric 12800b57cec5SDimitry Andric bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 12810b57cec5SDimitry Andric // If we're outside the body of a member function, then we'll have a specified 12820b57cec5SDimitry Andric // type for 'this'. 12830b57cec5SDimitry Andric if (CXXThisTypeOverride.isNull()) 12840b57cec5SDimitry Andric return false; 12850b57cec5SDimitry Andric 12860b57cec5SDimitry Andric // Determine whether we're looking into a class that's currently being 12870b57cec5SDimitry Andric // defined. 12880b57cec5SDimitry Andric CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 12890b57cec5SDimitry Andric return Class && Class->isBeingDefined(); 12900b57cec5SDimitry Andric } 12910b57cec5SDimitry Andric 12920b57cec5SDimitry Andric /// Parse construction of a specified type. 12930b57cec5SDimitry Andric /// Can be interpreted either as function-style casting ("int(x)") 12940b57cec5SDimitry Andric /// or class type construction ("ClassType(x,y,z)") 12950b57cec5SDimitry Andric /// or creation of a value-initialized type ("int()"). 12960b57cec5SDimitry Andric ExprResult 12970b57cec5SDimitry Andric Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 12980b57cec5SDimitry Andric SourceLocation LParenOrBraceLoc, 12990b57cec5SDimitry Andric MultiExprArg exprs, 13000b57cec5SDimitry Andric SourceLocation RParenOrBraceLoc, 13010b57cec5SDimitry Andric bool ListInitialization) { 13020b57cec5SDimitry Andric if (!TypeRep) 13030b57cec5SDimitry Andric return ExprError(); 13040b57cec5SDimitry Andric 13050b57cec5SDimitry Andric TypeSourceInfo *TInfo; 13060b57cec5SDimitry Andric QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 13070b57cec5SDimitry Andric if (!TInfo) 13080b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 13090b57cec5SDimitry Andric 13100b57cec5SDimitry Andric auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, 13110b57cec5SDimitry Andric RParenOrBraceLoc, ListInitialization); 13120b57cec5SDimitry Andric // Avoid creating a non-type-dependent expression that contains typos. 13130b57cec5SDimitry Andric // Non-type-dependent expressions are liable to be discarded without 13140b57cec5SDimitry Andric // checking for embedded typos. 13150b57cec5SDimitry Andric if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && 13160b57cec5SDimitry Andric !Result.get()->isTypeDependent()) 13170b57cec5SDimitry Andric Result = CorrectDelayedTyposInExpr(Result.get()); 13180b57cec5SDimitry Andric return Result; 13190b57cec5SDimitry Andric } 13200b57cec5SDimitry Andric 13210b57cec5SDimitry Andric ExprResult 13220b57cec5SDimitry Andric Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 13230b57cec5SDimitry Andric SourceLocation LParenOrBraceLoc, 13240b57cec5SDimitry Andric MultiExprArg Exprs, 13250b57cec5SDimitry Andric SourceLocation RParenOrBraceLoc, 13260b57cec5SDimitry Andric bool ListInitialization) { 13270b57cec5SDimitry Andric QualType Ty = TInfo->getType(); 13280b57cec5SDimitry Andric SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 13290b57cec5SDimitry Andric 13300b57cec5SDimitry Andric if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { 13310b57cec5SDimitry Andric // FIXME: CXXUnresolvedConstructExpr does not model list-initialization 13320b57cec5SDimitry Andric // directly. We work around this by dropping the locations of the braces. 13330b57cec5SDimitry Andric SourceRange Locs = ListInitialization 13340b57cec5SDimitry Andric ? SourceRange() 13350b57cec5SDimitry Andric : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 13360b57cec5SDimitry Andric return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(), 13370b57cec5SDimitry Andric Exprs, Locs.getEnd()); 13380b57cec5SDimitry Andric } 13390b57cec5SDimitry Andric 13400b57cec5SDimitry Andric assert((!ListInitialization || 13410b57cec5SDimitry Andric (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && 13420b57cec5SDimitry Andric "List initialization must have initializer list as expression."); 13430b57cec5SDimitry Andric SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); 13440b57cec5SDimitry Andric 13450b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo); 13460b57cec5SDimitry Andric InitializationKind Kind = 13470b57cec5SDimitry Andric Exprs.size() 13480b57cec5SDimitry Andric ? ListInitialization 13490b57cec5SDimitry Andric ? InitializationKind::CreateDirectList( 13500b57cec5SDimitry Andric TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) 13510b57cec5SDimitry Andric : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, 13520b57cec5SDimitry Andric RParenOrBraceLoc) 13530b57cec5SDimitry Andric : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, 13540b57cec5SDimitry Andric RParenOrBraceLoc); 13550b57cec5SDimitry Andric 13560b57cec5SDimitry Andric // C++1z [expr.type.conv]p1: 13570b57cec5SDimitry Andric // If the type is a placeholder for a deduced class type, [...perform class 13580b57cec5SDimitry Andric // template argument deduction...] 13590b57cec5SDimitry Andric DeducedType *Deduced = Ty->getContainedDeducedType(); 13600b57cec5SDimitry Andric if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 13610b57cec5SDimitry Andric Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, 13620b57cec5SDimitry Andric Kind, Exprs); 13630b57cec5SDimitry Andric if (Ty.isNull()) 13640b57cec5SDimitry Andric return ExprError(); 13650b57cec5SDimitry Andric Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); 13660b57cec5SDimitry Andric } 13670b57cec5SDimitry Andric 13680b57cec5SDimitry Andric // C++ [expr.type.conv]p1: 13690b57cec5SDimitry Andric // If the expression list is a parenthesized single expression, the type 13700b57cec5SDimitry Andric // conversion expression is equivalent (in definedness, and if defined in 13710b57cec5SDimitry Andric // meaning) to the corresponding cast expression. 13720b57cec5SDimitry Andric if (Exprs.size() == 1 && !ListInitialization && 13730b57cec5SDimitry Andric !isa<InitListExpr>(Exprs[0])) { 13740b57cec5SDimitry Andric Expr *Arg = Exprs[0]; 13750b57cec5SDimitry Andric return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, 13760b57cec5SDimitry Andric RParenOrBraceLoc); 13770b57cec5SDimitry Andric } 13780b57cec5SDimitry Andric 13790b57cec5SDimitry Andric // For an expression of the form T(), T shall not be an array type. 13800b57cec5SDimitry Andric QualType ElemTy = Ty; 13810b57cec5SDimitry Andric if (Ty->isArrayType()) { 13820b57cec5SDimitry Andric if (!ListInitialization) 13830b57cec5SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) 13840b57cec5SDimitry Andric << FullRange); 13850b57cec5SDimitry Andric ElemTy = Context.getBaseElementType(Ty); 13860b57cec5SDimitry Andric } 13870b57cec5SDimitry Andric 13880b57cec5SDimitry Andric // There doesn't seem to be an explicit rule against this but sanity demands 13890b57cec5SDimitry Andric // we only construct objects with object types. 13900b57cec5SDimitry Andric if (Ty->isFunctionType()) 13910b57cec5SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) 13920b57cec5SDimitry Andric << Ty << FullRange); 13930b57cec5SDimitry Andric 13940b57cec5SDimitry Andric // C++17 [expr.type.conv]p2: 13950b57cec5SDimitry Andric // If the type is cv void and the initializer is (), the expression is a 13960b57cec5SDimitry Andric // prvalue of the specified type that performs no initialization. 13970b57cec5SDimitry Andric if (!Ty->isVoidType() && 13980b57cec5SDimitry Andric RequireCompleteType(TyBeginLoc, ElemTy, 13990b57cec5SDimitry Andric diag::err_invalid_incomplete_type_use, FullRange)) 14000b57cec5SDimitry Andric return ExprError(); 14010b57cec5SDimitry Andric 14020b57cec5SDimitry Andric // Otherwise, the expression is a prvalue of the specified type whose 14030b57cec5SDimitry Andric // result object is direct-initialized (11.6) with the initializer. 14040b57cec5SDimitry Andric InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 14050b57cec5SDimitry Andric ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); 14060b57cec5SDimitry Andric 14070b57cec5SDimitry Andric if (Result.isInvalid()) 14080b57cec5SDimitry Andric return Result; 14090b57cec5SDimitry Andric 14100b57cec5SDimitry Andric Expr *Inner = Result.get(); 14110b57cec5SDimitry Andric if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) 14120b57cec5SDimitry Andric Inner = BTE->getSubExpr(); 14130b57cec5SDimitry Andric if (!isa<CXXTemporaryObjectExpr>(Inner) && 14140b57cec5SDimitry Andric !isa<CXXScalarValueInitExpr>(Inner)) { 14150b57cec5SDimitry Andric // If we created a CXXTemporaryObjectExpr, that node also represents the 14160b57cec5SDimitry Andric // functional cast. Otherwise, create an explicit cast to represent 14170b57cec5SDimitry Andric // the syntactic form of a functional-style cast that was used here. 14180b57cec5SDimitry Andric // 14190b57cec5SDimitry Andric // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr 14200b57cec5SDimitry Andric // would give a more consistent AST representation than using a 14210b57cec5SDimitry Andric // CXXTemporaryObjectExpr. It's also weird that the functional cast 14220b57cec5SDimitry Andric // is sometimes handled by initialization and sometimes not. 14230b57cec5SDimitry Andric QualType ResultType = Result.get()->getType(); 14240b57cec5SDimitry Andric SourceRange Locs = ListInitialization 14250b57cec5SDimitry Andric ? SourceRange() 14260b57cec5SDimitry Andric : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 14270b57cec5SDimitry Andric Result = CXXFunctionalCastExpr::Create( 14280b57cec5SDimitry Andric Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, 14290b57cec5SDimitry Andric Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd()); 14300b57cec5SDimitry Andric } 14310b57cec5SDimitry Andric 14320b57cec5SDimitry Andric return Result; 14330b57cec5SDimitry Andric } 14340b57cec5SDimitry Andric 14350b57cec5SDimitry Andric bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { 14360b57cec5SDimitry Andric // [CUDA] Ignore this function, if we can't call it. 14370b57cec5SDimitry Andric const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext); 14380b57cec5SDimitry Andric if (getLangOpts().CUDA && 14390b57cec5SDimitry Andric IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide) 14400b57cec5SDimitry Andric return false; 14410b57cec5SDimitry Andric 14420b57cec5SDimitry Andric SmallVector<const FunctionDecl*, 4> PreventedBy; 14430b57cec5SDimitry Andric bool Result = Method->isUsualDeallocationFunction(PreventedBy); 14440b57cec5SDimitry Andric 14450b57cec5SDimitry Andric if (Result || !getLangOpts().CUDA || PreventedBy.empty()) 14460b57cec5SDimitry Andric return Result; 14470b57cec5SDimitry Andric 14480b57cec5SDimitry Andric // In case of CUDA, return true if none of the 1-argument deallocator 14490b57cec5SDimitry Andric // functions are actually callable. 14500b57cec5SDimitry Andric return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { 14510b57cec5SDimitry Andric assert(FD->getNumParams() == 1 && 14520b57cec5SDimitry Andric "Only single-operand functions should be in PreventedBy"); 14530b57cec5SDimitry Andric return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; 14540b57cec5SDimitry Andric }); 14550b57cec5SDimitry Andric } 14560b57cec5SDimitry Andric 14570b57cec5SDimitry Andric /// Determine whether the given function is a non-placement 14580b57cec5SDimitry Andric /// deallocation function. 14590b57cec5SDimitry Andric static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { 14600b57cec5SDimitry Andric if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 14610b57cec5SDimitry Andric return S.isUsualDeallocationFunction(Method); 14620b57cec5SDimitry Andric 14630b57cec5SDimitry Andric if (FD->getOverloadedOperator() != OO_Delete && 14640b57cec5SDimitry Andric FD->getOverloadedOperator() != OO_Array_Delete) 14650b57cec5SDimitry Andric return false; 14660b57cec5SDimitry Andric 14670b57cec5SDimitry Andric unsigned UsualParams = 1; 14680b57cec5SDimitry Andric 14690b57cec5SDimitry Andric if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && 14700b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 14710b57cec5SDimitry Andric FD->getParamDecl(UsualParams)->getType(), 14720b57cec5SDimitry Andric S.Context.getSizeType())) 14730b57cec5SDimitry Andric ++UsualParams; 14740b57cec5SDimitry Andric 14750b57cec5SDimitry Andric if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && 14760b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 14770b57cec5SDimitry Andric FD->getParamDecl(UsualParams)->getType(), 14780b57cec5SDimitry Andric S.Context.getTypeDeclType(S.getStdAlignValT()))) 14790b57cec5SDimitry Andric ++UsualParams; 14800b57cec5SDimitry Andric 14810b57cec5SDimitry Andric return UsualParams == FD->getNumParams(); 14820b57cec5SDimitry Andric } 14830b57cec5SDimitry Andric 14840b57cec5SDimitry Andric namespace { 14850b57cec5SDimitry Andric struct UsualDeallocFnInfo { 14860b57cec5SDimitry Andric UsualDeallocFnInfo() : Found(), FD(nullptr) {} 14870b57cec5SDimitry Andric UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) 14880b57cec5SDimitry Andric : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), 14890b57cec5SDimitry Andric Destroying(false), HasSizeT(false), HasAlignValT(false), 14900b57cec5SDimitry Andric CUDAPref(Sema::CFP_Native) { 14910b57cec5SDimitry Andric // A function template declaration is never a usual deallocation function. 14920b57cec5SDimitry Andric if (!FD) 14930b57cec5SDimitry Andric return; 14940b57cec5SDimitry Andric unsigned NumBaseParams = 1; 14950b57cec5SDimitry Andric if (FD->isDestroyingOperatorDelete()) { 14960b57cec5SDimitry Andric Destroying = true; 14970b57cec5SDimitry Andric ++NumBaseParams; 14980b57cec5SDimitry Andric } 14990b57cec5SDimitry Andric 15000b57cec5SDimitry Andric if (NumBaseParams < FD->getNumParams() && 15010b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 15020b57cec5SDimitry Andric FD->getParamDecl(NumBaseParams)->getType(), 15030b57cec5SDimitry Andric S.Context.getSizeType())) { 15040b57cec5SDimitry Andric ++NumBaseParams; 15050b57cec5SDimitry Andric HasSizeT = true; 15060b57cec5SDimitry Andric } 15070b57cec5SDimitry Andric 15080b57cec5SDimitry Andric if (NumBaseParams < FD->getNumParams() && 15090b57cec5SDimitry Andric FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { 15100b57cec5SDimitry Andric ++NumBaseParams; 15110b57cec5SDimitry Andric HasAlignValT = true; 15120b57cec5SDimitry Andric } 15130b57cec5SDimitry Andric 15140b57cec5SDimitry Andric // In CUDA, determine how much we'd like / dislike to call this. 15150b57cec5SDimitry Andric if (S.getLangOpts().CUDA) 15160b57cec5SDimitry Andric if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 15170b57cec5SDimitry Andric CUDAPref = S.IdentifyCUDAPreference(Caller, FD); 15180b57cec5SDimitry Andric } 15190b57cec5SDimitry Andric 15200b57cec5SDimitry Andric explicit operator bool() const { return FD; } 15210b57cec5SDimitry Andric 15220b57cec5SDimitry Andric bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, 15230b57cec5SDimitry Andric bool WantAlign) const { 15240b57cec5SDimitry Andric // C++ P0722: 15250b57cec5SDimitry Andric // A destroying operator delete is preferred over a non-destroying 15260b57cec5SDimitry Andric // operator delete. 15270b57cec5SDimitry Andric if (Destroying != Other.Destroying) 15280b57cec5SDimitry Andric return Destroying; 15290b57cec5SDimitry Andric 15300b57cec5SDimitry Andric // C++17 [expr.delete]p10: 15310b57cec5SDimitry Andric // If the type has new-extended alignment, a function with a parameter 15320b57cec5SDimitry Andric // of type std::align_val_t is preferred; otherwise a function without 15330b57cec5SDimitry Andric // such a parameter is preferred 15340b57cec5SDimitry Andric if (HasAlignValT != Other.HasAlignValT) 15350b57cec5SDimitry Andric return HasAlignValT == WantAlign; 15360b57cec5SDimitry Andric 15370b57cec5SDimitry Andric if (HasSizeT != Other.HasSizeT) 15380b57cec5SDimitry Andric return HasSizeT == WantSize; 15390b57cec5SDimitry Andric 15400b57cec5SDimitry Andric // Use CUDA call preference as a tiebreaker. 15410b57cec5SDimitry Andric return CUDAPref > Other.CUDAPref; 15420b57cec5SDimitry Andric } 15430b57cec5SDimitry Andric 15440b57cec5SDimitry Andric DeclAccessPair Found; 15450b57cec5SDimitry Andric FunctionDecl *FD; 15460b57cec5SDimitry Andric bool Destroying, HasSizeT, HasAlignValT; 15470b57cec5SDimitry Andric Sema::CUDAFunctionPreference CUDAPref; 15480b57cec5SDimitry Andric }; 15490b57cec5SDimitry Andric } 15500b57cec5SDimitry Andric 15510b57cec5SDimitry Andric /// Determine whether a type has new-extended alignment. This may be called when 15520b57cec5SDimitry Andric /// the type is incomplete (for a delete-expression with an incomplete pointee 15530b57cec5SDimitry Andric /// type), in which case it will conservatively return false if the alignment is 15540b57cec5SDimitry Andric /// not known. 15550b57cec5SDimitry Andric static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { 15560b57cec5SDimitry Andric return S.getLangOpts().AlignedAllocation && 15570b57cec5SDimitry Andric S.getASTContext().getTypeAlignIfKnown(AllocType) > 15580b57cec5SDimitry Andric S.getASTContext().getTargetInfo().getNewAlign(); 15590b57cec5SDimitry Andric } 15600b57cec5SDimitry Andric 15610b57cec5SDimitry Andric /// Select the correct "usual" deallocation function to use from a selection of 15620b57cec5SDimitry Andric /// deallocation functions (either global or class-scope). 15630b57cec5SDimitry Andric static UsualDeallocFnInfo resolveDeallocationOverload( 15640b57cec5SDimitry Andric Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 15650b57cec5SDimitry Andric llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { 15660b57cec5SDimitry Andric UsualDeallocFnInfo Best; 15670b57cec5SDimitry Andric 15680b57cec5SDimitry Andric for (auto I = R.begin(), E = R.end(); I != E; ++I) { 15690b57cec5SDimitry Andric UsualDeallocFnInfo Info(S, I.getPair()); 15700b57cec5SDimitry Andric if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || 15710b57cec5SDimitry Andric Info.CUDAPref == Sema::CFP_Never) 15720b57cec5SDimitry Andric continue; 15730b57cec5SDimitry Andric 15740b57cec5SDimitry Andric if (!Best) { 15750b57cec5SDimitry Andric Best = Info; 15760b57cec5SDimitry Andric if (BestFns) 15770b57cec5SDimitry Andric BestFns->push_back(Info); 15780b57cec5SDimitry Andric continue; 15790b57cec5SDimitry Andric } 15800b57cec5SDimitry Andric 15810b57cec5SDimitry Andric if (Best.isBetterThan(Info, WantSize, WantAlign)) 15820b57cec5SDimitry Andric continue; 15830b57cec5SDimitry Andric 15840b57cec5SDimitry Andric // If more than one preferred function is found, all non-preferred 15850b57cec5SDimitry Andric // functions are eliminated from further consideration. 15860b57cec5SDimitry Andric if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) 15870b57cec5SDimitry Andric BestFns->clear(); 15880b57cec5SDimitry Andric 15890b57cec5SDimitry Andric Best = Info; 15900b57cec5SDimitry Andric if (BestFns) 15910b57cec5SDimitry Andric BestFns->push_back(Info); 15920b57cec5SDimitry Andric } 15930b57cec5SDimitry Andric 15940b57cec5SDimitry Andric return Best; 15950b57cec5SDimitry Andric } 15960b57cec5SDimitry Andric 15970b57cec5SDimitry Andric /// Determine whether a given type is a class for which 'delete[]' would call 15980b57cec5SDimitry Andric /// a member 'operator delete[]' with a 'size_t' parameter. This implies that 15990b57cec5SDimitry Andric /// we need to store the array size (even if the type is 16000b57cec5SDimitry Andric /// trivially-destructible). 16010b57cec5SDimitry Andric static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 16020b57cec5SDimitry Andric QualType allocType) { 16030b57cec5SDimitry Andric const RecordType *record = 16040b57cec5SDimitry Andric allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 16050b57cec5SDimitry Andric if (!record) return false; 16060b57cec5SDimitry Andric 16070b57cec5SDimitry Andric // Try to find an operator delete[] in class scope. 16080b57cec5SDimitry Andric 16090b57cec5SDimitry Andric DeclarationName deleteName = 16100b57cec5SDimitry Andric S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 16110b57cec5SDimitry Andric LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 16120b57cec5SDimitry Andric S.LookupQualifiedName(ops, record->getDecl()); 16130b57cec5SDimitry Andric 16140b57cec5SDimitry Andric // We're just doing this for information. 16150b57cec5SDimitry Andric ops.suppressDiagnostics(); 16160b57cec5SDimitry Andric 16170b57cec5SDimitry Andric // Very likely: there's no operator delete[]. 16180b57cec5SDimitry Andric if (ops.empty()) return false; 16190b57cec5SDimitry Andric 16200b57cec5SDimitry Andric // If it's ambiguous, it should be illegal to call operator delete[] 16210b57cec5SDimitry Andric // on this thing, so it doesn't matter if we allocate extra space or not. 16220b57cec5SDimitry Andric if (ops.isAmbiguous()) return false; 16230b57cec5SDimitry Andric 16240b57cec5SDimitry Andric // C++17 [expr.delete]p10: 16250b57cec5SDimitry Andric // If the deallocation functions have class scope, the one without a 16260b57cec5SDimitry Andric // parameter of type std::size_t is selected. 16270b57cec5SDimitry Andric auto Best = resolveDeallocationOverload( 16280b57cec5SDimitry Andric S, ops, /*WantSize*/false, 16290b57cec5SDimitry Andric /*WantAlign*/hasNewExtendedAlignment(S, allocType)); 16300b57cec5SDimitry Andric return Best && Best.HasSizeT; 16310b57cec5SDimitry Andric } 16320b57cec5SDimitry Andric 16330b57cec5SDimitry Andric /// Parsed a C++ 'new' expression (C++ 5.3.4). 16340b57cec5SDimitry Andric /// 16350b57cec5SDimitry Andric /// E.g.: 16360b57cec5SDimitry Andric /// @code new (memory) int[size][4] @endcode 16370b57cec5SDimitry Andric /// or 16380b57cec5SDimitry Andric /// @code ::new Foo(23, "hello") @endcode 16390b57cec5SDimitry Andric /// 16400b57cec5SDimitry Andric /// \param StartLoc The first location of the expression. 16410b57cec5SDimitry Andric /// \param UseGlobal True if 'new' was prefixed with '::'. 16420b57cec5SDimitry Andric /// \param PlacementLParen Opening paren of the placement arguments. 16430b57cec5SDimitry Andric /// \param PlacementArgs Placement new arguments. 16440b57cec5SDimitry Andric /// \param PlacementRParen Closing paren of the placement arguments. 16450b57cec5SDimitry Andric /// \param TypeIdParens If the type is in parens, the source range. 16460b57cec5SDimitry Andric /// \param D The type to be allocated, as well as array dimensions. 16470b57cec5SDimitry Andric /// \param Initializer The initializing expression or initializer-list, or null 16480b57cec5SDimitry Andric /// if there is none. 16490b57cec5SDimitry Andric ExprResult 16500b57cec5SDimitry Andric Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 16510b57cec5SDimitry Andric SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 16520b57cec5SDimitry Andric SourceLocation PlacementRParen, SourceRange TypeIdParens, 16530b57cec5SDimitry Andric Declarator &D, Expr *Initializer) { 16540b57cec5SDimitry Andric Optional<Expr *> ArraySize; 16550b57cec5SDimitry Andric // If the specified type is an array, unwrap it and save the expression. 16560b57cec5SDimitry Andric if (D.getNumTypeObjects() > 0 && 16570b57cec5SDimitry Andric D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 16580b57cec5SDimitry Andric DeclaratorChunk &Chunk = D.getTypeObject(0); 16590b57cec5SDimitry Andric if (D.getDeclSpec().hasAutoTypeSpec()) 16600b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 16610b57cec5SDimitry Andric << D.getSourceRange()); 16620b57cec5SDimitry Andric if (Chunk.Arr.hasStatic) 16630b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 16640b57cec5SDimitry Andric << D.getSourceRange()); 16650b57cec5SDimitry Andric if (!Chunk.Arr.NumElts && !Initializer) 16660b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 16670b57cec5SDimitry Andric << D.getSourceRange()); 16680b57cec5SDimitry Andric 16690b57cec5SDimitry Andric ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 16700b57cec5SDimitry Andric D.DropFirstTypeObject(); 16710b57cec5SDimitry Andric } 16720b57cec5SDimitry Andric 16730b57cec5SDimitry Andric // Every dimension shall be of constant size. 16740b57cec5SDimitry Andric if (ArraySize) { 16750b57cec5SDimitry Andric for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 16760b57cec5SDimitry Andric if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 16770b57cec5SDimitry Andric break; 16780b57cec5SDimitry Andric 16790b57cec5SDimitry Andric DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 16800b57cec5SDimitry Andric if (Expr *NumElts = (Expr *)Array.NumElts) { 16810b57cec5SDimitry Andric if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 16820b57cec5SDimitry Andric if (getLangOpts().CPlusPlus14) { 16830b57cec5SDimitry Andric // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator 16840b57cec5SDimitry Andric // shall be a converted constant expression (5.19) of type std::size_t 16850b57cec5SDimitry Andric // and shall evaluate to a strictly positive value. 16860b57cec5SDimitry Andric unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16870b57cec5SDimitry Andric assert(IntWidth && "Builtin type of size 0?"); 16880b57cec5SDimitry Andric llvm::APSInt Value(IntWidth); 16890b57cec5SDimitry Andric Array.NumElts 16900b57cec5SDimitry Andric = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, 16910b57cec5SDimitry Andric CCEK_NewExpr) 16920b57cec5SDimitry Andric .get(); 16930b57cec5SDimitry Andric } else { 16940b57cec5SDimitry Andric Array.NumElts 16950b57cec5SDimitry Andric = VerifyIntegerConstantExpression(NumElts, nullptr, 16960b57cec5SDimitry Andric diag::err_new_array_nonconst) 16970b57cec5SDimitry Andric .get(); 16980b57cec5SDimitry Andric } 16990b57cec5SDimitry Andric if (!Array.NumElts) 17000b57cec5SDimitry Andric return ExprError(); 17010b57cec5SDimitry Andric } 17020b57cec5SDimitry Andric } 17030b57cec5SDimitry Andric } 17040b57cec5SDimitry Andric } 17050b57cec5SDimitry Andric 17060b57cec5SDimitry Andric TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); 17070b57cec5SDimitry Andric QualType AllocType = TInfo->getType(); 17080b57cec5SDimitry Andric if (D.isInvalidType()) 17090b57cec5SDimitry Andric return ExprError(); 17100b57cec5SDimitry Andric 17110b57cec5SDimitry Andric SourceRange DirectInitRange; 17120b57cec5SDimitry Andric if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 17130b57cec5SDimitry Andric DirectInitRange = List->getSourceRange(); 17140b57cec5SDimitry Andric 17150b57cec5SDimitry Andric return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, 17160b57cec5SDimitry Andric PlacementLParen, PlacementArgs, PlacementRParen, 17170b57cec5SDimitry Andric TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, 17180b57cec5SDimitry Andric Initializer); 17190b57cec5SDimitry Andric } 17200b57cec5SDimitry Andric 17210b57cec5SDimitry Andric static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 17220b57cec5SDimitry Andric Expr *Init) { 17230b57cec5SDimitry Andric if (!Init) 17240b57cec5SDimitry Andric return true; 17250b57cec5SDimitry Andric if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 17260b57cec5SDimitry Andric return PLE->getNumExprs() == 0; 17270b57cec5SDimitry Andric if (isa<ImplicitValueInitExpr>(Init)) 17280b57cec5SDimitry Andric return true; 17290b57cec5SDimitry Andric else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 17300b57cec5SDimitry Andric return !CCE->isListInitialization() && 17310b57cec5SDimitry Andric CCE->getConstructor()->isDefaultConstructor(); 17320b57cec5SDimitry Andric else if (Style == CXXNewExpr::ListInit) { 17330b57cec5SDimitry Andric assert(isa<InitListExpr>(Init) && 17340b57cec5SDimitry Andric "Shouldn't create list CXXConstructExprs for arrays."); 17350b57cec5SDimitry Andric return true; 17360b57cec5SDimitry Andric } 17370b57cec5SDimitry Andric return false; 17380b57cec5SDimitry Andric } 17390b57cec5SDimitry Andric 17400b57cec5SDimitry Andric bool 17410b57cec5SDimitry Andric Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { 17420b57cec5SDimitry Andric if (!getLangOpts().AlignedAllocationUnavailable) 17430b57cec5SDimitry Andric return false; 17440b57cec5SDimitry Andric if (FD.isDefined()) 17450b57cec5SDimitry Andric return false; 17460b57cec5SDimitry Andric bool IsAligned = false; 17470b57cec5SDimitry Andric if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned) 17480b57cec5SDimitry Andric return true; 17490b57cec5SDimitry Andric return false; 17500b57cec5SDimitry Andric } 17510b57cec5SDimitry Andric 17520b57cec5SDimitry Andric // Emit a diagnostic if an aligned allocation/deallocation function that is not 17530b57cec5SDimitry Andric // implemented in the standard library is selected. 17540b57cec5SDimitry Andric void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 17550b57cec5SDimitry Andric SourceLocation Loc) { 17560b57cec5SDimitry Andric if (isUnavailableAlignedAllocationFunction(FD)) { 17570b57cec5SDimitry Andric const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); 17580b57cec5SDimitry Andric StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( 17590b57cec5SDimitry Andric getASTContext().getTargetInfo().getPlatformName()); 17600b57cec5SDimitry Andric 17610b57cec5SDimitry Andric OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); 17620b57cec5SDimitry Andric bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; 17630b57cec5SDimitry Andric Diag(Loc, diag::err_aligned_allocation_unavailable) 17640b57cec5SDimitry Andric << IsDelete << FD.getType().getAsString() << OSName 17650b57cec5SDimitry Andric << alignedAllocMinVersion(T.getOS()).getAsString(); 17660b57cec5SDimitry Andric Diag(Loc, diag::note_silence_aligned_allocation_unavailable); 17670b57cec5SDimitry Andric } 17680b57cec5SDimitry Andric } 17690b57cec5SDimitry Andric 17700b57cec5SDimitry Andric ExprResult 17710b57cec5SDimitry Andric Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, 17720b57cec5SDimitry Andric SourceLocation PlacementLParen, 17730b57cec5SDimitry Andric MultiExprArg PlacementArgs, 17740b57cec5SDimitry Andric SourceLocation PlacementRParen, 17750b57cec5SDimitry Andric SourceRange TypeIdParens, 17760b57cec5SDimitry Andric QualType AllocType, 17770b57cec5SDimitry Andric TypeSourceInfo *AllocTypeInfo, 17780b57cec5SDimitry Andric Optional<Expr *> ArraySize, 17790b57cec5SDimitry Andric SourceRange DirectInitRange, 17800b57cec5SDimitry Andric Expr *Initializer) { 17810b57cec5SDimitry Andric SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 17820b57cec5SDimitry Andric SourceLocation StartLoc = Range.getBegin(); 17830b57cec5SDimitry Andric 17840b57cec5SDimitry Andric CXXNewExpr::InitializationStyle initStyle; 17850b57cec5SDimitry Andric if (DirectInitRange.isValid()) { 17860b57cec5SDimitry Andric assert(Initializer && "Have parens but no initializer."); 17870b57cec5SDimitry Andric initStyle = CXXNewExpr::CallInit; 17880b57cec5SDimitry Andric } else if (Initializer && isa<InitListExpr>(Initializer)) 17890b57cec5SDimitry Andric initStyle = CXXNewExpr::ListInit; 17900b57cec5SDimitry Andric else { 17910b57cec5SDimitry Andric assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || 17920b57cec5SDimitry Andric isa<CXXConstructExpr>(Initializer)) && 17930b57cec5SDimitry Andric "Initializer expression that cannot have been implicitly created."); 17940b57cec5SDimitry Andric initStyle = CXXNewExpr::NoInit; 17950b57cec5SDimitry Andric } 17960b57cec5SDimitry Andric 17970b57cec5SDimitry Andric Expr **Inits = &Initializer; 17980b57cec5SDimitry Andric unsigned NumInits = Initializer ? 1 : 0; 17990b57cec5SDimitry Andric if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { 18000b57cec5SDimitry Andric assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init"); 18010b57cec5SDimitry Andric Inits = List->getExprs(); 18020b57cec5SDimitry Andric NumInits = List->getNumExprs(); 18030b57cec5SDimitry Andric } 18040b57cec5SDimitry Andric 18050b57cec5SDimitry Andric // C++11 [expr.new]p15: 18060b57cec5SDimitry Andric // A new-expression that creates an object of type T initializes that 18070b57cec5SDimitry Andric // object as follows: 18080b57cec5SDimitry Andric InitializationKind Kind 18090b57cec5SDimitry Andric // - If the new-initializer is omitted, the object is default- 18100b57cec5SDimitry Andric // initialized (8.5); if no initialization is performed, 18110b57cec5SDimitry Andric // the object has indeterminate value 18120b57cec5SDimitry Andric = initStyle == CXXNewExpr::NoInit 18130b57cec5SDimitry Andric ? InitializationKind::CreateDefault(TypeRange.getBegin()) 18140b57cec5SDimitry Andric // - Otherwise, the new-initializer is interpreted according to 18150b57cec5SDimitry Andric // the 18160b57cec5SDimitry Andric // initialization rules of 8.5 for direct-initialization. 18170b57cec5SDimitry Andric : initStyle == CXXNewExpr::ListInit 18180b57cec5SDimitry Andric ? InitializationKind::CreateDirectList( 18190b57cec5SDimitry Andric TypeRange.getBegin(), Initializer->getBeginLoc(), 18200b57cec5SDimitry Andric Initializer->getEndLoc()) 18210b57cec5SDimitry Andric : InitializationKind::CreateDirect(TypeRange.getBegin(), 18220b57cec5SDimitry Andric DirectInitRange.getBegin(), 18230b57cec5SDimitry Andric DirectInitRange.getEnd()); 18240b57cec5SDimitry Andric 18250b57cec5SDimitry Andric // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. 18260b57cec5SDimitry Andric auto *Deduced = AllocType->getContainedDeducedType(); 18270b57cec5SDimitry Andric if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 18280b57cec5SDimitry Andric if (ArraySize) 18290b57cec5SDimitry Andric return ExprError( 18300b57cec5SDimitry Andric Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), 18310b57cec5SDimitry Andric diag::err_deduced_class_template_compound_type) 18320b57cec5SDimitry Andric << /*array*/ 2 18330b57cec5SDimitry Andric << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); 18340b57cec5SDimitry Andric 18350b57cec5SDimitry Andric InitializedEntity Entity 18360b57cec5SDimitry Andric = InitializedEntity::InitializeNew(StartLoc, AllocType); 18370b57cec5SDimitry Andric AllocType = DeduceTemplateSpecializationFromInitializer( 18380b57cec5SDimitry Andric AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits)); 18390b57cec5SDimitry Andric if (AllocType.isNull()) 18400b57cec5SDimitry Andric return ExprError(); 18410b57cec5SDimitry Andric } else if (Deduced) { 18420b57cec5SDimitry Andric bool Braced = (initStyle == CXXNewExpr::ListInit); 18430b57cec5SDimitry Andric if (NumInits == 1) { 18440b57cec5SDimitry Andric if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) { 18450b57cec5SDimitry Andric Inits = p->getInits(); 18460b57cec5SDimitry Andric NumInits = p->getNumInits(); 18470b57cec5SDimitry Andric Braced = true; 18480b57cec5SDimitry Andric } 18490b57cec5SDimitry Andric } 18500b57cec5SDimitry Andric 18510b57cec5SDimitry Andric if (initStyle == CXXNewExpr::NoInit || NumInits == 0) 18520b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 18530b57cec5SDimitry Andric << AllocType << TypeRange); 18540b57cec5SDimitry Andric if (NumInits > 1) { 18550b57cec5SDimitry Andric Expr *FirstBad = Inits[1]; 18560b57cec5SDimitry Andric return ExprError(Diag(FirstBad->getBeginLoc(), 18570b57cec5SDimitry Andric diag::err_auto_new_ctor_multiple_expressions) 18580b57cec5SDimitry Andric << AllocType << TypeRange); 18590b57cec5SDimitry Andric } 18600b57cec5SDimitry Andric if (Braced && !getLangOpts().CPlusPlus17) 18610b57cec5SDimitry Andric Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) 18620b57cec5SDimitry Andric << AllocType << TypeRange; 18630b57cec5SDimitry Andric Expr *Deduce = Inits[0]; 18640b57cec5SDimitry Andric QualType DeducedType; 18650b57cec5SDimitry Andric if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 18660b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 18670b57cec5SDimitry Andric << AllocType << Deduce->getType() 18680b57cec5SDimitry Andric << TypeRange << Deduce->getSourceRange()); 18690b57cec5SDimitry Andric if (DeducedType.isNull()) 18700b57cec5SDimitry Andric return ExprError(); 18710b57cec5SDimitry Andric AllocType = DeducedType; 18720b57cec5SDimitry Andric } 18730b57cec5SDimitry Andric 18740b57cec5SDimitry Andric // Per C++0x [expr.new]p5, the type being constructed may be a 18750b57cec5SDimitry Andric // typedef of an array type. 18760b57cec5SDimitry Andric if (!ArraySize) { 18770b57cec5SDimitry Andric if (const ConstantArrayType *Array 18780b57cec5SDimitry Andric = Context.getAsConstantArrayType(AllocType)) { 18790b57cec5SDimitry Andric ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 18800b57cec5SDimitry Andric Context.getSizeType(), 18810b57cec5SDimitry Andric TypeRange.getEnd()); 18820b57cec5SDimitry Andric AllocType = Array->getElementType(); 18830b57cec5SDimitry Andric } 18840b57cec5SDimitry Andric } 18850b57cec5SDimitry Andric 18860b57cec5SDimitry Andric if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 18870b57cec5SDimitry Andric return ExprError(); 18880b57cec5SDimitry Andric 18890b57cec5SDimitry Andric // In ARC, infer 'retaining' for the allocated 18900b57cec5SDimitry Andric if (getLangOpts().ObjCAutoRefCount && 18910b57cec5SDimitry Andric AllocType.getObjCLifetime() == Qualifiers::OCL_None && 18920b57cec5SDimitry Andric AllocType->isObjCLifetimeType()) { 18930b57cec5SDimitry Andric AllocType = Context.getLifetimeQualifiedType(AllocType, 18940b57cec5SDimitry Andric AllocType->getObjCARCImplicitLifetime()); 18950b57cec5SDimitry Andric } 18960b57cec5SDimitry Andric 18970b57cec5SDimitry Andric QualType ResultType = Context.getPointerType(AllocType); 18980b57cec5SDimitry Andric 18990b57cec5SDimitry Andric if (ArraySize && *ArraySize && 19000b57cec5SDimitry Andric (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { 19010b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(*ArraySize); 19020b57cec5SDimitry Andric if (result.isInvalid()) return ExprError(); 19030b57cec5SDimitry Andric ArraySize = result.get(); 19040b57cec5SDimitry Andric } 19050b57cec5SDimitry Andric // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 19060b57cec5SDimitry Andric // integral or enumeration type with a non-negative value." 19070b57cec5SDimitry Andric // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 19080b57cec5SDimitry Andric // enumeration type, or a class type for which a single non-explicit 19090b57cec5SDimitry Andric // conversion function to integral or unscoped enumeration type exists. 19100b57cec5SDimitry Andric // C++1y [expr.new]p6: The expression [...] is implicitly converted to 19110b57cec5SDimitry Andric // std::size_t. 19120b57cec5SDimitry Andric llvm::Optional<uint64_t> KnownArraySize; 19130b57cec5SDimitry Andric if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { 19140b57cec5SDimitry Andric ExprResult ConvertedSize; 19150b57cec5SDimitry Andric if (getLangOpts().CPlusPlus14) { 19160b57cec5SDimitry Andric assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"); 19170b57cec5SDimitry Andric 19180b57cec5SDimitry Andric ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), 19190b57cec5SDimitry Andric AA_Converting); 19200b57cec5SDimitry Andric 19210b57cec5SDimitry Andric if (!ConvertedSize.isInvalid() && 19220b57cec5SDimitry Andric (*ArraySize)->getType()->getAs<RecordType>()) 19230b57cec5SDimitry Andric // Diagnose the compatibility of this conversion. 19240b57cec5SDimitry Andric Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 19250b57cec5SDimitry Andric << (*ArraySize)->getType() << 0 << "'size_t'"; 19260b57cec5SDimitry Andric } else { 19270b57cec5SDimitry Andric class SizeConvertDiagnoser : public ICEConvertDiagnoser { 19280b57cec5SDimitry Andric protected: 19290b57cec5SDimitry Andric Expr *ArraySize; 19300b57cec5SDimitry Andric 19310b57cec5SDimitry Andric public: 19320b57cec5SDimitry Andric SizeConvertDiagnoser(Expr *ArraySize) 19330b57cec5SDimitry Andric : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 19340b57cec5SDimitry Andric ArraySize(ArraySize) {} 19350b57cec5SDimitry Andric 19360b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 19370b57cec5SDimitry Andric QualType T) override { 19380b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_not_integral) 19390b57cec5SDimitry Andric << S.getLangOpts().CPlusPlus11 << T; 19400b57cec5SDimitry Andric } 19410b57cec5SDimitry Andric 19420b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseIncomplete( 19430b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T) override { 19440b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_incomplete_type) 19450b57cec5SDimitry Andric << T << ArraySize->getSourceRange(); 19460b57cec5SDimitry Andric } 19470b57cec5SDimitry Andric 19480b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseExplicitConv( 19490b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 19500b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 19510b57cec5SDimitry Andric } 19520b57cec5SDimitry Andric 19530b57cec5SDimitry Andric SemaDiagnosticBuilder noteExplicitConv( 19540b57cec5SDimitry Andric Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 19550b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 19560b57cec5SDimitry Andric << ConvTy->isEnumeralType() << ConvTy; 19570b57cec5SDimitry Andric } 19580b57cec5SDimitry Andric 19590b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseAmbiguous( 19600b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T) override { 19610b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 19620b57cec5SDimitry Andric } 19630b57cec5SDimitry Andric 19640b57cec5SDimitry Andric SemaDiagnosticBuilder noteAmbiguous( 19650b57cec5SDimitry Andric Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 19660b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 19670b57cec5SDimitry Andric << ConvTy->isEnumeralType() << ConvTy; 19680b57cec5SDimitry Andric } 19690b57cec5SDimitry Andric 19700b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 19710b57cec5SDimitry Andric QualType T, 19720b57cec5SDimitry Andric QualType ConvTy) override { 19730b57cec5SDimitry Andric return S.Diag(Loc, 19740b57cec5SDimitry Andric S.getLangOpts().CPlusPlus11 19750b57cec5SDimitry Andric ? diag::warn_cxx98_compat_array_size_conversion 19760b57cec5SDimitry Andric : diag::ext_array_size_conversion) 19770b57cec5SDimitry Andric << T << ConvTy->isEnumeralType() << ConvTy; 19780b57cec5SDimitry Andric } 19790b57cec5SDimitry Andric } SizeDiagnoser(*ArraySize); 19800b57cec5SDimitry Andric 19810b57cec5SDimitry Andric ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, 19820b57cec5SDimitry Andric SizeDiagnoser); 19830b57cec5SDimitry Andric } 19840b57cec5SDimitry Andric if (ConvertedSize.isInvalid()) 19850b57cec5SDimitry Andric return ExprError(); 19860b57cec5SDimitry Andric 19870b57cec5SDimitry Andric ArraySize = ConvertedSize.get(); 19880b57cec5SDimitry Andric QualType SizeType = (*ArraySize)->getType(); 19890b57cec5SDimitry Andric 19900b57cec5SDimitry Andric if (!SizeType->isIntegralOrUnscopedEnumerationType()) 19910b57cec5SDimitry Andric return ExprError(); 19920b57cec5SDimitry Andric 19930b57cec5SDimitry Andric // C++98 [expr.new]p7: 19940b57cec5SDimitry Andric // The expression in a direct-new-declarator shall have integral type 19950b57cec5SDimitry Andric // with a non-negative value. 19960b57cec5SDimitry Andric // 19970b57cec5SDimitry Andric // Let's see if this is a constant < 0. If so, we reject it out of hand, 19980b57cec5SDimitry Andric // per CWG1464. Otherwise, if it's not a constant, we must have an 19990b57cec5SDimitry Andric // unparenthesized array type. 20000b57cec5SDimitry Andric if (!(*ArraySize)->isValueDependent()) { 20010b57cec5SDimitry Andric llvm::APSInt Value; 20020b57cec5SDimitry Andric // We've already performed any required implicit conversion to integer or 20030b57cec5SDimitry Andric // unscoped enumeration type. 20040b57cec5SDimitry Andric // FIXME: Per CWG1464, we are required to check the value prior to 20050b57cec5SDimitry Andric // converting to size_t. This will never find a negative array size in 20060b57cec5SDimitry Andric // C++14 onwards, because Value is always unsigned here! 20070b57cec5SDimitry Andric if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) { 20080b57cec5SDimitry Andric if (Value.isSigned() && Value.isNegative()) { 20090b57cec5SDimitry Andric return ExprError(Diag((*ArraySize)->getBeginLoc(), 20100b57cec5SDimitry Andric diag::err_typecheck_negative_array_size) 20110b57cec5SDimitry Andric << (*ArraySize)->getSourceRange()); 20120b57cec5SDimitry Andric } 20130b57cec5SDimitry Andric 20140b57cec5SDimitry Andric if (!AllocType->isDependentType()) { 20150b57cec5SDimitry Andric unsigned ActiveSizeBits = 20160b57cec5SDimitry Andric ConstantArrayType::getNumAddressingBits(Context, AllocType, Value); 20170b57cec5SDimitry Andric if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 20180b57cec5SDimitry Andric return ExprError( 20190b57cec5SDimitry Andric Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) 20200b57cec5SDimitry Andric << Value.toString(10) << (*ArraySize)->getSourceRange()); 20210b57cec5SDimitry Andric } 20220b57cec5SDimitry Andric 20230b57cec5SDimitry Andric KnownArraySize = Value.getZExtValue(); 20240b57cec5SDimitry Andric } else if (TypeIdParens.isValid()) { 20250b57cec5SDimitry Andric // Can't have dynamic array size when the type-id is in parentheses. 20260b57cec5SDimitry Andric Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) 20270b57cec5SDimitry Andric << (*ArraySize)->getSourceRange() 20280b57cec5SDimitry Andric << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 20290b57cec5SDimitry Andric << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 20300b57cec5SDimitry Andric 20310b57cec5SDimitry Andric TypeIdParens = SourceRange(); 20320b57cec5SDimitry Andric } 20330b57cec5SDimitry Andric } 20340b57cec5SDimitry Andric 20350b57cec5SDimitry Andric // Note that we do *not* convert the argument in any way. It can 20360b57cec5SDimitry Andric // be signed, larger than size_t, whatever. 20370b57cec5SDimitry Andric } 20380b57cec5SDimitry Andric 20390b57cec5SDimitry Andric FunctionDecl *OperatorNew = nullptr; 20400b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 20410b57cec5SDimitry Andric unsigned Alignment = 20420b57cec5SDimitry Andric AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); 20430b57cec5SDimitry Andric unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); 20440b57cec5SDimitry Andric bool PassAlignment = getLangOpts().AlignedAllocation && 20450b57cec5SDimitry Andric Alignment > NewAlignment; 20460b57cec5SDimitry Andric 20470b57cec5SDimitry Andric AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; 20480b57cec5SDimitry Andric if (!AllocType->isDependentType() && 20490b57cec5SDimitry Andric !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 20500b57cec5SDimitry Andric FindAllocationFunctions( 20510b57cec5SDimitry Andric StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, 20520b57cec5SDimitry Andric AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs, 20530b57cec5SDimitry Andric OperatorNew, OperatorDelete)) 20540b57cec5SDimitry Andric return ExprError(); 20550b57cec5SDimitry Andric 20560b57cec5SDimitry Andric // If this is an array allocation, compute whether the usual array 20570b57cec5SDimitry Andric // deallocation function for the type has a size_t parameter. 20580b57cec5SDimitry Andric bool UsualArrayDeleteWantsSize = false; 20590b57cec5SDimitry Andric if (ArraySize && !AllocType->isDependentType()) 20600b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 20610b57cec5SDimitry Andric doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 20620b57cec5SDimitry Andric 20630b57cec5SDimitry Andric SmallVector<Expr *, 8> AllPlaceArgs; 20640b57cec5SDimitry Andric if (OperatorNew) { 20650b57cec5SDimitry Andric const FunctionProtoType *Proto = 20660b57cec5SDimitry Andric OperatorNew->getType()->getAs<FunctionProtoType>(); 20670b57cec5SDimitry Andric VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction 20680b57cec5SDimitry Andric : VariadicDoesNotApply; 20690b57cec5SDimitry Andric 20700b57cec5SDimitry Andric // We've already converted the placement args, just fill in any default 20710b57cec5SDimitry Andric // arguments. Skip the first parameter because we don't have a corresponding 20720b57cec5SDimitry Andric // argument. Skip the second parameter too if we're passing in the 20730b57cec5SDimitry Andric // alignment; we've already filled it in. 20740b57cec5SDimitry Andric if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 20750b57cec5SDimitry Andric PassAlignment ? 2 : 1, PlacementArgs, 20760b57cec5SDimitry Andric AllPlaceArgs, CallType)) 20770b57cec5SDimitry Andric return ExprError(); 20780b57cec5SDimitry Andric 20790b57cec5SDimitry Andric if (!AllPlaceArgs.empty()) 20800b57cec5SDimitry Andric PlacementArgs = AllPlaceArgs; 20810b57cec5SDimitry Andric 20820b57cec5SDimitry Andric // FIXME: This is wrong: PlacementArgs misses out the first (size) argument. 20830b57cec5SDimitry Andric DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs); 20840b57cec5SDimitry Andric 20850b57cec5SDimitry Andric // FIXME: Missing call to CheckFunctionCall or equivalent 20860b57cec5SDimitry Andric 20870b57cec5SDimitry Andric // Warn if the type is over-aligned and is being allocated by (unaligned) 20880b57cec5SDimitry Andric // global operator new. 20890b57cec5SDimitry Andric if (PlacementArgs.empty() && !PassAlignment && 20900b57cec5SDimitry Andric (OperatorNew->isImplicit() || 20910b57cec5SDimitry Andric (OperatorNew->getBeginLoc().isValid() && 20920b57cec5SDimitry Andric getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { 20930b57cec5SDimitry Andric if (Alignment > NewAlignment) 20940b57cec5SDimitry Andric Diag(StartLoc, diag::warn_overaligned_type) 20950b57cec5SDimitry Andric << AllocType 20960b57cec5SDimitry Andric << unsigned(Alignment / Context.getCharWidth()) 20970b57cec5SDimitry Andric << unsigned(NewAlignment / Context.getCharWidth()); 20980b57cec5SDimitry Andric } 20990b57cec5SDimitry Andric } 21000b57cec5SDimitry Andric 21010b57cec5SDimitry Andric // Array 'new' can't have any initializers except empty parentheses. 21020b57cec5SDimitry Andric // Initializer lists are also allowed, in C++11. Rely on the parser for the 21030b57cec5SDimitry Andric // dialect distinction. 21040b57cec5SDimitry Andric if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { 21050b57cec5SDimitry Andric SourceRange InitRange(Inits[0]->getBeginLoc(), 21060b57cec5SDimitry Andric Inits[NumInits - 1]->getEndLoc()); 21070b57cec5SDimitry Andric Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 21080b57cec5SDimitry Andric return ExprError(); 21090b57cec5SDimitry Andric } 21100b57cec5SDimitry Andric 21110b57cec5SDimitry Andric // If we can perform the initialization, and we've not already done so, 21120b57cec5SDimitry Andric // do it now. 21130b57cec5SDimitry Andric if (!AllocType->isDependentType() && 21140b57cec5SDimitry Andric !Expr::hasAnyTypeDependentArguments( 21150b57cec5SDimitry Andric llvm::makeArrayRef(Inits, NumInits))) { 21160b57cec5SDimitry Andric // The type we initialize is the complete type, including the array bound. 21170b57cec5SDimitry Andric QualType InitType; 21180b57cec5SDimitry Andric if (KnownArraySize) 21190b57cec5SDimitry Andric InitType = Context.getConstantArrayType( 2120a7dea167SDimitry Andric AllocType, 2121a7dea167SDimitry Andric llvm::APInt(Context.getTypeSize(Context.getSizeType()), 21220b57cec5SDimitry Andric *KnownArraySize), 2123a7dea167SDimitry Andric *ArraySize, ArrayType::Normal, 0); 21240b57cec5SDimitry Andric else if (ArraySize) 21250b57cec5SDimitry Andric InitType = 21260b57cec5SDimitry Andric Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); 21270b57cec5SDimitry Andric else 21280b57cec5SDimitry Andric InitType = AllocType; 21290b57cec5SDimitry Andric 21300b57cec5SDimitry Andric InitializedEntity Entity 21310b57cec5SDimitry Andric = InitializedEntity::InitializeNew(StartLoc, InitType); 21320b57cec5SDimitry Andric InitializationSequence InitSeq(*this, Entity, Kind, 21330b57cec5SDimitry Andric MultiExprArg(Inits, NumInits)); 21340b57cec5SDimitry Andric ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 21350b57cec5SDimitry Andric MultiExprArg(Inits, NumInits)); 21360b57cec5SDimitry Andric if (FullInit.isInvalid()) 21370b57cec5SDimitry Andric return ExprError(); 21380b57cec5SDimitry Andric 21390b57cec5SDimitry Andric // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 21400b57cec5SDimitry Andric // we don't want the initialized object to be destructed. 21410b57cec5SDimitry Andric // FIXME: We should not create these in the first place. 21420b57cec5SDimitry Andric if (CXXBindTemporaryExpr *Binder = 21430b57cec5SDimitry Andric dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 21440b57cec5SDimitry Andric FullInit = Binder->getSubExpr(); 21450b57cec5SDimitry Andric 21460b57cec5SDimitry Andric Initializer = FullInit.get(); 21470b57cec5SDimitry Andric 21480b57cec5SDimitry Andric // FIXME: If we have a KnownArraySize, check that the array bound of the 21490b57cec5SDimitry Andric // initializer is no greater than that constant value. 21500b57cec5SDimitry Andric 21510b57cec5SDimitry Andric if (ArraySize && !*ArraySize) { 21520b57cec5SDimitry Andric auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); 21530b57cec5SDimitry Andric if (CAT) { 21540b57cec5SDimitry Andric // FIXME: Track that the array size was inferred rather than explicitly 21550b57cec5SDimitry Andric // specified. 21560b57cec5SDimitry Andric ArraySize = IntegerLiteral::Create( 21570b57cec5SDimitry Andric Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); 21580b57cec5SDimitry Andric } else { 21590b57cec5SDimitry Andric Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) 21600b57cec5SDimitry Andric << Initializer->getSourceRange(); 21610b57cec5SDimitry Andric } 21620b57cec5SDimitry Andric } 21630b57cec5SDimitry Andric } 21640b57cec5SDimitry Andric 21650b57cec5SDimitry Andric // Mark the new and delete operators as referenced. 21660b57cec5SDimitry Andric if (OperatorNew) { 21670b57cec5SDimitry Andric if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 21680b57cec5SDimitry Andric return ExprError(); 21690b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorNew); 21700b57cec5SDimitry Andric } 21710b57cec5SDimitry Andric if (OperatorDelete) { 21720b57cec5SDimitry Andric if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 21730b57cec5SDimitry Andric return ExprError(); 21740b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorDelete); 21750b57cec5SDimitry Andric } 21760b57cec5SDimitry Andric 21770b57cec5SDimitry Andric return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, 21780b57cec5SDimitry Andric PassAlignment, UsualArrayDeleteWantsSize, 21790b57cec5SDimitry Andric PlacementArgs, TypeIdParens, ArraySize, initStyle, 21800b57cec5SDimitry Andric Initializer, ResultType, AllocTypeInfo, Range, 21810b57cec5SDimitry Andric DirectInitRange); 21820b57cec5SDimitry Andric } 21830b57cec5SDimitry Andric 21840b57cec5SDimitry Andric /// Checks that a type is suitable as the allocated type 21850b57cec5SDimitry Andric /// in a new-expression. 21860b57cec5SDimitry Andric bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 21870b57cec5SDimitry Andric SourceRange R) { 21880b57cec5SDimitry Andric // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 21890b57cec5SDimitry Andric // abstract class type or array thereof. 21900b57cec5SDimitry Andric if (AllocType->isFunctionType()) 21910b57cec5SDimitry Andric return Diag(Loc, diag::err_bad_new_type) 21920b57cec5SDimitry Andric << AllocType << 0 << R; 21930b57cec5SDimitry Andric else if (AllocType->isReferenceType()) 21940b57cec5SDimitry Andric return Diag(Loc, diag::err_bad_new_type) 21950b57cec5SDimitry Andric << AllocType << 1 << R; 21960b57cec5SDimitry Andric else if (!AllocType->isDependentType() && 21970b57cec5SDimitry Andric RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R)) 21980b57cec5SDimitry Andric return true; 21990b57cec5SDimitry Andric else if (RequireNonAbstractType(Loc, AllocType, 22000b57cec5SDimitry Andric diag::err_allocation_of_abstract_type)) 22010b57cec5SDimitry Andric return true; 22020b57cec5SDimitry Andric else if (AllocType->isVariablyModifiedType()) 22030b57cec5SDimitry Andric return Diag(Loc, diag::err_variably_modified_new_type) 22040b57cec5SDimitry Andric << AllocType; 22050b57cec5SDimitry Andric else if (AllocType.getAddressSpace() != LangAS::Default && 22060b57cec5SDimitry Andric !getLangOpts().OpenCLCPlusPlus) 22070b57cec5SDimitry Andric return Diag(Loc, diag::err_address_space_qualified_new) 22080b57cec5SDimitry Andric << AllocType.getUnqualifiedType() 22090b57cec5SDimitry Andric << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); 22100b57cec5SDimitry Andric else if (getLangOpts().ObjCAutoRefCount) { 22110b57cec5SDimitry Andric if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 22120b57cec5SDimitry Andric QualType BaseAllocType = Context.getBaseElementType(AT); 22130b57cec5SDimitry Andric if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 22140b57cec5SDimitry Andric BaseAllocType->isObjCLifetimeType()) 22150b57cec5SDimitry Andric return Diag(Loc, diag::err_arc_new_array_without_ownership) 22160b57cec5SDimitry Andric << BaseAllocType; 22170b57cec5SDimitry Andric } 22180b57cec5SDimitry Andric } 22190b57cec5SDimitry Andric 22200b57cec5SDimitry Andric return false; 22210b57cec5SDimitry Andric } 22220b57cec5SDimitry Andric 22230b57cec5SDimitry Andric static bool resolveAllocationOverload( 22240b57cec5SDimitry Andric Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, 22250b57cec5SDimitry Andric bool &PassAlignment, FunctionDecl *&Operator, 22260b57cec5SDimitry Andric OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { 22270b57cec5SDimitry Andric OverloadCandidateSet Candidates(R.getNameLoc(), 22280b57cec5SDimitry Andric OverloadCandidateSet::CSK_Normal); 22290b57cec5SDimitry Andric for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 22300b57cec5SDimitry Andric Alloc != AllocEnd; ++Alloc) { 22310b57cec5SDimitry Andric // Even member operator new/delete are implicitly treated as 22320b57cec5SDimitry Andric // static, so don't use AddMemberCandidate. 22330b57cec5SDimitry Andric NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 22340b57cec5SDimitry Andric 22350b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 22360b57cec5SDimitry Andric S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 22370b57cec5SDimitry Andric /*ExplicitTemplateArgs=*/nullptr, Args, 22380b57cec5SDimitry Andric Candidates, 22390b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 22400b57cec5SDimitry Andric continue; 22410b57cec5SDimitry Andric } 22420b57cec5SDimitry Andric 22430b57cec5SDimitry Andric FunctionDecl *Fn = cast<FunctionDecl>(D); 22440b57cec5SDimitry Andric S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 22450b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 22460b57cec5SDimitry Andric } 22470b57cec5SDimitry Andric 22480b57cec5SDimitry Andric // Do the resolution. 22490b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 22500b57cec5SDimitry Andric switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 22510b57cec5SDimitry Andric case OR_Success: { 22520b57cec5SDimitry Andric // Got one! 22530b57cec5SDimitry Andric FunctionDecl *FnDecl = Best->Function; 22540b57cec5SDimitry Andric if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), 22550b57cec5SDimitry Andric Best->FoundDecl) == Sema::AR_inaccessible) 22560b57cec5SDimitry Andric return true; 22570b57cec5SDimitry Andric 22580b57cec5SDimitry Andric Operator = FnDecl; 22590b57cec5SDimitry Andric return false; 22600b57cec5SDimitry Andric } 22610b57cec5SDimitry Andric 22620b57cec5SDimitry Andric case OR_No_Viable_Function: 22630b57cec5SDimitry Andric // C++17 [expr.new]p13: 22640b57cec5SDimitry Andric // If no matching function is found and the allocated object type has 22650b57cec5SDimitry Andric // new-extended alignment, the alignment argument is removed from the 22660b57cec5SDimitry Andric // argument list, and overload resolution is performed again. 22670b57cec5SDimitry Andric if (PassAlignment) { 22680b57cec5SDimitry Andric PassAlignment = false; 22690b57cec5SDimitry Andric AlignArg = Args[1]; 22700b57cec5SDimitry Andric Args.erase(Args.begin() + 1); 22710b57cec5SDimitry Andric return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 22720b57cec5SDimitry Andric Operator, &Candidates, AlignArg, 22730b57cec5SDimitry Andric Diagnose); 22740b57cec5SDimitry Andric } 22750b57cec5SDimitry Andric 22760b57cec5SDimitry Andric // MSVC will fall back on trying to find a matching global operator new 22770b57cec5SDimitry Andric // if operator new[] cannot be found. Also, MSVC will leak by not 22780b57cec5SDimitry Andric // generating a call to operator delete or operator delete[], but we 22790b57cec5SDimitry Andric // will not replicate that bug. 22800b57cec5SDimitry Andric // FIXME: Find out how this interacts with the std::align_val_t fallback 22810b57cec5SDimitry Andric // once MSVC implements it. 22820b57cec5SDimitry Andric if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && 22830b57cec5SDimitry Andric S.Context.getLangOpts().MSVCCompat) { 22840b57cec5SDimitry Andric R.clear(); 22850b57cec5SDimitry Andric R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); 22860b57cec5SDimitry Andric S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 22870b57cec5SDimitry Andric // FIXME: This will give bad diagnostics pointing at the wrong functions. 22880b57cec5SDimitry Andric return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 22890b57cec5SDimitry Andric Operator, /*Candidates=*/nullptr, 22900b57cec5SDimitry Andric /*AlignArg=*/nullptr, Diagnose); 22910b57cec5SDimitry Andric } 22920b57cec5SDimitry Andric 22930b57cec5SDimitry Andric if (Diagnose) { 22940b57cec5SDimitry Andric PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call) 22950b57cec5SDimitry Andric << R.getLookupName() << Range); 22960b57cec5SDimitry Andric 22970b57cec5SDimitry Andric // If we have aligned candidates, only note the align_val_t candidates 22980b57cec5SDimitry Andric // from AlignedCandidates and the non-align_val_t candidates from 22990b57cec5SDimitry Andric // Candidates. 23000b57cec5SDimitry Andric if (AlignedCandidates) { 23010b57cec5SDimitry Andric auto IsAligned = [](OverloadCandidate &C) { 23020b57cec5SDimitry Andric return C.Function->getNumParams() > 1 && 23030b57cec5SDimitry Andric C.Function->getParamDecl(1)->getType()->isAlignValT(); 23040b57cec5SDimitry Andric }; 23050b57cec5SDimitry Andric auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; 23060b57cec5SDimitry Andric 23070b57cec5SDimitry Andric // This was an overaligned allocation, so list the aligned candidates 23080b57cec5SDimitry Andric // first. 23090b57cec5SDimitry Andric Args.insert(Args.begin() + 1, AlignArg); 23100b57cec5SDimitry Andric AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "", 23110b57cec5SDimitry Andric R.getNameLoc(), IsAligned); 23120b57cec5SDimitry Andric Args.erase(Args.begin() + 1); 23130b57cec5SDimitry Andric Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(), 23140b57cec5SDimitry Andric IsUnaligned); 23150b57cec5SDimitry Andric } else { 23160b57cec5SDimitry Andric Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args); 23170b57cec5SDimitry Andric } 23180b57cec5SDimitry Andric } 23190b57cec5SDimitry Andric return true; 23200b57cec5SDimitry Andric 23210b57cec5SDimitry Andric case OR_Ambiguous: 23220b57cec5SDimitry Andric if (Diagnose) { 23230b57cec5SDimitry Andric Candidates.NoteCandidates( 23240b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 23250b57cec5SDimitry Andric S.PDiag(diag::err_ovl_ambiguous_call) 23260b57cec5SDimitry Andric << R.getLookupName() << Range), 2327480093f4SDimitry Andric S, OCD_AmbiguousCandidates, Args); 23280b57cec5SDimitry Andric } 23290b57cec5SDimitry Andric return true; 23300b57cec5SDimitry Andric 23310b57cec5SDimitry Andric case OR_Deleted: { 23320b57cec5SDimitry Andric if (Diagnose) { 23330b57cec5SDimitry Andric Candidates.NoteCandidates( 23340b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 23350b57cec5SDimitry Andric S.PDiag(diag::err_ovl_deleted_call) 23360b57cec5SDimitry Andric << R.getLookupName() << Range), 23370b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 23380b57cec5SDimitry Andric } 23390b57cec5SDimitry Andric return true; 23400b57cec5SDimitry Andric } 23410b57cec5SDimitry Andric } 23420b57cec5SDimitry Andric llvm_unreachable("Unreachable, bad result from BestViableFunction"); 23430b57cec5SDimitry Andric } 23440b57cec5SDimitry Andric 23450b57cec5SDimitry Andric bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 23460b57cec5SDimitry Andric AllocationFunctionScope NewScope, 23470b57cec5SDimitry Andric AllocationFunctionScope DeleteScope, 23480b57cec5SDimitry Andric QualType AllocType, bool IsArray, 23490b57cec5SDimitry Andric bool &PassAlignment, MultiExprArg PlaceArgs, 23500b57cec5SDimitry Andric FunctionDecl *&OperatorNew, 23510b57cec5SDimitry Andric FunctionDecl *&OperatorDelete, 23520b57cec5SDimitry Andric bool Diagnose) { 23530b57cec5SDimitry Andric // --- Choosing an allocation function --- 23540b57cec5SDimitry Andric // C++ 5.3.4p8 - 14 & 18 23550b57cec5SDimitry Andric // 1) If looking in AFS_Global scope for allocation functions, only look in 23560b57cec5SDimitry Andric // the global scope. Else, if AFS_Class, only look in the scope of the 23570b57cec5SDimitry Andric // allocated class. If AFS_Both, look in both. 23580b57cec5SDimitry Andric // 2) If an array size is given, look for operator new[], else look for 23590b57cec5SDimitry Andric // operator new. 23600b57cec5SDimitry Andric // 3) The first argument is always size_t. Append the arguments from the 23610b57cec5SDimitry Andric // placement form. 23620b57cec5SDimitry Andric 23630b57cec5SDimitry Andric SmallVector<Expr*, 8> AllocArgs; 23640b57cec5SDimitry Andric AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); 23650b57cec5SDimitry Andric 23660b57cec5SDimitry Andric // We don't care about the actual value of these arguments. 23670b57cec5SDimitry Andric // FIXME: Should the Sema create the expression and embed it in the syntax 23680b57cec5SDimitry Andric // tree? Or should the consumer just recalculate the value? 23690b57cec5SDimitry Andric // FIXME: Using a dummy value will interact poorly with attribute enable_if. 23700b57cec5SDimitry Andric IntegerLiteral Size(Context, llvm::APInt::getNullValue( 23710b57cec5SDimitry Andric Context.getTargetInfo().getPointerWidth(0)), 23720b57cec5SDimitry Andric Context.getSizeType(), 23730b57cec5SDimitry Andric SourceLocation()); 23740b57cec5SDimitry Andric AllocArgs.push_back(&Size); 23750b57cec5SDimitry Andric 23760b57cec5SDimitry Andric QualType AlignValT = Context.VoidTy; 23770b57cec5SDimitry Andric if (PassAlignment) { 23780b57cec5SDimitry Andric DeclareGlobalNewDelete(); 23790b57cec5SDimitry Andric AlignValT = Context.getTypeDeclType(getStdAlignValT()); 23800b57cec5SDimitry Andric } 23810b57cec5SDimitry Andric CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); 23820b57cec5SDimitry Andric if (PassAlignment) 23830b57cec5SDimitry Andric AllocArgs.push_back(&Align); 23840b57cec5SDimitry Andric 23850b57cec5SDimitry Andric AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); 23860b57cec5SDimitry Andric 23870b57cec5SDimitry Andric // C++ [expr.new]p8: 23880b57cec5SDimitry Andric // If the allocated type is a non-array type, the allocation 23890b57cec5SDimitry Andric // function's name is operator new and the deallocation function's 23900b57cec5SDimitry Andric // name is operator delete. If the allocated type is an array 23910b57cec5SDimitry Andric // type, the allocation function's name is operator new[] and the 23920b57cec5SDimitry Andric // deallocation function's name is operator delete[]. 23930b57cec5SDimitry Andric DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 23940b57cec5SDimitry Andric IsArray ? OO_Array_New : OO_New); 23950b57cec5SDimitry Andric 23960b57cec5SDimitry Andric QualType AllocElemType = Context.getBaseElementType(AllocType); 23970b57cec5SDimitry Andric 23980b57cec5SDimitry Andric // Find the allocation function. 23990b57cec5SDimitry Andric { 24000b57cec5SDimitry Andric LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); 24010b57cec5SDimitry Andric 24020b57cec5SDimitry Andric // C++1z [expr.new]p9: 24030b57cec5SDimitry Andric // If the new-expression begins with a unary :: operator, the allocation 24040b57cec5SDimitry Andric // function's name is looked up in the global scope. Otherwise, if the 24050b57cec5SDimitry Andric // allocated type is a class type T or array thereof, the allocation 24060b57cec5SDimitry Andric // function's name is looked up in the scope of T. 24070b57cec5SDimitry Andric if (AllocElemType->isRecordType() && NewScope != AFS_Global) 24080b57cec5SDimitry Andric LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); 24090b57cec5SDimitry Andric 24100b57cec5SDimitry Andric // We can see ambiguity here if the allocation function is found in 24110b57cec5SDimitry Andric // multiple base classes. 24120b57cec5SDimitry Andric if (R.isAmbiguous()) 24130b57cec5SDimitry Andric return true; 24140b57cec5SDimitry Andric 24150b57cec5SDimitry Andric // If this lookup fails to find the name, or if the allocated type is not 24160b57cec5SDimitry Andric // a class type, the allocation function's name is looked up in the 24170b57cec5SDimitry Andric // global scope. 24180b57cec5SDimitry Andric if (R.empty()) { 24190b57cec5SDimitry Andric if (NewScope == AFS_Class) 24200b57cec5SDimitry Andric return true; 24210b57cec5SDimitry Andric 24220b57cec5SDimitry Andric LookupQualifiedName(R, Context.getTranslationUnitDecl()); 24230b57cec5SDimitry Andric } 24240b57cec5SDimitry Andric 24250b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus && R.empty()) { 24260b57cec5SDimitry Andric if (PlaceArgs.empty()) { 24270b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; 24280b57cec5SDimitry Andric } else { 24290b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_placement_new); 24300b57cec5SDimitry Andric } 24310b57cec5SDimitry Andric return true; 24320b57cec5SDimitry Andric } 24330b57cec5SDimitry Andric 24340b57cec5SDimitry Andric assert(!R.empty() && "implicitly declared allocation functions not found"); 24350b57cec5SDimitry Andric assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 24360b57cec5SDimitry Andric 24370b57cec5SDimitry Andric // We do our own custom access checks below. 24380b57cec5SDimitry Andric R.suppressDiagnostics(); 24390b57cec5SDimitry Andric 24400b57cec5SDimitry Andric if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, 24410b57cec5SDimitry Andric OperatorNew, /*Candidates=*/nullptr, 24420b57cec5SDimitry Andric /*AlignArg=*/nullptr, Diagnose)) 24430b57cec5SDimitry Andric return true; 24440b57cec5SDimitry Andric } 24450b57cec5SDimitry Andric 24460b57cec5SDimitry Andric // We don't need an operator delete if we're running under -fno-exceptions. 24470b57cec5SDimitry Andric if (!getLangOpts().Exceptions) { 24480b57cec5SDimitry Andric OperatorDelete = nullptr; 24490b57cec5SDimitry Andric return false; 24500b57cec5SDimitry Andric } 24510b57cec5SDimitry Andric 24520b57cec5SDimitry Andric // Note, the name of OperatorNew might have been changed from array to 24530b57cec5SDimitry Andric // non-array by resolveAllocationOverload. 24540b57cec5SDimitry Andric DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 24550b57cec5SDimitry Andric OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New 24560b57cec5SDimitry Andric ? OO_Array_Delete 24570b57cec5SDimitry Andric : OO_Delete); 24580b57cec5SDimitry Andric 24590b57cec5SDimitry Andric // C++ [expr.new]p19: 24600b57cec5SDimitry Andric // 24610b57cec5SDimitry Andric // If the new-expression begins with a unary :: operator, the 24620b57cec5SDimitry Andric // deallocation function's name is looked up in the global 24630b57cec5SDimitry Andric // scope. Otherwise, if the allocated type is a class type T or an 24640b57cec5SDimitry Andric // array thereof, the deallocation function's name is looked up in 24650b57cec5SDimitry Andric // the scope of T. If this lookup fails to find the name, or if 24660b57cec5SDimitry Andric // the allocated type is not a class type or array thereof, the 24670b57cec5SDimitry Andric // deallocation function's name is looked up in the global scope. 24680b57cec5SDimitry Andric LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 24690b57cec5SDimitry Andric if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { 2470a7dea167SDimitry Andric auto *RD = 2471a7dea167SDimitry Andric cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); 24720b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, RD); 24730b57cec5SDimitry Andric } 24740b57cec5SDimitry Andric if (FoundDelete.isAmbiguous()) 24750b57cec5SDimitry Andric return true; // FIXME: clean up expressions? 24760b57cec5SDimitry Andric 24770b57cec5SDimitry Andric bool FoundGlobalDelete = FoundDelete.empty(); 24780b57cec5SDimitry Andric if (FoundDelete.empty()) { 24790b57cec5SDimitry Andric if (DeleteScope == AFS_Class) 24800b57cec5SDimitry Andric return true; 24810b57cec5SDimitry Andric 24820b57cec5SDimitry Andric DeclareGlobalNewDelete(); 24830b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 24840b57cec5SDimitry Andric } 24850b57cec5SDimitry Andric 24860b57cec5SDimitry Andric FoundDelete.suppressDiagnostics(); 24870b57cec5SDimitry Andric 24880b57cec5SDimitry Andric SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 24890b57cec5SDimitry Andric 24900b57cec5SDimitry Andric // Whether we're looking for a placement operator delete is dictated 24910b57cec5SDimitry Andric // by whether we selected a placement operator new, not by whether 24920b57cec5SDimitry Andric // we had explicit placement arguments. This matters for things like 24930b57cec5SDimitry Andric // struct A { void *operator new(size_t, int = 0); ... }; 24940b57cec5SDimitry Andric // A *a = new A() 24950b57cec5SDimitry Andric // 24960b57cec5SDimitry Andric // We don't have any definition for what a "placement allocation function" 24970b57cec5SDimitry Andric // is, but we assume it's any allocation function whose 24980b57cec5SDimitry Andric // parameter-declaration-clause is anything other than (size_t). 24990b57cec5SDimitry Andric // 25000b57cec5SDimitry Andric // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? 25010b57cec5SDimitry Andric // This affects whether an exception from the constructor of an overaligned 25020b57cec5SDimitry Andric // type uses the sized or non-sized form of aligned operator delete. 25030b57cec5SDimitry Andric bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || 25040b57cec5SDimitry Andric OperatorNew->isVariadic(); 25050b57cec5SDimitry Andric 25060b57cec5SDimitry Andric if (isPlacementNew) { 25070b57cec5SDimitry Andric // C++ [expr.new]p20: 25080b57cec5SDimitry Andric // A declaration of a placement deallocation function matches the 25090b57cec5SDimitry Andric // declaration of a placement allocation function if it has the 25100b57cec5SDimitry Andric // same number of parameters and, after parameter transformations 25110b57cec5SDimitry Andric // (8.3.5), all parameter types except the first are 25120b57cec5SDimitry Andric // identical. [...] 25130b57cec5SDimitry Andric // 25140b57cec5SDimitry Andric // To perform this comparison, we compute the function type that 25150b57cec5SDimitry Andric // the deallocation function should have, and use that type both 25160b57cec5SDimitry Andric // for template argument deduction and for comparison purposes. 25170b57cec5SDimitry Andric QualType ExpectedFunctionType; 25180b57cec5SDimitry Andric { 25190b57cec5SDimitry Andric const FunctionProtoType *Proto 25200b57cec5SDimitry Andric = OperatorNew->getType()->getAs<FunctionProtoType>(); 25210b57cec5SDimitry Andric 25220b57cec5SDimitry Andric SmallVector<QualType, 4> ArgTypes; 25230b57cec5SDimitry Andric ArgTypes.push_back(Context.VoidPtrTy); 25240b57cec5SDimitry Andric for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) 25250b57cec5SDimitry Andric ArgTypes.push_back(Proto->getParamType(I)); 25260b57cec5SDimitry Andric 25270b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI; 25280b57cec5SDimitry Andric // FIXME: This is not part of the standard's rule. 25290b57cec5SDimitry Andric EPI.Variadic = Proto->isVariadic(); 25300b57cec5SDimitry Andric 25310b57cec5SDimitry Andric ExpectedFunctionType 25320b57cec5SDimitry Andric = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 25330b57cec5SDimitry Andric } 25340b57cec5SDimitry Andric 25350b57cec5SDimitry Andric for (LookupResult::iterator D = FoundDelete.begin(), 25360b57cec5SDimitry Andric DEnd = FoundDelete.end(); 25370b57cec5SDimitry Andric D != DEnd; ++D) { 25380b57cec5SDimitry Andric FunctionDecl *Fn = nullptr; 25390b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTmpl = 25400b57cec5SDimitry Andric dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 25410b57cec5SDimitry Andric // Perform template argument deduction to try to match the 25420b57cec5SDimitry Andric // expected function type. 25430b57cec5SDimitry Andric TemplateDeductionInfo Info(StartLoc); 25440b57cec5SDimitry Andric if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, 25450b57cec5SDimitry Andric Info)) 25460b57cec5SDimitry Andric continue; 25470b57cec5SDimitry Andric } else 25480b57cec5SDimitry Andric Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 25490b57cec5SDimitry Andric 25500b57cec5SDimitry Andric if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), 25510b57cec5SDimitry Andric ExpectedFunctionType, 25520b57cec5SDimitry Andric /*AdjustExcpetionSpec*/true), 25530b57cec5SDimitry Andric ExpectedFunctionType)) 25540b57cec5SDimitry Andric Matches.push_back(std::make_pair(D.getPair(), Fn)); 25550b57cec5SDimitry Andric } 25560b57cec5SDimitry Andric 25570b57cec5SDimitry Andric if (getLangOpts().CUDA) 25580b57cec5SDimitry Andric EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches); 25590b57cec5SDimitry Andric } else { 25600b57cec5SDimitry Andric // C++1y [expr.new]p22: 25610b57cec5SDimitry Andric // For a non-placement allocation function, the normal deallocation 25620b57cec5SDimitry Andric // function lookup is used 25630b57cec5SDimitry Andric // 25640b57cec5SDimitry Andric // Per [expr.delete]p10, this lookup prefers a member operator delete 25650b57cec5SDimitry Andric // without a size_t argument, but prefers a non-member operator delete 25660b57cec5SDimitry Andric // with a size_t where possible (which it always is in this case). 25670b57cec5SDimitry Andric llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; 25680b57cec5SDimitry Andric UsualDeallocFnInfo Selected = resolveDeallocationOverload( 25690b57cec5SDimitry Andric *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, 25700b57cec5SDimitry Andric /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), 25710b57cec5SDimitry Andric &BestDeallocFns); 25720b57cec5SDimitry Andric if (Selected) 25730b57cec5SDimitry Andric Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); 25740b57cec5SDimitry Andric else { 25750b57cec5SDimitry Andric // If we failed to select an operator, all remaining functions are viable 25760b57cec5SDimitry Andric // but ambiguous. 25770b57cec5SDimitry Andric for (auto Fn : BestDeallocFns) 25780b57cec5SDimitry Andric Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); 25790b57cec5SDimitry Andric } 25800b57cec5SDimitry Andric } 25810b57cec5SDimitry Andric 25820b57cec5SDimitry Andric // C++ [expr.new]p20: 25830b57cec5SDimitry Andric // [...] If the lookup finds a single matching deallocation 25840b57cec5SDimitry Andric // function, that function will be called; otherwise, no 25850b57cec5SDimitry Andric // deallocation function will be called. 25860b57cec5SDimitry Andric if (Matches.size() == 1) { 25870b57cec5SDimitry Andric OperatorDelete = Matches[0].second; 25880b57cec5SDimitry Andric 25890b57cec5SDimitry Andric // C++1z [expr.new]p23: 25900b57cec5SDimitry Andric // If the lookup finds a usual deallocation function (3.7.4.2) 25910b57cec5SDimitry Andric // with a parameter of type std::size_t and that function, considered 25920b57cec5SDimitry Andric // as a placement deallocation function, would have been 25930b57cec5SDimitry Andric // selected as a match for the allocation function, the program 25940b57cec5SDimitry Andric // is ill-formed. 25950b57cec5SDimitry Andric if (getLangOpts().CPlusPlus11 && isPlacementNew && 25960b57cec5SDimitry Andric isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 25970b57cec5SDimitry Andric UsualDeallocFnInfo Info(*this, 25980b57cec5SDimitry Andric DeclAccessPair::make(OperatorDelete, AS_public)); 25990b57cec5SDimitry Andric // Core issue, per mail to core reflector, 2016-10-09: 26000b57cec5SDimitry Andric // If this is a member operator delete, and there is a corresponding 26010b57cec5SDimitry Andric // non-sized member operator delete, this isn't /really/ a sized 26020b57cec5SDimitry Andric // deallocation function, it just happens to have a size_t parameter. 26030b57cec5SDimitry Andric bool IsSizedDelete = Info.HasSizeT; 26040b57cec5SDimitry Andric if (IsSizedDelete && !FoundGlobalDelete) { 26050b57cec5SDimitry Andric auto NonSizedDelete = 26060b57cec5SDimitry Andric resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, 26070b57cec5SDimitry Andric /*WantAlign*/Info.HasAlignValT); 26080b57cec5SDimitry Andric if (NonSizedDelete && !NonSizedDelete.HasSizeT && 26090b57cec5SDimitry Andric NonSizedDelete.HasAlignValT == Info.HasAlignValT) 26100b57cec5SDimitry Andric IsSizedDelete = false; 26110b57cec5SDimitry Andric } 26120b57cec5SDimitry Andric 26130b57cec5SDimitry Andric if (IsSizedDelete) { 26140b57cec5SDimitry Andric SourceRange R = PlaceArgs.empty() 26150b57cec5SDimitry Andric ? SourceRange() 26160b57cec5SDimitry Andric : SourceRange(PlaceArgs.front()->getBeginLoc(), 26170b57cec5SDimitry Andric PlaceArgs.back()->getEndLoc()); 26180b57cec5SDimitry Andric Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; 26190b57cec5SDimitry Andric if (!OperatorDelete->isImplicit()) 26200b57cec5SDimitry Andric Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 26210b57cec5SDimitry Andric << DeleteName; 26220b57cec5SDimitry Andric } 26230b57cec5SDimitry Andric } 26240b57cec5SDimitry Andric 26250b57cec5SDimitry Andric CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 26260b57cec5SDimitry Andric Matches[0].first); 26270b57cec5SDimitry Andric } else if (!Matches.empty()) { 26280b57cec5SDimitry Andric // We found multiple suitable operators. Per [expr.new]p20, that means we 26290b57cec5SDimitry Andric // call no 'operator delete' function, but we should at least warn the user. 26300b57cec5SDimitry Andric // FIXME: Suppress this warning if the construction cannot throw. 26310b57cec5SDimitry Andric Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) 26320b57cec5SDimitry Andric << DeleteName << AllocElemType; 26330b57cec5SDimitry Andric 26340b57cec5SDimitry Andric for (auto &Match : Matches) 26350b57cec5SDimitry Andric Diag(Match.second->getLocation(), 26360b57cec5SDimitry Andric diag::note_member_declared_here) << DeleteName; 26370b57cec5SDimitry Andric } 26380b57cec5SDimitry Andric 26390b57cec5SDimitry Andric return false; 26400b57cec5SDimitry Andric } 26410b57cec5SDimitry Andric 26420b57cec5SDimitry Andric /// DeclareGlobalNewDelete - Declare the global forms of operator new and 26430b57cec5SDimitry Andric /// delete. These are: 26440b57cec5SDimitry Andric /// @code 26450b57cec5SDimitry Andric /// // C++03: 26460b57cec5SDimitry Andric /// void* operator new(std::size_t) throw(std::bad_alloc); 26470b57cec5SDimitry Andric /// void* operator new[](std::size_t) throw(std::bad_alloc); 26480b57cec5SDimitry Andric /// void operator delete(void *) throw(); 26490b57cec5SDimitry Andric /// void operator delete[](void *) throw(); 26500b57cec5SDimitry Andric /// // C++11: 26510b57cec5SDimitry Andric /// void* operator new(std::size_t); 26520b57cec5SDimitry Andric /// void* operator new[](std::size_t); 26530b57cec5SDimitry Andric /// void operator delete(void *) noexcept; 26540b57cec5SDimitry Andric /// void operator delete[](void *) noexcept; 26550b57cec5SDimitry Andric /// // C++1y: 26560b57cec5SDimitry Andric /// void* operator new(std::size_t); 26570b57cec5SDimitry Andric /// void* operator new[](std::size_t); 26580b57cec5SDimitry Andric /// void operator delete(void *) noexcept; 26590b57cec5SDimitry Andric /// void operator delete[](void *) noexcept; 26600b57cec5SDimitry Andric /// void operator delete(void *, std::size_t) noexcept; 26610b57cec5SDimitry Andric /// void operator delete[](void *, std::size_t) noexcept; 26620b57cec5SDimitry Andric /// @endcode 26630b57cec5SDimitry Andric /// Note that the placement and nothrow forms of new are *not* implicitly 26640b57cec5SDimitry Andric /// declared. Their use requires including \<new\>. 26650b57cec5SDimitry Andric void Sema::DeclareGlobalNewDelete() { 26660b57cec5SDimitry Andric if (GlobalNewDeleteDeclared) 26670b57cec5SDimitry Andric return; 26680b57cec5SDimitry Andric 26690b57cec5SDimitry Andric // The implicitly declared new and delete operators 26700b57cec5SDimitry Andric // are not supported in OpenCL. 26710b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) 26720b57cec5SDimitry Andric return; 26730b57cec5SDimitry Andric 26740b57cec5SDimitry Andric // C++ [basic.std.dynamic]p2: 26750b57cec5SDimitry Andric // [...] The following allocation and deallocation functions (18.4) are 26760b57cec5SDimitry Andric // implicitly declared in global scope in each translation unit of a 26770b57cec5SDimitry Andric // program 26780b57cec5SDimitry Andric // 26790b57cec5SDimitry Andric // C++03: 26800b57cec5SDimitry Andric // void* operator new(std::size_t) throw(std::bad_alloc); 26810b57cec5SDimitry Andric // void* operator new[](std::size_t) throw(std::bad_alloc); 26820b57cec5SDimitry Andric // void operator delete(void*) throw(); 26830b57cec5SDimitry Andric // void operator delete[](void*) throw(); 26840b57cec5SDimitry Andric // C++11: 26850b57cec5SDimitry Andric // void* operator new(std::size_t); 26860b57cec5SDimitry Andric // void* operator new[](std::size_t); 26870b57cec5SDimitry Andric // void operator delete(void*) noexcept; 26880b57cec5SDimitry Andric // void operator delete[](void*) noexcept; 26890b57cec5SDimitry Andric // C++1y: 26900b57cec5SDimitry Andric // void* operator new(std::size_t); 26910b57cec5SDimitry Andric // void* operator new[](std::size_t); 26920b57cec5SDimitry Andric // void operator delete(void*) noexcept; 26930b57cec5SDimitry Andric // void operator delete[](void*) noexcept; 26940b57cec5SDimitry Andric // void operator delete(void*, std::size_t) noexcept; 26950b57cec5SDimitry Andric // void operator delete[](void*, std::size_t) noexcept; 26960b57cec5SDimitry Andric // 26970b57cec5SDimitry Andric // These implicit declarations introduce only the function names operator 26980b57cec5SDimitry Andric // new, operator new[], operator delete, operator delete[]. 26990b57cec5SDimitry Andric // 27000b57cec5SDimitry Andric // Here, we need to refer to std::bad_alloc, so we will implicitly declare 27010b57cec5SDimitry Andric // "std" or "bad_alloc" as necessary to form the exception specification. 27020b57cec5SDimitry Andric // However, we do not make these implicit declarations visible to name 27030b57cec5SDimitry Andric // lookup. 27040b57cec5SDimitry Andric if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 27050b57cec5SDimitry Andric // The "std::bad_alloc" class has not yet been declared, so build it 27060b57cec5SDimitry Andric // implicitly. 27070b57cec5SDimitry Andric StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 27080b57cec5SDimitry Andric getOrCreateStdNamespace(), 27090b57cec5SDimitry Andric SourceLocation(), SourceLocation(), 27100b57cec5SDimitry Andric &PP.getIdentifierTable().get("bad_alloc"), 27110b57cec5SDimitry Andric nullptr); 27120b57cec5SDimitry Andric getStdBadAlloc()->setImplicit(true); 27130b57cec5SDimitry Andric } 27140b57cec5SDimitry Andric if (!StdAlignValT && getLangOpts().AlignedAllocation) { 27150b57cec5SDimitry Andric // The "std::align_val_t" enum class has not yet been declared, so build it 27160b57cec5SDimitry Andric // implicitly. 27170b57cec5SDimitry Andric auto *AlignValT = EnumDecl::Create( 27180b57cec5SDimitry Andric Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), 27190b57cec5SDimitry Andric &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); 27200b57cec5SDimitry Andric AlignValT->setIntegerType(Context.getSizeType()); 27210b57cec5SDimitry Andric AlignValT->setPromotionType(Context.getSizeType()); 27220b57cec5SDimitry Andric AlignValT->setImplicit(true); 27230b57cec5SDimitry Andric StdAlignValT = AlignValT; 27240b57cec5SDimitry Andric } 27250b57cec5SDimitry Andric 27260b57cec5SDimitry Andric GlobalNewDeleteDeclared = true; 27270b57cec5SDimitry Andric 27280b57cec5SDimitry Andric QualType VoidPtr = Context.getPointerType(Context.VoidTy); 27290b57cec5SDimitry Andric QualType SizeT = Context.getSizeType(); 27300b57cec5SDimitry Andric 27310b57cec5SDimitry Andric auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, 27320b57cec5SDimitry Andric QualType Return, QualType Param) { 27330b57cec5SDimitry Andric llvm::SmallVector<QualType, 3> Params; 27340b57cec5SDimitry Andric Params.push_back(Param); 27350b57cec5SDimitry Andric 27360b57cec5SDimitry Andric // Create up to four variants of the function (sized/aligned). 27370b57cec5SDimitry Andric bool HasSizedVariant = getLangOpts().SizedDeallocation && 27380b57cec5SDimitry Andric (Kind == OO_Delete || Kind == OO_Array_Delete); 27390b57cec5SDimitry Andric bool HasAlignedVariant = getLangOpts().AlignedAllocation; 27400b57cec5SDimitry Andric 27410b57cec5SDimitry Andric int NumSizeVariants = (HasSizedVariant ? 2 : 1); 27420b57cec5SDimitry Andric int NumAlignVariants = (HasAlignedVariant ? 2 : 1); 27430b57cec5SDimitry Andric for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { 27440b57cec5SDimitry Andric if (Sized) 27450b57cec5SDimitry Andric Params.push_back(SizeT); 27460b57cec5SDimitry Andric 27470b57cec5SDimitry Andric for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { 27480b57cec5SDimitry Andric if (Aligned) 27490b57cec5SDimitry Andric Params.push_back(Context.getTypeDeclType(getStdAlignValT())); 27500b57cec5SDimitry Andric 27510b57cec5SDimitry Andric DeclareGlobalAllocationFunction( 27520b57cec5SDimitry Andric Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); 27530b57cec5SDimitry Andric 27540b57cec5SDimitry Andric if (Aligned) 27550b57cec5SDimitry Andric Params.pop_back(); 27560b57cec5SDimitry Andric } 27570b57cec5SDimitry Andric } 27580b57cec5SDimitry Andric }; 27590b57cec5SDimitry Andric 27600b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); 27610b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); 27620b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); 27630b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); 27640b57cec5SDimitry Andric } 27650b57cec5SDimitry Andric 27660b57cec5SDimitry Andric /// DeclareGlobalAllocationFunction - Declares a single implicit global 27670b57cec5SDimitry Andric /// allocation function if it doesn't already exist. 27680b57cec5SDimitry Andric void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 27690b57cec5SDimitry Andric QualType Return, 27700b57cec5SDimitry Andric ArrayRef<QualType> Params) { 27710b57cec5SDimitry Andric DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 27720b57cec5SDimitry Andric 27730b57cec5SDimitry Andric // Check if this function is already declared. 27740b57cec5SDimitry Andric DeclContext::lookup_result R = GlobalCtx->lookup(Name); 27750b57cec5SDimitry Andric for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 27760b57cec5SDimitry Andric Alloc != AllocEnd; ++Alloc) { 27770b57cec5SDimitry Andric // Only look at non-template functions, as it is the predefined, 27780b57cec5SDimitry Andric // non-templated allocation function we are trying to declare here. 27790b57cec5SDimitry Andric if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 27800b57cec5SDimitry Andric if (Func->getNumParams() == Params.size()) { 27810b57cec5SDimitry Andric llvm::SmallVector<QualType, 3> FuncParams; 27820b57cec5SDimitry Andric for (auto *P : Func->parameters()) 27830b57cec5SDimitry Andric FuncParams.push_back( 27840b57cec5SDimitry Andric Context.getCanonicalType(P->getType().getUnqualifiedType())); 27850b57cec5SDimitry Andric if (llvm::makeArrayRef(FuncParams) == Params) { 27860b57cec5SDimitry Andric // Make the function visible to name lookup, even if we found it in 27870b57cec5SDimitry Andric // an unimported module. It either is an implicitly-declared global 27880b57cec5SDimitry Andric // allocation function, or is suppressing that function. 27890b57cec5SDimitry Andric Func->setVisibleDespiteOwningModule(); 27900b57cec5SDimitry Andric return; 27910b57cec5SDimitry Andric } 27920b57cec5SDimitry Andric } 27930b57cec5SDimitry Andric } 27940b57cec5SDimitry Andric } 27950b57cec5SDimitry Andric 27960b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 27970b57cec5SDimitry Andric /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 27980b57cec5SDimitry Andric 27990b57cec5SDimitry Andric QualType BadAllocType; 28000b57cec5SDimitry Andric bool HasBadAllocExceptionSpec 28010b57cec5SDimitry Andric = (Name.getCXXOverloadedOperator() == OO_New || 28020b57cec5SDimitry Andric Name.getCXXOverloadedOperator() == OO_Array_New); 28030b57cec5SDimitry Andric if (HasBadAllocExceptionSpec) { 28040b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus11) { 28050b57cec5SDimitry Andric BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 28060b57cec5SDimitry Andric assert(StdBadAlloc && "Must have std::bad_alloc declared"); 28070b57cec5SDimitry Andric EPI.ExceptionSpec.Type = EST_Dynamic; 28080b57cec5SDimitry Andric EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); 28090b57cec5SDimitry Andric } 28100b57cec5SDimitry Andric } else { 28110b57cec5SDimitry Andric EPI.ExceptionSpec = 28120b57cec5SDimitry Andric getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 28130b57cec5SDimitry Andric } 28140b57cec5SDimitry Andric 28150b57cec5SDimitry Andric auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { 28160b57cec5SDimitry Andric QualType FnType = Context.getFunctionType(Return, Params, EPI); 28170b57cec5SDimitry Andric FunctionDecl *Alloc = FunctionDecl::Create( 28180b57cec5SDimitry Andric Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, 28190b57cec5SDimitry Andric FnType, /*TInfo=*/nullptr, SC_None, false, true); 28200b57cec5SDimitry Andric Alloc->setImplicit(); 28210b57cec5SDimitry Andric // Global allocation functions should always be visible. 28220b57cec5SDimitry Andric Alloc->setVisibleDespiteOwningModule(); 28230b57cec5SDimitry Andric 28240b57cec5SDimitry Andric Alloc->addAttr(VisibilityAttr::CreateImplicit( 28250b57cec5SDimitry Andric Context, LangOpts.GlobalAllocationFunctionVisibilityHidden 28260b57cec5SDimitry Andric ? VisibilityAttr::Hidden 28270b57cec5SDimitry Andric : VisibilityAttr::Default)); 28280b57cec5SDimitry Andric 28290b57cec5SDimitry Andric llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; 28300b57cec5SDimitry Andric for (QualType T : Params) { 28310b57cec5SDimitry Andric ParamDecls.push_back(ParmVarDecl::Create( 28320b57cec5SDimitry Andric Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, 28330b57cec5SDimitry Andric /*TInfo=*/nullptr, SC_None, nullptr)); 28340b57cec5SDimitry Andric ParamDecls.back()->setImplicit(); 28350b57cec5SDimitry Andric } 28360b57cec5SDimitry Andric Alloc->setParams(ParamDecls); 28370b57cec5SDimitry Andric if (ExtraAttr) 28380b57cec5SDimitry Andric Alloc->addAttr(ExtraAttr); 28390b57cec5SDimitry Andric Context.getTranslationUnitDecl()->addDecl(Alloc); 28400b57cec5SDimitry Andric IdResolver.tryAddTopLevelDecl(Alloc, Name); 28410b57cec5SDimitry Andric }; 28420b57cec5SDimitry Andric 28430b57cec5SDimitry Andric if (!LangOpts.CUDA) 28440b57cec5SDimitry Andric CreateAllocationFunctionDecl(nullptr); 28450b57cec5SDimitry Andric else { 28460b57cec5SDimitry Andric // Host and device get their own declaration so each can be 28470b57cec5SDimitry Andric // defined or re-declared independently. 28480b57cec5SDimitry Andric CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); 28490b57cec5SDimitry Andric CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); 28500b57cec5SDimitry Andric } 28510b57cec5SDimitry Andric } 28520b57cec5SDimitry Andric 28530b57cec5SDimitry Andric FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 28540b57cec5SDimitry Andric bool CanProvideSize, 28550b57cec5SDimitry Andric bool Overaligned, 28560b57cec5SDimitry Andric DeclarationName Name) { 28570b57cec5SDimitry Andric DeclareGlobalNewDelete(); 28580b57cec5SDimitry Andric 28590b57cec5SDimitry Andric LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 28600b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 28610b57cec5SDimitry Andric 28620b57cec5SDimitry Andric // FIXME: It's possible for this to result in ambiguity, through a 28630b57cec5SDimitry Andric // user-declared variadic operator delete or the enable_if attribute. We 28640b57cec5SDimitry Andric // should probably not consider those cases to be usual deallocation 28650b57cec5SDimitry Andric // functions. But for now we just make an arbitrary choice in that case. 28660b57cec5SDimitry Andric auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, 28670b57cec5SDimitry Andric Overaligned); 28680b57cec5SDimitry Andric assert(Result.FD && "operator delete missing from global scope?"); 28690b57cec5SDimitry Andric return Result.FD; 28700b57cec5SDimitry Andric } 28710b57cec5SDimitry Andric 28720b57cec5SDimitry Andric FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, 28730b57cec5SDimitry Andric CXXRecordDecl *RD) { 28740b57cec5SDimitry Andric DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 28750b57cec5SDimitry Andric 28760b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 28770b57cec5SDimitry Andric if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 28780b57cec5SDimitry Andric return nullptr; 28790b57cec5SDimitry Andric if (OperatorDelete) 28800b57cec5SDimitry Andric return OperatorDelete; 28810b57cec5SDimitry Andric 28820b57cec5SDimitry Andric // If there's no class-specific operator delete, look up the global 28830b57cec5SDimitry Andric // non-array delete. 28840b57cec5SDimitry Andric return FindUsualDeallocationFunction( 28850b57cec5SDimitry Andric Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), 28860b57cec5SDimitry Andric Name); 28870b57cec5SDimitry Andric } 28880b57cec5SDimitry Andric 28890b57cec5SDimitry Andric bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 28900b57cec5SDimitry Andric DeclarationName Name, 28910b57cec5SDimitry Andric FunctionDecl *&Operator, bool Diagnose) { 28920b57cec5SDimitry Andric LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 28930b57cec5SDimitry Andric // Try to find operator delete/operator delete[] in class scope. 28940b57cec5SDimitry Andric LookupQualifiedName(Found, RD); 28950b57cec5SDimitry Andric 28960b57cec5SDimitry Andric if (Found.isAmbiguous()) 28970b57cec5SDimitry Andric return true; 28980b57cec5SDimitry Andric 28990b57cec5SDimitry Andric Found.suppressDiagnostics(); 29000b57cec5SDimitry Andric 29010b57cec5SDimitry Andric bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); 29020b57cec5SDimitry Andric 29030b57cec5SDimitry Andric // C++17 [expr.delete]p10: 29040b57cec5SDimitry Andric // If the deallocation functions have class scope, the one without a 29050b57cec5SDimitry Andric // parameter of type std::size_t is selected. 29060b57cec5SDimitry Andric llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; 29070b57cec5SDimitry Andric resolveDeallocationOverload(*this, Found, /*WantSize*/ false, 29080b57cec5SDimitry Andric /*WantAlign*/ Overaligned, &Matches); 29090b57cec5SDimitry Andric 29100b57cec5SDimitry Andric // If we could find an overload, use it. 29110b57cec5SDimitry Andric if (Matches.size() == 1) { 29120b57cec5SDimitry Andric Operator = cast<CXXMethodDecl>(Matches[0].FD); 29130b57cec5SDimitry Andric 29140b57cec5SDimitry Andric // FIXME: DiagnoseUseOfDecl? 29150b57cec5SDimitry Andric if (Operator->isDeleted()) { 29160b57cec5SDimitry Andric if (Diagnose) { 29170b57cec5SDimitry Andric Diag(StartLoc, diag::err_deleted_function_use); 29180b57cec5SDimitry Andric NoteDeletedFunction(Operator); 29190b57cec5SDimitry Andric } 29200b57cec5SDimitry Andric return true; 29210b57cec5SDimitry Andric } 29220b57cec5SDimitry Andric 29230b57cec5SDimitry Andric if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 29240b57cec5SDimitry Andric Matches[0].Found, Diagnose) == AR_inaccessible) 29250b57cec5SDimitry Andric return true; 29260b57cec5SDimitry Andric 29270b57cec5SDimitry Andric return false; 29280b57cec5SDimitry Andric } 29290b57cec5SDimitry Andric 29300b57cec5SDimitry Andric // We found multiple suitable operators; complain about the ambiguity. 29310b57cec5SDimitry Andric // FIXME: The standard doesn't say to do this; it appears that the intent 29320b57cec5SDimitry Andric // is that this should never happen. 29330b57cec5SDimitry Andric if (!Matches.empty()) { 29340b57cec5SDimitry Andric if (Diagnose) { 29350b57cec5SDimitry Andric Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 29360b57cec5SDimitry Andric << Name << RD; 29370b57cec5SDimitry Andric for (auto &Match : Matches) 29380b57cec5SDimitry Andric Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; 29390b57cec5SDimitry Andric } 29400b57cec5SDimitry Andric return true; 29410b57cec5SDimitry Andric } 29420b57cec5SDimitry Andric 29430b57cec5SDimitry Andric // We did find operator delete/operator delete[] declarations, but 29440b57cec5SDimitry Andric // none of them were suitable. 29450b57cec5SDimitry Andric if (!Found.empty()) { 29460b57cec5SDimitry Andric if (Diagnose) { 29470b57cec5SDimitry Andric Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 29480b57cec5SDimitry Andric << Name << RD; 29490b57cec5SDimitry Andric 29500b57cec5SDimitry Andric for (NamedDecl *D : Found) 29510b57cec5SDimitry Andric Diag(D->getUnderlyingDecl()->getLocation(), 29520b57cec5SDimitry Andric diag::note_member_declared_here) << Name; 29530b57cec5SDimitry Andric } 29540b57cec5SDimitry Andric return true; 29550b57cec5SDimitry Andric } 29560b57cec5SDimitry Andric 29570b57cec5SDimitry Andric Operator = nullptr; 29580b57cec5SDimitry Andric return false; 29590b57cec5SDimitry Andric } 29600b57cec5SDimitry Andric 29610b57cec5SDimitry Andric namespace { 29620b57cec5SDimitry Andric /// Checks whether delete-expression, and new-expression used for 29630b57cec5SDimitry Andric /// initializing deletee have the same array form. 29640b57cec5SDimitry Andric class MismatchingNewDeleteDetector { 29650b57cec5SDimitry Andric public: 29660b57cec5SDimitry Andric enum MismatchResult { 29670b57cec5SDimitry Andric /// Indicates that there is no mismatch or a mismatch cannot be proven. 29680b57cec5SDimitry Andric NoMismatch, 29690b57cec5SDimitry Andric /// Indicates that variable is initialized with mismatching form of \a new. 29700b57cec5SDimitry Andric VarInitMismatches, 29710b57cec5SDimitry Andric /// Indicates that member is initialized with mismatching form of \a new. 29720b57cec5SDimitry Andric MemberInitMismatches, 29730b57cec5SDimitry Andric /// Indicates that 1 or more constructors' definitions could not been 29740b57cec5SDimitry Andric /// analyzed, and they will be checked again at the end of translation unit. 29750b57cec5SDimitry Andric AnalyzeLater 29760b57cec5SDimitry Andric }; 29770b57cec5SDimitry Andric 29780b57cec5SDimitry Andric /// \param EndOfTU True, if this is the final analysis at the end of 29790b57cec5SDimitry Andric /// translation unit. False, if this is the initial analysis at the point 29800b57cec5SDimitry Andric /// delete-expression was encountered. 29810b57cec5SDimitry Andric explicit MismatchingNewDeleteDetector(bool EndOfTU) 29820b57cec5SDimitry Andric : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), 29830b57cec5SDimitry Andric HasUndefinedConstructors(false) {} 29840b57cec5SDimitry Andric 29850b57cec5SDimitry Andric /// Checks whether pointee of a delete-expression is initialized with 29860b57cec5SDimitry Andric /// matching form of new-expression. 29870b57cec5SDimitry Andric /// 29880b57cec5SDimitry Andric /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the 29890b57cec5SDimitry Andric /// point where delete-expression is encountered, then a warning will be 29900b57cec5SDimitry Andric /// issued immediately. If return value is \c AnalyzeLater at the point where 29910b57cec5SDimitry Andric /// delete-expression is seen, then member will be analyzed at the end of 29920b57cec5SDimitry Andric /// translation unit. \c AnalyzeLater is returned iff at least one constructor 29930b57cec5SDimitry Andric /// couldn't be analyzed. If at least one constructor initializes the member 29940b57cec5SDimitry Andric /// with matching type of new, the return value is \c NoMismatch. 29950b57cec5SDimitry Andric MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); 29960b57cec5SDimitry Andric /// Analyzes a class member. 29970b57cec5SDimitry Andric /// \param Field Class member to analyze. 29980b57cec5SDimitry Andric /// \param DeleteWasArrayForm Array form-ness of the delete-expression used 29990b57cec5SDimitry Andric /// for deleting the \p Field. 30000b57cec5SDimitry Andric MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); 30010b57cec5SDimitry Andric FieldDecl *Field; 30020b57cec5SDimitry Andric /// List of mismatching new-expressions used for initialization of the pointee 30030b57cec5SDimitry Andric llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; 30040b57cec5SDimitry Andric /// Indicates whether delete-expression was in array form. 30050b57cec5SDimitry Andric bool IsArrayForm; 30060b57cec5SDimitry Andric 30070b57cec5SDimitry Andric private: 30080b57cec5SDimitry Andric const bool EndOfTU; 30090b57cec5SDimitry Andric /// Indicates that there is at least one constructor without body. 30100b57cec5SDimitry Andric bool HasUndefinedConstructors; 30110b57cec5SDimitry Andric /// Returns \c CXXNewExpr from given initialization expression. 30120b57cec5SDimitry Andric /// \param E Expression used for initializing pointee in delete-expression. 30130b57cec5SDimitry Andric /// E can be a single-element \c InitListExpr consisting of new-expression. 30140b57cec5SDimitry Andric const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); 30150b57cec5SDimitry Andric /// Returns whether member is initialized with mismatching form of 30160b57cec5SDimitry Andric /// \c new either by the member initializer or in-class initialization. 30170b57cec5SDimitry Andric /// 30180b57cec5SDimitry Andric /// If bodies of all constructors are not visible at the end of translation 30190b57cec5SDimitry Andric /// unit or at least one constructor initializes member with the matching 30200b57cec5SDimitry Andric /// form of \c new, mismatch cannot be proven, and this function will return 30210b57cec5SDimitry Andric /// \c NoMismatch. 30220b57cec5SDimitry Andric MismatchResult analyzeMemberExpr(const MemberExpr *ME); 30230b57cec5SDimitry Andric /// Returns whether variable is initialized with mismatching form of 30240b57cec5SDimitry Andric /// \c new. 30250b57cec5SDimitry Andric /// 30260b57cec5SDimitry Andric /// If variable is initialized with matching form of \c new or variable is not 30270b57cec5SDimitry Andric /// initialized with a \c new expression, this function will return true. 30280b57cec5SDimitry Andric /// If variable is initialized with mismatching form of \c new, returns false. 30290b57cec5SDimitry Andric /// \param D Variable to analyze. 30300b57cec5SDimitry Andric bool hasMatchingVarInit(const DeclRefExpr *D); 30310b57cec5SDimitry Andric /// Checks whether the constructor initializes pointee with mismatching 30320b57cec5SDimitry Andric /// form of \c new. 30330b57cec5SDimitry Andric /// 30340b57cec5SDimitry Andric /// Returns true, if member is initialized with matching form of \c new in 30350b57cec5SDimitry Andric /// member initializer list. Returns false, if member is initialized with the 30360b57cec5SDimitry Andric /// matching form of \c new in this constructor's initializer or given 30370b57cec5SDimitry Andric /// constructor isn't defined at the point where delete-expression is seen, or 30380b57cec5SDimitry Andric /// member isn't initialized by the constructor. 30390b57cec5SDimitry Andric bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); 30400b57cec5SDimitry Andric /// Checks whether member is initialized with matching form of 30410b57cec5SDimitry Andric /// \c new in member initializer list. 30420b57cec5SDimitry Andric bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); 30430b57cec5SDimitry Andric /// Checks whether member is initialized with mismatching form of \c new by 30440b57cec5SDimitry Andric /// in-class initializer. 30450b57cec5SDimitry Andric MismatchResult analyzeInClassInitializer(); 30460b57cec5SDimitry Andric }; 30470b57cec5SDimitry Andric } 30480b57cec5SDimitry Andric 30490b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 30500b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { 30510b57cec5SDimitry Andric NewExprs.clear(); 30520b57cec5SDimitry Andric assert(DE && "Expected delete-expression"); 30530b57cec5SDimitry Andric IsArrayForm = DE->isArrayForm(); 30540b57cec5SDimitry Andric const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); 30550b57cec5SDimitry Andric if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { 30560b57cec5SDimitry Andric return analyzeMemberExpr(ME); 30570b57cec5SDimitry Andric } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { 30580b57cec5SDimitry Andric if (!hasMatchingVarInit(D)) 30590b57cec5SDimitry Andric return VarInitMismatches; 30600b57cec5SDimitry Andric } 30610b57cec5SDimitry Andric return NoMismatch; 30620b57cec5SDimitry Andric } 30630b57cec5SDimitry Andric 30640b57cec5SDimitry Andric const CXXNewExpr * 30650b57cec5SDimitry Andric MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { 30660b57cec5SDimitry Andric assert(E != nullptr && "Expected a valid initializer expression"); 30670b57cec5SDimitry Andric E = E->IgnoreParenImpCasts(); 30680b57cec5SDimitry Andric if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { 30690b57cec5SDimitry Andric if (ILE->getNumInits() == 1) 30700b57cec5SDimitry Andric E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); 30710b57cec5SDimitry Andric } 30720b57cec5SDimitry Andric 30730b57cec5SDimitry Andric return dyn_cast_or_null<const CXXNewExpr>(E); 30740b57cec5SDimitry Andric } 30750b57cec5SDimitry Andric 30760b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( 30770b57cec5SDimitry Andric const CXXCtorInitializer *CI) { 30780b57cec5SDimitry Andric const CXXNewExpr *NE = nullptr; 30790b57cec5SDimitry Andric if (Field == CI->getMember() && 30800b57cec5SDimitry Andric (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { 30810b57cec5SDimitry Andric if (NE->isArray() == IsArrayForm) 30820b57cec5SDimitry Andric return true; 30830b57cec5SDimitry Andric else 30840b57cec5SDimitry Andric NewExprs.push_back(NE); 30850b57cec5SDimitry Andric } 30860b57cec5SDimitry Andric return false; 30870b57cec5SDimitry Andric } 30880b57cec5SDimitry Andric 30890b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( 30900b57cec5SDimitry Andric const CXXConstructorDecl *CD) { 30910b57cec5SDimitry Andric if (CD->isImplicit()) 30920b57cec5SDimitry Andric return false; 30930b57cec5SDimitry Andric const FunctionDecl *Definition = CD; 30940b57cec5SDimitry Andric if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { 30950b57cec5SDimitry Andric HasUndefinedConstructors = true; 30960b57cec5SDimitry Andric return EndOfTU; 30970b57cec5SDimitry Andric } 30980b57cec5SDimitry Andric for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { 30990b57cec5SDimitry Andric if (hasMatchingNewInCtorInit(CI)) 31000b57cec5SDimitry Andric return true; 31010b57cec5SDimitry Andric } 31020b57cec5SDimitry Andric return false; 31030b57cec5SDimitry Andric } 31040b57cec5SDimitry Andric 31050b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 31060b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeInClassInitializer() { 31070b57cec5SDimitry Andric assert(Field != nullptr && "This should be called only for members"); 31080b57cec5SDimitry Andric const Expr *InitExpr = Field->getInClassInitializer(); 31090b57cec5SDimitry Andric if (!InitExpr) 31100b57cec5SDimitry Andric return EndOfTU ? NoMismatch : AnalyzeLater; 31110b57cec5SDimitry Andric if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { 31120b57cec5SDimitry Andric if (NE->isArray() != IsArrayForm) { 31130b57cec5SDimitry Andric NewExprs.push_back(NE); 31140b57cec5SDimitry Andric return MemberInitMismatches; 31150b57cec5SDimitry Andric } 31160b57cec5SDimitry Andric } 31170b57cec5SDimitry Andric return NoMismatch; 31180b57cec5SDimitry Andric } 31190b57cec5SDimitry Andric 31200b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 31210b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, 31220b57cec5SDimitry Andric bool DeleteWasArrayForm) { 31230b57cec5SDimitry Andric assert(Field != nullptr && "Analysis requires a valid class member."); 31240b57cec5SDimitry Andric this->Field = Field; 31250b57cec5SDimitry Andric IsArrayForm = DeleteWasArrayForm; 31260b57cec5SDimitry Andric const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); 31270b57cec5SDimitry Andric for (const auto *CD : RD->ctors()) { 31280b57cec5SDimitry Andric if (hasMatchingNewInCtor(CD)) 31290b57cec5SDimitry Andric return NoMismatch; 31300b57cec5SDimitry Andric } 31310b57cec5SDimitry Andric if (HasUndefinedConstructors) 31320b57cec5SDimitry Andric return EndOfTU ? NoMismatch : AnalyzeLater; 31330b57cec5SDimitry Andric if (!NewExprs.empty()) 31340b57cec5SDimitry Andric return MemberInitMismatches; 31350b57cec5SDimitry Andric return Field->hasInClassInitializer() ? analyzeInClassInitializer() 31360b57cec5SDimitry Andric : NoMismatch; 31370b57cec5SDimitry Andric } 31380b57cec5SDimitry Andric 31390b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 31400b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { 31410b57cec5SDimitry Andric assert(ME != nullptr && "Expected a member expression"); 31420b57cec5SDimitry Andric if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) 31430b57cec5SDimitry Andric return analyzeField(F, IsArrayForm); 31440b57cec5SDimitry Andric return NoMismatch; 31450b57cec5SDimitry Andric } 31460b57cec5SDimitry Andric 31470b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { 31480b57cec5SDimitry Andric const CXXNewExpr *NE = nullptr; 31490b57cec5SDimitry Andric if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { 31500b57cec5SDimitry Andric if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && 31510b57cec5SDimitry Andric NE->isArray() != IsArrayForm) { 31520b57cec5SDimitry Andric NewExprs.push_back(NE); 31530b57cec5SDimitry Andric } 31540b57cec5SDimitry Andric } 31550b57cec5SDimitry Andric return NewExprs.empty(); 31560b57cec5SDimitry Andric } 31570b57cec5SDimitry Andric 31580b57cec5SDimitry Andric static void 31590b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, 31600b57cec5SDimitry Andric const MismatchingNewDeleteDetector &Detector) { 31610b57cec5SDimitry Andric SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); 31620b57cec5SDimitry Andric FixItHint H; 31630b57cec5SDimitry Andric if (!Detector.IsArrayForm) 31640b57cec5SDimitry Andric H = FixItHint::CreateInsertion(EndOfDelete, "[]"); 31650b57cec5SDimitry Andric else { 31660b57cec5SDimitry Andric SourceLocation RSquare = Lexer::findLocationAfterToken( 31670b57cec5SDimitry Andric DeleteLoc, tok::l_square, SemaRef.getSourceManager(), 31680b57cec5SDimitry Andric SemaRef.getLangOpts(), true); 31690b57cec5SDimitry Andric if (RSquare.isValid()) 31700b57cec5SDimitry Andric H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); 31710b57cec5SDimitry Andric } 31720b57cec5SDimitry Andric SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) 31730b57cec5SDimitry Andric << Detector.IsArrayForm << H; 31740b57cec5SDimitry Andric 31750b57cec5SDimitry Andric for (const auto *NE : Detector.NewExprs) 31760b57cec5SDimitry Andric SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) 31770b57cec5SDimitry Andric << Detector.IsArrayForm; 31780b57cec5SDimitry Andric } 31790b57cec5SDimitry Andric 31800b57cec5SDimitry Andric void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { 31810b57cec5SDimitry Andric if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) 31820b57cec5SDimitry Andric return; 31830b57cec5SDimitry Andric MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); 31840b57cec5SDimitry Andric switch (Detector.analyzeDeleteExpr(DE)) { 31850b57cec5SDimitry Andric case MismatchingNewDeleteDetector::VarInitMismatches: 31860b57cec5SDimitry Andric case MismatchingNewDeleteDetector::MemberInitMismatches: { 31870b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); 31880b57cec5SDimitry Andric break; 31890b57cec5SDimitry Andric } 31900b57cec5SDimitry Andric case MismatchingNewDeleteDetector::AnalyzeLater: { 31910b57cec5SDimitry Andric DeleteExprs[Detector.Field].push_back( 31920b57cec5SDimitry Andric std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); 31930b57cec5SDimitry Andric break; 31940b57cec5SDimitry Andric } 31950b57cec5SDimitry Andric case MismatchingNewDeleteDetector::NoMismatch: 31960b57cec5SDimitry Andric break; 31970b57cec5SDimitry Andric } 31980b57cec5SDimitry Andric } 31990b57cec5SDimitry Andric 32000b57cec5SDimitry Andric void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 32010b57cec5SDimitry Andric bool DeleteWasArrayForm) { 32020b57cec5SDimitry Andric MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); 32030b57cec5SDimitry Andric switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { 32040b57cec5SDimitry Andric case MismatchingNewDeleteDetector::VarInitMismatches: 32050b57cec5SDimitry Andric llvm_unreachable("This analysis should have been done for class members."); 32060b57cec5SDimitry Andric case MismatchingNewDeleteDetector::AnalyzeLater: 32070b57cec5SDimitry Andric llvm_unreachable("Analysis cannot be postponed any point beyond end of " 32080b57cec5SDimitry Andric "translation unit."); 32090b57cec5SDimitry Andric case MismatchingNewDeleteDetector::MemberInitMismatches: 32100b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); 32110b57cec5SDimitry Andric break; 32120b57cec5SDimitry Andric case MismatchingNewDeleteDetector::NoMismatch: 32130b57cec5SDimitry Andric break; 32140b57cec5SDimitry Andric } 32150b57cec5SDimitry Andric } 32160b57cec5SDimitry Andric 32170b57cec5SDimitry Andric /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 32180b57cec5SDimitry Andric /// @code ::delete ptr; @endcode 32190b57cec5SDimitry Andric /// or 32200b57cec5SDimitry Andric /// @code delete [] ptr; @endcode 32210b57cec5SDimitry Andric ExprResult 32220b57cec5SDimitry Andric Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 32230b57cec5SDimitry Andric bool ArrayForm, Expr *ExE) { 32240b57cec5SDimitry Andric // C++ [expr.delete]p1: 32250b57cec5SDimitry Andric // The operand shall have a pointer type, or a class type having a single 32260b57cec5SDimitry Andric // non-explicit conversion function to a pointer type. The result has type 32270b57cec5SDimitry Andric // void. 32280b57cec5SDimitry Andric // 32290b57cec5SDimitry Andric // DR599 amends "pointer type" to "pointer to object type" in both cases. 32300b57cec5SDimitry Andric 32310b57cec5SDimitry Andric ExprResult Ex = ExE; 32320b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 32330b57cec5SDimitry Andric bool ArrayFormAsWritten = ArrayForm; 32340b57cec5SDimitry Andric bool UsualArrayDeleteWantsSize = false; 32350b57cec5SDimitry Andric 32360b57cec5SDimitry Andric if (!Ex.get()->isTypeDependent()) { 32370b57cec5SDimitry Andric // Perform lvalue-to-rvalue cast, if needed. 32380b57cec5SDimitry Andric Ex = DefaultLvalueConversion(Ex.get()); 32390b57cec5SDimitry Andric if (Ex.isInvalid()) 32400b57cec5SDimitry Andric return ExprError(); 32410b57cec5SDimitry Andric 32420b57cec5SDimitry Andric QualType Type = Ex.get()->getType(); 32430b57cec5SDimitry Andric 32440b57cec5SDimitry Andric class DeleteConverter : public ContextualImplicitConverter { 32450b57cec5SDimitry Andric public: 32460b57cec5SDimitry Andric DeleteConverter() : ContextualImplicitConverter(false, true) {} 32470b57cec5SDimitry Andric 32480b57cec5SDimitry Andric bool match(QualType ConvType) override { 32490b57cec5SDimitry Andric // FIXME: If we have an operator T* and an operator void*, we must pick 32500b57cec5SDimitry Andric // the operator T*. 32510b57cec5SDimitry Andric if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 32520b57cec5SDimitry Andric if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 32530b57cec5SDimitry Andric return true; 32540b57cec5SDimitry Andric return false; 32550b57cec5SDimitry Andric } 32560b57cec5SDimitry Andric 32570b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 32580b57cec5SDimitry Andric QualType T) override { 32590b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_operand) << T; 32600b57cec5SDimitry Andric } 32610b57cec5SDimitry Andric 32620b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 32630b57cec5SDimitry Andric QualType T) override { 32640b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 32650b57cec5SDimitry Andric } 32660b57cec5SDimitry Andric 32670b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 32680b57cec5SDimitry Andric QualType T, 32690b57cec5SDimitry Andric QualType ConvTy) override { 32700b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 32710b57cec5SDimitry Andric } 32720b57cec5SDimitry Andric 32730b57cec5SDimitry Andric SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 32740b57cec5SDimitry Andric QualType ConvTy) override { 32750b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 32760b57cec5SDimitry Andric << ConvTy; 32770b57cec5SDimitry Andric } 32780b57cec5SDimitry Andric 32790b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 32800b57cec5SDimitry Andric QualType T) override { 32810b57cec5SDimitry Andric return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 32820b57cec5SDimitry Andric } 32830b57cec5SDimitry Andric 32840b57cec5SDimitry Andric SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 32850b57cec5SDimitry Andric QualType ConvTy) override { 32860b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 32870b57cec5SDimitry Andric << ConvTy; 32880b57cec5SDimitry Andric } 32890b57cec5SDimitry Andric 32900b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 32910b57cec5SDimitry Andric QualType T, 32920b57cec5SDimitry Andric QualType ConvTy) override { 32930b57cec5SDimitry Andric llvm_unreachable("conversion functions are permitted"); 32940b57cec5SDimitry Andric } 32950b57cec5SDimitry Andric } Converter; 32960b57cec5SDimitry Andric 32970b57cec5SDimitry Andric Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); 32980b57cec5SDimitry Andric if (Ex.isInvalid()) 32990b57cec5SDimitry Andric return ExprError(); 33000b57cec5SDimitry Andric Type = Ex.get()->getType(); 33010b57cec5SDimitry Andric if (!Converter.match(Type)) 33020b57cec5SDimitry Andric // FIXME: PerformContextualImplicitConversion should return ExprError 33030b57cec5SDimitry Andric // itself in this case. 33040b57cec5SDimitry Andric return ExprError(); 33050b57cec5SDimitry Andric 3306a7dea167SDimitry Andric QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); 33070b57cec5SDimitry Andric QualType PointeeElem = Context.getBaseElementType(Pointee); 33080b57cec5SDimitry Andric 33090b57cec5SDimitry Andric if (Pointee.getAddressSpace() != LangAS::Default && 33100b57cec5SDimitry Andric !getLangOpts().OpenCLCPlusPlus) 33110b57cec5SDimitry Andric return Diag(Ex.get()->getBeginLoc(), 33120b57cec5SDimitry Andric diag::err_address_space_qualified_delete) 33130b57cec5SDimitry Andric << Pointee.getUnqualifiedType() 33140b57cec5SDimitry Andric << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); 33150b57cec5SDimitry Andric 33160b57cec5SDimitry Andric CXXRecordDecl *PointeeRD = nullptr; 33170b57cec5SDimitry Andric if (Pointee->isVoidType() && !isSFINAEContext()) { 33180b57cec5SDimitry Andric // The C++ standard bans deleting a pointer to a non-object type, which 33190b57cec5SDimitry Andric // effectively bans deletion of "void*". However, most compilers support 33200b57cec5SDimitry Andric // this, so we treat it as a warning unless we're in a SFINAE context. 33210b57cec5SDimitry Andric Diag(StartLoc, diag::ext_delete_void_ptr_operand) 33220b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange(); 33230b57cec5SDimitry Andric } else if (Pointee->isFunctionType() || Pointee->isVoidType()) { 33240b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_delete_operand) 33250b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange()); 33260b57cec5SDimitry Andric } else if (!Pointee->isDependentType()) { 33270b57cec5SDimitry Andric // FIXME: This can result in errors if the definition was imported from a 33280b57cec5SDimitry Andric // module but is hidden. 33290b57cec5SDimitry Andric if (!RequireCompleteType(StartLoc, Pointee, 33300b57cec5SDimitry Andric diag::warn_delete_incomplete, Ex.get())) { 33310b57cec5SDimitry Andric if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 33320b57cec5SDimitry Andric PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 33330b57cec5SDimitry Andric } 33340b57cec5SDimitry Andric } 33350b57cec5SDimitry Andric 33360b57cec5SDimitry Andric if (Pointee->isArrayType() && !ArrayForm) { 33370b57cec5SDimitry Andric Diag(StartLoc, diag::warn_delete_array_type) 33380b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange() 33390b57cec5SDimitry Andric << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); 33400b57cec5SDimitry Andric ArrayForm = true; 33410b57cec5SDimitry Andric } 33420b57cec5SDimitry Andric 33430b57cec5SDimitry Andric DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 33440b57cec5SDimitry Andric ArrayForm ? OO_Array_Delete : OO_Delete); 33450b57cec5SDimitry Andric 33460b57cec5SDimitry Andric if (PointeeRD) { 33470b57cec5SDimitry Andric if (!UseGlobal && 33480b57cec5SDimitry Andric FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 33490b57cec5SDimitry Andric OperatorDelete)) 33500b57cec5SDimitry Andric return ExprError(); 33510b57cec5SDimitry Andric 33520b57cec5SDimitry Andric // If we're allocating an array of records, check whether the 33530b57cec5SDimitry Andric // usual operator delete[] has a size_t parameter. 33540b57cec5SDimitry Andric if (ArrayForm) { 33550b57cec5SDimitry Andric // If the user specifically asked to use the global allocator, 33560b57cec5SDimitry Andric // we'll need to do the lookup into the class. 33570b57cec5SDimitry Andric if (UseGlobal) 33580b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 33590b57cec5SDimitry Andric doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 33600b57cec5SDimitry Andric 33610b57cec5SDimitry Andric // Otherwise, the usual operator delete[] should be the 33620b57cec5SDimitry Andric // function we just found. 33630b57cec5SDimitry Andric else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) 33640b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 33650b57cec5SDimitry Andric UsualDeallocFnInfo(*this, 33660b57cec5SDimitry Andric DeclAccessPair::make(OperatorDelete, AS_public)) 33670b57cec5SDimitry Andric .HasSizeT; 33680b57cec5SDimitry Andric } 33690b57cec5SDimitry Andric 33700b57cec5SDimitry Andric if (!PointeeRD->hasIrrelevantDestructor()) 33710b57cec5SDimitry Andric if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 33720b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, 33730b57cec5SDimitry Andric const_cast<CXXDestructorDecl*>(Dtor)); 33740b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Dtor, StartLoc)) 33750b57cec5SDimitry Andric return ExprError(); 33760b57cec5SDimitry Andric } 33770b57cec5SDimitry Andric 33780b57cec5SDimitry Andric CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, 33790b57cec5SDimitry Andric /*IsDelete=*/true, /*CallCanBeVirtual=*/true, 33800b57cec5SDimitry Andric /*WarnOnNonAbstractTypes=*/!ArrayForm, 33810b57cec5SDimitry Andric SourceLocation()); 33820b57cec5SDimitry Andric } 33830b57cec5SDimitry Andric 33840b57cec5SDimitry Andric if (!OperatorDelete) { 33850b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) { 33860b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; 33870b57cec5SDimitry Andric return ExprError(); 33880b57cec5SDimitry Andric } 33890b57cec5SDimitry Andric 33900b57cec5SDimitry Andric bool IsComplete = isCompleteType(StartLoc, Pointee); 33910b57cec5SDimitry Andric bool CanProvideSize = 33920b57cec5SDimitry Andric IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || 33930b57cec5SDimitry Andric Pointee.isDestructedType()); 33940b57cec5SDimitry Andric bool Overaligned = hasNewExtendedAlignment(*this, Pointee); 33950b57cec5SDimitry Andric 33960b57cec5SDimitry Andric // Look for a global declaration. 33970b57cec5SDimitry Andric OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, 33980b57cec5SDimitry Andric Overaligned, DeleteName); 33990b57cec5SDimitry Andric } 34000b57cec5SDimitry Andric 34010b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorDelete); 34020b57cec5SDimitry Andric 34030b57cec5SDimitry Andric // Check access and ambiguity of destructor if we're going to call it. 34040b57cec5SDimitry Andric // Note that this is required even for a virtual delete. 34050b57cec5SDimitry Andric bool IsVirtualDelete = false; 34060b57cec5SDimitry Andric if (PointeeRD) { 34070b57cec5SDimitry Andric if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 34080b57cec5SDimitry Andric CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 34090b57cec5SDimitry Andric PDiag(diag::err_access_dtor) << PointeeElem); 34100b57cec5SDimitry Andric IsVirtualDelete = Dtor->isVirtual(); 34110b57cec5SDimitry Andric } 34120b57cec5SDimitry Andric } 34130b57cec5SDimitry Andric 34140b57cec5SDimitry Andric DiagnoseUseOfDecl(OperatorDelete, StartLoc); 34150b57cec5SDimitry Andric 34160b57cec5SDimitry Andric // Convert the operand to the type of the first parameter of operator 34170b57cec5SDimitry Andric // delete. This is only necessary if we selected a destroying operator 34180b57cec5SDimitry Andric // delete that we are going to call (non-virtually); converting to void* 34190b57cec5SDimitry Andric // is trivial and left to AST consumers to handle. 34200b57cec5SDimitry Andric QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 34210b57cec5SDimitry Andric if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { 34220b57cec5SDimitry Andric Qualifiers Qs = Pointee.getQualifiers(); 34230b57cec5SDimitry Andric if (Qs.hasCVRQualifiers()) { 34240b57cec5SDimitry Andric // Qualifiers are irrelevant to this conversion; we're only looking 34250b57cec5SDimitry Andric // for access and ambiguity. 34260b57cec5SDimitry Andric Qs.removeCVRQualifiers(); 34270b57cec5SDimitry Andric QualType Unqual = Context.getPointerType( 34280b57cec5SDimitry Andric Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); 34290b57cec5SDimitry Andric Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); 34300b57cec5SDimitry Andric } 34310b57cec5SDimitry Andric Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); 34320b57cec5SDimitry Andric if (Ex.isInvalid()) 34330b57cec5SDimitry Andric return ExprError(); 34340b57cec5SDimitry Andric } 34350b57cec5SDimitry Andric } 34360b57cec5SDimitry Andric 34370b57cec5SDimitry Andric CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( 34380b57cec5SDimitry Andric Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, 34390b57cec5SDimitry Andric UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); 34400b57cec5SDimitry Andric AnalyzeDeleteExprMismatch(Result); 34410b57cec5SDimitry Andric return Result; 34420b57cec5SDimitry Andric } 34430b57cec5SDimitry Andric 34440b57cec5SDimitry Andric static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, 34450b57cec5SDimitry Andric bool IsDelete, 34460b57cec5SDimitry Andric FunctionDecl *&Operator) { 34470b57cec5SDimitry Andric 34480b57cec5SDimitry Andric DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( 34490b57cec5SDimitry Andric IsDelete ? OO_Delete : OO_New); 34500b57cec5SDimitry Andric 34510b57cec5SDimitry Andric LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); 34520b57cec5SDimitry Andric S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 34530b57cec5SDimitry Andric assert(!R.empty() && "implicitly declared allocation functions not found"); 34540b57cec5SDimitry Andric assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 34550b57cec5SDimitry Andric 34560b57cec5SDimitry Andric // We do our own custom access checks below. 34570b57cec5SDimitry Andric R.suppressDiagnostics(); 34580b57cec5SDimitry Andric 34590b57cec5SDimitry Andric SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end()); 34600b57cec5SDimitry Andric OverloadCandidateSet Candidates(R.getNameLoc(), 34610b57cec5SDimitry Andric OverloadCandidateSet::CSK_Normal); 34620b57cec5SDimitry Andric for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); 34630b57cec5SDimitry Andric FnOvl != FnOvlEnd; ++FnOvl) { 34640b57cec5SDimitry Andric // Even member operator new/delete are implicitly treated as 34650b57cec5SDimitry Andric // static, so don't use AddMemberCandidate. 34660b57cec5SDimitry Andric NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); 34670b57cec5SDimitry Andric 34680b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 34690b57cec5SDimitry Andric S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), 34700b57cec5SDimitry Andric /*ExplicitTemplateArgs=*/nullptr, Args, 34710b57cec5SDimitry Andric Candidates, 34720b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 34730b57cec5SDimitry Andric continue; 34740b57cec5SDimitry Andric } 34750b57cec5SDimitry Andric 34760b57cec5SDimitry Andric FunctionDecl *Fn = cast<FunctionDecl>(D); 34770b57cec5SDimitry Andric S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, 34780b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 34790b57cec5SDimitry Andric } 34800b57cec5SDimitry Andric 34810b57cec5SDimitry Andric SourceRange Range = TheCall->getSourceRange(); 34820b57cec5SDimitry Andric 34830b57cec5SDimitry Andric // Do the resolution. 34840b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 34850b57cec5SDimitry Andric switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 34860b57cec5SDimitry Andric case OR_Success: { 34870b57cec5SDimitry Andric // Got one! 34880b57cec5SDimitry Andric FunctionDecl *FnDecl = Best->Function; 34890b57cec5SDimitry Andric assert(R.getNamingClass() == nullptr && 34900b57cec5SDimitry Andric "class members should not be considered"); 34910b57cec5SDimitry Andric 34920b57cec5SDimitry Andric if (!FnDecl->isReplaceableGlobalAllocationFunction()) { 34930b57cec5SDimitry Andric S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) 34940b57cec5SDimitry Andric << (IsDelete ? 1 : 0) << Range; 34950b57cec5SDimitry Andric S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) 34960b57cec5SDimitry Andric << R.getLookupName() << FnDecl->getSourceRange(); 34970b57cec5SDimitry Andric return true; 34980b57cec5SDimitry Andric } 34990b57cec5SDimitry Andric 35000b57cec5SDimitry Andric Operator = FnDecl; 35010b57cec5SDimitry Andric return false; 35020b57cec5SDimitry Andric } 35030b57cec5SDimitry Andric 35040b57cec5SDimitry Andric case OR_No_Viable_Function: 35050b57cec5SDimitry Andric Candidates.NoteCandidates( 35060b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 35070b57cec5SDimitry Andric S.PDiag(diag::err_ovl_no_viable_function_in_call) 35080b57cec5SDimitry Andric << R.getLookupName() << Range), 35090b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 35100b57cec5SDimitry Andric return true; 35110b57cec5SDimitry Andric 35120b57cec5SDimitry Andric case OR_Ambiguous: 35130b57cec5SDimitry Andric Candidates.NoteCandidates( 35140b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 35150b57cec5SDimitry Andric S.PDiag(diag::err_ovl_ambiguous_call) 35160b57cec5SDimitry Andric << R.getLookupName() << Range), 3517480093f4SDimitry Andric S, OCD_AmbiguousCandidates, Args); 35180b57cec5SDimitry Andric return true; 35190b57cec5SDimitry Andric 35200b57cec5SDimitry Andric case OR_Deleted: { 35210b57cec5SDimitry Andric Candidates.NoteCandidates( 35220b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call) 35230b57cec5SDimitry Andric << R.getLookupName() << Range), 35240b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 35250b57cec5SDimitry Andric return true; 35260b57cec5SDimitry Andric } 35270b57cec5SDimitry Andric } 35280b57cec5SDimitry Andric llvm_unreachable("Unreachable, bad result from BestViableFunction"); 35290b57cec5SDimitry Andric } 35300b57cec5SDimitry Andric 35310b57cec5SDimitry Andric ExprResult 35320b57cec5SDimitry Andric Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 35330b57cec5SDimitry Andric bool IsDelete) { 35340b57cec5SDimitry Andric CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 35350b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) { 35360b57cec5SDimitry Andric Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 35370b57cec5SDimitry Andric << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") 35380b57cec5SDimitry Andric << "C++"; 35390b57cec5SDimitry Andric return ExprError(); 35400b57cec5SDimitry Andric } 35410b57cec5SDimitry Andric // CodeGen assumes it can find the global new and delete to call, 35420b57cec5SDimitry Andric // so ensure that they are declared. 35430b57cec5SDimitry Andric DeclareGlobalNewDelete(); 35440b57cec5SDimitry Andric 35450b57cec5SDimitry Andric FunctionDecl *OperatorNewOrDelete = nullptr; 35460b57cec5SDimitry Andric if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, 35470b57cec5SDimitry Andric OperatorNewOrDelete)) 35480b57cec5SDimitry Andric return ExprError(); 35490b57cec5SDimitry Andric assert(OperatorNewOrDelete && "should be found"); 35500b57cec5SDimitry Andric 35510b57cec5SDimitry Andric DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); 35520b57cec5SDimitry Andric MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); 35530b57cec5SDimitry Andric 35540b57cec5SDimitry Andric TheCall->setType(OperatorNewOrDelete->getReturnType()); 35550b57cec5SDimitry Andric for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 35560b57cec5SDimitry Andric QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); 35570b57cec5SDimitry Andric InitializedEntity Entity = 35580b57cec5SDimitry Andric InitializedEntity::InitializeParameter(Context, ParamTy, false); 35590b57cec5SDimitry Andric ExprResult Arg = PerformCopyInitialization( 35600b57cec5SDimitry Andric Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); 35610b57cec5SDimitry Andric if (Arg.isInvalid()) 35620b57cec5SDimitry Andric return ExprError(); 35630b57cec5SDimitry Andric TheCall->setArg(i, Arg.get()); 35640b57cec5SDimitry Andric } 35650b57cec5SDimitry Andric auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); 35660b57cec5SDimitry Andric assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && 35670b57cec5SDimitry Andric "Callee expected to be implicit cast to a builtin function pointer"); 35680b57cec5SDimitry Andric Callee->setType(OperatorNewOrDelete->getType()); 35690b57cec5SDimitry Andric 35700b57cec5SDimitry Andric return TheCallResult; 35710b57cec5SDimitry Andric } 35720b57cec5SDimitry Andric 35730b57cec5SDimitry Andric void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 35740b57cec5SDimitry Andric bool IsDelete, bool CallCanBeVirtual, 35750b57cec5SDimitry Andric bool WarnOnNonAbstractTypes, 35760b57cec5SDimitry Andric SourceLocation DtorLoc) { 35770b57cec5SDimitry Andric if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) 35780b57cec5SDimitry Andric return; 35790b57cec5SDimitry Andric 35800b57cec5SDimitry Andric // C++ [expr.delete]p3: 35810b57cec5SDimitry Andric // In the first alternative (delete object), if the static type of the 35820b57cec5SDimitry Andric // object to be deleted is different from its dynamic type, the static 35830b57cec5SDimitry Andric // type shall be a base class of the dynamic type of the object to be 35840b57cec5SDimitry Andric // deleted and the static type shall have a virtual destructor or the 35850b57cec5SDimitry Andric // behavior is undefined. 35860b57cec5SDimitry Andric // 35870b57cec5SDimitry Andric const CXXRecordDecl *PointeeRD = dtor->getParent(); 35880b57cec5SDimitry Andric // Note: a final class cannot be derived from, no issue there 35890b57cec5SDimitry Andric if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) 35900b57cec5SDimitry Andric return; 35910b57cec5SDimitry Andric 35920b57cec5SDimitry Andric // If the superclass is in a system header, there's nothing that can be done. 35930b57cec5SDimitry Andric // The `delete` (where we emit the warning) can be in a system header, 35940b57cec5SDimitry Andric // what matters for this warning is where the deleted type is defined. 35950b57cec5SDimitry Andric if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) 35960b57cec5SDimitry Andric return; 35970b57cec5SDimitry Andric 35980b57cec5SDimitry Andric QualType ClassType = dtor->getThisType()->getPointeeType(); 35990b57cec5SDimitry Andric if (PointeeRD->isAbstract()) { 36000b57cec5SDimitry Andric // If the class is abstract, we warn by default, because we're 36010b57cec5SDimitry Andric // sure the code has undefined behavior. 36020b57cec5SDimitry Andric Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) 36030b57cec5SDimitry Andric << ClassType; 36040b57cec5SDimitry Andric } else if (WarnOnNonAbstractTypes) { 36050b57cec5SDimitry Andric // Otherwise, if this is not an array delete, it's a bit suspect, 36060b57cec5SDimitry Andric // but not necessarily wrong. 36070b57cec5SDimitry Andric Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) 36080b57cec5SDimitry Andric << ClassType; 36090b57cec5SDimitry Andric } 36100b57cec5SDimitry Andric if (!IsDelete) { 36110b57cec5SDimitry Andric std::string TypeStr; 36120b57cec5SDimitry Andric ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); 36130b57cec5SDimitry Andric Diag(DtorLoc, diag::note_delete_non_virtual) 36140b57cec5SDimitry Andric << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); 36150b57cec5SDimitry Andric } 36160b57cec5SDimitry Andric } 36170b57cec5SDimitry Andric 36180b57cec5SDimitry Andric Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, 36190b57cec5SDimitry Andric SourceLocation StmtLoc, 36200b57cec5SDimitry Andric ConditionKind CK) { 36210b57cec5SDimitry Andric ExprResult E = 36220b57cec5SDimitry Andric CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); 36230b57cec5SDimitry Andric if (E.isInvalid()) 36240b57cec5SDimitry Andric return ConditionError(); 36250b57cec5SDimitry Andric return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), 36260b57cec5SDimitry Andric CK == ConditionKind::ConstexprIf); 36270b57cec5SDimitry Andric } 36280b57cec5SDimitry Andric 36290b57cec5SDimitry Andric /// Check the use of the given variable as a C++ condition in an if, 36300b57cec5SDimitry Andric /// while, do-while, or switch statement. 36310b57cec5SDimitry Andric ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 36320b57cec5SDimitry Andric SourceLocation StmtLoc, 36330b57cec5SDimitry Andric ConditionKind CK) { 36340b57cec5SDimitry Andric if (ConditionVar->isInvalidDecl()) 36350b57cec5SDimitry Andric return ExprError(); 36360b57cec5SDimitry Andric 36370b57cec5SDimitry Andric QualType T = ConditionVar->getType(); 36380b57cec5SDimitry Andric 36390b57cec5SDimitry Andric // C++ [stmt.select]p2: 36400b57cec5SDimitry Andric // The declarator shall not specify a function or an array. 36410b57cec5SDimitry Andric if (T->isFunctionType()) 36420b57cec5SDimitry Andric return ExprError(Diag(ConditionVar->getLocation(), 36430b57cec5SDimitry Andric diag::err_invalid_use_of_function_type) 36440b57cec5SDimitry Andric << ConditionVar->getSourceRange()); 36450b57cec5SDimitry Andric else if (T->isArrayType()) 36460b57cec5SDimitry Andric return ExprError(Diag(ConditionVar->getLocation(), 36470b57cec5SDimitry Andric diag::err_invalid_use_of_array_type) 36480b57cec5SDimitry Andric << ConditionVar->getSourceRange()); 36490b57cec5SDimitry Andric 36500b57cec5SDimitry Andric ExprResult Condition = BuildDeclRefExpr( 36510b57cec5SDimitry Andric ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, 36520b57cec5SDimitry Andric ConditionVar->getLocation()); 36530b57cec5SDimitry Andric 36540b57cec5SDimitry Andric switch (CK) { 36550b57cec5SDimitry Andric case ConditionKind::Boolean: 36560b57cec5SDimitry Andric return CheckBooleanCondition(StmtLoc, Condition.get()); 36570b57cec5SDimitry Andric 36580b57cec5SDimitry Andric case ConditionKind::ConstexprIf: 36590b57cec5SDimitry Andric return CheckBooleanCondition(StmtLoc, Condition.get(), true); 36600b57cec5SDimitry Andric 36610b57cec5SDimitry Andric case ConditionKind::Switch: 36620b57cec5SDimitry Andric return CheckSwitchCondition(StmtLoc, Condition.get()); 36630b57cec5SDimitry Andric } 36640b57cec5SDimitry Andric 36650b57cec5SDimitry Andric llvm_unreachable("unexpected condition kind"); 36660b57cec5SDimitry Andric } 36670b57cec5SDimitry Andric 36680b57cec5SDimitry Andric /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 36690b57cec5SDimitry Andric ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { 36700b57cec5SDimitry Andric // C++ 6.4p4: 36710b57cec5SDimitry Andric // The value of a condition that is an initialized declaration in a statement 36720b57cec5SDimitry Andric // other than a switch statement is the value of the declared variable 36730b57cec5SDimitry Andric // implicitly converted to type bool. If that conversion is ill-formed, the 36740b57cec5SDimitry Andric // program is ill-formed. 36750b57cec5SDimitry Andric // The value of a condition that is an expression is the value of the 36760b57cec5SDimitry Andric // expression, implicitly converted to bool. 36770b57cec5SDimitry Andric // 36780b57cec5SDimitry Andric // FIXME: Return this value to the caller so they don't need to recompute it. 36790b57cec5SDimitry Andric llvm::APSInt Value(/*BitWidth*/1); 36800b57cec5SDimitry Andric return (IsConstexpr && !CondExpr->isValueDependent()) 36810b57cec5SDimitry Andric ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value, 36820b57cec5SDimitry Andric CCEK_ConstexprIf) 36830b57cec5SDimitry Andric : PerformContextuallyConvertToBool(CondExpr); 36840b57cec5SDimitry Andric } 36850b57cec5SDimitry Andric 36860b57cec5SDimitry Andric /// Helper function to determine whether this is the (deprecated) C++ 36870b57cec5SDimitry Andric /// conversion from a string literal to a pointer to non-const char or 36880b57cec5SDimitry Andric /// non-const wchar_t (for narrow and wide string literals, 36890b57cec5SDimitry Andric /// respectively). 36900b57cec5SDimitry Andric bool 36910b57cec5SDimitry Andric Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 36920b57cec5SDimitry Andric // Look inside the implicit cast, if it exists. 36930b57cec5SDimitry Andric if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 36940b57cec5SDimitry Andric From = Cast->getSubExpr(); 36950b57cec5SDimitry Andric 36960b57cec5SDimitry Andric // A string literal (2.13.4) that is not a wide string literal can 36970b57cec5SDimitry Andric // be converted to an rvalue of type "pointer to char"; a wide 36980b57cec5SDimitry Andric // string literal can be converted to an rvalue of type "pointer 36990b57cec5SDimitry Andric // to wchar_t" (C++ 4.2p2). 37000b57cec5SDimitry Andric if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 37010b57cec5SDimitry Andric if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 37020b57cec5SDimitry Andric if (const BuiltinType *ToPointeeType 37030b57cec5SDimitry Andric = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 37040b57cec5SDimitry Andric // This conversion is considered only when there is an 37050b57cec5SDimitry Andric // explicit appropriate pointer target type (C++ 4.2p2). 37060b57cec5SDimitry Andric if (!ToPtrType->getPointeeType().hasQualifiers()) { 37070b57cec5SDimitry Andric switch (StrLit->getKind()) { 37080b57cec5SDimitry Andric case StringLiteral::UTF8: 37090b57cec5SDimitry Andric case StringLiteral::UTF16: 37100b57cec5SDimitry Andric case StringLiteral::UTF32: 37110b57cec5SDimitry Andric // We don't allow UTF literals to be implicitly converted 37120b57cec5SDimitry Andric break; 37130b57cec5SDimitry Andric case StringLiteral::Ascii: 37140b57cec5SDimitry Andric return (ToPointeeType->getKind() == BuiltinType::Char_U || 37150b57cec5SDimitry Andric ToPointeeType->getKind() == BuiltinType::Char_S); 37160b57cec5SDimitry Andric case StringLiteral::Wide: 37170b57cec5SDimitry Andric return Context.typesAreCompatible(Context.getWideCharType(), 37180b57cec5SDimitry Andric QualType(ToPointeeType, 0)); 37190b57cec5SDimitry Andric } 37200b57cec5SDimitry Andric } 37210b57cec5SDimitry Andric } 37220b57cec5SDimitry Andric 37230b57cec5SDimitry Andric return false; 37240b57cec5SDimitry Andric } 37250b57cec5SDimitry Andric 37260b57cec5SDimitry Andric static ExprResult BuildCXXCastArgument(Sema &S, 37270b57cec5SDimitry Andric SourceLocation CastLoc, 37280b57cec5SDimitry Andric QualType Ty, 37290b57cec5SDimitry Andric CastKind Kind, 37300b57cec5SDimitry Andric CXXMethodDecl *Method, 37310b57cec5SDimitry Andric DeclAccessPair FoundDecl, 37320b57cec5SDimitry Andric bool HadMultipleCandidates, 37330b57cec5SDimitry Andric Expr *From) { 37340b57cec5SDimitry Andric switch (Kind) { 37350b57cec5SDimitry Andric default: llvm_unreachable("Unhandled cast kind!"); 37360b57cec5SDimitry Andric case CK_ConstructorConversion: { 37370b57cec5SDimitry Andric CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 37380b57cec5SDimitry Andric SmallVector<Expr*, 8> ConstructorArgs; 37390b57cec5SDimitry Andric 37400b57cec5SDimitry Andric if (S.RequireNonAbstractType(CastLoc, Ty, 37410b57cec5SDimitry Andric diag::err_allocation_of_abstract_type)) 37420b57cec5SDimitry Andric return ExprError(); 37430b57cec5SDimitry Andric 37440b57cec5SDimitry Andric if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs)) 37450b57cec5SDimitry Andric return ExprError(); 37460b57cec5SDimitry Andric 37470b57cec5SDimitry Andric S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, 37480b57cec5SDimitry Andric InitializedEntity::InitializeTemporary(Ty)); 37490b57cec5SDimitry Andric if (S.DiagnoseUseOfDecl(Method, CastLoc)) 37500b57cec5SDimitry Andric return ExprError(); 37510b57cec5SDimitry Andric 37520b57cec5SDimitry Andric ExprResult Result = S.BuildCXXConstructExpr( 37530b57cec5SDimitry Andric CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), 37540b57cec5SDimitry Andric ConstructorArgs, HadMultipleCandidates, 37550b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 37560b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 37570b57cec5SDimitry Andric if (Result.isInvalid()) 37580b57cec5SDimitry Andric return ExprError(); 37590b57cec5SDimitry Andric 37600b57cec5SDimitry Andric return S.MaybeBindToTemporary(Result.getAs<Expr>()); 37610b57cec5SDimitry Andric } 37620b57cec5SDimitry Andric 37630b57cec5SDimitry Andric case CK_UserDefinedConversion: { 37640b57cec5SDimitry Andric assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 37650b57cec5SDimitry Andric 37660b57cec5SDimitry Andric S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); 37670b57cec5SDimitry Andric if (S.DiagnoseUseOfDecl(Method, CastLoc)) 37680b57cec5SDimitry Andric return ExprError(); 37690b57cec5SDimitry Andric 37700b57cec5SDimitry Andric // Create an implicit call expr that calls it. 37710b57cec5SDimitry Andric CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 37720b57cec5SDimitry Andric ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 37730b57cec5SDimitry Andric HadMultipleCandidates); 37740b57cec5SDimitry Andric if (Result.isInvalid()) 37750b57cec5SDimitry Andric return ExprError(); 37760b57cec5SDimitry Andric // Record usage of conversion in an implicit cast. 37770b57cec5SDimitry Andric Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), 37780b57cec5SDimitry Andric CK_UserDefinedConversion, Result.get(), 37790b57cec5SDimitry Andric nullptr, Result.get()->getValueKind()); 37800b57cec5SDimitry Andric 37810b57cec5SDimitry Andric return S.MaybeBindToTemporary(Result.get()); 37820b57cec5SDimitry Andric } 37830b57cec5SDimitry Andric } 37840b57cec5SDimitry Andric } 37850b57cec5SDimitry Andric 37860b57cec5SDimitry Andric /// PerformImplicitConversion - Perform an implicit conversion of the 37870b57cec5SDimitry Andric /// expression From to the type ToType using the pre-computed implicit 37880b57cec5SDimitry Andric /// conversion sequence ICS. Returns the converted 37890b57cec5SDimitry Andric /// expression. Action is the kind of conversion we're performing, 37900b57cec5SDimitry Andric /// used in the error message. 37910b57cec5SDimitry Andric ExprResult 37920b57cec5SDimitry Andric Sema::PerformImplicitConversion(Expr *From, QualType ToType, 37930b57cec5SDimitry Andric const ImplicitConversionSequence &ICS, 37940b57cec5SDimitry Andric AssignmentAction Action, 37950b57cec5SDimitry Andric CheckedConversionKind CCK) { 37960b57cec5SDimitry Andric // C++ [over.match.oper]p7: [...] operands of class type are converted [...] 37970b57cec5SDimitry Andric if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) 37980b57cec5SDimitry Andric return From; 37990b57cec5SDimitry Andric 38000b57cec5SDimitry Andric switch (ICS.getKind()) { 38010b57cec5SDimitry Andric case ImplicitConversionSequence::StandardConversion: { 38020b57cec5SDimitry Andric ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 38030b57cec5SDimitry Andric Action, CCK); 38040b57cec5SDimitry Andric if (Res.isInvalid()) 38050b57cec5SDimitry Andric return ExprError(); 38060b57cec5SDimitry Andric From = Res.get(); 38070b57cec5SDimitry Andric break; 38080b57cec5SDimitry Andric } 38090b57cec5SDimitry Andric 38100b57cec5SDimitry Andric case ImplicitConversionSequence::UserDefinedConversion: { 38110b57cec5SDimitry Andric 38120b57cec5SDimitry Andric FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 38130b57cec5SDimitry Andric CastKind CastKind; 38140b57cec5SDimitry Andric QualType BeforeToType; 38150b57cec5SDimitry Andric assert(FD && "no conversion function for user-defined conversion seq"); 38160b57cec5SDimitry Andric if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 38170b57cec5SDimitry Andric CastKind = CK_UserDefinedConversion; 38180b57cec5SDimitry Andric 38190b57cec5SDimitry Andric // If the user-defined conversion is specified by a conversion function, 38200b57cec5SDimitry Andric // the initial standard conversion sequence converts the source type to 38210b57cec5SDimitry Andric // the implicit object parameter of the conversion function. 38220b57cec5SDimitry Andric BeforeToType = Context.getTagDeclType(Conv->getParent()); 38230b57cec5SDimitry Andric } else { 38240b57cec5SDimitry Andric const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 38250b57cec5SDimitry Andric CastKind = CK_ConstructorConversion; 38260b57cec5SDimitry Andric // Do no conversion if dealing with ... for the first conversion. 38270b57cec5SDimitry Andric if (!ICS.UserDefined.EllipsisConversion) { 38280b57cec5SDimitry Andric // If the user-defined conversion is specified by a constructor, the 38290b57cec5SDimitry Andric // initial standard conversion sequence converts the source type to 38300b57cec5SDimitry Andric // the type required by the argument of the constructor 38310b57cec5SDimitry Andric BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 38320b57cec5SDimitry Andric } 38330b57cec5SDimitry Andric } 38340b57cec5SDimitry Andric // Watch out for ellipsis conversion. 38350b57cec5SDimitry Andric if (!ICS.UserDefined.EllipsisConversion) { 38360b57cec5SDimitry Andric ExprResult Res = 38370b57cec5SDimitry Andric PerformImplicitConversion(From, BeforeToType, 38380b57cec5SDimitry Andric ICS.UserDefined.Before, AA_Converting, 38390b57cec5SDimitry Andric CCK); 38400b57cec5SDimitry Andric if (Res.isInvalid()) 38410b57cec5SDimitry Andric return ExprError(); 38420b57cec5SDimitry Andric From = Res.get(); 38430b57cec5SDimitry Andric } 38440b57cec5SDimitry Andric 38450b57cec5SDimitry Andric ExprResult CastArg = BuildCXXCastArgument( 38460b57cec5SDimitry Andric *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, 38470b57cec5SDimitry Andric cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, 38480b57cec5SDimitry Andric ICS.UserDefined.HadMultipleCandidates, From); 38490b57cec5SDimitry Andric 38500b57cec5SDimitry Andric if (CastArg.isInvalid()) 38510b57cec5SDimitry Andric return ExprError(); 38520b57cec5SDimitry Andric 38530b57cec5SDimitry Andric From = CastArg.get(); 38540b57cec5SDimitry Andric 38550b57cec5SDimitry Andric // C++ [over.match.oper]p7: 38560b57cec5SDimitry Andric // [...] the second standard conversion sequence of a user-defined 38570b57cec5SDimitry Andric // conversion sequence is not applied. 38580b57cec5SDimitry Andric if (CCK == CCK_ForBuiltinOverloadedOp) 38590b57cec5SDimitry Andric return From; 38600b57cec5SDimitry Andric 38610b57cec5SDimitry Andric return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 38620b57cec5SDimitry Andric AA_Converting, CCK); 38630b57cec5SDimitry Andric } 38640b57cec5SDimitry Andric 38650b57cec5SDimitry Andric case ImplicitConversionSequence::AmbiguousConversion: 38660b57cec5SDimitry Andric ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 38670b57cec5SDimitry Andric PDiag(diag::err_typecheck_ambiguous_condition) 38680b57cec5SDimitry Andric << From->getSourceRange()); 38690b57cec5SDimitry Andric return ExprError(); 38700b57cec5SDimitry Andric 38710b57cec5SDimitry Andric case ImplicitConversionSequence::EllipsisConversion: 38720b57cec5SDimitry Andric llvm_unreachable("Cannot perform an ellipsis conversion"); 38730b57cec5SDimitry Andric 38740b57cec5SDimitry Andric case ImplicitConversionSequence::BadConversion: 38750b57cec5SDimitry Andric bool Diagnosed = 38760b57cec5SDimitry Andric DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType, 38770b57cec5SDimitry Andric From->getType(), From, Action); 38780b57cec5SDimitry Andric assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed; 38790b57cec5SDimitry Andric return ExprError(); 38800b57cec5SDimitry Andric } 38810b57cec5SDimitry Andric 38820b57cec5SDimitry Andric // Everything went well. 38830b57cec5SDimitry Andric return From; 38840b57cec5SDimitry Andric } 38850b57cec5SDimitry Andric 38860b57cec5SDimitry Andric /// PerformImplicitConversion - Perform an implicit conversion of the 38870b57cec5SDimitry Andric /// expression From to the type ToType by following the standard 38880b57cec5SDimitry Andric /// conversion sequence SCS. Returns the converted 38890b57cec5SDimitry Andric /// expression. Flavor is the context in which we're performing this 38900b57cec5SDimitry Andric /// conversion, for use in error messages. 38910b57cec5SDimitry Andric ExprResult 38920b57cec5SDimitry Andric Sema::PerformImplicitConversion(Expr *From, QualType ToType, 38930b57cec5SDimitry Andric const StandardConversionSequence& SCS, 38940b57cec5SDimitry Andric AssignmentAction Action, 38950b57cec5SDimitry Andric CheckedConversionKind CCK) { 38960b57cec5SDimitry Andric bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 38970b57cec5SDimitry Andric 38980b57cec5SDimitry Andric // Overall FIXME: we are recomputing too many types here and doing far too 38990b57cec5SDimitry Andric // much extra work. What this means is that we need to keep track of more 39000b57cec5SDimitry Andric // information that is computed when we try the implicit conversion initially, 39010b57cec5SDimitry Andric // so that we don't need to recompute anything here. 39020b57cec5SDimitry Andric QualType FromType = From->getType(); 39030b57cec5SDimitry Andric 39040b57cec5SDimitry Andric if (SCS.CopyConstructor) { 39050b57cec5SDimitry Andric // FIXME: When can ToType be a reference type? 39060b57cec5SDimitry Andric assert(!ToType->isReferenceType()); 39070b57cec5SDimitry Andric if (SCS.Second == ICK_Derived_To_Base) { 39080b57cec5SDimitry Andric SmallVector<Expr*, 8> ConstructorArgs; 39090b57cec5SDimitry Andric if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor), 39100b57cec5SDimitry Andric From, /*FIXME:ConstructLoc*/SourceLocation(), 39110b57cec5SDimitry Andric ConstructorArgs)) 39120b57cec5SDimitry Andric return ExprError(); 39130b57cec5SDimitry Andric return BuildCXXConstructExpr( 39140b57cec5SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 39150b57cec5SDimitry Andric SCS.FoundCopyConstructor, SCS.CopyConstructor, 39160b57cec5SDimitry Andric ConstructorArgs, /*HadMultipleCandidates*/ false, 39170b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 39180b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 39190b57cec5SDimitry Andric } 39200b57cec5SDimitry Andric return BuildCXXConstructExpr( 39210b57cec5SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 39220b57cec5SDimitry Andric SCS.FoundCopyConstructor, SCS.CopyConstructor, 39230b57cec5SDimitry Andric From, /*HadMultipleCandidates*/ false, 39240b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 39250b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 39260b57cec5SDimitry Andric } 39270b57cec5SDimitry Andric 39280b57cec5SDimitry Andric // Resolve overloaded function references. 39290b57cec5SDimitry Andric if (Context.hasSameType(FromType, Context.OverloadTy)) { 39300b57cec5SDimitry Andric DeclAccessPair Found; 39310b57cec5SDimitry Andric FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 39320b57cec5SDimitry Andric true, Found); 39330b57cec5SDimitry Andric if (!Fn) 39340b57cec5SDimitry Andric return ExprError(); 39350b57cec5SDimitry Andric 39360b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) 39370b57cec5SDimitry Andric return ExprError(); 39380b57cec5SDimitry Andric 39390b57cec5SDimitry Andric From = FixOverloadedFunctionReference(From, Found, Fn); 39400b57cec5SDimitry Andric FromType = From->getType(); 39410b57cec5SDimitry Andric } 39420b57cec5SDimitry Andric 39430b57cec5SDimitry Andric // If we're converting to an atomic type, first convert to the corresponding 39440b57cec5SDimitry Andric // non-atomic type. 39450b57cec5SDimitry Andric QualType ToAtomicType; 39460b57cec5SDimitry Andric if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 39470b57cec5SDimitry Andric ToAtomicType = ToType; 39480b57cec5SDimitry Andric ToType = ToAtomic->getValueType(); 39490b57cec5SDimitry Andric } 39500b57cec5SDimitry Andric 39510b57cec5SDimitry Andric QualType InitialFromType = FromType; 39520b57cec5SDimitry Andric // Perform the first implicit conversion. 39530b57cec5SDimitry Andric switch (SCS.First) { 39540b57cec5SDimitry Andric case ICK_Identity: 39550b57cec5SDimitry Andric if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { 39560b57cec5SDimitry Andric FromType = FromAtomic->getValueType().getUnqualifiedType(); 39570b57cec5SDimitry Andric From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, 39580b57cec5SDimitry Andric From, /*BasePath=*/nullptr, VK_RValue); 39590b57cec5SDimitry Andric } 39600b57cec5SDimitry Andric break; 39610b57cec5SDimitry Andric 39620b57cec5SDimitry Andric case ICK_Lvalue_To_Rvalue: { 39630b57cec5SDimitry Andric assert(From->getObjectKind() != OK_ObjCProperty); 39640b57cec5SDimitry Andric ExprResult FromRes = DefaultLvalueConversion(From); 39650b57cec5SDimitry Andric assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!"); 39660b57cec5SDimitry Andric From = FromRes.get(); 39670b57cec5SDimitry Andric FromType = From->getType(); 39680b57cec5SDimitry Andric break; 39690b57cec5SDimitry Andric } 39700b57cec5SDimitry Andric 39710b57cec5SDimitry Andric case ICK_Array_To_Pointer: 39720b57cec5SDimitry Andric FromType = Context.getArrayDecayedType(FromType); 39730b57cec5SDimitry Andric From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, 39740b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 39750b57cec5SDimitry Andric break; 39760b57cec5SDimitry Andric 39770b57cec5SDimitry Andric case ICK_Function_To_Pointer: 39780b57cec5SDimitry Andric FromType = Context.getPointerType(FromType); 39790b57cec5SDimitry Andric From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 39800b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 39810b57cec5SDimitry Andric break; 39820b57cec5SDimitry Andric 39830b57cec5SDimitry Andric default: 39840b57cec5SDimitry Andric llvm_unreachable("Improper first standard conversion"); 39850b57cec5SDimitry Andric } 39860b57cec5SDimitry Andric 39870b57cec5SDimitry Andric // Perform the second implicit conversion 39880b57cec5SDimitry Andric switch (SCS.Second) { 39890b57cec5SDimitry Andric case ICK_Identity: 39900b57cec5SDimitry Andric // C++ [except.spec]p5: 39910b57cec5SDimitry Andric // [For] assignment to and initialization of pointers to functions, 39920b57cec5SDimitry Andric // pointers to member functions, and references to functions: the 39930b57cec5SDimitry Andric // target entity shall allow at least the exceptions allowed by the 39940b57cec5SDimitry Andric // source value in the assignment or initialization. 39950b57cec5SDimitry Andric switch (Action) { 39960b57cec5SDimitry Andric case AA_Assigning: 39970b57cec5SDimitry Andric case AA_Initializing: 39980b57cec5SDimitry Andric // Note, function argument passing and returning are initialization. 39990b57cec5SDimitry Andric case AA_Passing: 40000b57cec5SDimitry Andric case AA_Returning: 40010b57cec5SDimitry Andric case AA_Sending: 40020b57cec5SDimitry Andric case AA_Passing_CFAudited: 40030b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 40040b57cec5SDimitry Andric return ExprError(); 40050b57cec5SDimitry Andric break; 40060b57cec5SDimitry Andric 40070b57cec5SDimitry Andric case AA_Casting: 40080b57cec5SDimitry Andric case AA_Converting: 40090b57cec5SDimitry Andric // Casts and implicit conversions are not initialization, so are not 40100b57cec5SDimitry Andric // checked for exception specification mismatches. 40110b57cec5SDimitry Andric break; 40120b57cec5SDimitry Andric } 40130b57cec5SDimitry Andric // Nothing else to do. 40140b57cec5SDimitry Andric break; 40150b57cec5SDimitry Andric 40160b57cec5SDimitry Andric case ICK_Integral_Promotion: 40170b57cec5SDimitry Andric case ICK_Integral_Conversion: 40180b57cec5SDimitry Andric if (ToType->isBooleanType()) { 40190b57cec5SDimitry Andric assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && 40200b57cec5SDimitry Andric SCS.Second == ICK_Integral_Promotion && 40210b57cec5SDimitry Andric "only enums with fixed underlying type can promote to bool"); 40220b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, 40230b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 40240b57cec5SDimitry Andric } else { 40250b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralCast, 40260b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 40270b57cec5SDimitry Andric } 40280b57cec5SDimitry Andric break; 40290b57cec5SDimitry Andric 40300b57cec5SDimitry Andric case ICK_Floating_Promotion: 40310b57cec5SDimitry Andric case ICK_Floating_Conversion: 40320b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_FloatingCast, 40330b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 40340b57cec5SDimitry Andric break; 40350b57cec5SDimitry Andric 40360b57cec5SDimitry Andric case ICK_Complex_Promotion: 40370b57cec5SDimitry Andric case ICK_Complex_Conversion: { 4038a7dea167SDimitry Andric QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); 4039a7dea167SDimitry Andric QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); 40400b57cec5SDimitry Andric CastKind CK; 40410b57cec5SDimitry Andric if (FromEl->isRealFloatingType()) { 40420b57cec5SDimitry Andric if (ToEl->isRealFloatingType()) 40430b57cec5SDimitry Andric CK = CK_FloatingComplexCast; 40440b57cec5SDimitry Andric else 40450b57cec5SDimitry Andric CK = CK_FloatingComplexToIntegralComplex; 40460b57cec5SDimitry Andric } else if (ToEl->isRealFloatingType()) { 40470b57cec5SDimitry Andric CK = CK_IntegralComplexToFloatingComplex; 40480b57cec5SDimitry Andric } else { 40490b57cec5SDimitry Andric CK = CK_IntegralComplexCast; 40500b57cec5SDimitry Andric } 40510b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK, 40520b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 40530b57cec5SDimitry Andric break; 40540b57cec5SDimitry Andric } 40550b57cec5SDimitry Andric 40560b57cec5SDimitry Andric case ICK_Floating_Integral: 40570b57cec5SDimitry Andric if (ToType->isRealFloatingType()) 40580b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, 40590b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 40600b57cec5SDimitry Andric else 40610b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, 40620b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 40630b57cec5SDimitry Andric break; 40640b57cec5SDimitry Andric 40650b57cec5SDimitry Andric case ICK_Compatible_Conversion: 4066f13e6193SDimitry Andric From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), 4067f13e6193SDimitry Andric /*BasePath=*/nullptr, CCK).get(); 40680b57cec5SDimitry Andric break; 40690b57cec5SDimitry Andric 40700b57cec5SDimitry Andric case ICK_Writeback_Conversion: 40710b57cec5SDimitry Andric case ICK_Pointer_Conversion: { 40720b57cec5SDimitry Andric if (SCS.IncompatibleObjC && Action != AA_Casting) { 40730b57cec5SDimitry Andric // Diagnose incompatible Objective-C conversions 40740b57cec5SDimitry Andric if (Action == AA_Initializing || Action == AA_Assigning) 40750b57cec5SDimitry Andric Diag(From->getBeginLoc(), 40760b57cec5SDimitry Andric diag::ext_typecheck_convert_incompatible_pointer) 40770b57cec5SDimitry Andric << ToType << From->getType() << Action << From->getSourceRange() 40780b57cec5SDimitry Andric << 0; 40790b57cec5SDimitry Andric else 40800b57cec5SDimitry Andric Diag(From->getBeginLoc(), 40810b57cec5SDimitry Andric diag::ext_typecheck_convert_incompatible_pointer) 40820b57cec5SDimitry Andric << From->getType() << ToType << Action << From->getSourceRange() 40830b57cec5SDimitry Andric << 0; 40840b57cec5SDimitry Andric 40850b57cec5SDimitry Andric if (From->getType()->isObjCObjectPointerType() && 40860b57cec5SDimitry Andric ToType->isObjCObjectPointerType()) 40870b57cec5SDimitry Andric EmitRelatedResultTypeNote(From); 40880b57cec5SDimitry Andric } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 40890b57cec5SDimitry Andric !CheckObjCARCUnavailableWeakConversion(ToType, 40900b57cec5SDimitry Andric From->getType())) { 40910b57cec5SDimitry Andric if (Action == AA_Initializing) 40920b57cec5SDimitry Andric Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); 40930b57cec5SDimitry Andric else 40940b57cec5SDimitry Andric Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) 40950b57cec5SDimitry Andric << (Action == AA_Casting) << From->getType() << ToType 40960b57cec5SDimitry Andric << From->getSourceRange(); 40970b57cec5SDimitry Andric } 40980b57cec5SDimitry Andric 4099480093f4SDimitry Andric // Defer address space conversion to the third conversion. 4100480093f4SDimitry Andric QualType FromPteeType = From->getType()->getPointeeType(); 4101480093f4SDimitry Andric QualType ToPteeType = ToType->getPointeeType(); 4102480093f4SDimitry Andric QualType NewToType = ToType; 4103480093f4SDimitry Andric if (!FromPteeType.isNull() && !ToPteeType.isNull() && 4104480093f4SDimitry Andric FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { 4105480093f4SDimitry Andric NewToType = Context.removeAddrSpaceQualType(ToPteeType); 4106480093f4SDimitry Andric NewToType = Context.getAddrSpaceQualType(NewToType, 4107480093f4SDimitry Andric FromPteeType.getAddressSpace()); 4108480093f4SDimitry Andric if (ToType->isObjCObjectPointerType()) 4109480093f4SDimitry Andric NewToType = Context.getObjCObjectPointerType(NewToType); 4110480093f4SDimitry Andric else if (ToType->isBlockPointerType()) 4111480093f4SDimitry Andric NewToType = Context.getBlockPointerType(NewToType); 4112480093f4SDimitry Andric else 4113480093f4SDimitry Andric NewToType = Context.getPointerType(NewToType); 4114480093f4SDimitry Andric } 4115480093f4SDimitry Andric 41160b57cec5SDimitry Andric CastKind Kind; 41170b57cec5SDimitry Andric CXXCastPath BasePath; 4118480093f4SDimitry Andric if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) 41190b57cec5SDimitry Andric return ExprError(); 41200b57cec5SDimitry Andric 41210b57cec5SDimitry Andric // Make sure we extend blocks if necessary. 41220b57cec5SDimitry Andric // FIXME: doing this here is really ugly. 41230b57cec5SDimitry Andric if (Kind == CK_BlockPointerToObjCPointerCast) { 41240b57cec5SDimitry Andric ExprResult E = From; 41250b57cec5SDimitry Andric (void) PrepareCastToObjCObjectPointer(E); 41260b57cec5SDimitry Andric From = E.get(); 41270b57cec5SDimitry Andric } 41280b57cec5SDimitry Andric if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 4129480093f4SDimitry Andric CheckObjCConversion(SourceRange(), NewToType, From, CCK); 4130480093f4SDimitry Andric From = ImpCastExprToType(From, NewToType, Kind, VK_RValue, &BasePath, CCK) 41310b57cec5SDimitry Andric .get(); 41320b57cec5SDimitry Andric break; 41330b57cec5SDimitry Andric } 41340b57cec5SDimitry Andric 41350b57cec5SDimitry Andric case ICK_Pointer_Member: { 41360b57cec5SDimitry Andric CastKind Kind; 41370b57cec5SDimitry Andric CXXCastPath BasePath; 41380b57cec5SDimitry Andric if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 41390b57cec5SDimitry Andric return ExprError(); 41400b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 41410b57cec5SDimitry Andric return ExprError(); 41420b57cec5SDimitry Andric 41430b57cec5SDimitry Andric // We may not have been able to figure out what this member pointer resolved 41440b57cec5SDimitry Andric // to up until this exact point. Attempt to lock-in it's inheritance model. 41450b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 41460b57cec5SDimitry Andric (void)isCompleteType(From->getExprLoc(), From->getType()); 41470b57cec5SDimitry Andric (void)isCompleteType(From->getExprLoc(), ToType); 41480b57cec5SDimitry Andric } 41490b57cec5SDimitry Andric 41500b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK) 41510b57cec5SDimitry Andric .get(); 41520b57cec5SDimitry Andric break; 41530b57cec5SDimitry Andric } 41540b57cec5SDimitry Andric 41550b57cec5SDimitry Andric case ICK_Boolean_Conversion: 41560b57cec5SDimitry Andric // Perform half-to-boolean conversion via float. 41570b57cec5SDimitry Andric if (From->getType()->isHalfType()) { 41580b57cec5SDimitry Andric From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); 41590b57cec5SDimitry Andric FromType = Context.FloatTy; 41600b57cec5SDimitry Andric } 41610b57cec5SDimitry Andric 41620b57cec5SDimitry Andric From = ImpCastExprToType(From, Context.BoolTy, 41630b57cec5SDimitry Andric ScalarTypeToBooleanCastKind(FromType), 41640b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 41650b57cec5SDimitry Andric break; 41660b57cec5SDimitry Andric 41670b57cec5SDimitry Andric case ICK_Derived_To_Base: { 41680b57cec5SDimitry Andric CXXCastPath BasePath; 41690b57cec5SDimitry Andric if (CheckDerivedToBaseConversion( 41700b57cec5SDimitry Andric From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), 41710b57cec5SDimitry Andric From->getSourceRange(), &BasePath, CStyle)) 41720b57cec5SDimitry Andric return ExprError(); 41730b57cec5SDimitry Andric 41740b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getNonReferenceType(), 41750b57cec5SDimitry Andric CK_DerivedToBase, From->getValueKind(), 41760b57cec5SDimitry Andric &BasePath, CCK).get(); 41770b57cec5SDimitry Andric break; 41780b57cec5SDimitry Andric } 41790b57cec5SDimitry Andric 41800b57cec5SDimitry Andric case ICK_Vector_Conversion: 41810b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_BitCast, 41820b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 41830b57cec5SDimitry Andric break; 41840b57cec5SDimitry Andric 41850b57cec5SDimitry Andric case ICK_Vector_Splat: { 41860b57cec5SDimitry Andric // Vector splat from any arithmetic type to a vector. 41870b57cec5SDimitry Andric Expr *Elem = prepareVectorSplat(ToType, From).get(); 41880b57cec5SDimitry Andric From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue, 41890b57cec5SDimitry Andric /*BasePath=*/nullptr, CCK).get(); 41900b57cec5SDimitry Andric break; 41910b57cec5SDimitry Andric } 41920b57cec5SDimitry Andric 41930b57cec5SDimitry Andric case ICK_Complex_Real: 41940b57cec5SDimitry Andric // Case 1. x -> _Complex y 41950b57cec5SDimitry Andric if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 41960b57cec5SDimitry Andric QualType ElType = ToComplex->getElementType(); 41970b57cec5SDimitry Andric bool isFloatingComplex = ElType->isRealFloatingType(); 41980b57cec5SDimitry Andric 41990b57cec5SDimitry Andric // x -> y 42000b57cec5SDimitry Andric if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 42010b57cec5SDimitry Andric // do nothing 42020b57cec5SDimitry Andric } else if (From->getType()->isRealFloatingType()) { 42030b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 42040b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); 42050b57cec5SDimitry Andric } else { 42060b57cec5SDimitry Andric assert(From->getType()->isIntegerType()); 42070b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 42080b57cec5SDimitry Andric isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); 42090b57cec5SDimitry Andric } 42100b57cec5SDimitry Andric // y -> _Complex y 42110b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 42120b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingRealToComplex 42130b57cec5SDimitry Andric : CK_IntegralRealToComplex).get(); 42140b57cec5SDimitry Andric 42150b57cec5SDimitry Andric // Case 2. _Complex x -> y 42160b57cec5SDimitry Andric } else { 42170b57cec5SDimitry Andric const ComplexType *FromComplex = From->getType()->getAs<ComplexType>(); 42180b57cec5SDimitry Andric assert(FromComplex); 42190b57cec5SDimitry Andric 42200b57cec5SDimitry Andric QualType ElType = FromComplex->getElementType(); 42210b57cec5SDimitry Andric bool isFloatingComplex = ElType->isRealFloatingType(); 42220b57cec5SDimitry Andric 42230b57cec5SDimitry Andric // _Complex x -> x 42240b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 42250b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingComplexToReal 42260b57cec5SDimitry Andric : CK_IntegralComplexToReal, 42270b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42280b57cec5SDimitry Andric 42290b57cec5SDimitry Andric // x -> y 42300b57cec5SDimitry Andric if (Context.hasSameUnqualifiedType(ElType, ToType)) { 42310b57cec5SDimitry Andric // do nothing 42320b57cec5SDimitry Andric } else if (ToType->isRealFloatingType()) { 42330b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 42340b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating, 42350b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42360b57cec5SDimitry Andric } else { 42370b57cec5SDimitry Andric assert(ToType->isIntegerType()); 42380b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 42390b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast, 42400b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42410b57cec5SDimitry Andric } 42420b57cec5SDimitry Andric } 42430b57cec5SDimitry Andric break; 42440b57cec5SDimitry Andric 42450b57cec5SDimitry Andric case ICK_Block_Pointer_Conversion: { 42460b57cec5SDimitry Andric LangAS AddrSpaceL = 42470b57cec5SDimitry Andric ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 42480b57cec5SDimitry Andric LangAS AddrSpaceR = 42490b57cec5SDimitry Andric FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 42500b57cec5SDimitry Andric assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && 42510b57cec5SDimitry Andric "Invalid cast"); 42520b57cec5SDimitry Andric CastKind Kind = 42530b57cec5SDimitry Andric AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 42540b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, 42550b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 42560b57cec5SDimitry Andric break; 42570b57cec5SDimitry Andric } 42580b57cec5SDimitry Andric 42590b57cec5SDimitry Andric case ICK_TransparentUnionConversion: { 42600b57cec5SDimitry Andric ExprResult FromRes = From; 42610b57cec5SDimitry Andric Sema::AssignConvertType ConvTy = 42620b57cec5SDimitry Andric CheckTransparentUnionArgumentConstraints(ToType, FromRes); 42630b57cec5SDimitry Andric if (FromRes.isInvalid()) 42640b57cec5SDimitry Andric return ExprError(); 42650b57cec5SDimitry Andric From = FromRes.get(); 42660b57cec5SDimitry Andric assert ((ConvTy == Sema::Compatible) && 42670b57cec5SDimitry Andric "Improper transparent union conversion"); 42680b57cec5SDimitry Andric (void)ConvTy; 42690b57cec5SDimitry Andric break; 42700b57cec5SDimitry Andric } 42710b57cec5SDimitry Andric 42720b57cec5SDimitry Andric case ICK_Zero_Event_Conversion: 42730b57cec5SDimitry Andric case ICK_Zero_Queue_Conversion: 42740b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 42750b57cec5SDimitry Andric CK_ZeroToOCLOpaqueType, 42760b57cec5SDimitry Andric From->getValueKind()).get(); 42770b57cec5SDimitry Andric break; 42780b57cec5SDimitry Andric 42790b57cec5SDimitry Andric case ICK_Lvalue_To_Rvalue: 42800b57cec5SDimitry Andric case ICK_Array_To_Pointer: 42810b57cec5SDimitry Andric case ICK_Function_To_Pointer: 42820b57cec5SDimitry Andric case ICK_Function_Conversion: 42830b57cec5SDimitry Andric case ICK_Qualification: 42840b57cec5SDimitry Andric case ICK_Num_Conversion_Kinds: 42850b57cec5SDimitry Andric case ICK_C_Only_Conversion: 42860b57cec5SDimitry Andric case ICK_Incompatible_Pointer_Conversion: 42870b57cec5SDimitry Andric llvm_unreachable("Improper second standard conversion"); 42880b57cec5SDimitry Andric } 42890b57cec5SDimitry Andric 42900b57cec5SDimitry Andric switch (SCS.Third) { 42910b57cec5SDimitry Andric case ICK_Identity: 42920b57cec5SDimitry Andric // Nothing to do. 42930b57cec5SDimitry Andric break; 42940b57cec5SDimitry Andric 42950b57cec5SDimitry Andric case ICK_Function_Conversion: 42960b57cec5SDimitry Andric // If both sides are functions (or pointers/references to them), there could 42970b57cec5SDimitry Andric // be incompatible exception declarations. 42980b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 42990b57cec5SDimitry Andric return ExprError(); 43000b57cec5SDimitry Andric 43010b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, CK_NoOp, 43020b57cec5SDimitry Andric VK_RValue, /*BasePath=*/nullptr, CCK).get(); 43030b57cec5SDimitry Andric break; 43040b57cec5SDimitry Andric 43050b57cec5SDimitry Andric case ICK_Qualification: { 4306f13e6193SDimitry Andric ExprValueKind VK = From->getValueKind(); 43070b57cec5SDimitry Andric CastKind CK = CK_NoOp; 43080b57cec5SDimitry Andric 43090b57cec5SDimitry Andric if (ToType->isReferenceType() && 43100b57cec5SDimitry Andric ToType->getPointeeType().getAddressSpace() != 43110b57cec5SDimitry Andric From->getType().getAddressSpace()) 43120b57cec5SDimitry Andric CK = CK_AddressSpaceConversion; 43130b57cec5SDimitry Andric 43140b57cec5SDimitry Andric if (ToType->isPointerType() && 43150b57cec5SDimitry Andric ToType->getPointeeType().getAddressSpace() != 43160b57cec5SDimitry Andric From->getType()->getPointeeType().getAddressSpace()) 43170b57cec5SDimitry Andric CK = CK_AddressSpaceConversion; 43180b57cec5SDimitry Andric 43190b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, 43200b57cec5SDimitry Andric /*BasePath=*/nullptr, CCK) 43210b57cec5SDimitry Andric .get(); 43220b57cec5SDimitry Andric 43230b57cec5SDimitry Andric if (SCS.DeprecatedStringLiteralToCharPtr && 43240b57cec5SDimitry Andric !getLangOpts().WritableStrings) { 43250b57cec5SDimitry Andric Diag(From->getBeginLoc(), 43260b57cec5SDimitry Andric getLangOpts().CPlusPlus11 43270b57cec5SDimitry Andric ? diag::ext_deprecated_string_literal_conversion 43280b57cec5SDimitry Andric : diag::warn_deprecated_string_literal_conversion) 43290b57cec5SDimitry Andric << ToType.getNonReferenceType(); 43300b57cec5SDimitry Andric } 43310b57cec5SDimitry Andric 43320b57cec5SDimitry Andric break; 43330b57cec5SDimitry Andric } 43340b57cec5SDimitry Andric 43350b57cec5SDimitry Andric default: 43360b57cec5SDimitry Andric llvm_unreachable("Improper third standard conversion"); 43370b57cec5SDimitry Andric } 43380b57cec5SDimitry Andric 43390b57cec5SDimitry Andric // If this conversion sequence involved a scalar -> atomic conversion, perform 43400b57cec5SDimitry Andric // that conversion now. 43410b57cec5SDimitry Andric if (!ToAtomicType.isNull()) { 43420b57cec5SDimitry Andric assert(Context.hasSameType( 43430b57cec5SDimitry Andric ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); 43440b57cec5SDimitry Andric From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 43450b57cec5SDimitry Andric VK_RValue, nullptr, CCK).get(); 43460b57cec5SDimitry Andric } 43470b57cec5SDimitry Andric 43480b57cec5SDimitry Andric // If this conversion sequence succeeded and involved implicitly converting a 43490b57cec5SDimitry Andric // _Nullable type to a _Nonnull one, complain. 43500b57cec5SDimitry Andric if (!isCast(CCK)) 43510b57cec5SDimitry Andric diagnoseNullableToNonnullConversion(ToType, InitialFromType, 43520b57cec5SDimitry Andric From->getBeginLoc()); 43530b57cec5SDimitry Andric 43540b57cec5SDimitry Andric return From; 43550b57cec5SDimitry Andric } 43560b57cec5SDimitry Andric 43570b57cec5SDimitry Andric /// Check the completeness of a type in a unary type trait. 43580b57cec5SDimitry Andric /// 43590b57cec5SDimitry Andric /// If the particular type trait requires a complete type, tries to complete 43600b57cec5SDimitry Andric /// it. If completing the type fails, a diagnostic is emitted and false 43610b57cec5SDimitry Andric /// returned. If completing the type succeeds or no completion was required, 43620b57cec5SDimitry Andric /// returns true. 43630b57cec5SDimitry Andric static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, 43640b57cec5SDimitry Andric SourceLocation Loc, 43650b57cec5SDimitry Andric QualType ArgTy) { 43660b57cec5SDimitry Andric // C++0x [meta.unary.prop]p3: 43670b57cec5SDimitry Andric // For all of the class templates X declared in this Clause, instantiating 43680b57cec5SDimitry Andric // that template with a template argument that is a class template 43690b57cec5SDimitry Andric // specialization may result in the implicit instantiation of the template 43700b57cec5SDimitry Andric // argument if and only if the semantics of X require that the argument 43710b57cec5SDimitry Andric // must be a complete type. 43720b57cec5SDimitry Andric // We apply this rule to all the type trait expressions used to implement 43730b57cec5SDimitry Andric // these class templates. We also try to follow any GCC documented behavior 43740b57cec5SDimitry Andric // in these expressions to ensure portability of standard libraries. 43750b57cec5SDimitry Andric switch (UTT) { 43760b57cec5SDimitry Andric default: llvm_unreachable("not a UTT"); 43770b57cec5SDimitry Andric // is_complete_type somewhat obviously cannot require a complete type. 43780b57cec5SDimitry Andric case UTT_IsCompleteType: 43790b57cec5SDimitry Andric // Fall-through 43800b57cec5SDimitry Andric 43810b57cec5SDimitry Andric // These traits are modeled on the type predicates in C++0x 43820b57cec5SDimitry Andric // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 43830b57cec5SDimitry Andric // requiring a complete type, as whether or not they return true cannot be 43840b57cec5SDimitry Andric // impacted by the completeness of the type. 43850b57cec5SDimitry Andric case UTT_IsVoid: 43860b57cec5SDimitry Andric case UTT_IsIntegral: 43870b57cec5SDimitry Andric case UTT_IsFloatingPoint: 43880b57cec5SDimitry Andric case UTT_IsArray: 43890b57cec5SDimitry Andric case UTT_IsPointer: 43900b57cec5SDimitry Andric case UTT_IsLvalueReference: 43910b57cec5SDimitry Andric case UTT_IsRvalueReference: 43920b57cec5SDimitry Andric case UTT_IsMemberFunctionPointer: 43930b57cec5SDimitry Andric case UTT_IsMemberObjectPointer: 43940b57cec5SDimitry Andric case UTT_IsEnum: 43950b57cec5SDimitry Andric case UTT_IsUnion: 43960b57cec5SDimitry Andric case UTT_IsClass: 43970b57cec5SDimitry Andric case UTT_IsFunction: 43980b57cec5SDimitry Andric case UTT_IsReference: 43990b57cec5SDimitry Andric case UTT_IsArithmetic: 44000b57cec5SDimitry Andric case UTT_IsFundamental: 44010b57cec5SDimitry Andric case UTT_IsObject: 44020b57cec5SDimitry Andric case UTT_IsScalar: 44030b57cec5SDimitry Andric case UTT_IsCompound: 44040b57cec5SDimitry Andric case UTT_IsMemberPointer: 44050b57cec5SDimitry Andric // Fall-through 44060b57cec5SDimitry Andric 44070b57cec5SDimitry Andric // These traits are modeled on type predicates in C++0x [meta.unary.prop] 44080b57cec5SDimitry Andric // which requires some of its traits to have the complete type. However, 44090b57cec5SDimitry Andric // the completeness of the type cannot impact these traits' semantics, and 44100b57cec5SDimitry Andric // so they don't require it. This matches the comments on these traits in 44110b57cec5SDimitry Andric // Table 49. 44120b57cec5SDimitry Andric case UTT_IsConst: 44130b57cec5SDimitry Andric case UTT_IsVolatile: 44140b57cec5SDimitry Andric case UTT_IsSigned: 44150b57cec5SDimitry Andric case UTT_IsUnsigned: 44160b57cec5SDimitry Andric 44170b57cec5SDimitry Andric // This type trait always returns false, checking the type is moot. 44180b57cec5SDimitry Andric case UTT_IsInterfaceClass: 44190b57cec5SDimitry Andric return true; 44200b57cec5SDimitry Andric 44210b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 44220b57cec5SDimitry Andric // If T is a non-union class type, T shall be a complete type. 44230b57cec5SDimitry Andric case UTT_IsEmpty: 44240b57cec5SDimitry Andric case UTT_IsPolymorphic: 44250b57cec5SDimitry Andric case UTT_IsAbstract: 44260b57cec5SDimitry Andric if (const auto *RD = ArgTy->getAsCXXRecordDecl()) 44270b57cec5SDimitry Andric if (!RD->isUnion()) 44280b57cec5SDimitry Andric return !S.RequireCompleteType( 44290b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 44300b57cec5SDimitry Andric return true; 44310b57cec5SDimitry Andric 44320b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 44330b57cec5SDimitry Andric // If T is a class type, T shall be a complete type. 44340b57cec5SDimitry Andric case UTT_IsFinal: 44350b57cec5SDimitry Andric case UTT_IsSealed: 44360b57cec5SDimitry Andric if (ArgTy->getAsCXXRecordDecl()) 44370b57cec5SDimitry Andric return !S.RequireCompleteType( 44380b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 44390b57cec5SDimitry Andric return true; 44400b57cec5SDimitry Andric 44410b57cec5SDimitry Andric // C++1z [meta.unary.prop]: 44420b57cec5SDimitry Andric // remove_all_extents_t<T> shall be a complete type or cv void. 44430b57cec5SDimitry Andric case UTT_IsAggregate: 44440b57cec5SDimitry Andric case UTT_IsTrivial: 44450b57cec5SDimitry Andric case UTT_IsTriviallyCopyable: 44460b57cec5SDimitry Andric case UTT_IsStandardLayout: 44470b57cec5SDimitry Andric case UTT_IsPOD: 44480b57cec5SDimitry Andric case UTT_IsLiteral: 44490b57cec5SDimitry Andric // Per the GCC type traits documentation, T shall be a complete type, cv void, 44500b57cec5SDimitry Andric // or an array of unknown bound. But GCC actually imposes the same constraints 44510b57cec5SDimitry Andric // as above. 44520b57cec5SDimitry Andric case UTT_HasNothrowAssign: 44530b57cec5SDimitry Andric case UTT_HasNothrowMoveAssign: 44540b57cec5SDimitry Andric case UTT_HasNothrowConstructor: 44550b57cec5SDimitry Andric case UTT_HasNothrowCopy: 44560b57cec5SDimitry Andric case UTT_HasTrivialAssign: 44570b57cec5SDimitry Andric case UTT_HasTrivialMoveAssign: 44580b57cec5SDimitry Andric case UTT_HasTrivialDefaultConstructor: 44590b57cec5SDimitry Andric case UTT_HasTrivialMoveConstructor: 44600b57cec5SDimitry Andric case UTT_HasTrivialCopy: 44610b57cec5SDimitry Andric case UTT_HasTrivialDestructor: 44620b57cec5SDimitry Andric case UTT_HasVirtualDestructor: 44630b57cec5SDimitry Andric ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); 44640b57cec5SDimitry Andric LLVM_FALLTHROUGH; 44650b57cec5SDimitry Andric 44660b57cec5SDimitry Andric // C++1z [meta.unary.prop]: 44670b57cec5SDimitry Andric // T shall be a complete type, cv void, or an array of unknown bound. 44680b57cec5SDimitry Andric case UTT_IsDestructible: 44690b57cec5SDimitry Andric case UTT_IsNothrowDestructible: 44700b57cec5SDimitry Andric case UTT_IsTriviallyDestructible: 44710b57cec5SDimitry Andric case UTT_HasUniqueObjectRepresentations: 44720b57cec5SDimitry Andric if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) 44730b57cec5SDimitry Andric return true; 44740b57cec5SDimitry Andric 44750b57cec5SDimitry Andric return !S.RequireCompleteType( 44760b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 44770b57cec5SDimitry Andric } 44780b57cec5SDimitry Andric } 44790b57cec5SDimitry Andric 44800b57cec5SDimitry Andric static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 44810b57cec5SDimitry Andric Sema &Self, SourceLocation KeyLoc, ASTContext &C, 44820b57cec5SDimitry Andric bool (CXXRecordDecl::*HasTrivial)() const, 44830b57cec5SDimitry Andric bool (CXXRecordDecl::*HasNonTrivial)() const, 44840b57cec5SDimitry Andric bool (CXXMethodDecl::*IsDesiredOp)() const) 44850b57cec5SDimitry Andric { 44860b57cec5SDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 44870b57cec5SDimitry Andric if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 44880b57cec5SDimitry Andric return true; 44890b57cec5SDimitry Andric 44900b57cec5SDimitry Andric DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 44910b57cec5SDimitry Andric DeclarationNameInfo NameInfo(Name, KeyLoc); 44920b57cec5SDimitry Andric LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 44930b57cec5SDimitry Andric if (Self.LookupQualifiedName(Res, RD)) { 44940b57cec5SDimitry Andric bool FoundOperator = false; 44950b57cec5SDimitry Andric Res.suppressDiagnostics(); 44960b57cec5SDimitry Andric for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 44970b57cec5SDimitry Andric Op != OpEnd; ++Op) { 44980b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(*Op)) 44990b57cec5SDimitry Andric continue; 45000b57cec5SDimitry Andric 45010b57cec5SDimitry Andric CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 45020b57cec5SDimitry Andric if((Operator->*IsDesiredOp)()) { 45030b57cec5SDimitry Andric FoundOperator = true; 45040b57cec5SDimitry Andric const FunctionProtoType *CPT = 45050b57cec5SDimitry Andric Operator->getType()->getAs<FunctionProtoType>(); 45060b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 45070b57cec5SDimitry Andric if (!CPT || !CPT->isNothrow()) 45080b57cec5SDimitry Andric return false; 45090b57cec5SDimitry Andric } 45100b57cec5SDimitry Andric } 45110b57cec5SDimitry Andric return FoundOperator; 45120b57cec5SDimitry Andric } 45130b57cec5SDimitry Andric return false; 45140b57cec5SDimitry Andric } 45150b57cec5SDimitry Andric 45160b57cec5SDimitry Andric static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, 45170b57cec5SDimitry Andric SourceLocation KeyLoc, QualType T) { 45180b57cec5SDimitry Andric assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 45190b57cec5SDimitry Andric 45200b57cec5SDimitry Andric ASTContext &C = Self.Context; 45210b57cec5SDimitry Andric switch(UTT) { 45220b57cec5SDimitry Andric default: llvm_unreachable("not a UTT"); 45230b57cec5SDimitry Andric // Type trait expressions corresponding to the primary type category 45240b57cec5SDimitry Andric // predicates in C++0x [meta.unary.cat]. 45250b57cec5SDimitry Andric case UTT_IsVoid: 45260b57cec5SDimitry Andric return T->isVoidType(); 45270b57cec5SDimitry Andric case UTT_IsIntegral: 45280b57cec5SDimitry Andric return T->isIntegralType(C); 45290b57cec5SDimitry Andric case UTT_IsFloatingPoint: 45300b57cec5SDimitry Andric return T->isFloatingType(); 45310b57cec5SDimitry Andric case UTT_IsArray: 45320b57cec5SDimitry Andric return T->isArrayType(); 45330b57cec5SDimitry Andric case UTT_IsPointer: 45340b57cec5SDimitry Andric return T->isPointerType(); 45350b57cec5SDimitry Andric case UTT_IsLvalueReference: 45360b57cec5SDimitry Andric return T->isLValueReferenceType(); 45370b57cec5SDimitry Andric case UTT_IsRvalueReference: 45380b57cec5SDimitry Andric return T->isRValueReferenceType(); 45390b57cec5SDimitry Andric case UTT_IsMemberFunctionPointer: 45400b57cec5SDimitry Andric return T->isMemberFunctionPointerType(); 45410b57cec5SDimitry Andric case UTT_IsMemberObjectPointer: 45420b57cec5SDimitry Andric return T->isMemberDataPointerType(); 45430b57cec5SDimitry Andric case UTT_IsEnum: 45440b57cec5SDimitry Andric return T->isEnumeralType(); 45450b57cec5SDimitry Andric case UTT_IsUnion: 45460b57cec5SDimitry Andric return T->isUnionType(); 45470b57cec5SDimitry Andric case UTT_IsClass: 45480b57cec5SDimitry Andric return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 45490b57cec5SDimitry Andric case UTT_IsFunction: 45500b57cec5SDimitry Andric return T->isFunctionType(); 45510b57cec5SDimitry Andric 45520b57cec5SDimitry Andric // Type trait expressions which correspond to the convenient composition 45530b57cec5SDimitry Andric // predicates in C++0x [meta.unary.comp]. 45540b57cec5SDimitry Andric case UTT_IsReference: 45550b57cec5SDimitry Andric return T->isReferenceType(); 45560b57cec5SDimitry Andric case UTT_IsArithmetic: 45570b57cec5SDimitry Andric return T->isArithmeticType() && !T->isEnumeralType(); 45580b57cec5SDimitry Andric case UTT_IsFundamental: 45590b57cec5SDimitry Andric return T->isFundamentalType(); 45600b57cec5SDimitry Andric case UTT_IsObject: 45610b57cec5SDimitry Andric return T->isObjectType(); 45620b57cec5SDimitry Andric case UTT_IsScalar: 45630b57cec5SDimitry Andric // Note: semantic analysis depends on Objective-C lifetime types to be 45640b57cec5SDimitry Andric // considered scalar types. However, such types do not actually behave 45650b57cec5SDimitry Andric // like scalar types at run time (since they may require retain/release 45660b57cec5SDimitry Andric // operations), so we report them as non-scalar. 45670b57cec5SDimitry Andric if (T->isObjCLifetimeType()) { 45680b57cec5SDimitry Andric switch (T.getObjCLifetime()) { 45690b57cec5SDimitry Andric case Qualifiers::OCL_None: 45700b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone: 45710b57cec5SDimitry Andric return true; 45720b57cec5SDimitry Andric 45730b57cec5SDimitry Andric case Qualifiers::OCL_Strong: 45740b57cec5SDimitry Andric case Qualifiers::OCL_Weak: 45750b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing: 45760b57cec5SDimitry Andric return false; 45770b57cec5SDimitry Andric } 45780b57cec5SDimitry Andric } 45790b57cec5SDimitry Andric 45800b57cec5SDimitry Andric return T->isScalarType(); 45810b57cec5SDimitry Andric case UTT_IsCompound: 45820b57cec5SDimitry Andric return T->isCompoundType(); 45830b57cec5SDimitry Andric case UTT_IsMemberPointer: 45840b57cec5SDimitry Andric return T->isMemberPointerType(); 45850b57cec5SDimitry Andric 45860b57cec5SDimitry Andric // Type trait expressions which correspond to the type property predicates 45870b57cec5SDimitry Andric // in C++0x [meta.unary.prop]. 45880b57cec5SDimitry Andric case UTT_IsConst: 45890b57cec5SDimitry Andric return T.isConstQualified(); 45900b57cec5SDimitry Andric case UTT_IsVolatile: 45910b57cec5SDimitry Andric return T.isVolatileQualified(); 45920b57cec5SDimitry Andric case UTT_IsTrivial: 45930b57cec5SDimitry Andric return T.isTrivialType(C); 45940b57cec5SDimitry Andric case UTT_IsTriviallyCopyable: 45950b57cec5SDimitry Andric return T.isTriviallyCopyableType(C); 45960b57cec5SDimitry Andric case UTT_IsStandardLayout: 45970b57cec5SDimitry Andric return T->isStandardLayoutType(); 45980b57cec5SDimitry Andric case UTT_IsPOD: 45990b57cec5SDimitry Andric return T.isPODType(C); 46000b57cec5SDimitry Andric case UTT_IsLiteral: 46010b57cec5SDimitry Andric return T->isLiteralType(C); 46020b57cec5SDimitry Andric case UTT_IsEmpty: 46030b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 46040b57cec5SDimitry Andric return !RD->isUnion() && RD->isEmpty(); 46050b57cec5SDimitry Andric return false; 46060b57cec5SDimitry Andric case UTT_IsPolymorphic: 46070b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 46080b57cec5SDimitry Andric return !RD->isUnion() && RD->isPolymorphic(); 46090b57cec5SDimitry Andric return false; 46100b57cec5SDimitry Andric case UTT_IsAbstract: 46110b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 46120b57cec5SDimitry Andric return !RD->isUnion() && RD->isAbstract(); 46130b57cec5SDimitry Andric return false; 46140b57cec5SDimitry Andric case UTT_IsAggregate: 46150b57cec5SDimitry Andric // Report vector extensions and complex types as aggregates because they 46160b57cec5SDimitry Andric // support aggregate initialization. GCC mirrors this behavior for vectors 46170b57cec5SDimitry Andric // but not _Complex. 46180b57cec5SDimitry Andric return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || 46190b57cec5SDimitry Andric T->isAnyComplexType(); 46200b57cec5SDimitry Andric // __is_interface_class only returns true when CL is invoked in /CLR mode and 46210b57cec5SDimitry Andric // even then only when it is used with the 'interface struct ...' syntax 46220b57cec5SDimitry Andric // Clang doesn't support /CLR which makes this type trait moot. 46230b57cec5SDimitry Andric case UTT_IsInterfaceClass: 46240b57cec5SDimitry Andric return false; 46250b57cec5SDimitry Andric case UTT_IsFinal: 46260b57cec5SDimitry Andric case UTT_IsSealed: 46270b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 46280b57cec5SDimitry Andric return RD->hasAttr<FinalAttr>(); 46290b57cec5SDimitry Andric return false; 46300b57cec5SDimitry Andric case UTT_IsSigned: 4631a7dea167SDimitry Andric // Enum types should always return false. 4632a7dea167SDimitry Andric // Floating points should always return true. 4633a7dea167SDimitry Andric return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType()); 46340b57cec5SDimitry Andric case UTT_IsUnsigned: 46350b57cec5SDimitry Andric return T->isUnsignedIntegerType(); 46360b57cec5SDimitry Andric 46370b57cec5SDimitry Andric // Type trait expressions which query classes regarding their construction, 46380b57cec5SDimitry Andric // destruction, and copying. Rather than being based directly on the 46390b57cec5SDimitry Andric // related type predicates in the standard, they are specified by both 46400b57cec5SDimitry Andric // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 46410b57cec5SDimitry Andric // specifications. 46420b57cec5SDimitry Andric // 46430b57cec5SDimitry Andric // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 46440b57cec5SDimitry Andric // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 46450b57cec5SDimitry Andric // 46460b57cec5SDimitry Andric // Note that these builtins do not behave as documented in g++: if a class 46470b57cec5SDimitry Andric // has both a trivial and a non-trivial special member of a particular kind, 46480b57cec5SDimitry Andric // they return false! For now, we emulate this behavior. 46490b57cec5SDimitry Andric // FIXME: This appears to be a g++ bug: more complex cases reveal that it 46500b57cec5SDimitry Andric // does not correctly compute triviality in the presence of multiple special 46510b57cec5SDimitry Andric // members of the same kind. Revisit this once the g++ bug is fixed. 46520b57cec5SDimitry Andric case UTT_HasTrivialDefaultConstructor: 46530b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 46540b57cec5SDimitry Andric // If __is_pod (type) is true then the trait is true, else if type is 46550b57cec5SDimitry Andric // a cv class or union type (or array thereof) with a trivial default 46560b57cec5SDimitry Andric // constructor ([class.ctor]) then the trait is true, else it is false. 46570b57cec5SDimitry Andric if (T.isPODType(C)) 46580b57cec5SDimitry Andric return true; 46590b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 46600b57cec5SDimitry Andric return RD->hasTrivialDefaultConstructor() && 46610b57cec5SDimitry Andric !RD->hasNonTrivialDefaultConstructor(); 46620b57cec5SDimitry Andric return false; 46630b57cec5SDimitry Andric case UTT_HasTrivialMoveConstructor: 46640b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 46650b57cec5SDimitry Andric // standard library headers. Specifically this is used as the logic 46660b57cec5SDimitry Andric // behind std::is_trivially_move_constructible (20.9.4.3). 46670b57cec5SDimitry Andric if (T.isPODType(C)) 46680b57cec5SDimitry Andric return true; 46690b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 46700b57cec5SDimitry Andric return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 46710b57cec5SDimitry Andric return false; 46720b57cec5SDimitry Andric case UTT_HasTrivialCopy: 46730b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 46740b57cec5SDimitry Andric // If __is_pod (type) is true or type is a reference type then 46750b57cec5SDimitry Andric // the trait is true, else if type is a cv class or union type 46760b57cec5SDimitry Andric // with a trivial copy constructor ([class.copy]) then the trait 46770b57cec5SDimitry Andric // is true, else it is false. 46780b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType()) 46790b57cec5SDimitry Andric return true; 46800b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 46810b57cec5SDimitry Andric return RD->hasTrivialCopyConstructor() && 46820b57cec5SDimitry Andric !RD->hasNonTrivialCopyConstructor(); 46830b57cec5SDimitry Andric return false; 46840b57cec5SDimitry Andric case UTT_HasTrivialMoveAssign: 46850b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 46860b57cec5SDimitry Andric // standard library headers. Specifically it is used as the logic 46870b57cec5SDimitry Andric // behind std::is_trivially_move_assignable (20.9.4.3) 46880b57cec5SDimitry Andric if (T.isPODType(C)) 46890b57cec5SDimitry Andric return true; 46900b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 46910b57cec5SDimitry Andric return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 46920b57cec5SDimitry Andric return false; 46930b57cec5SDimitry Andric case UTT_HasTrivialAssign: 46940b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 46950b57cec5SDimitry Andric // If type is const qualified or is a reference type then the 46960b57cec5SDimitry Andric // trait is false. Otherwise if __is_pod (type) is true then the 46970b57cec5SDimitry Andric // trait is true, else if type is a cv class or union type with 46980b57cec5SDimitry Andric // a trivial copy assignment ([class.copy]) then the trait is 46990b57cec5SDimitry Andric // true, else it is false. 47000b57cec5SDimitry Andric // Note: the const and reference restrictions are interesting, 47010b57cec5SDimitry Andric // given that const and reference members don't prevent a class 47020b57cec5SDimitry Andric // from having a trivial copy assignment operator (but do cause 47030b57cec5SDimitry Andric // errors if the copy assignment operator is actually used, q.v. 47040b57cec5SDimitry Andric // [class.copy]p12). 47050b57cec5SDimitry Andric 47060b57cec5SDimitry Andric if (T.isConstQualified()) 47070b57cec5SDimitry Andric return false; 47080b57cec5SDimitry Andric if (T.isPODType(C)) 47090b57cec5SDimitry Andric return true; 47100b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 47110b57cec5SDimitry Andric return RD->hasTrivialCopyAssignment() && 47120b57cec5SDimitry Andric !RD->hasNonTrivialCopyAssignment(); 47130b57cec5SDimitry Andric return false; 47140b57cec5SDimitry Andric case UTT_IsDestructible: 47150b57cec5SDimitry Andric case UTT_IsTriviallyDestructible: 47160b57cec5SDimitry Andric case UTT_IsNothrowDestructible: 47170b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 47180b57cec5SDimitry Andric // For reference types, is_destructible<T>::value is true. 47190b57cec5SDimitry Andric if (T->isReferenceType()) 47200b57cec5SDimitry Andric return true; 47210b57cec5SDimitry Andric 47220b57cec5SDimitry Andric // Objective-C++ ARC: autorelease types don't require destruction. 47230b57cec5SDimitry Andric if (T->isObjCLifetimeType() && 47240b57cec5SDimitry Andric T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 47250b57cec5SDimitry Andric return true; 47260b57cec5SDimitry Andric 47270b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 47280b57cec5SDimitry Andric // For incomplete types and function types, is_destructible<T>::value is 47290b57cec5SDimitry Andric // false. 47300b57cec5SDimitry Andric if (T->isIncompleteType() || T->isFunctionType()) 47310b57cec5SDimitry Andric return false; 47320b57cec5SDimitry Andric 47330b57cec5SDimitry Andric // A type that requires destruction (via a non-trivial destructor or ARC 47340b57cec5SDimitry Andric // lifetime semantics) is not trivially-destructible. 47350b57cec5SDimitry Andric if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) 47360b57cec5SDimitry Andric return false; 47370b57cec5SDimitry Andric 47380b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 47390b57cec5SDimitry Andric // For object types and given U equal to remove_all_extents_t<T>, if the 47400b57cec5SDimitry Andric // expression std::declval<U&>().~U() is well-formed when treated as an 47410b57cec5SDimitry Andric // unevaluated operand (Clause 5), then is_destructible<T>::value is true 47420b57cec5SDimitry Andric if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 47430b57cec5SDimitry Andric CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); 47440b57cec5SDimitry Andric if (!Destructor) 47450b57cec5SDimitry Andric return false; 47460b57cec5SDimitry Andric // C++14 [dcl.fct.def.delete]p2: 47470b57cec5SDimitry Andric // A program that refers to a deleted function implicitly or 47480b57cec5SDimitry Andric // explicitly, other than to declare it, is ill-formed. 47490b57cec5SDimitry Andric if (Destructor->isDeleted()) 47500b57cec5SDimitry Andric return false; 47510b57cec5SDimitry Andric if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) 47520b57cec5SDimitry Andric return false; 47530b57cec5SDimitry Andric if (UTT == UTT_IsNothrowDestructible) { 47540b57cec5SDimitry Andric const FunctionProtoType *CPT = 47550b57cec5SDimitry Andric Destructor->getType()->getAs<FunctionProtoType>(); 47560b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 47570b57cec5SDimitry Andric if (!CPT || !CPT->isNothrow()) 47580b57cec5SDimitry Andric return false; 47590b57cec5SDimitry Andric } 47600b57cec5SDimitry Andric } 47610b57cec5SDimitry Andric return true; 47620b57cec5SDimitry Andric 47630b57cec5SDimitry Andric case UTT_HasTrivialDestructor: 47640b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 47650b57cec5SDimitry Andric // If __is_pod (type) is true or type is a reference type 47660b57cec5SDimitry Andric // then the trait is true, else if type is a cv class or union 47670b57cec5SDimitry Andric // type (or array thereof) with a trivial destructor 47680b57cec5SDimitry Andric // ([class.dtor]) then the trait is true, else it is 47690b57cec5SDimitry Andric // false. 47700b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType()) 47710b57cec5SDimitry Andric return true; 47720b57cec5SDimitry Andric 47730b57cec5SDimitry Andric // Objective-C++ ARC: autorelease types don't require destruction. 47740b57cec5SDimitry Andric if (T->isObjCLifetimeType() && 47750b57cec5SDimitry Andric T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 47760b57cec5SDimitry Andric return true; 47770b57cec5SDimitry Andric 47780b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 47790b57cec5SDimitry Andric return RD->hasTrivialDestructor(); 47800b57cec5SDimitry Andric return false; 47810b57cec5SDimitry Andric // TODO: Propagate nothrowness for implicitly declared special members. 47820b57cec5SDimitry Andric case UTT_HasNothrowAssign: 47830b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 47840b57cec5SDimitry Andric // If type is const qualified or is a reference type then the 47850b57cec5SDimitry Andric // trait is false. Otherwise if __has_trivial_assign (type) 47860b57cec5SDimitry Andric // is true then the trait is true, else if type is a cv class 47870b57cec5SDimitry Andric // or union type with copy assignment operators that are known 47880b57cec5SDimitry Andric // not to throw an exception then the trait is true, else it is 47890b57cec5SDimitry Andric // false. 47900b57cec5SDimitry Andric if (C.getBaseElementType(T).isConstQualified()) 47910b57cec5SDimitry Andric return false; 47920b57cec5SDimitry Andric if (T->isReferenceType()) 47930b57cec5SDimitry Andric return false; 47940b57cec5SDimitry Andric if (T.isPODType(C) || T->isObjCLifetimeType()) 47950b57cec5SDimitry Andric return true; 47960b57cec5SDimitry Andric 47970b57cec5SDimitry Andric if (const RecordType *RT = T->getAs<RecordType>()) 47980b57cec5SDimitry Andric return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 47990b57cec5SDimitry Andric &CXXRecordDecl::hasTrivialCopyAssignment, 48000b57cec5SDimitry Andric &CXXRecordDecl::hasNonTrivialCopyAssignment, 48010b57cec5SDimitry Andric &CXXMethodDecl::isCopyAssignmentOperator); 48020b57cec5SDimitry Andric return false; 48030b57cec5SDimitry Andric case UTT_HasNothrowMoveAssign: 48040b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 48050b57cec5SDimitry Andric // standard library headers. Specifically this is used as the logic 48060b57cec5SDimitry Andric // behind std::is_nothrow_move_assignable (20.9.4.3). 48070b57cec5SDimitry Andric if (T.isPODType(C)) 48080b57cec5SDimitry Andric return true; 48090b57cec5SDimitry Andric 48100b57cec5SDimitry Andric if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 48110b57cec5SDimitry Andric return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 48120b57cec5SDimitry Andric &CXXRecordDecl::hasTrivialMoveAssignment, 48130b57cec5SDimitry Andric &CXXRecordDecl::hasNonTrivialMoveAssignment, 48140b57cec5SDimitry Andric &CXXMethodDecl::isMoveAssignmentOperator); 48150b57cec5SDimitry Andric return false; 48160b57cec5SDimitry Andric case UTT_HasNothrowCopy: 48170b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 48180b57cec5SDimitry Andric // If __has_trivial_copy (type) is true then the trait is true, else 48190b57cec5SDimitry Andric // if type is a cv class or union type with copy constructors that are 48200b57cec5SDimitry Andric // known not to throw an exception then the trait is true, else it is 48210b57cec5SDimitry Andric // false. 48220b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 48230b57cec5SDimitry Andric return true; 48240b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 48250b57cec5SDimitry Andric if (RD->hasTrivialCopyConstructor() && 48260b57cec5SDimitry Andric !RD->hasNonTrivialCopyConstructor()) 48270b57cec5SDimitry Andric return true; 48280b57cec5SDimitry Andric 48290b57cec5SDimitry Andric bool FoundConstructor = false; 48300b57cec5SDimitry Andric unsigned FoundTQs; 48310b57cec5SDimitry Andric for (const auto *ND : Self.LookupConstructors(RD)) { 48320b57cec5SDimitry Andric // A template constructor is never a copy constructor. 48330b57cec5SDimitry Andric // FIXME: However, it may actually be selected at the actual overload 48340b57cec5SDimitry Andric // resolution point. 48350b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 48360b57cec5SDimitry Andric continue; 48370b57cec5SDimitry Andric // UsingDecl itself is not a constructor 48380b57cec5SDimitry Andric if (isa<UsingDecl>(ND)) 48390b57cec5SDimitry Andric continue; 48400b57cec5SDimitry Andric auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 48410b57cec5SDimitry Andric if (Constructor->isCopyConstructor(FoundTQs)) { 48420b57cec5SDimitry Andric FoundConstructor = true; 48430b57cec5SDimitry Andric const FunctionProtoType *CPT 48440b57cec5SDimitry Andric = Constructor->getType()->getAs<FunctionProtoType>(); 48450b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 48460b57cec5SDimitry Andric if (!CPT) 48470b57cec5SDimitry Andric return false; 48480b57cec5SDimitry Andric // TODO: check whether evaluating default arguments can throw. 48490b57cec5SDimitry Andric // For now, we'll be conservative and assume that they can throw. 48500b57cec5SDimitry Andric if (!CPT->isNothrow() || CPT->getNumParams() > 1) 48510b57cec5SDimitry Andric return false; 48520b57cec5SDimitry Andric } 48530b57cec5SDimitry Andric } 48540b57cec5SDimitry Andric 48550b57cec5SDimitry Andric return FoundConstructor; 48560b57cec5SDimitry Andric } 48570b57cec5SDimitry Andric return false; 48580b57cec5SDimitry Andric case UTT_HasNothrowConstructor: 48590b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 48600b57cec5SDimitry Andric // If __has_trivial_constructor (type) is true then the trait is 48610b57cec5SDimitry Andric // true, else if type is a cv class or union type (or array 48620b57cec5SDimitry Andric // thereof) with a default constructor that is known not to 48630b57cec5SDimitry Andric // throw an exception then the trait is true, else it is false. 48640b57cec5SDimitry Andric if (T.isPODType(C) || T->isObjCLifetimeType()) 48650b57cec5SDimitry Andric return true; 48660b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 48670b57cec5SDimitry Andric if (RD->hasTrivialDefaultConstructor() && 48680b57cec5SDimitry Andric !RD->hasNonTrivialDefaultConstructor()) 48690b57cec5SDimitry Andric return true; 48700b57cec5SDimitry Andric 48710b57cec5SDimitry Andric bool FoundConstructor = false; 48720b57cec5SDimitry Andric for (const auto *ND : Self.LookupConstructors(RD)) { 48730b57cec5SDimitry Andric // FIXME: In C++0x, a constructor template can be a default constructor. 48740b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 48750b57cec5SDimitry Andric continue; 48760b57cec5SDimitry Andric // UsingDecl itself is not a constructor 48770b57cec5SDimitry Andric if (isa<UsingDecl>(ND)) 48780b57cec5SDimitry Andric continue; 48790b57cec5SDimitry Andric auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 48800b57cec5SDimitry Andric if (Constructor->isDefaultConstructor()) { 48810b57cec5SDimitry Andric FoundConstructor = true; 48820b57cec5SDimitry Andric const FunctionProtoType *CPT 48830b57cec5SDimitry Andric = Constructor->getType()->getAs<FunctionProtoType>(); 48840b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 48850b57cec5SDimitry Andric if (!CPT) 48860b57cec5SDimitry Andric return false; 48870b57cec5SDimitry Andric // FIXME: check whether evaluating default arguments can throw. 48880b57cec5SDimitry Andric // For now, we'll be conservative and assume that they can throw. 48890b57cec5SDimitry Andric if (!CPT->isNothrow() || CPT->getNumParams() > 0) 48900b57cec5SDimitry Andric return false; 48910b57cec5SDimitry Andric } 48920b57cec5SDimitry Andric } 48930b57cec5SDimitry Andric return FoundConstructor; 48940b57cec5SDimitry Andric } 48950b57cec5SDimitry Andric return false; 48960b57cec5SDimitry Andric case UTT_HasVirtualDestructor: 48970b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 48980b57cec5SDimitry Andric // If type is a class type with a virtual destructor ([class.dtor]) 48990b57cec5SDimitry Andric // then the trait is true, else it is false. 49000b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49010b57cec5SDimitry Andric if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 49020b57cec5SDimitry Andric return Destructor->isVirtual(); 49030b57cec5SDimitry Andric return false; 49040b57cec5SDimitry Andric 49050b57cec5SDimitry Andric // These type trait expressions are modeled on the specifications for the 49060b57cec5SDimitry Andric // Embarcadero C++0x type trait functions: 49070b57cec5SDimitry Andric // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 49080b57cec5SDimitry Andric case UTT_IsCompleteType: 49090b57cec5SDimitry Andric // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 49100b57cec5SDimitry Andric // Returns True if and only if T is a complete type at the point of the 49110b57cec5SDimitry Andric // function call. 49120b57cec5SDimitry Andric return !T->isIncompleteType(); 49130b57cec5SDimitry Andric case UTT_HasUniqueObjectRepresentations: 49140b57cec5SDimitry Andric return C.hasUniqueObjectRepresentations(T); 49150b57cec5SDimitry Andric } 49160b57cec5SDimitry Andric } 49170b57cec5SDimitry Andric 49180b57cec5SDimitry Andric static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 49190b57cec5SDimitry Andric QualType RhsT, SourceLocation KeyLoc); 49200b57cec5SDimitry Andric 49210b57cec5SDimitry Andric static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 49220b57cec5SDimitry Andric ArrayRef<TypeSourceInfo *> Args, 49230b57cec5SDimitry Andric SourceLocation RParenLoc) { 49240b57cec5SDimitry Andric if (Kind <= UTT_Last) 49250b57cec5SDimitry Andric return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); 49260b57cec5SDimitry Andric 49270b57cec5SDimitry Andric // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible 49280b57cec5SDimitry Andric // traits to avoid duplication. 49290b57cec5SDimitry Andric if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) 49300b57cec5SDimitry Andric return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), 49310b57cec5SDimitry Andric Args[1]->getType(), RParenLoc); 49320b57cec5SDimitry Andric 49330b57cec5SDimitry Andric switch (Kind) { 49340b57cec5SDimitry Andric case clang::BTT_ReferenceBindsToTemporary: 49350b57cec5SDimitry Andric case clang::TT_IsConstructible: 49360b57cec5SDimitry Andric case clang::TT_IsNothrowConstructible: 49370b57cec5SDimitry Andric case clang::TT_IsTriviallyConstructible: { 49380b57cec5SDimitry Andric // C++11 [meta.unary.prop]: 49390b57cec5SDimitry Andric // is_trivially_constructible is defined as: 49400b57cec5SDimitry Andric // 49410b57cec5SDimitry Andric // is_constructible<T, Args...>::value is true and the variable 49420b57cec5SDimitry Andric // definition for is_constructible, as defined below, is known to call 49430b57cec5SDimitry Andric // no operation that is not trivial. 49440b57cec5SDimitry Andric // 49450b57cec5SDimitry Andric // The predicate condition for a template specialization 49460b57cec5SDimitry Andric // is_constructible<T, Args...> shall be satisfied if and only if the 49470b57cec5SDimitry Andric // following variable definition would be well-formed for some invented 49480b57cec5SDimitry Andric // variable t: 49490b57cec5SDimitry Andric // 49500b57cec5SDimitry Andric // T t(create<Args>()...); 49510b57cec5SDimitry Andric assert(!Args.empty()); 49520b57cec5SDimitry Andric 49530b57cec5SDimitry Andric // Precondition: T and all types in the parameter pack Args shall be 49540b57cec5SDimitry Andric // complete types, (possibly cv-qualified) void, or arrays of 49550b57cec5SDimitry Andric // unknown bound. 49560b57cec5SDimitry Andric for (const auto *TSI : Args) { 49570b57cec5SDimitry Andric QualType ArgTy = TSI->getType(); 49580b57cec5SDimitry Andric if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 49590b57cec5SDimitry Andric continue; 49600b57cec5SDimitry Andric 49610b57cec5SDimitry Andric if (S.RequireCompleteType(KWLoc, ArgTy, 49620b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 49630b57cec5SDimitry Andric return false; 49640b57cec5SDimitry Andric } 49650b57cec5SDimitry Andric 49660b57cec5SDimitry Andric // Make sure the first argument is not incomplete nor a function type. 49670b57cec5SDimitry Andric QualType T = Args[0]->getType(); 49680b57cec5SDimitry Andric if (T->isIncompleteType() || T->isFunctionType()) 49690b57cec5SDimitry Andric return false; 49700b57cec5SDimitry Andric 49710b57cec5SDimitry Andric // Make sure the first argument is not an abstract type. 49720b57cec5SDimitry Andric CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 49730b57cec5SDimitry Andric if (RD && RD->isAbstract()) 49740b57cec5SDimitry Andric return false; 49750b57cec5SDimitry Andric 49760b57cec5SDimitry Andric SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs; 49770b57cec5SDimitry Andric SmallVector<Expr *, 2> ArgExprs; 49780b57cec5SDimitry Andric ArgExprs.reserve(Args.size() - 1); 49790b57cec5SDimitry Andric for (unsigned I = 1, N = Args.size(); I != N; ++I) { 49800b57cec5SDimitry Andric QualType ArgTy = Args[I]->getType(); 49810b57cec5SDimitry Andric if (ArgTy->isObjectType() || ArgTy->isFunctionType()) 49820b57cec5SDimitry Andric ArgTy = S.Context.getRValueReferenceType(ArgTy); 49830b57cec5SDimitry Andric OpaqueArgExprs.push_back( 49840b57cec5SDimitry Andric OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), 49850b57cec5SDimitry Andric ArgTy.getNonLValueExprType(S.Context), 49860b57cec5SDimitry Andric Expr::getValueKindForType(ArgTy))); 49870b57cec5SDimitry Andric } 49880b57cec5SDimitry Andric for (Expr &E : OpaqueArgExprs) 49890b57cec5SDimitry Andric ArgExprs.push_back(&E); 49900b57cec5SDimitry Andric 49910b57cec5SDimitry Andric // Perform the initialization in an unevaluated context within a SFINAE 49920b57cec5SDimitry Andric // trap at translation unit scope. 49930b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 49940b57cec5SDimitry Andric S, Sema::ExpressionEvaluationContext::Unevaluated); 49950b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 49960b57cec5SDimitry Andric Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 49970b57cec5SDimitry Andric InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0])); 49980b57cec5SDimitry Andric InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 49990b57cec5SDimitry Andric RParenLoc)); 50000b57cec5SDimitry Andric InitializationSequence Init(S, To, InitKind, ArgExprs); 50010b57cec5SDimitry Andric if (Init.Failed()) 50020b57cec5SDimitry Andric return false; 50030b57cec5SDimitry Andric 50040b57cec5SDimitry Andric ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 50050b57cec5SDimitry Andric if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 50060b57cec5SDimitry Andric return false; 50070b57cec5SDimitry Andric 50080b57cec5SDimitry Andric if (Kind == clang::TT_IsConstructible) 50090b57cec5SDimitry Andric return true; 50100b57cec5SDimitry Andric 50110b57cec5SDimitry Andric if (Kind == clang::BTT_ReferenceBindsToTemporary) { 50120b57cec5SDimitry Andric if (!T->isReferenceType()) 50130b57cec5SDimitry Andric return false; 50140b57cec5SDimitry Andric 50150b57cec5SDimitry Andric return !Init.isDirectReferenceBinding(); 50160b57cec5SDimitry Andric } 50170b57cec5SDimitry Andric 50180b57cec5SDimitry Andric if (Kind == clang::TT_IsNothrowConstructible) 50190b57cec5SDimitry Andric return S.canThrow(Result.get()) == CT_Cannot; 50200b57cec5SDimitry Andric 50210b57cec5SDimitry Andric if (Kind == clang::TT_IsTriviallyConstructible) { 50220b57cec5SDimitry Andric // Under Objective-C ARC and Weak, if the destination has non-trivial 50230b57cec5SDimitry Andric // Objective-C lifetime, this is a non-trivial construction. 50240b57cec5SDimitry Andric if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) 50250b57cec5SDimitry Andric return false; 50260b57cec5SDimitry Andric 50270b57cec5SDimitry Andric // The initialization succeeded; now make sure there are no non-trivial 50280b57cec5SDimitry Andric // calls. 50290b57cec5SDimitry Andric return !Result.get()->hasNonTrivialCall(S.Context); 50300b57cec5SDimitry Andric } 50310b57cec5SDimitry Andric 50320b57cec5SDimitry Andric llvm_unreachable("unhandled type trait"); 50330b57cec5SDimitry Andric return false; 50340b57cec5SDimitry Andric } 50350b57cec5SDimitry Andric default: llvm_unreachable("not a TT"); 50360b57cec5SDimitry Andric } 50370b57cec5SDimitry Andric 50380b57cec5SDimitry Andric return false; 50390b57cec5SDimitry Andric } 50400b57cec5SDimitry Andric 50410b57cec5SDimitry Andric ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 50420b57cec5SDimitry Andric ArrayRef<TypeSourceInfo *> Args, 50430b57cec5SDimitry Andric SourceLocation RParenLoc) { 50440b57cec5SDimitry Andric QualType ResultType = Context.getLogicalOperationType(); 50450b57cec5SDimitry Andric 50460b57cec5SDimitry Andric if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( 50470b57cec5SDimitry Andric *this, Kind, KWLoc, Args[0]->getType())) 50480b57cec5SDimitry Andric return ExprError(); 50490b57cec5SDimitry Andric 50500b57cec5SDimitry Andric bool Dependent = false; 50510b57cec5SDimitry Andric for (unsigned I = 0, N = Args.size(); I != N; ++I) { 50520b57cec5SDimitry Andric if (Args[I]->getType()->isDependentType()) { 50530b57cec5SDimitry Andric Dependent = true; 50540b57cec5SDimitry Andric break; 50550b57cec5SDimitry Andric } 50560b57cec5SDimitry Andric } 50570b57cec5SDimitry Andric 50580b57cec5SDimitry Andric bool Result = false; 50590b57cec5SDimitry Andric if (!Dependent) 50600b57cec5SDimitry Andric Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 50610b57cec5SDimitry Andric 50620b57cec5SDimitry Andric return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, 50630b57cec5SDimitry Andric RParenLoc, Result); 50640b57cec5SDimitry Andric } 50650b57cec5SDimitry Andric 50660b57cec5SDimitry Andric ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 50670b57cec5SDimitry Andric ArrayRef<ParsedType> Args, 50680b57cec5SDimitry Andric SourceLocation RParenLoc) { 50690b57cec5SDimitry Andric SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 50700b57cec5SDimitry Andric ConvertedArgs.reserve(Args.size()); 50710b57cec5SDimitry Andric 50720b57cec5SDimitry Andric for (unsigned I = 0, N = Args.size(); I != N; ++I) { 50730b57cec5SDimitry Andric TypeSourceInfo *TInfo; 50740b57cec5SDimitry Andric QualType T = GetTypeFromParser(Args[I], &TInfo); 50750b57cec5SDimitry Andric if (!TInfo) 50760b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 50770b57cec5SDimitry Andric 50780b57cec5SDimitry Andric ConvertedArgs.push_back(TInfo); 50790b57cec5SDimitry Andric } 50800b57cec5SDimitry Andric 50810b57cec5SDimitry Andric return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 50820b57cec5SDimitry Andric } 50830b57cec5SDimitry Andric 50840b57cec5SDimitry Andric static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 50850b57cec5SDimitry Andric QualType RhsT, SourceLocation KeyLoc) { 50860b57cec5SDimitry Andric assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 50870b57cec5SDimitry Andric "Cannot evaluate traits of dependent types"); 50880b57cec5SDimitry Andric 50890b57cec5SDimitry Andric switch(BTT) { 50900b57cec5SDimitry Andric case BTT_IsBaseOf: { 50910b57cec5SDimitry Andric // C++0x [meta.rel]p2 50920b57cec5SDimitry Andric // Base is a base class of Derived without regard to cv-qualifiers or 50930b57cec5SDimitry Andric // Base and Derived are not unions and name the same class type without 50940b57cec5SDimitry Andric // regard to cv-qualifiers. 50950b57cec5SDimitry Andric 50960b57cec5SDimitry Andric const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 50970b57cec5SDimitry Andric const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 50980b57cec5SDimitry Andric if (!rhsRecord || !lhsRecord) { 50990b57cec5SDimitry Andric const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); 51000b57cec5SDimitry Andric const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); 51010b57cec5SDimitry Andric if (!LHSObjTy || !RHSObjTy) 51020b57cec5SDimitry Andric return false; 51030b57cec5SDimitry Andric 51040b57cec5SDimitry Andric ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); 51050b57cec5SDimitry Andric ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); 51060b57cec5SDimitry Andric if (!BaseInterface || !DerivedInterface) 51070b57cec5SDimitry Andric return false; 51080b57cec5SDimitry Andric 51090b57cec5SDimitry Andric if (Self.RequireCompleteType( 51100b57cec5SDimitry Andric KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) 51110b57cec5SDimitry Andric return false; 51120b57cec5SDimitry Andric 51130b57cec5SDimitry Andric return BaseInterface->isSuperClassOf(DerivedInterface); 51140b57cec5SDimitry Andric } 51150b57cec5SDimitry Andric 51160b57cec5SDimitry Andric assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 51170b57cec5SDimitry Andric == (lhsRecord == rhsRecord)); 51180b57cec5SDimitry Andric 51190b57cec5SDimitry Andric // Unions are never base classes, and never have base classes. 51200b57cec5SDimitry Andric // It doesn't matter if they are complete or not. See PR#41843 51210b57cec5SDimitry Andric if (lhsRecord && lhsRecord->getDecl()->isUnion()) 51220b57cec5SDimitry Andric return false; 51230b57cec5SDimitry Andric if (rhsRecord && rhsRecord->getDecl()->isUnion()) 51240b57cec5SDimitry Andric return false; 51250b57cec5SDimitry Andric 51260b57cec5SDimitry Andric if (lhsRecord == rhsRecord) 51270b57cec5SDimitry Andric return true; 51280b57cec5SDimitry Andric 51290b57cec5SDimitry Andric // C++0x [meta.rel]p2: 51300b57cec5SDimitry Andric // If Base and Derived are class types and are different types 51310b57cec5SDimitry Andric // (ignoring possible cv-qualifiers) then Derived shall be a 51320b57cec5SDimitry Andric // complete type. 51330b57cec5SDimitry Andric if (Self.RequireCompleteType(KeyLoc, RhsT, 51340b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 51350b57cec5SDimitry Andric return false; 51360b57cec5SDimitry Andric 51370b57cec5SDimitry Andric return cast<CXXRecordDecl>(rhsRecord->getDecl()) 51380b57cec5SDimitry Andric ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 51390b57cec5SDimitry Andric } 51400b57cec5SDimitry Andric case BTT_IsSame: 51410b57cec5SDimitry Andric return Self.Context.hasSameType(LhsT, RhsT); 51420b57cec5SDimitry Andric case BTT_TypeCompatible: { 51430b57cec5SDimitry Andric // GCC ignores cv-qualifiers on arrays for this builtin. 51440b57cec5SDimitry Andric Qualifiers LhsQuals, RhsQuals; 51450b57cec5SDimitry Andric QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); 51460b57cec5SDimitry Andric QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); 51470b57cec5SDimitry Andric return Self.Context.typesAreCompatible(Lhs, Rhs); 51480b57cec5SDimitry Andric } 51490b57cec5SDimitry Andric case BTT_IsConvertible: 51500b57cec5SDimitry Andric case BTT_IsConvertibleTo: { 51510b57cec5SDimitry Andric // C++0x [meta.rel]p4: 51520b57cec5SDimitry Andric // Given the following function prototype: 51530b57cec5SDimitry Andric // 51540b57cec5SDimitry Andric // template <class T> 51550b57cec5SDimitry Andric // typename add_rvalue_reference<T>::type create(); 51560b57cec5SDimitry Andric // 51570b57cec5SDimitry Andric // the predicate condition for a template specialization 51580b57cec5SDimitry Andric // is_convertible<From, To> shall be satisfied if and only if 51590b57cec5SDimitry Andric // the return expression in the following code would be 51600b57cec5SDimitry Andric // well-formed, including any implicit conversions to the return 51610b57cec5SDimitry Andric // type of the function: 51620b57cec5SDimitry Andric // 51630b57cec5SDimitry Andric // To test() { 51640b57cec5SDimitry Andric // return create<From>(); 51650b57cec5SDimitry Andric // } 51660b57cec5SDimitry Andric // 51670b57cec5SDimitry Andric // Access checking is performed as if in a context unrelated to To and 51680b57cec5SDimitry Andric // From. Only the validity of the immediate context of the expression 51690b57cec5SDimitry Andric // of the return-statement (including conversions to the return type) 51700b57cec5SDimitry Andric // is considered. 51710b57cec5SDimitry Andric // 51720b57cec5SDimitry Andric // We model the initialization as a copy-initialization of a temporary 51730b57cec5SDimitry Andric // of the appropriate type, which for this expression is identical to the 51740b57cec5SDimitry Andric // return statement (since NRVO doesn't apply). 51750b57cec5SDimitry Andric 51760b57cec5SDimitry Andric // Functions aren't allowed to return function or array types. 51770b57cec5SDimitry Andric if (RhsT->isFunctionType() || RhsT->isArrayType()) 51780b57cec5SDimitry Andric return false; 51790b57cec5SDimitry Andric 51800b57cec5SDimitry Andric // A return statement in a void function must have void type. 51810b57cec5SDimitry Andric if (RhsT->isVoidType()) 51820b57cec5SDimitry Andric return LhsT->isVoidType(); 51830b57cec5SDimitry Andric 51840b57cec5SDimitry Andric // A function definition requires a complete, non-abstract return type. 51850b57cec5SDimitry Andric if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) 51860b57cec5SDimitry Andric return false; 51870b57cec5SDimitry Andric 51880b57cec5SDimitry Andric // Compute the result of add_rvalue_reference. 51890b57cec5SDimitry Andric if (LhsT->isObjectType() || LhsT->isFunctionType()) 51900b57cec5SDimitry Andric LhsT = Self.Context.getRValueReferenceType(LhsT); 51910b57cec5SDimitry Andric 51920b57cec5SDimitry Andric // Build a fake source and destination for initialization. 51930b57cec5SDimitry Andric InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 51940b57cec5SDimitry Andric OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 51950b57cec5SDimitry Andric Expr::getValueKindForType(LhsT)); 51960b57cec5SDimitry Andric Expr *FromPtr = &From; 51970b57cec5SDimitry Andric InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 51980b57cec5SDimitry Andric SourceLocation())); 51990b57cec5SDimitry Andric 52000b57cec5SDimitry Andric // Perform the initialization in an unevaluated context within a SFINAE 52010b57cec5SDimitry Andric // trap at translation unit scope. 52020b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 52030b57cec5SDimitry Andric Self, Sema::ExpressionEvaluationContext::Unevaluated); 52040b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 52050b57cec5SDimitry Andric Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 52060b57cec5SDimitry Andric InitializationSequence Init(Self, To, Kind, FromPtr); 52070b57cec5SDimitry Andric if (Init.Failed()) 52080b57cec5SDimitry Andric return false; 52090b57cec5SDimitry Andric 52100b57cec5SDimitry Andric ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 52110b57cec5SDimitry Andric return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 52120b57cec5SDimitry Andric } 52130b57cec5SDimitry Andric 52140b57cec5SDimitry Andric case BTT_IsAssignable: 52150b57cec5SDimitry Andric case BTT_IsNothrowAssignable: 52160b57cec5SDimitry Andric case BTT_IsTriviallyAssignable: { 52170b57cec5SDimitry Andric // C++11 [meta.unary.prop]p3: 52180b57cec5SDimitry Andric // is_trivially_assignable is defined as: 52190b57cec5SDimitry Andric // is_assignable<T, U>::value is true and the assignment, as defined by 52200b57cec5SDimitry Andric // is_assignable, is known to call no operation that is not trivial 52210b57cec5SDimitry Andric // 52220b57cec5SDimitry Andric // is_assignable is defined as: 52230b57cec5SDimitry Andric // The expression declval<T>() = declval<U>() is well-formed when 52240b57cec5SDimitry Andric // treated as an unevaluated operand (Clause 5). 52250b57cec5SDimitry Andric // 52260b57cec5SDimitry Andric // For both, T and U shall be complete types, (possibly cv-qualified) 52270b57cec5SDimitry Andric // void, or arrays of unknown bound. 52280b57cec5SDimitry Andric if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 52290b57cec5SDimitry Andric Self.RequireCompleteType(KeyLoc, LhsT, 52300b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 52310b57cec5SDimitry Andric return false; 52320b57cec5SDimitry Andric if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 52330b57cec5SDimitry Andric Self.RequireCompleteType(KeyLoc, RhsT, 52340b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 52350b57cec5SDimitry Andric return false; 52360b57cec5SDimitry Andric 52370b57cec5SDimitry Andric // cv void is never assignable. 52380b57cec5SDimitry Andric if (LhsT->isVoidType() || RhsT->isVoidType()) 52390b57cec5SDimitry Andric return false; 52400b57cec5SDimitry Andric 52410b57cec5SDimitry Andric // Build expressions that emulate the effect of declval<T>() and 52420b57cec5SDimitry Andric // declval<U>(). 52430b57cec5SDimitry Andric if (LhsT->isObjectType() || LhsT->isFunctionType()) 52440b57cec5SDimitry Andric LhsT = Self.Context.getRValueReferenceType(LhsT); 52450b57cec5SDimitry Andric if (RhsT->isObjectType() || RhsT->isFunctionType()) 52460b57cec5SDimitry Andric RhsT = Self.Context.getRValueReferenceType(RhsT); 52470b57cec5SDimitry Andric OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 52480b57cec5SDimitry Andric Expr::getValueKindForType(LhsT)); 52490b57cec5SDimitry Andric OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 52500b57cec5SDimitry Andric Expr::getValueKindForType(RhsT)); 52510b57cec5SDimitry Andric 52520b57cec5SDimitry Andric // Attempt the assignment in an unevaluated context within a SFINAE 52530b57cec5SDimitry Andric // trap at translation unit scope. 52540b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 52550b57cec5SDimitry Andric Self, Sema::ExpressionEvaluationContext::Unevaluated); 52560b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 52570b57cec5SDimitry Andric Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 52580b57cec5SDimitry Andric ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, 52590b57cec5SDimitry Andric &Rhs); 5260a7dea167SDimitry Andric if (Result.isInvalid()) 5261a7dea167SDimitry Andric return false; 5262a7dea167SDimitry Andric 5263a7dea167SDimitry Andric // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. 5264a7dea167SDimitry Andric Self.CheckUnusedVolatileAssignment(Result.get()); 5265a7dea167SDimitry Andric 5266a7dea167SDimitry Andric if (SFINAE.hasErrorOccurred()) 52670b57cec5SDimitry Andric return false; 52680b57cec5SDimitry Andric 52690b57cec5SDimitry Andric if (BTT == BTT_IsAssignable) 52700b57cec5SDimitry Andric return true; 52710b57cec5SDimitry Andric 52720b57cec5SDimitry Andric if (BTT == BTT_IsNothrowAssignable) 52730b57cec5SDimitry Andric return Self.canThrow(Result.get()) == CT_Cannot; 52740b57cec5SDimitry Andric 52750b57cec5SDimitry Andric if (BTT == BTT_IsTriviallyAssignable) { 52760b57cec5SDimitry Andric // Under Objective-C ARC and Weak, if the destination has non-trivial 52770b57cec5SDimitry Andric // Objective-C lifetime, this is a non-trivial assignment. 52780b57cec5SDimitry Andric if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) 52790b57cec5SDimitry Andric return false; 52800b57cec5SDimitry Andric 52810b57cec5SDimitry Andric return !Result.get()->hasNonTrivialCall(Self.Context); 52820b57cec5SDimitry Andric } 52830b57cec5SDimitry Andric 52840b57cec5SDimitry Andric llvm_unreachable("unhandled type trait"); 52850b57cec5SDimitry Andric return false; 52860b57cec5SDimitry Andric } 52870b57cec5SDimitry Andric default: llvm_unreachable("not a BTT"); 52880b57cec5SDimitry Andric } 52890b57cec5SDimitry Andric llvm_unreachable("Unknown type trait or not implemented"); 52900b57cec5SDimitry Andric } 52910b57cec5SDimitry Andric 52920b57cec5SDimitry Andric ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 52930b57cec5SDimitry Andric SourceLocation KWLoc, 52940b57cec5SDimitry Andric ParsedType Ty, 52950b57cec5SDimitry Andric Expr* DimExpr, 52960b57cec5SDimitry Andric SourceLocation RParen) { 52970b57cec5SDimitry Andric TypeSourceInfo *TSInfo; 52980b57cec5SDimitry Andric QualType T = GetTypeFromParser(Ty, &TSInfo); 52990b57cec5SDimitry Andric if (!TSInfo) 53000b57cec5SDimitry Andric TSInfo = Context.getTrivialTypeSourceInfo(T); 53010b57cec5SDimitry Andric 53020b57cec5SDimitry Andric return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 53030b57cec5SDimitry Andric } 53040b57cec5SDimitry Andric 53050b57cec5SDimitry Andric static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 53060b57cec5SDimitry Andric QualType T, Expr *DimExpr, 53070b57cec5SDimitry Andric SourceLocation KeyLoc) { 53080b57cec5SDimitry Andric assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 53090b57cec5SDimitry Andric 53100b57cec5SDimitry Andric switch(ATT) { 53110b57cec5SDimitry Andric case ATT_ArrayRank: 53120b57cec5SDimitry Andric if (T->isArrayType()) { 53130b57cec5SDimitry Andric unsigned Dim = 0; 53140b57cec5SDimitry Andric while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 53150b57cec5SDimitry Andric ++Dim; 53160b57cec5SDimitry Andric T = AT->getElementType(); 53170b57cec5SDimitry Andric } 53180b57cec5SDimitry Andric return Dim; 53190b57cec5SDimitry Andric } 53200b57cec5SDimitry Andric return 0; 53210b57cec5SDimitry Andric 53220b57cec5SDimitry Andric case ATT_ArrayExtent: { 53230b57cec5SDimitry Andric llvm::APSInt Value; 53240b57cec5SDimitry Andric uint64_t Dim; 53250b57cec5SDimitry Andric if (Self.VerifyIntegerConstantExpression(DimExpr, &Value, 53260b57cec5SDimitry Andric diag::err_dimension_expr_not_constant_integer, 53270b57cec5SDimitry Andric false).isInvalid()) 53280b57cec5SDimitry Andric return 0; 53290b57cec5SDimitry Andric if (Value.isSigned() && Value.isNegative()) { 53300b57cec5SDimitry Andric Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 53310b57cec5SDimitry Andric << DimExpr->getSourceRange(); 53320b57cec5SDimitry Andric return 0; 53330b57cec5SDimitry Andric } 53340b57cec5SDimitry Andric Dim = Value.getLimitedValue(); 53350b57cec5SDimitry Andric 53360b57cec5SDimitry Andric if (T->isArrayType()) { 53370b57cec5SDimitry Andric unsigned D = 0; 53380b57cec5SDimitry Andric bool Matched = false; 53390b57cec5SDimitry Andric while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 53400b57cec5SDimitry Andric if (Dim == D) { 53410b57cec5SDimitry Andric Matched = true; 53420b57cec5SDimitry Andric break; 53430b57cec5SDimitry Andric } 53440b57cec5SDimitry Andric ++D; 53450b57cec5SDimitry Andric T = AT->getElementType(); 53460b57cec5SDimitry Andric } 53470b57cec5SDimitry Andric 53480b57cec5SDimitry Andric if (Matched && T->isArrayType()) { 53490b57cec5SDimitry Andric if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 53500b57cec5SDimitry Andric return CAT->getSize().getLimitedValue(); 53510b57cec5SDimitry Andric } 53520b57cec5SDimitry Andric } 53530b57cec5SDimitry Andric return 0; 53540b57cec5SDimitry Andric } 53550b57cec5SDimitry Andric } 53560b57cec5SDimitry Andric llvm_unreachable("Unknown type trait or not implemented"); 53570b57cec5SDimitry Andric } 53580b57cec5SDimitry Andric 53590b57cec5SDimitry Andric ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 53600b57cec5SDimitry Andric SourceLocation KWLoc, 53610b57cec5SDimitry Andric TypeSourceInfo *TSInfo, 53620b57cec5SDimitry Andric Expr* DimExpr, 53630b57cec5SDimitry Andric SourceLocation RParen) { 53640b57cec5SDimitry Andric QualType T = TSInfo->getType(); 53650b57cec5SDimitry Andric 53660b57cec5SDimitry Andric // FIXME: This should likely be tracked as an APInt to remove any host 53670b57cec5SDimitry Andric // assumptions about the width of size_t on the target. 53680b57cec5SDimitry Andric uint64_t Value = 0; 53690b57cec5SDimitry Andric if (!T->isDependentType()) 53700b57cec5SDimitry Andric Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 53710b57cec5SDimitry Andric 53720b57cec5SDimitry Andric // While the specification for these traits from the Embarcadero C++ 53730b57cec5SDimitry Andric // compiler's documentation says the return type is 'unsigned int', Clang 53740b57cec5SDimitry Andric // returns 'size_t'. On Windows, the primary platform for the Embarcadero 53750b57cec5SDimitry Andric // compiler, there is no difference. On several other platforms this is an 53760b57cec5SDimitry Andric // important distinction. 53770b57cec5SDimitry Andric return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, 53780b57cec5SDimitry Andric RParen, Context.getSizeType()); 53790b57cec5SDimitry Andric } 53800b57cec5SDimitry Andric 53810b57cec5SDimitry Andric ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 53820b57cec5SDimitry Andric SourceLocation KWLoc, 53830b57cec5SDimitry Andric Expr *Queried, 53840b57cec5SDimitry Andric SourceLocation RParen) { 53850b57cec5SDimitry Andric // If error parsing the expression, ignore. 53860b57cec5SDimitry Andric if (!Queried) 53870b57cec5SDimitry Andric return ExprError(); 53880b57cec5SDimitry Andric 53890b57cec5SDimitry Andric ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 53900b57cec5SDimitry Andric 53910b57cec5SDimitry Andric return Result; 53920b57cec5SDimitry Andric } 53930b57cec5SDimitry Andric 53940b57cec5SDimitry Andric static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 53950b57cec5SDimitry Andric switch (ET) { 53960b57cec5SDimitry Andric case ET_IsLValueExpr: return E->isLValue(); 53970b57cec5SDimitry Andric case ET_IsRValueExpr: return E->isRValue(); 53980b57cec5SDimitry Andric } 53990b57cec5SDimitry Andric llvm_unreachable("Expression trait not covered by switch"); 54000b57cec5SDimitry Andric } 54010b57cec5SDimitry Andric 54020b57cec5SDimitry Andric ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 54030b57cec5SDimitry Andric SourceLocation KWLoc, 54040b57cec5SDimitry Andric Expr *Queried, 54050b57cec5SDimitry Andric SourceLocation RParen) { 54060b57cec5SDimitry Andric if (Queried->isTypeDependent()) { 54070b57cec5SDimitry Andric // Delay type-checking for type-dependent expressions. 54080b57cec5SDimitry Andric } else if (Queried->getType()->isPlaceholderType()) { 54090b57cec5SDimitry Andric ExprResult PE = CheckPlaceholderExpr(Queried); 54100b57cec5SDimitry Andric if (PE.isInvalid()) return ExprError(); 54110b57cec5SDimitry Andric return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); 54120b57cec5SDimitry Andric } 54130b57cec5SDimitry Andric 54140b57cec5SDimitry Andric bool Value = EvaluateExpressionTrait(ET, Queried); 54150b57cec5SDimitry Andric 54160b57cec5SDimitry Andric return new (Context) 54170b57cec5SDimitry Andric ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); 54180b57cec5SDimitry Andric } 54190b57cec5SDimitry Andric 54200b57cec5SDimitry Andric QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 54210b57cec5SDimitry Andric ExprValueKind &VK, 54220b57cec5SDimitry Andric SourceLocation Loc, 54230b57cec5SDimitry Andric bool isIndirect) { 54240b57cec5SDimitry Andric assert(!LHS.get()->getType()->isPlaceholderType() && 54250b57cec5SDimitry Andric !RHS.get()->getType()->isPlaceholderType() && 54260b57cec5SDimitry Andric "placeholders should have been weeded out by now"); 54270b57cec5SDimitry Andric 54280b57cec5SDimitry Andric // The LHS undergoes lvalue conversions if this is ->*, and undergoes the 54290b57cec5SDimitry Andric // temporary materialization conversion otherwise. 54300b57cec5SDimitry Andric if (isIndirect) 54310b57cec5SDimitry Andric LHS = DefaultLvalueConversion(LHS.get()); 54320b57cec5SDimitry Andric else if (LHS.get()->isRValue()) 54330b57cec5SDimitry Andric LHS = TemporaryMaterializationConversion(LHS.get()); 54340b57cec5SDimitry Andric if (LHS.isInvalid()) 54350b57cec5SDimitry Andric return QualType(); 54360b57cec5SDimitry Andric 54370b57cec5SDimitry Andric // The RHS always undergoes lvalue conversions. 54380b57cec5SDimitry Andric RHS = DefaultLvalueConversion(RHS.get()); 54390b57cec5SDimitry Andric if (RHS.isInvalid()) return QualType(); 54400b57cec5SDimitry Andric 54410b57cec5SDimitry Andric const char *OpSpelling = isIndirect ? "->*" : ".*"; 54420b57cec5SDimitry Andric // C++ 5.5p2 54430b57cec5SDimitry Andric // The binary operator .* [p3: ->*] binds its second operand, which shall 54440b57cec5SDimitry Andric // be of type "pointer to member of T" (where T is a completely-defined 54450b57cec5SDimitry Andric // class type) [...] 54460b57cec5SDimitry Andric QualType RHSType = RHS.get()->getType(); 54470b57cec5SDimitry Andric const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 54480b57cec5SDimitry Andric if (!MemPtr) { 54490b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_rhs) 54500b57cec5SDimitry Andric << OpSpelling << RHSType << RHS.get()->getSourceRange(); 54510b57cec5SDimitry Andric return QualType(); 54520b57cec5SDimitry Andric } 54530b57cec5SDimitry Andric 54540b57cec5SDimitry Andric QualType Class(MemPtr->getClass(), 0); 54550b57cec5SDimitry Andric 54560b57cec5SDimitry Andric // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 54570b57cec5SDimitry Andric // member pointer points must be completely-defined. However, there is no 54580b57cec5SDimitry Andric // reason for this semantic distinction, and the rule is not enforced by 54590b57cec5SDimitry Andric // other compilers. Therefore, we do not check this property, as it is 54600b57cec5SDimitry Andric // likely to be considered a defect. 54610b57cec5SDimitry Andric 54620b57cec5SDimitry Andric // C++ 5.5p2 54630b57cec5SDimitry Andric // [...] to its first operand, which shall be of class T or of a class of 54640b57cec5SDimitry Andric // which T is an unambiguous and accessible base class. [p3: a pointer to 54650b57cec5SDimitry Andric // such a class] 54660b57cec5SDimitry Andric QualType LHSType = LHS.get()->getType(); 54670b57cec5SDimitry Andric if (isIndirect) { 54680b57cec5SDimitry Andric if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 54690b57cec5SDimitry Andric LHSType = Ptr->getPointeeType(); 54700b57cec5SDimitry Andric else { 54710b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_lhs) 54720b57cec5SDimitry Andric << OpSpelling << 1 << LHSType 54730b57cec5SDimitry Andric << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 54740b57cec5SDimitry Andric return QualType(); 54750b57cec5SDimitry Andric } 54760b57cec5SDimitry Andric } 54770b57cec5SDimitry Andric 54780b57cec5SDimitry Andric if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 54790b57cec5SDimitry Andric // If we want to check the hierarchy, we need a complete type. 54800b57cec5SDimitry Andric if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 54810b57cec5SDimitry Andric OpSpelling, (int)isIndirect)) { 54820b57cec5SDimitry Andric return QualType(); 54830b57cec5SDimitry Andric } 54840b57cec5SDimitry Andric 54850b57cec5SDimitry Andric if (!IsDerivedFrom(Loc, LHSType, Class)) { 54860b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 54870b57cec5SDimitry Andric << (int)isIndirect << LHS.get()->getType(); 54880b57cec5SDimitry Andric return QualType(); 54890b57cec5SDimitry Andric } 54900b57cec5SDimitry Andric 54910b57cec5SDimitry Andric CXXCastPath BasePath; 54920b57cec5SDimitry Andric if (CheckDerivedToBaseConversion( 54930b57cec5SDimitry Andric LHSType, Class, Loc, 54940b57cec5SDimitry Andric SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), 54950b57cec5SDimitry Andric &BasePath)) 54960b57cec5SDimitry Andric return QualType(); 54970b57cec5SDimitry Andric 54980b57cec5SDimitry Andric // Cast LHS to type of use. 54990b57cec5SDimitry Andric QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); 55000b57cec5SDimitry Andric if (isIndirect) 55010b57cec5SDimitry Andric UseType = Context.getPointerType(UseType); 55020b57cec5SDimitry Andric ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind(); 55030b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, 55040b57cec5SDimitry Andric &BasePath); 55050b57cec5SDimitry Andric } 55060b57cec5SDimitry Andric 55070b57cec5SDimitry Andric if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 55080b57cec5SDimitry Andric // Diagnose use of pointer-to-member type which when used as 55090b57cec5SDimitry Andric // the functional cast in a pointer-to-member expression. 55100b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 55110b57cec5SDimitry Andric return QualType(); 55120b57cec5SDimitry Andric } 55130b57cec5SDimitry Andric 55140b57cec5SDimitry Andric // C++ 5.5p2 55150b57cec5SDimitry Andric // The result is an object or a function of the type specified by the 55160b57cec5SDimitry Andric // second operand. 55170b57cec5SDimitry Andric // The cv qualifiers are the union of those in the pointer and the left side, 55180b57cec5SDimitry Andric // in accordance with 5.5p5 and 5.2.5. 55190b57cec5SDimitry Andric QualType Result = MemPtr->getPointeeType(); 55200b57cec5SDimitry Andric Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 55210b57cec5SDimitry Andric 55220b57cec5SDimitry Andric // C++0x [expr.mptr.oper]p6: 55230b57cec5SDimitry Andric // In a .* expression whose object expression is an rvalue, the program is 55240b57cec5SDimitry Andric // ill-formed if the second operand is a pointer to member function with 55250b57cec5SDimitry Andric // ref-qualifier &. In a ->* expression or in a .* expression whose object 55260b57cec5SDimitry Andric // expression is an lvalue, the program is ill-formed if the second operand 55270b57cec5SDimitry Andric // is a pointer to member function with ref-qualifier &&. 55280b57cec5SDimitry Andric if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 55290b57cec5SDimitry Andric switch (Proto->getRefQualifier()) { 55300b57cec5SDimitry Andric case RQ_None: 55310b57cec5SDimitry Andric // Do nothing 55320b57cec5SDimitry Andric break; 55330b57cec5SDimitry Andric 55340b57cec5SDimitry Andric case RQ_LValue: 55350b57cec5SDimitry Andric if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { 55360b57cec5SDimitry Andric // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq 55370b57cec5SDimitry Andric // is (exactly) 'const'. 55380b57cec5SDimitry Andric if (Proto->isConst() && !Proto->isVolatile()) 55390b57cec5SDimitry Andric Diag(Loc, getLangOpts().CPlusPlus2a 55400b57cec5SDimitry Andric ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue 55410b57cec5SDimitry Andric : diag::ext_pointer_to_const_ref_member_on_rvalue); 55420b57cec5SDimitry Andric else 55430b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 55440b57cec5SDimitry Andric << RHSType << 1 << LHS.get()->getSourceRange(); 55450b57cec5SDimitry Andric } 55460b57cec5SDimitry Andric break; 55470b57cec5SDimitry Andric 55480b57cec5SDimitry Andric case RQ_RValue: 55490b57cec5SDimitry Andric if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 55500b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 55510b57cec5SDimitry Andric << RHSType << 0 << LHS.get()->getSourceRange(); 55520b57cec5SDimitry Andric break; 55530b57cec5SDimitry Andric } 55540b57cec5SDimitry Andric } 55550b57cec5SDimitry Andric 55560b57cec5SDimitry Andric // C++ [expr.mptr.oper]p6: 55570b57cec5SDimitry Andric // The result of a .* expression whose second operand is a pointer 55580b57cec5SDimitry Andric // to a data member is of the same value category as its 55590b57cec5SDimitry Andric // first operand. The result of a .* expression whose second 55600b57cec5SDimitry Andric // operand is a pointer to a member function is a prvalue. The 55610b57cec5SDimitry Andric // result of an ->* expression is an lvalue if its second operand 55620b57cec5SDimitry Andric // is a pointer to data member and a prvalue otherwise. 55630b57cec5SDimitry Andric if (Result->isFunctionType()) { 55640b57cec5SDimitry Andric VK = VK_RValue; 55650b57cec5SDimitry Andric return Context.BoundMemberTy; 55660b57cec5SDimitry Andric } else if (isIndirect) { 55670b57cec5SDimitry Andric VK = VK_LValue; 55680b57cec5SDimitry Andric } else { 55690b57cec5SDimitry Andric VK = LHS.get()->getValueKind(); 55700b57cec5SDimitry Andric } 55710b57cec5SDimitry Andric 55720b57cec5SDimitry Andric return Result; 55730b57cec5SDimitry Andric } 55740b57cec5SDimitry Andric 55750b57cec5SDimitry Andric /// Try to convert a type to another according to C++11 5.16p3. 55760b57cec5SDimitry Andric /// 55770b57cec5SDimitry Andric /// This is part of the parameter validation for the ? operator. If either 55780b57cec5SDimitry Andric /// value operand is a class type, the two operands are attempted to be 55790b57cec5SDimitry Andric /// converted to each other. This function does the conversion in one direction. 55800b57cec5SDimitry Andric /// It returns true if the program is ill-formed and has already been diagnosed 55810b57cec5SDimitry Andric /// as such. 55820b57cec5SDimitry Andric static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 55830b57cec5SDimitry Andric SourceLocation QuestionLoc, 55840b57cec5SDimitry Andric bool &HaveConversion, 55850b57cec5SDimitry Andric QualType &ToType) { 55860b57cec5SDimitry Andric HaveConversion = false; 55870b57cec5SDimitry Andric ToType = To->getType(); 55880b57cec5SDimitry Andric 55890b57cec5SDimitry Andric InitializationKind Kind = 55900b57cec5SDimitry Andric InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); 55910b57cec5SDimitry Andric // C++11 5.16p3 55920b57cec5SDimitry Andric // The process for determining whether an operand expression E1 of type T1 55930b57cec5SDimitry Andric // can be converted to match an operand expression E2 of type T2 is defined 55940b57cec5SDimitry Andric // as follows: 55950b57cec5SDimitry Andric // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be 55960b57cec5SDimitry Andric // implicitly converted to type "lvalue reference to T2", subject to the 55970b57cec5SDimitry Andric // constraint that in the conversion the reference must bind directly to 55980b57cec5SDimitry Andric // an lvalue. 55990b57cec5SDimitry Andric // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be 56000b57cec5SDimitry Andric // implicitly converted to the type "rvalue reference to R2", subject to 56010b57cec5SDimitry Andric // the constraint that the reference must bind directly. 56020b57cec5SDimitry Andric if (To->isLValue() || To->isXValue()) { 56030b57cec5SDimitry Andric QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType) 56040b57cec5SDimitry Andric : Self.Context.getRValueReferenceType(ToType); 56050b57cec5SDimitry Andric 56060b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 56070b57cec5SDimitry Andric 56080b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 56090b57cec5SDimitry Andric if (InitSeq.isDirectReferenceBinding()) { 56100b57cec5SDimitry Andric ToType = T; 56110b57cec5SDimitry Andric HaveConversion = true; 56120b57cec5SDimitry Andric return false; 56130b57cec5SDimitry Andric } 56140b57cec5SDimitry Andric 56150b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 56160b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 56170b57cec5SDimitry Andric } 56180b57cec5SDimitry Andric 56190b57cec5SDimitry Andric // -- If E2 is an rvalue, or if the conversion above cannot be done: 56200b57cec5SDimitry Andric // -- if E1 and E2 have class type, and the underlying class types are 56210b57cec5SDimitry Andric // the same or one is a base class of the other: 56220b57cec5SDimitry Andric QualType FTy = From->getType(); 56230b57cec5SDimitry Andric QualType TTy = To->getType(); 56240b57cec5SDimitry Andric const RecordType *FRec = FTy->getAs<RecordType>(); 56250b57cec5SDimitry Andric const RecordType *TRec = TTy->getAs<RecordType>(); 56260b57cec5SDimitry Andric bool FDerivedFromT = FRec && TRec && FRec != TRec && 56270b57cec5SDimitry Andric Self.IsDerivedFrom(QuestionLoc, FTy, TTy); 56280b57cec5SDimitry Andric if (FRec && TRec && (FRec == TRec || FDerivedFromT || 56290b57cec5SDimitry Andric Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { 56300b57cec5SDimitry Andric // E1 can be converted to match E2 if the class of T2 is the 56310b57cec5SDimitry Andric // same type as, or a base class of, the class of T1, and 56320b57cec5SDimitry Andric // [cv2 > cv1]. 56330b57cec5SDimitry Andric if (FRec == TRec || FDerivedFromT) { 56340b57cec5SDimitry Andric if (TTy.isAtLeastAsQualifiedAs(FTy)) { 56350b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 56360b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 56370b57cec5SDimitry Andric if (InitSeq) { 56380b57cec5SDimitry Andric HaveConversion = true; 56390b57cec5SDimitry Andric return false; 56400b57cec5SDimitry Andric } 56410b57cec5SDimitry Andric 56420b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 56430b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 56440b57cec5SDimitry Andric } 56450b57cec5SDimitry Andric } 56460b57cec5SDimitry Andric 56470b57cec5SDimitry Andric return false; 56480b57cec5SDimitry Andric } 56490b57cec5SDimitry Andric 56500b57cec5SDimitry Andric // -- Otherwise: E1 can be converted to match E2 if E1 can be 56510b57cec5SDimitry Andric // implicitly converted to the type that expression E2 would have 56520b57cec5SDimitry Andric // if E2 were converted to an rvalue (or the type it has, if E2 is 56530b57cec5SDimitry Andric // an rvalue). 56540b57cec5SDimitry Andric // 56550b57cec5SDimitry Andric // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 56560b57cec5SDimitry Andric // to the array-to-pointer or function-to-pointer conversions. 56570b57cec5SDimitry Andric TTy = TTy.getNonLValueExprType(Self.Context); 56580b57cec5SDimitry Andric 56590b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 56600b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 56610b57cec5SDimitry Andric HaveConversion = !InitSeq.Failed(); 56620b57cec5SDimitry Andric ToType = TTy; 56630b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 56640b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 56650b57cec5SDimitry Andric 56660b57cec5SDimitry Andric return false; 56670b57cec5SDimitry Andric } 56680b57cec5SDimitry Andric 56690b57cec5SDimitry Andric /// Try to find a common type for two according to C++0x 5.16p5. 56700b57cec5SDimitry Andric /// 56710b57cec5SDimitry Andric /// This is part of the parameter validation for the ? operator. If either 56720b57cec5SDimitry Andric /// value operand is a class type, overload resolution is used to find a 56730b57cec5SDimitry Andric /// conversion to a common type. 56740b57cec5SDimitry Andric static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 56750b57cec5SDimitry Andric SourceLocation QuestionLoc) { 56760b57cec5SDimitry Andric Expr *Args[2] = { LHS.get(), RHS.get() }; 56770b57cec5SDimitry Andric OverloadCandidateSet CandidateSet(QuestionLoc, 56780b57cec5SDimitry Andric OverloadCandidateSet::CSK_Operator); 56790b57cec5SDimitry Andric Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 56800b57cec5SDimitry Andric CandidateSet); 56810b57cec5SDimitry Andric 56820b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 56830b57cec5SDimitry Andric switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 56840b57cec5SDimitry Andric case OR_Success: { 56850b57cec5SDimitry Andric // We found a match. Perform the conversions on the arguments and move on. 56860b57cec5SDimitry Andric ExprResult LHSRes = Self.PerformImplicitConversion( 56870b57cec5SDimitry Andric LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], 56880b57cec5SDimitry Andric Sema::AA_Converting); 56890b57cec5SDimitry Andric if (LHSRes.isInvalid()) 56900b57cec5SDimitry Andric break; 56910b57cec5SDimitry Andric LHS = LHSRes; 56920b57cec5SDimitry Andric 56930b57cec5SDimitry Andric ExprResult RHSRes = Self.PerformImplicitConversion( 56940b57cec5SDimitry Andric RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], 56950b57cec5SDimitry Andric Sema::AA_Converting); 56960b57cec5SDimitry Andric if (RHSRes.isInvalid()) 56970b57cec5SDimitry Andric break; 56980b57cec5SDimitry Andric RHS = RHSRes; 56990b57cec5SDimitry Andric if (Best->Function) 57000b57cec5SDimitry Andric Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 57010b57cec5SDimitry Andric return false; 57020b57cec5SDimitry Andric } 57030b57cec5SDimitry Andric 57040b57cec5SDimitry Andric case OR_No_Viable_Function: 57050b57cec5SDimitry Andric 57060b57cec5SDimitry Andric // Emit a better diagnostic if one of the expressions is a null pointer 57070b57cec5SDimitry Andric // constant and the other is a pointer type. In this case, the user most 57080b57cec5SDimitry Andric // likely forgot to take the address of the other expression. 57090b57cec5SDimitry Andric if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 57100b57cec5SDimitry Andric return true; 57110b57cec5SDimitry Andric 57120b57cec5SDimitry Andric Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 57130b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 57140b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 57150b57cec5SDimitry Andric return true; 57160b57cec5SDimitry Andric 57170b57cec5SDimitry Andric case OR_Ambiguous: 57180b57cec5SDimitry Andric Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 57190b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 57200b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 57210b57cec5SDimitry Andric // FIXME: Print the possible common types by printing the return types of 57220b57cec5SDimitry Andric // the viable candidates. 57230b57cec5SDimitry Andric break; 57240b57cec5SDimitry Andric 57250b57cec5SDimitry Andric case OR_Deleted: 57260b57cec5SDimitry Andric llvm_unreachable("Conditional operator has only built-in overloads"); 57270b57cec5SDimitry Andric } 57280b57cec5SDimitry Andric return true; 57290b57cec5SDimitry Andric } 57300b57cec5SDimitry Andric 57310b57cec5SDimitry Andric /// Perform an "extended" implicit conversion as returned by 57320b57cec5SDimitry Andric /// TryClassUnification. 57330b57cec5SDimitry Andric static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 57340b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 57350b57cec5SDimitry Andric InitializationKind Kind = 57360b57cec5SDimitry Andric InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); 57370b57cec5SDimitry Andric Expr *Arg = E.get(); 57380b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, Arg); 57390b57cec5SDimitry Andric ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); 57400b57cec5SDimitry Andric if (Result.isInvalid()) 57410b57cec5SDimitry Andric return true; 57420b57cec5SDimitry Andric 57430b57cec5SDimitry Andric E = Result; 57440b57cec5SDimitry Andric return false; 57450b57cec5SDimitry Andric } 57460b57cec5SDimitry Andric 5747480093f4SDimitry Andric // Check the condition operand of ?: to see if it is valid for the GCC 5748480093f4SDimitry Andric // extension. 5749480093f4SDimitry Andric static bool isValidVectorForConditionalCondition(ASTContext &Ctx, 5750480093f4SDimitry Andric QualType CondTy) { 5751480093f4SDimitry Andric if (!CondTy->isVectorType() || CondTy->isExtVectorType()) 5752480093f4SDimitry Andric return false; 5753480093f4SDimitry Andric const QualType EltTy = 5754480093f4SDimitry Andric cast<VectorType>(CondTy.getCanonicalType())->getElementType(); 5755480093f4SDimitry Andric 5756480093f4SDimitry Andric assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() && 5757480093f4SDimitry Andric "Vectors cant be boolean or enum types"); 5758480093f4SDimitry Andric return EltTy->isIntegralType(Ctx); 5759480093f4SDimitry Andric } 5760480093f4SDimitry Andric 5761480093f4SDimitry Andric QualType Sema::CheckGNUVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 5762480093f4SDimitry Andric ExprResult &RHS, 5763480093f4SDimitry Andric SourceLocation QuestionLoc) { 5764480093f4SDimitry Andric LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 5765480093f4SDimitry Andric RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 5766480093f4SDimitry Andric 5767480093f4SDimitry Andric QualType CondType = Cond.get()->getType(); 5768480093f4SDimitry Andric const auto *CondVT = CondType->getAs<VectorType>(); 5769480093f4SDimitry Andric QualType CondElementTy = CondVT->getElementType(); 5770480093f4SDimitry Andric unsigned CondElementCount = CondVT->getNumElements(); 5771480093f4SDimitry Andric QualType LHSType = LHS.get()->getType(); 5772480093f4SDimitry Andric const auto *LHSVT = LHSType->getAs<VectorType>(); 5773480093f4SDimitry Andric QualType RHSType = RHS.get()->getType(); 5774480093f4SDimitry Andric const auto *RHSVT = RHSType->getAs<VectorType>(); 5775480093f4SDimitry Andric 5776480093f4SDimitry Andric QualType ResultType; 5777480093f4SDimitry Andric 5778480093f4SDimitry Andric // FIXME: In the future we should define what the Extvector conditional 5779480093f4SDimitry Andric // operator looks like. 5780480093f4SDimitry Andric if (LHSVT && isa<ExtVectorType>(LHSVT)) { 5781480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 5782480093f4SDimitry Andric << /*isExtVector*/ true << LHSType; 5783480093f4SDimitry Andric return {}; 5784480093f4SDimitry Andric } 5785480093f4SDimitry Andric 5786480093f4SDimitry Andric if (RHSVT && isa<ExtVectorType>(RHSVT)) { 5787480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 5788480093f4SDimitry Andric << /*isExtVector*/ true << RHSType; 5789480093f4SDimitry Andric return {}; 5790480093f4SDimitry Andric } 5791480093f4SDimitry Andric 5792480093f4SDimitry Andric if (LHSVT && RHSVT) { 5793480093f4SDimitry Andric // If both are vector types, they must be the same type. 5794480093f4SDimitry Andric if (!Context.hasSameType(LHSType, RHSType)) { 5795480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_mismatched_vectors) 5796480093f4SDimitry Andric << LHSType << RHSType; 5797480093f4SDimitry Andric return {}; 5798480093f4SDimitry Andric } 5799480093f4SDimitry Andric ResultType = LHSType; 5800480093f4SDimitry Andric } else if (LHSVT || RHSVT) { 5801480093f4SDimitry Andric ResultType = CheckVectorOperands( 5802480093f4SDimitry Andric LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true, 5803480093f4SDimitry Andric /*AllowBoolConversions*/ false); 5804480093f4SDimitry Andric if (ResultType.isNull()) 5805480093f4SDimitry Andric return {}; 5806480093f4SDimitry Andric } else { 5807480093f4SDimitry Andric // Both are scalar. 5808480093f4SDimitry Andric QualType ResultElementTy; 5809480093f4SDimitry Andric LHSType = LHSType.getCanonicalType().getUnqualifiedType(); 5810480093f4SDimitry Andric RHSType = RHSType.getCanonicalType().getUnqualifiedType(); 5811480093f4SDimitry Andric 5812480093f4SDimitry Andric if (Context.hasSameType(LHSType, RHSType)) 5813480093f4SDimitry Andric ResultElementTy = LHSType; 5814480093f4SDimitry Andric else 5815480093f4SDimitry Andric ResultElementTy = 5816480093f4SDimitry Andric UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 5817480093f4SDimitry Andric 5818480093f4SDimitry Andric if (ResultElementTy->isEnumeralType()) { 5819480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 5820480093f4SDimitry Andric << /*isExtVector*/ false << ResultElementTy; 5821480093f4SDimitry Andric return {}; 5822480093f4SDimitry Andric } 5823480093f4SDimitry Andric ResultType = Context.getVectorType( 5824480093f4SDimitry Andric ResultElementTy, CondType->getAs<VectorType>()->getNumElements(), 5825480093f4SDimitry Andric VectorType::GenericVector); 5826480093f4SDimitry Andric 5827480093f4SDimitry Andric LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); 5828480093f4SDimitry Andric RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); 5829480093f4SDimitry Andric } 5830480093f4SDimitry Andric 5831480093f4SDimitry Andric assert(!ResultType.isNull() && ResultType->isVectorType() && 5832480093f4SDimitry Andric "Result should have been a vector type"); 5833480093f4SDimitry Andric QualType ResultElementTy = ResultType->getAs<VectorType>()->getElementType(); 5834480093f4SDimitry Andric unsigned ResultElementCount = 5835480093f4SDimitry Andric ResultType->getAs<VectorType>()->getNumElements(); 5836480093f4SDimitry Andric 5837480093f4SDimitry Andric if (ResultElementCount != CondElementCount) { 5838480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType 5839480093f4SDimitry Andric << ResultType; 5840480093f4SDimitry Andric return {}; 5841480093f4SDimitry Andric } 5842480093f4SDimitry Andric 5843480093f4SDimitry Andric if (Context.getTypeSize(ResultElementTy) != 5844480093f4SDimitry Andric Context.getTypeSize(CondElementTy)) { 5845480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType 5846480093f4SDimitry Andric << ResultType; 5847480093f4SDimitry Andric return {}; 5848480093f4SDimitry Andric } 5849480093f4SDimitry Andric 5850480093f4SDimitry Andric return ResultType; 5851480093f4SDimitry Andric } 5852480093f4SDimitry Andric 58530b57cec5SDimitry Andric /// Check the operands of ?: under C++ semantics. 58540b57cec5SDimitry Andric /// 58550b57cec5SDimitry Andric /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 58560b57cec5SDimitry Andric /// extension. In this case, LHS == Cond. (But they're not aliases.) 5857480093f4SDimitry Andric /// 5858480093f4SDimitry Andric /// This function also implements GCC's vector extension for conditionals. 5859480093f4SDimitry Andric /// GCC's vector extension permits the use of a?b:c where the type of 5860480093f4SDimitry Andric /// a is that of a integer vector with the same number of elements and 5861480093f4SDimitry Andric /// size as the vectors of b and c. If one of either b or c is a scalar 5862480093f4SDimitry Andric /// it is implicitly converted to match the type of the vector. 5863480093f4SDimitry Andric /// Otherwise the expression is ill-formed. If both b and c are scalars, 5864480093f4SDimitry Andric /// then b and c are checked and converted to the type of a if possible. 5865480093f4SDimitry Andric /// Unlike the OpenCL ?: operator, the expression is evaluated as 5866480093f4SDimitry Andric /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). 58670b57cec5SDimitry Andric QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 58680b57cec5SDimitry Andric ExprResult &RHS, ExprValueKind &VK, 58690b57cec5SDimitry Andric ExprObjectKind &OK, 58700b57cec5SDimitry Andric SourceLocation QuestionLoc) { 5871480093f4SDimitry Andric // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface 5872480093f4SDimitry Andric // pointers. 58730b57cec5SDimitry Andric 58740b57cec5SDimitry Andric // Assume r-value. 58750b57cec5SDimitry Andric VK = VK_RValue; 58760b57cec5SDimitry Andric OK = OK_Ordinary; 5877480093f4SDimitry Andric bool IsVectorConditional = 5878480093f4SDimitry Andric isValidVectorForConditionalCondition(Context, Cond.get()->getType()); 5879480093f4SDimitry Andric 5880480093f4SDimitry Andric // C++11 [expr.cond]p1 5881480093f4SDimitry Andric // The first expression is contextually converted to bool. 5882480093f4SDimitry Andric if (!Cond.get()->isTypeDependent()) { 5883480093f4SDimitry Andric ExprResult CondRes = IsVectorConditional 5884480093f4SDimitry Andric ? DefaultFunctionArrayLvalueConversion(Cond.get()) 5885480093f4SDimitry Andric : CheckCXXBooleanCondition(Cond.get()); 5886480093f4SDimitry Andric if (CondRes.isInvalid()) 5887480093f4SDimitry Andric return QualType(); 5888480093f4SDimitry Andric Cond = CondRes; 5889480093f4SDimitry Andric } else { 5890480093f4SDimitry Andric // To implement C++, the first expression typically doesn't alter the result 5891480093f4SDimitry Andric // type of the conditional, however the GCC compatible vector extension 5892480093f4SDimitry Andric // changes the result type to be that of the conditional. Since we cannot 5893480093f4SDimitry Andric // know if this is a vector extension here, delay the conversion of the 5894480093f4SDimitry Andric // LHS/RHS below until later. 5895480093f4SDimitry Andric return Context.DependentTy; 5896480093f4SDimitry Andric } 5897480093f4SDimitry Andric 58980b57cec5SDimitry Andric 58990b57cec5SDimitry Andric // Either of the arguments dependent? 59000b57cec5SDimitry Andric if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 59010b57cec5SDimitry Andric return Context.DependentTy; 59020b57cec5SDimitry Andric 59030b57cec5SDimitry Andric // C++11 [expr.cond]p2 59040b57cec5SDimitry Andric // If either the second or the third operand has type (cv) void, ... 59050b57cec5SDimitry Andric QualType LTy = LHS.get()->getType(); 59060b57cec5SDimitry Andric QualType RTy = RHS.get()->getType(); 59070b57cec5SDimitry Andric bool LVoid = LTy->isVoidType(); 59080b57cec5SDimitry Andric bool RVoid = RTy->isVoidType(); 59090b57cec5SDimitry Andric if (LVoid || RVoid) { 59100b57cec5SDimitry Andric // ... one of the following shall hold: 59110b57cec5SDimitry Andric // -- The second or the third operand (but not both) is a (possibly 59120b57cec5SDimitry Andric // parenthesized) throw-expression; the result is of the type 59130b57cec5SDimitry Andric // and value category of the other. 59140b57cec5SDimitry Andric bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); 59150b57cec5SDimitry Andric bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); 5916480093f4SDimitry Andric 5917480093f4SDimitry Andric // Void expressions aren't legal in the vector-conditional expressions. 5918480093f4SDimitry Andric if (IsVectorConditional) { 5919480093f4SDimitry Andric SourceRange DiagLoc = 5920480093f4SDimitry Andric LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); 5921480093f4SDimitry Andric bool IsThrow = LVoid ? LThrow : RThrow; 5922480093f4SDimitry Andric Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) 5923480093f4SDimitry Andric << DiagLoc << IsThrow; 5924480093f4SDimitry Andric return QualType(); 5925480093f4SDimitry Andric } 5926480093f4SDimitry Andric 59270b57cec5SDimitry Andric if (LThrow != RThrow) { 59280b57cec5SDimitry Andric Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); 59290b57cec5SDimitry Andric VK = NonThrow->getValueKind(); 59300b57cec5SDimitry Andric // DR (no number yet): the result is a bit-field if the 59310b57cec5SDimitry Andric // non-throw-expression operand is a bit-field. 59320b57cec5SDimitry Andric OK = NonThrow->getObjectKind(); 59330b57cec5SDimitry Andric return NonThrow->getType(); 59340b57cec5SDimitry Andric } 59350b57cec5SDimitry Andric 59360b57cec5SDimitry Andric // -- Both the second and third operands have type void; the result is of 59370b57cec5SDimitry Andric // type void and is a prvalue. 59380b57cec5SDimitry Andric if (LVoid && RVoid) 59390b57cec5SDimitry Andric return Context.VoidTy; 59400b57cec5SDimitry Andric 59410b57cec5SDimitry Andric // Neither holds, error. 59420b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 59430b57cec5SDimitry Andric << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 59440b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 59450b57cec5SDimitry Andric return QualType(); 59460b57cec5SDimitry Andric } 59470b57cec5SDimitry Andric 59480b57cec5SDimitry Andric // Neither is void. 5949480093f4SDimitry Andric if (IsVectorConditional) 5950480093f4SDimitry Andric return CheckGNUVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); 59510b57cec5SDimitry Andric 59520b57cec5SDimitry Andric // C++11 [expr.cond]p3 59530b57cec5SDimitry Andric // Otherwise, if the second and third operand have different types, and 59540b57cec5SDimitry Andric // either has (cv) class type [...] an attempt is made to convert each of 59550b57cec5SDimitry Andric // those operands to the type of the other. 59560b57cec5SDimitry Andric if (!Context.hasSameType(LTy, RTy) && 59570b57cec5SDimitry Andric (LTy->isRecordType() || RTy->isRecordType())) { 59580b57cec5SDimitry Andric // These return true if a single direction is already ambiguous. 59590b57cec5SDimitry Andric QualType L2RType, R2LType; 59600b57cec5SDimitry Andric bool HaveL2R, HaveR2L; 59610b57cec5SDimitry Andric if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 59620b57cec5SDimitry Andric return QualType(); 59630b57cec5SDimitry Andric if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 59640b57cec5SDimitry Andric return QualType(); 59650b57cec5SDimitry Andric 59660b57cec5SDimitry Andric // If both can be converted, [...] the program is ill-formed. 59670b57cec5SDimitry Andric if (HaveL2R && HaveR2L) { 59680b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_conditional_ambiguous) 59690b57cec5SDimitry Andric << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 59700b57cec5SDimitry Andric return QualType(); 59710b57cec5SDimitry Andric } 59720b57cec5SDimitry Andric 59730b57cec5SDimitry Andric // If exactly one conversion is possible, that conversion is applied to 59740b57cec5SDimitry Andric // the chosen operand and the converted operands are used in place of the 59750b57cec5SDimitry Andric // original operands for the remainder of this section. 59760b57cec5SDimitry Andric if (HaveL2R) { 59770b57cec5SDimitry Andric if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 59780b57cec5SDimitry Andric return QualType(); 59790b57cec5SDimitry Andric LTy = LHS.get()->getType(); 59800b57cec5SDimitry Andric } else if (HaveR2L) { 59810b57cec5SDimitry Andric if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 59820b57cec5SDimitry Andric return QualType(); 59830b57cec5SDimitry Andric RTy = RHS.get()->getType(); 59840b57cec5SDimitry Andric } 59850b57cec5SDimitry Andric } 59860b57cec5SDimitry Andric 59870b57cec5SDimitry Andric // C++11 [expr.cond]p3 59880b57cec5SDimitry Andric // if both are glvalues of the same value category and the same type except 59890b57cec5SDimitry Andric // for cv-qualification, an attempt is made to convert each of those 59900b57cec5SDimitry Andric // operands to the type of the other. 59910b57cec5SDimitry Andric // FIXME: 59920b57cec5SDimitry Andric // Resolving a defect in P0012R1: we extend this to cover all cases where 59930b57cec5SDimitry Andric // one of the operands is reference-compatible with the other, in order 5994480093f4SDimitry Andric // to support conditionals between functions differing in noexcept. This 5995480093f4SDimitry Andric // will similarly cover difference in array bounds after P0388R4. 5996480093f4SDimitry Andric // FIXME: If LTy and RTy have a composite pointer type, should we convert to 5997480093f4SDimitry Andric // that instead? 59980b57cec5SDimitry Andric ExprValueKind LVK = LHS.get()->getValueKind(); 59990b57cec5SDimitry Andric ExprValueKind RVK = RHS.get()->getValueKind(); 60000b57cec5SDimitry Andric if (!Context.hasSameType(LTy, RTy) && 60010b57cec5SDimitry Andric LVK == RVK && LVK != VK_RValue) { 60020b57cec5SDimitry Andric // DerivedToBase was already handled by the class-specific case above. 60030b57cec5SDimitry Andric // FIXME: Should we allow ObjC conversions here? 6004480093f4SDimitry Andric const ReferenceConversions AllowedConversions = 6005480093f4SDimitry Andric ReferenceConversions::Qualification | 6006480093f4SDimitry Andric ReferenceConversions::NestedQualification | 6007480093f4SDimitry Andric ReferenceConversions::Function; 6008480093f4SDimitry Andric 6009480093f4SDimitry Andric ReferenceConversions RefConv; 6010480093f4SDimitry Andric if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) == 6011480093f4SDimitry Andric Ref_Compatible && 6012480093f4SDimitry Andric !(RefConv & ~AllowedConversions) && 60130b57cec5SDimitry Andric // [...] subject to the constraint that the reference must bind 60140b57cec5SDimitry Andric // directly [...] 6015a7dea167SDimitry Andric !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { 60160b57cec5SDimitry Andric RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); 60170b57cec5SDimitry Andric RTy = RHS.get()->getType(); 6018480093f4SDimitry Andric } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) == 6019480093f4SDimitry Andric Ref_Compatible && 6020480093f4SDimitry Andric !(RefConv & ~AllowedConversions) && 60210b57cec5SDimitry Andric !LHS.get()->refersToBitField() && 60220b57cec5SDimitry Andric !LHS.get()->refersToVectorElement()) { 60230b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); 60240b57cec5SDimitry Andric LTy = LHS.get()->getType(); 60250b57cec5SDimitry Andric } 60260b57cec5SDimitry Andric } 60270b57cec5SDimitry Andric 60280b57cec5SDimitry Andric // C++11 [expr.cond]p4 60290b57cec5SDimitry Andric // If the second and third operands are glvalues of the same value 60300b57cec5SDimitry Andric // category and have the same type, the result is of that type and 60310b57cec5SDimitry Andric // value category and it is a bit-field if the second or the third 60320b57cec5SDimitry Andric // operand is a bit-field, or if both are bit-fields. 60330b57cec5SDimitry Andric // We only extend this to bitfields, not to the crazy other kinds of 60340b57cec5SDimitry Andric // l-values. 60350b57cec5SDimitry Andric bool Same = Context.hasSameType(LTy, RTy); 60360b57cec5SDimitry Andric if (Same && LVK == RVK && LVK != VK_RValue && 60370b57cec5SDimitry Andric LHS.get()->isOrdinaryOrBitFieldObject() && 60380b57cec5SDimitry Andric RHS.get()->isOrdinaryOrBitFieldObject()) { 60390b57cec5SDimitry Andric VK = LHS.get()->getValueKind(); 60400b57cec5SDimitry Andric if (LHS.get()->getObjectKind() == OK_BitField || 60410b57cec5SDimitry Andric RHS.get()->getObjectKind() == OK_BitField) 60420b57cec5SDimitry Andric OK = OK_BitField; 60430b57cec5SDimitry Andric 60440b57cec5SDimitry Andric // If we have function pointer types, unify them anyway to unify their 60450b57cec5SDimitry Andric // exception specifications, if any. 60460b57cec5SDimitry Andric if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 60470b57cec5SDimitry Andric Qualifiers Qs = LTy.getQualifiers(); 60480b57cec5SDimitry Andric LTy = FindCompositePointerType(QuestionLoc, LHS, RHS, 60490b57cec5SDimitry Andric /*ConvertArgs*/false); 60500b57cec5SDimitry Andric LTy = Context.getQualifiedType(LTy, Qs); 60510b57cec5SDimitry Andric 60520b57cec5SDimitry Andric assert(!LTy.isNull() && "failed to find composite pointer type for " 60530b57cec5SDimitry Andric "canonically equivalent function ptr types"); 60540b57cec5SDimitry Andric assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type"); 60550b57cec5SDimitry Andric } 60560b57cec5SDimitry Andric 60570b57cec5SDimitry Andric return LTy; 60580b57cec5SDimitry Andric } 60590b57cec5SDimitry Andric 60600b57cec5SDimitry Andric // C++11 [expr.cond]p5 60610b57cec5SDimitry Andric // Otherwise, the result is a prvalue. If the second and third operands 60620b57cec5SDimitry Andric // do not have the same type, and either has (cv) class type, ... 60630b57cec5SDimitry Andric if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 60640b57cec5SDimitry Andric // ... overload resolution is used to determine the conversions (if any) 60650b57cec5SDimitry Andric // to be applied to the operands. If the overload resolution fails, the 60660b57cec5SDimitry Andric // program is ill-formed. 60670b57cec5SDimitry Andric if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 60680b57cec5SDimitry Andric return QualType(); 60690b57cec5SDimitry Andric } 60700b57cec5SDimitry Andric 60710b57cec5SDimitry Andric // C++11 [expr.cond]p6 60720b57cec5SDimitry Andric // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 60730b57cec5SDimitry Andric // conversions are performed on the second and third operands. 60740b57cec5SDimitry Andric LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 60750b57cec5SDimitry Andric RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 60760b57cec5SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 60770b57cec5SDimitry Andric return QualType(); 60780b57cec5SDimitry Andric LTy = LHS.get()->getType(); 60790b57cec5SDimitry Andric RTy = RHS.get()->getType(); 60800b57cec5SDimitry Andric 60810b57cec5SDimitry Andric // After those conversions, one of the following shall hold: 60820b57cec5SDimitry Andric // -- The second and third operands have the same type; the result 60830b57cec5SDimitry Andric // is of that type. If the operands have class type, the result 60840b57cec5SDimitry Andric // is a prvalue temporary of the result type, which is 60850b57cec5SDimitry Andric // copy-initialized from either the second operand or the third 60860b57cec5SDimitry Andric // operand depending on the value of the first operand. 60870b57cec5SDimitry Andric if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 60880b57cec5SDimitry Andric if (LTy->isRecordType()) { 60890b57cec5SDimitry Andric // The operands have class type. Make a temporary copy. 60900b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 60910b57cec5SDimitry Andric 60920b57cec5SDimitry Andric ExprResult LHSCopy = PerformCopyInitialization(Entity, 60930b57cec5SDimitry Andric SourceLocation(), 60940b57cec5SDimitry Andric LHS); 60950b57cec5SDimitry Andric if (LHSCopy.isInvalid()) 60960b57cec5SDimitry Andric return QualType(); 60970b57cec5SDimitry Andric 60980b57cec5SDimitry Andric ExprResult RHSCopy = PerformCopyInitialization(Entity, 60990b57cec5SDimitry Andric SourceLocation(), 61000b57cec5SDimitry Andric RHS); 61010b57cec5SDimitry Andric if (RHSCopy.isInvalid()) 61020b57cec5SDimitry Andric return QualType(); 61030b57cec5SDimitry Andric 61040b57cec5SDimitry Andric LHS = LHSCopy; 61050b57cec5SDimitry Andric RHS = RHSCopy; 61060b57cec5SDimitry Andric } 61070b57cec5SDimitry Andric 61080b57cec5SDimitry Andric // If we have function pointer types, unify them anyway to unify their 61090b57cec5SDimitry Andric // exception specifications, if any. 61100b57cec5SDimitry Andric if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 61110b57cec5SDimitry Andric LTy = FindCompositePointerType(QuestionLoc, LHS, RHS); 61120b57cec5SDimitry Andric assert(!LTy.isNull() && "failed to find composite pointer type for " 61130b57cec5SDimitry Andric "canonically equivalent function ptr types"); 61140b57cec5SDimitry Andric } 61150b57cec5SDimitry Andric 61160b57cec5SDimitry Andric return LTy; 61170b57cec5SDimitry Andric } 61180b57cec5SDimitry Andric 61190b57cec5SDimitry Andric // Extension: conditional operator involving vector types. 61200b57cec5SDimitry Andric if (LTy->isVectorType() || RTy->isVectorType()) 61210b57cec5SDimitry Andric return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 61220b57cec5SDimitry Andric /*AllowBothBool*/true, 61230b57cec5SDimitry Andric /*AllowBoolConversions*/false); 61240b57cec5SDimitry Andric 61250b57cec5SDimitry Andric // -- The second and third operands have arithmetic or enumeration type; 61260b57cec5SDimitry Andric // the usual arithmetic conversions are performed to bring them to a 61270b57cec5SDimitry Andric // common type, and the result is of that type. 61280b57cec5SDimitry Andric if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 6129480093f4SDimitry Andric QualType ResTy = 6130480093f4SDimitry Andric UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 61310b57cec5SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 61320b57cec5SDimitry Andric return QualType(); 61330b57cec5SDimitry Andric if (ResTy.isNull()) { 61340b57cec5SDimitry Andric Diag(QuestionLoc, 61350b57cec5SDimitry Andric diag::err_typecheck_cond_incompatible_operands) << LTy << RTy 61360b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 61370b57cec5SDimitry Andric return QualType(); 61380b57cec5SDimitry Andric } 61390b57cec5SDimitry Andric 61400b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 61410b57cec5SDimitry Andric RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 61420b57cec5SDimitry Andric 61430b57cec5SDimitry Andric return ResTy; 61440b57cec5SDimitry Andric } 61450b57cec5SDimitry Andric 61460b57cec5SDimitry Andric // -- The second and third operands have pointer type, or one has pointer 61470b57cec5SDimitry Andric // type and the other is a null pointer constant, or both are null 61480b57cec5SDimitry Andric // pointer constants, at least one of which is non-integral; pointer 61490b57cec5SDimitry Andric // conversions and qualification conversions are performed to bring them 61500b57cec5SDimitry Andric // to their composite pointer type. The result is of the composite 61510b57cec5SDimitry Andric // pointer type. 61520b57cec5SDimitry Andric // -- The second and third operands have pointer to member type, or one has 61530b57cec5SDimitry Andric // pointer to member type and the other is a null pointer constant; 61540b57cec5SDimitry Andric // pointer to member conversions and qualification conversions are 61550b57cec5SDimitry Andric // performed to bring them to a common type, whose cv-qualification 61560b57cec5SDimitry Andric // shall match the cv-qualification of either the second or the third 61570b57cec5SDimitry Andric // operand. The result is of the common type. 61580b57cec5SDimitry Andric QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); 61590b57cec5SDimitry Andric if (!Composite.isNull()) 61600b57cec5SDimitry Andric return Composite; 61610b57cec5SDimitry Andric 61620b57cec5SDimitry Andric // Similarly, attempt to find composite type of two objective-c pointers. 61630b57cec5SDimitry Andric Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 61640b57cec5SDimitry Andric if (!Composite.isNull()) 61650b57cec5SDimitry Andric return Composite; 61660b57cec5SDimitry Andric 61670b57cec5SDimitry Andric // Check if we are using a null with a non-pointer type. 61680b57cec5SDimitry Andric if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 61690b57cec5SDimitry Andric return QualType(); 61700b57cec5SDimitry Andric 61710b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 61720b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 61730b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 61740b57cec5SDimitry Andric return QualType(); 61750b57cec5SDimitry Andric } 61760b57cec5SDimitry Andric 61770b57cec5SDimitry Andric static FunctionProtoType::ExceptionSpecInfo 61780b57cec5SDimitry Andric mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, 61790b57cec5SDimitry Andric FunctionProtoType::ExceptionSpecInfo ESI2, 61800b57cec5SDimitry Andric SmallVectorImpl<QualType> &ExceptionTypeStorage) { 61810b57cec5SDimitry Andric ExceptionSpecificationType EST1 = ESI1.Type; 61820b57cec5SDimitry Andric ExceptionSpecificationType EST2 = ESI2.Type; 61830b57cec5SDimitry Andric 61840b57cec5SDimitry Andric // If either of them can throw anything, that is the result. 61850b57cec5SDimitry Andric if (EST1 == EST_None) return ESI1; 61860b57cec5SDimitry Andric if (EST2 == EST_None) return ESI2; 61870b57cec5SDimitry Andric if (EST1 == EST_MSAny) return ESI1; 61880b57cec5SDimitry Andric if (EST2 == EST_MSAny) return ESI2; 61890b57cec5SDimitry Andric if (EST1 == EST_NoexceptFalse) return ESI1; 61900b57cec5SDimitry Andric if (EST2 == EST_NoexceptFalse) return ESI2; 61910b57cec5SDimitry Andric 61920b57cec5SDimitry Andric // If either of them is non-throwing, the result is the other. 61930b57cec5SDimitry Andric if (EST1 == EST_NoThrow) return ESI2; 61940b57cec5SDimitry Andric if (EST2 == EST_NoThrow) return ESI1; 61950b57cec5SDimitry Andric if (EST1 == EST_DynamicNone) return ESI2; 61960b57cec5SDimitry Andric if (EST2 == EST_DynamicNone) return ESI1; 61970b57cec5SDimitry Andric if (EST1 == EST_BasicNoexcept) return ESI2; 61980b57cec5SDimitry Andric if (EST2 == EST_BasicNoexcept) return ESI1; 61990b57cec5SDimitry Andric if (EST1 == EST_NoexceptTrue) return ESI2; 62000b57cec5SDimitry Andric if (EST2 == EST_NoexceptTrue) return ESI1; 62010b57cec5SDimitry Andric 62020b57cec5SDimitry Andric // If we're left with value-dependent computed noexcept expressions, we're 62030b57cec5SDimitry Andric // stuck. Before C++17, we can just drop the exception specification entirely, 62040b57cec5SDimitry Andric // since it's not actually part of the canonical type. And this should never 62050b57cec5SDimitry Andric // happen in C++17, because it would mean we were computing the composite 62060b57cec5SDimitry Andric // pointer type of dependent types, which should never happen. 62070b57cec5SDimitry Andric if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) { 62080b57cec5SDimitry Andric assert(!S.getLangOpts().CPlusPlus17 && 62090b57cec5SDimitry Andric "computing composite pointer type of dependent types"); 62100b57cec5SDimitry Andric return FunctionProtoType::ExceptionSpecInfo(); 62110b57cec5SDimitry Andric } 62120b57cec5SDimitry Andric 62130b57cec5SDimitry Andric // Switch over the possibilities so that people adding new values know to 62140b57cec5SDimitry Andric // update this function. 62150b57cec5SDimitry Andric switch (EST1) { 62160b57cec5SDimitry Andric case EST_None: 62170b57cec5SDimitry Andric case EST_DynamicNone: 62180b57cec5SDimitry Andric case EST_MSAny: 62190b57cec5SDimitry Andric case EST_BasicNoexcept: 62200b57cec5SDimitry Andric case EST_DependentNoexcept: 62210b57cec5SDimitry Andric case EST_NoexceptFalse: 62220b57cec5SDimitry Andric case EST_NoexceptTrue: 62230b57cec5SDimitry Andric case EST_NoThrow: 62240b57cec5SDimitry Andric llvm_unreachable("handled above"); 62250b57cec5SDimitry Andric 62260b57cec5SDimitry Andric case EST_Dynamic: { 62270b57cec5SDimitry Andric // This is the fun case: both exception specifications are dynamic. Form 62280b57cec5SDimitry Andric // the union of the two lists. 62290b57cec5SDimitry Andric assert(EST2 == EST_Dynamic && "other cases should already be handled"); 62300b57cec5SDimitry Andric llvm::SmallPtrSet<QualType, 8> Found; 62310b57cec5SDimitry Andric for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions}) 62320b57cec5SDimitry Andric for (QualType E : Exceptions) 62330b57cec5SDimitry Andric if (Found.insert(S.Context.getCanonicalType(E)).second) 62340b57cec5SDimitry Andric ExceptionTypeStorage.push_back(E); 62350b57cec5SDimitry Andric 62360b57cec5SDimitry Andric FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic); 62370b57cec5SDimitry Andric Result.Exceptions = ExceptionTypeStorage; 62380b57cec5SDimitry Andric return Result; 62390b57cec5SDimitry Andric } 62400b57cec5SDimitry Andric 62410b57cec5SDimitry Andric case EST_Unevaluated: 62420b57cec5SDimitry Andric case EST_Uninstantiated: 62430b57cec5SDimitry Andric case EST_Unparsed: 62440b57cec5SDimitry Andric llvm_unreachable("shouldn't see unresolved exception specifications here"); 62450b57cec5SDimitry Andric } 62460b57cec5SDimitry Andric 62470b57cec5SDimitry Andric llvm_unreachable("invalid ExceptionSpecificationType"); 62480b57cec5SDimitry Andric } 62490b57cec5SDimitry Andric 62500b57cec5SDimitry Andric /// Find a merged pointer type and convert the two expressions to it. 62510b57cec5SDimitry Andric /// 6252480093f4SDimitry Andric /// This finds the composite pointer type for \p E1 and \p E2 according to 6253480093f4SDimitry Andric /// C++2a [expr.type]p3. It converts both expressions to this type and returns 6254480093f4SDimitry Andric /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs 6255480093f4SDimitry Andric /// is \c true). 62560b57cec5SDimitry Andric /// 62570b57cec5SDimitry Andric /// \param Loc The location of the operator requiring these two expressions to 62580b57cec5SDimitry Andric /// be converted to the composite pointer type. 62590b57cec5SDimitry Andric /// 62600b57cec5SDimitry Andric /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. 62610b57cec5SDimitry Andric QualType Sema::FindCompositePointerType(SourceLocation Loc, 62620b57cec5SDimitry Andric Expr *&E1, Expr *&E2, 62630b57cec5SDimitry Andric bool ConvertArgs) { 62640b57cec5SDimitry Andric assert(getLangOpts().CPlusPlus && "This function assumes C++"); 62650b57cec5SDimitry Andric 62660b57cec5SDimitry Andric // C++1z [expr]p14: 62670b57cec5SDimitry Andric // The composite pointer type of two operands p1 and p2 having types T1 62680b57cec5SDimitry Andric // and T2 62690b57cec5SDimitry Andric QualType T1 = E1->getType(), T2 = E2->getType(); 62700b57cec5SDimitry Andric 62710b57cec5SDimitry Andric // where at least one is a pointer or pointer to member type or 62720b57cec5SDimitry Andric // std::nullptr_t is: 62730b57cec5SDimitry Andric bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || 62740b57cec5SDimitry Andric T1->isNullPtrType(); 62750b57cec5SDimitry Andric bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || 62760b57cec5SDimitry Andric T2->isNullPtrType(); 62770b57cec5SDimitry Andric if (!T1IsPointerLike && !T2IsPointerLike) 62780b57cec5SDimitry Andric return QualType(); 62790b57cec5SDimitry Andric 62800b57cec5SDimitry Andric // - if both p1 and p2 are null pointer constants, std::nullptr_t; 62810b57cec5SDimitry Andric // This can't actually happen, following the standard, but we also use this 62820b57cec5SDimitry Andric // to implement the end of [expr.conv], which hits this case. 62830b57cec5SDimitry Andric // 62840b57cec5SDimitry Andric // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; 62850b57cec5SDimitry Andric if (T1IsPointerLike && 62860b57cec5SDimitry Andric E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 62870b57cec5SDimitry Andric if (ConvertArgs) 62880b57cec5SDimitry Andric E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() 62890b57cec5SDimitry Andric ? CK_NullToMemberPointer 62900b57cec5SDimitry Andric : CK_NullToPointer).get(); 62910b57cec5SDimitry Andric return T1; 62920b57cec5SDimitry Andric } 62930b57cec5SDimitry Andric if (T2IsPointerLike && 62940b57cec5SDimitry Andric E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 62950b57cec5SDimitry Andric if (ConvertArgs) 62960b57cec5SDimitry Andric E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() 62970b57cec5SDimitry Andric ? CK_NullToMemberPointer 62980b57cec5SDimitry Andric : CK_NullToPointer).get(); 62990b57cec5SDimitry Andric return T2; 63000b57cec5SDimitry Andric } 63010b57cec5SDimitry Andric 63020b57cec5SDimitry Andric // Now both have to be pointers or member pointers. 63030b57cec5SDimitry Andric if (!T1IsPointerLike || !T2IsPointerLike) 63040b57cec5SDimitry Andric return QualType(); 63050b57cec5SDimitry Andric assert(!T1->isNullPtrType() && !T2->isNullPtrType() && 63060b57cec5SDimitry Andric "nullptr_t should be a null pointer constant"); 63070b57cec5SDimitry Andric 6308480093f4SDimitry Andric struct Step { 6309480093f4SDimitry Andric enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; 6310480093f4SDimitry Andric // Qualifiers to apply under the step kind. 6311480093f4SDimitry Andric Qualifiers Quals; 6312480093f4SDimitry Andric /// The class for a pointer-to-member; a constant array type with a bound 6313480093f4SDimitry Andric /// (if any) for an array. 6314480093f4SDimitry Andric const Type *ClassOrBound; 6315480093f4SDimitry Andric 6316480093f4SDimitry Andric Step(Kind K, const Type *ClassOrBound = nullptr) 6317480093f4SDimitry Andric : K(K), Quals(), ClassOrBound(ClassOrBound) {} 6318480093f4SDimitry Andric QualType rebuild(ASTContext &Ctx, QualType T) const { 6319480093f4SDimitry Andric T = Ctx.getQualifiedType(T, Quals); 6320480093f4SDimitry Andric switch (K) { 6321480093f4SDimitry Andric case Pointer: 6322480093f4SDimitry Andric return Ctx.getPointerType(T); 6323480093f4SDimitry Andric case MemberPointer: 6324480093f4SDimitry Andric return Ctx.getMemberPointerType(T, ClassOrBound); 6325480093f4SDimitry Andric case ObjCPointer: 6326480093f4SDimitry Andric return Ctx.getObjCObjectPointerType(T); 6327480093f4SDimitry Andric case Array: 6328480093f4SDimitry Andric if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound)) 6329480093f4SDimitry Andric return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr, 6330480093f4SDimitry Andric ArrayType::Normal, 0); 6331480093f4SDimitry Andric else 6332480093f4SDimitry Andric return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0); 6333480093f4SDimitry Andric } 6334480093f4SDimitry Andric llvm_unreachable("unknown step kind"); 6335480093f4SDimitry Andric } 6336480093f4SDimitry Andric }; 6337480093f4SDimitry Andric 6338480093f4SDimitry Andric SmallVector<Step, 8> Steps; 6339480093f4SDimitry Andric 63400b57cec5SDimitry Andric // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 63410b57cec5SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 63420b57cec5SDimitry Andric // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, 63430b57cec5SDimitry Andric // respectively; 63440b57cec5SDimitry Andric // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer 6345480093f4SDimitry Andric // to member of C2 of type cv2 U2" for some non-function type U, where 6346480093f4SDimitry Andric // C1 is reference-related to C2 or C2 is reference-related to C1, the 6347480093f4SDimitry Andric // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, 6348480093f4SDimitry Andric // respectively; 63490b57cec5SDimitry Andric // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and 63500b57cec5SDimitry Andric // T2; 63510b57cec5SDimitry Andric // 6352480093f4SDimitry Andric // Dismantle T1 and T2 to simultaneously determine whether they are similar 6353480093f4SDimitry Andric // and to prepare to form the cv-combined type if so. 63540b57cec5SDimitry Andric QualType Composite1 = T1; 63550b57cec5SDimitry Andric QualType Composite2 = T2; 63560b57cec5SDimitry Andric unsigned NeedConstBefore = 0; 63570b57cec5SDimitry Andric while (true) { 6358480093f4SDimitry Andric assert(!Composite1.isNull() && !Composite2.isNull()); 6359480093f4SDimitry Andric 6360480093f4SDimitry Andric Qualifiers Q1, Q2; 6361480093f4SDimitry Andric Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1); 6362480093f4SDimitry Andric Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2); 6363480093f4SDimitry Andric 6364480093f4SDimitry Andric // Top-level qualifiers are ignored. Merge at all lower levels. 6365480093f4SDimitry Andric if (!Steps.empty()) { 6366480093f4SDimitry Andric // Find the qualifier union: (approximately) the unique minimal set of 6367480093f4SDimitry Andric // qualifiers that is compatible with both types. 6368480093f4SDimitry Andric Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() | 6369480093f4SDimitry Andric Q2.getCVRUQualifiers()); 6370480093f4SDimitry Andric 6371480093f4SDimitry Andric // Under one level of pointer or pointer-to-member, we can change to an 6372480093f4SDimitry Andric // unambiguous compatible address space. 6373480093f4SDimitry Andric if (Q1.getAddressSpace() == Q2.getAddressSpace()) { 6374480093f4SDimitry Andric Quals.setAddressSpace(Q1.getAddressSpace()); 6375480093f4SDimitry Andric } else if (Steps.size() == 1) { 6376480093f4SDimitry Andric bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2); 6377480093f4SDimitry Andric bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1); 6378480093f4SDimitry Andric if (MaybeQ1 == MaybeQ2) 6379480093f4SDimitry Andric return QualType(); // No unique best address space. 6380480093f4SDimitry Andric Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() 6381480093f4SDimitry Andric : Q2.getAddressSpace()); 6382480093f4SDimitry Andric } else { 6383480093f4SDimitry Andric return QualType(); 6384480093f4SDimitry Andric } 6385480093f4SDimitry Andric 6386480093f4SDimitry Andric // FIXME: In C, we merge __strong and none to __strong at the top level. 6387480093f4SDimitry Andric if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) 6388480093f4SDimitry Andric Quals.setObjCGCAttr(Q1.getObjCGCAttr()); 6389480093f4SDimitry Andric else 6390480093f4SDimitry Andric return QualType(); 6391480093f4SDimitry Andric 6392480093f4SDimitry Andric // Mismatched lifetime qualifiers never compatibly include each other. 6393480093f4SDimitry Andric if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) 6394480093f4SDimitry Andric Quals.setObjCLifetime(Q1.getObjCLifetime()); 6395480093f4SDimitry Andric else 6396480093f4SDimitry Andric return QualType(); 6397480093f4SDimitry Andric 6398480093f4SDimitry Andric Steps.back().Quals = Quals; 6399480093f4SDimitry Andric if (Q1 != Quals || Q2 != Quals) 6400480093f4SDimitry Andric NeedConstBefore = Steps.size() - 1; 6401480093f4SDimitry Andric } 6402480093f4SDimitry Andric 6403480093f4SDimitry Andric // FIXME: Can we unify the following with UnwrapSimilarTypes? 64040b57cec5SDimitry Andric const PointerType *Ptr1, *Ptr2; 64050b57cec5SDimitry Andric if ((Ptr1 = Composite1->getAs<PointerType>()) && 64060b57cec5SDimitry Andric (Ptr2 = Composite2->getAs<PointerType>())) { 64070b57cec5SDimitry Andric Composite1 = Ptr1->getPointeeType(); 64080b57cec5SDimitry Andric Composite2 = Ptr2->getPointeeType(); 6409480093f4SDimitry Andric Steps.emplace_back(Step::Pointer); 6410480093f4SDimitry Andric continue; 6411480093f4SDimitry Andric } 64120b57cec5SDimitry Andric 6413480093f4SDimitry Andric const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; 6414480093f4SDimitry Andric if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && 6415480093f4SDimitry Andric (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { 6416480093f4SDimitry Andric Composite1 = ObjPtr1->getPointeeType(); 6417480093f4SDimitry Andric Composite2 = ObjPtr2->getPointeeType(); 6418480093f4SDimitry Andric Steps.emplace_back(Step::ObjCPointer); 64190b57cec5SDimitry Andric continue; 64200b57cec5SDimitry Andric } 64210b57cec5SDimitry Andric 64220b57cec5SDimitry Andric const MemberPointerType *MemPtr1, *MemPtr2; 64230b57cec5SDimitry Andric if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 64240b57cec5SDimitry Andric (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 64250b57cec5SDimitry Andric Composite1 = MemPtr1->getPointeeType(); 64260b57cec5SDimitry Andric Composite2 = MemPtr2->getPointeeType(); 64270b57cec5SDimitry Andric 6428480093f4SDimitry Andric // At the top level, we can perform a base-to-derived pointer-to-member 6429480093f4SDimitry Andric // conversion: 6430480093f4SDimitry Andric // 6431480093f4SDimitry Andric // - [...] where C1 is reference-related to C2 or C2 is 6432480093f4SDimitry Andric // reference-related to C1 6433480093f4SDimitry Andric // 6434480093f4SDimitry Andric // (Note that the only kinds of reference-relatedness in scope here are 6435480093f4SDimitry Andric // "same type or derived from".) At any other level, the class must 6436480093f4SDimitry Andric // exactly match. 6437480093f4SDimitry Andric const Type *Class = nullptr; 6438480093f4SDimitry Andric QualType Cls1(MemPtr1->getClass(), 0); 6439480093f4SDimitry Andric QualType Cls2(MemPtr2->getClass(), 0); 6440480093f4SDimitry Andric if (Context.hasSameType(Cls1, Cls2)) 6441480093f4SDimitry Andric Class = MemPtr1->getClass(); 6442480093f4SDimitry Andric else if (Steps.empty()) 6443480093f4SDimitry Andric Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() : 6444480093f4SDimitry Andric IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr; 6445480093f4SDimitry Andric if (!Class) 6446480093f4SDimitry Andric return QualType(); 64470b57cec5SDimitry Andric 6448480093f4SDimitry Andric Steps.emplace_back(Step::MemberPointer, Class); 64490b57cec5SDimitry Andric continue; 64500b57cec5SDimitry Andric } 64510b57cec5SDimitry Andric 6452480093f4SDimitry Andric // Special case: at the top level, we can decompose an Objective-C pointer 6453480093f4SDimitry Andric // and a 'cv void *'. Unify the qualifiers. 6454480093f4SDimitry Andric if (Steps.empty() && ((Composite1->isVoidPointerType() && 6455480093f4SDimitry Andric Composite2->isObjCObjectPointerType()) || 6456480093f4SDimitry Andric (Composite1->isObjCObjectPointerType() && 6457480093f4SDimitry Andric Composite2->isVoidPointerType()))) { 6458480093f4SDimitry Andric Composite1 = Composite1->getPointeeType(); 6459480093f4SDimitry Andric Composite2 = Composite2->getPointeeType(); 6460480093f4SDimitry Andric Steps.emplace_back(Step::Pointer); 6461480093f4SDimitry Andric continue; 6462480093f4SDimitry Andric } 6463480093f4SDimitry Andric 6464480093f4SDimitry Andric // FIXME: arrays 6465480093f4SDimitry Andric 64660b57cec5SDimitry Andric // FIXME: block pointer types? 64670b57cec5SDimitry Andric 64680b57cec5SDimitry Andric // Cannot unwrap any more types. 64690b57cec5SDimitry Andric break; 64700b57cec5SDimitry Andric } 64710b57cec5SDimitry Andric 6472480093f4SDimitry Andric // - if T1 or T2 is "pointer to noexcept function" and the other type is 6473480093f4SDimitry Andric // "pointer to function", where the function types are otherwise the same, 6474480093f4SDimitry Andric // "pointer to function"; 6475480093f4SDimitry Andric // - if T1 or T2 is "pointer to member of C1 of type function", the other 6476480093f4SDimitry Andric // type is "pointer to member of C2 of type noexcept function", and C1 6477480093f4SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1, where 6478480093f4SDimitry Andric // the function types are otherwise the same, "pointer to member of C2 of 6479480093f4SDimitry Andric // type function" or "pointer to member of C1 of type function", 6480480093f4SDimitry Andric // respectively; 6481480093f4SDimitry Andric // 6482480093f4SDimitry Andric // We also support 'noreturn' here, so as a Clang extension we generalize the 6483480093f4SDimitry Andric // above to: 6484480093f4SDimitry Andric // 6485480093f4SDimitry Andric // - [Clang] If T1 and T2 are both of type "pointer to function" or 6486480093f4SDimitry Andric // "pointer to member function" and the pointee types can be unified 6487480093f4SDimitry Andric // by a function pointer conversion, that conversion is applied 6488480093f4SDimitry Andric // before checking the following rules. 6489480093f4SDimitry Andric // 6490480093f4SDimitry Andric // We've already unwrapped down to the function types, and we want to merge 6491480093f4SDimitry Andric // rather than just convert, so do this ourselves rather than calling 64920b57cec5SDimitry Andric // IsFunctionConversion. 64930b57cec5SDimitry Andric // 64940b57cec5SDimitry Andric // FIXME: In order to match the standard wording as closely as possible, we 64950b57cec5SDimitry Andric // currently only do this under a single level of pointers. Ideally, we would 64960b57cec5SDimitry Andric // allow this in general, and set NeedConstBefore to the relevant depth on 6497480093f4SDimitry Andric // the side(s) where we changed anything. If we permit that, we should also 6498480093f4SDimitry Andric // consider this conversion when determining type similarity and model it as 6499480093f4SDimitry Andric // a qualification conversion. 6500480093f4SDimitry Andric if (Steps.size() == 1) { 65010b57cec5SDimitry Andric if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { 65020b57cec5SDimitry Andric if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { 65030b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); 65040b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); 65050b57cec5SDimitry Andric 65060b57cec5SDimitry Andric // The result is noreturn if both operands are. 65070b57cec5SDimitry Andric bool Noreturn = 65080b57cec5SDimitry Andric EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); 65090b57cec5SDimitry Andric EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); 65100b57cec5SDimitry Andric EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); 65110b57cec5SDimitry Andric 65120b57cec5SDimitry Andric // The result is nothrow if both operands are. 65130b57cec5SDimitry Andric SmallVector<QualType, 8> ExceptionTypeStorage; 65140b57cec5SDimitry Andric EPI1.ExceptionSpec = EPI2.ExceptionSpec = 65150b57cec5SDimitry Andric mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec, 65160b57cec5SDimitry Andric ExceptionTypeStorage); 65170b57cec5SDimitry Andric 65180b57cec5SDimitry Andric Composite1 = Context.getFunctionType(FPT1->getReturnType(), 65190b57cec5SDimitry Andric FPT1->getParamTypes(), EPI1); 65200b57cec5SDimitry Andric Composite2 = Context.getFunctionType(FPT2->getReturnType(), 65210b57cec5SDimitry Andric FPT2->getParamTypes(), EPI2); 65220b57cec5SDimitry Andric } 65230b57cec5SDimitry Andric } 65240b57cec5SDimitry Andric } 65250b57cec5SDimitry Andric 6526480093f4SDimitry Andric // There are some more conversions we can perform under exactly one pointer. 6527480093f4SDimitry Andric if (Steps.size() == 1 && Steps.front().K == Step::Pointer && 6528480093f4SDimitry Andric !Context.hasSameType(Composite1, Composite2)) { 6529480093f4SDimitry Andric // - if T1 or T2 is "pointer to cv1 void" and the other type is 6530480093f4SDimitry Andric // "pointer to cv2 T", where T is an object type or void, 6531480093f4SDimitry Andric // "pointer to cv12 void", where cv12 is the union of cv1 and cv2; 6532480093f4SDimitry Andric if (Composite1->isVoidType() && Composite2->isObjectType()) 6533480093f4SDimitry Andric Composite2 = Composite1; 6534480093f4SDimitry Andric else if (Composite2->isVoidType() && Composite1->isObjectType()) 6535480093f4SDimitry Andric Composite1 = Composite2; 6536480093f4SDimitry Andric // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 6537480093f4SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 6538480093f4SDimitry Andric // the cv-combined type of T1 and T2 or the cv-combined type of T2 and 6539480093f4SDimitry Andric // T1, respectively; 6540480093f4SDimitry Andric // 6541480093f4SDimitry Andric // The "similar type" handling covers all of this except for the "T1 is a 6542480093f4SDimitry Andric // base class of T2" case in the definition of reference-related. 6543480093f4SDimitry Andric else if (IsDerivedFrom(Loc, Composite1, Composite2)) 6544480093f4SDimitry Andric Composite1 = Composite2; 6545480093f4SDimitry Andric else if (IsDerivedFrom(Loc, Composite2, Composite1)) 6546480093f4SDimitry Andric Composite2 = Composite1; 6547480093f4SDimitry Andric } 6548480093f4SDimitry Andric 6549480093f4SDimitry Andric // At this point, either the inner types are the same or we have failed to 6550480093f4SDimitry Andric // find a composite pointer type. 6551480093f4SDimitry Andric if (!Context.hasSameType(Composite1, Composite2)) 6552480093f4SDimitry Andric return QualType(); 6553480093f4SDimitry Andric 6554480093f4SDimitry Andric // Per C++ [conv.qual]p3, add 'const' to every level before the last 6555480093f4SDimitry Andric // differing qualifier. 65560b57cec5SDimitry Andric for (unsigned I = 0; I != NeedConstBefore; ++I) 6557480093f4SDimitry Andric Steps[I].Quals.addConst(); 65580b57cec5SDimitry Andric 6559480093f4SDimitry Andric // Rebuild the composite type. 6560480093f4SDimitry Andric QualType Composite = Composite1; 6561480093f4SDimitry Andric for (auto &S : llvm::reverse(Steps)) 6562480093f4SDimitry Andric Composite = S.rebuild(Context, Composite); 65630b57cec5SDimitry Andric 6564480093f4SDimitry Andric if (ConvertArgs) { 6565480093f4SDimitry Andric // Convert the expressions to the composite pointer type. 6566480093f4SDimitry Andric InitializedEntity Entity = 6567480093f4SDimitry Andric InitializedEntity::InitializeTemporary(Composite); 6568480093f4SDimitry Andric InitializationKind Kind = 6569480093f4SDimitry Andric InitializationKind::CreateCopy(Loc, SourceLocation()); 65700b57cec5SDimitry Andric 6571480093f4SDimitry Andric InitializationSequence E1ToC(*this, Entity, Kind, E1); 6572480093f4SDimitry Andric if (!E1ToC) 6573480093f4SDimitry Andric return QualType(); 65740b57cec5SDimitry Andric 6575480093f4SDimitry Andric InitializationSequence E2ToC(*this, Entity, Kind, E2); 6576480093f4SDimitry Andric if (!E2ToC) 6577480093f4SDimitry Andric return QualType(); 6578480093f4SDimitry Andric 6579480093f4SDimitry Andric // FIXME: Let the caller know if these fail to avoid duplicate diagnostics. 6580480093f4SDimitry Andric ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1); 65810b57cec5SDimitry Andric if (E1Result.isInvalid()) 6582480093f4SDimitry Andric return QualType(); 6583480093f4SDimitry Andric E1 = E1Result.get(); 65840b57cec5SDimitry Andric 6585480093f4SDimitry Andric ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2); 65860b57cec5SDimitry Andric if (E2Result.isInvalid()) 65870b57cec5SDimitry Andric return QualType(); 6588480093f4SDimitry Andric E2 = E2Result.get(); 65890b57cec5SDimitry Andric } 65900b57cec5SDimitry Andric 6591480093f4SDimitry Andric return Composite; 65920b57cec5SDimitry Andric } 65930b57cec5SDimitry Andric 65940b57cec5SDimitry Andric ExprResult Sema::MaybeBindToTemporary(Expr *E) { 65950b57cec5SDimitry Andric if (!E) 65960b57cec5SDimitry Andric return ExprError(); 65970b57cec5SDimitry Andric 65980b57cec5SDimitry Andric assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 65990b57cec5SDimitry Andric 66000b57cec5SDimitry Andric // If the result is a glvalue, we shouldn't bind it. 66010b57cec5SDimitry Andric if (!E->isRValue()) 66020b57cec5SDimitry Andric return E; 66030b57cec5SDimitry Andric 66040b57cec5SDimitry Andric // In ARC, calls that return a retainable type can return retained, 66050b57cec5SDimitry Andric // in which case we have to insert a consuming cast. 66060b57cec5SDimitry Andric if (getLangOpts().ObjCAutoRefCount && 66070b57cec5SDimitry Andric E->getType()->isObjCRetainableType()) { 66080b57cec5SDimitry Andric 66090b57cec5SDimitry Andric bool ReturnsRetained; 66100b57cec5SDimitry Andric 66110b57cec5SDimitry Andric // For actual calls, we compute this by examining the type of the 66120b57cec5SDimitry Andric // called value. 66130b57cec5SDimitry Andric if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 66140b57cec5SDimitry Andric Expr *Callee = Call->getCallee()->IgnoreParens(); 66150b57cec5SDimitry Andric QualType T = Callee->getType(); 66160b57cec5SDimitry Andric 66170b57cec5SDimitry Andric if (T == Context.BoundMemberTy) { 66180b57cec5SDimitry Andric // Handle pointer-to-members. 66190b57cec5SDimitry Andric if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 66200b57cec5SDimitry Andric T = BinOp->getRHS()->getType(); 66210b57cec5SDimitry Andric else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 66220b57cec5SDimitry Andric T = Mem->getMemberDecl()->getType(); 66230b57cec5SDimitry Andric } 66240b57cec5SDimitry Andric 66250b57cec5SDimitry Andric if (const PointerType *Ptr = T->getAs<PointerType>()) 66260b57cec5SDimitry Andric T = Ptr->getPointeeType(); 66270b57cec5SDimitry Andric else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 66280b57cec5SDimitry Andric T = Ptr->getPointeeType(); 66290b57cec5SDimitry Andric else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 66300b57cec5SDimitry Andric T = MemPtr->getPointeeType(); 66310b57cec5SDimitry Andric 66320b57cec5SDimitry Andric const FunctionType *FTy = T->getAs<FunctionType>(); 66330b57cec5SDimitry Andric assert(FTy && "call to value not of function type?"); 66340b57cec5SDimitry Andric ReturnsRetained = FTy->getExtInfo().getProducesResult(); 66350b57cec5SDimitry Andric 66360b57cec5SDimitry Andric // ActOnStmtExpr arranges things so that StmtExprs of retainable 66370b57cec5SDimitry Andric // type always produce a +1 object. 66380b57cec5SDimitry Andric } else if (isa<StmtExpr>(E)) { 66390b57cec5SDimitry Andric ReturnsRetained = true; 66400b57cec5SDimitry Andric 66410b57cec5SDimitry Andric // We hit this case with the lambda conversion-to-block optimization; 66420b57cec5SDimitry Andric // we don't want any extra casts here. 66430b57cec5SDimitry Andric } else if (isa<CastExpr>(E) && 66440b57cec5SDimitry Andric isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 66450b57cec5SDimitry Andric return E; 66460b57cec5SDimitry Andric 66470b57cec5SDimitry Andric // For message sends and property references, we try to find an 66480b57cec5SDimitry Andric // actual method. FIXME: we should infer retention by selector in 66490b57cec5SDimitry Andric // cases where we don't have an actual method. 66500b57cec5SDimitry Andric } else { 66510b57cec5SDimitry Andric ObjCMethodDecl *D = nullptr; 66520b57cec5SDimitry Andric if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 66530b57cec5SDimitry Andric D = Send->getMethodDecl(); 66540b57cec5SDimitry Andric } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 66550b57cec5SDimitry Andric D = BoxedExpr->getBoxingMethod(); 66560b57cec5SDimitry Andric } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 66570b57cec5SDimitry Andric // Don't do reclaims if we're using the zero-element array 66580b57cec5SDimitry Andric // constant. 66590b57cec5SDimitry Andric if (ArrayLit->getNumElements() == 0 && 66600b57cec5SDimitry Andric Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 66610b57cec5SDimitry Andric return E; 66620b57cec5SDimitry Andric 66630b57cec5SDimitry Andric D = ArrayLit->getArrayWithObjectsMethod(); 66640b57cec5SDimitry Andric } else if (ObjCDictionaryLiteral *DictLit 66650b57cec5SDimitry Andric = dyn_cast<ObjCDictionaryLiteral>(E)) { 66660b57cec5SDimitry Andric // Don't do reclaims if we're using the zero-element dictionary 66670b57cec5SDimitry Andric // constant. 66680b57cec5SDimitry Andric if (DictLit->getNumElements() == 0 && 66690b57cec5SDimitry Andric Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 66700b57cec5SDimitry Andric return E; 66710b57cec5SDimitry Andric 66720b57cec5SDimitry Andric D = DictLit->getDictWithObjectsMethod(); 66730b57cec5SDimitry Andric } 66740b57cec5SDimitry Andric 66750b57cec5SDimitry Andric ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 66760b57cec5SDimitry Andric 66770b57cec5SDimitry Andric // Don't do reclaims on performSelector calls; despite their 66780b57cec5SDimitry Andric // return type, the invoked method doesn't necessarily actually 66790b57cec5SDimitry Andric // return an object. 66800b57cec5SDimitry Andric if (!ReturnsRetained && 66810b57cec5SDimitry Andric D && D->getMethodFamily() == OMF_performSelector) 66820b57cec5SDimitry Andric return E; 66830b57cec5SDimitry Andric } 66840b57cec5SDimitry Andric 66850b57cec5SDimitry Andric // Don't reclaim an object of Class type. 66860b57cec5SDimitry Andric if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 66870b57cec5SDimitry Andric return E; 66880b57cec5SDimitry Andric 66890b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 66900b57cec5SDimitry Andric 66910b57cec5SDimitry Andric CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 66920b57cec5SDimitry Andric : CK_ARCReclaimReturnedObject); 66930b57cec5SDimitry Andric return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, 66940b57cec5SDimitry Andric VK_RValue); 66950b57cec5SDimitry Andric } 66960b57cec5SDimitry Andric 66970b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) 66980b57cec5SDimitry Andric return E; 66990b57cec5SDimitry Andric 67000b57cec5SDimitry Andric // Search for the base element type (cf. ASTContext::getBaseElementType) with 67010b57cec5SDimitry Andric // a fast path for the common case that the type is directly a RecordType. 67020b57cec5SDimitry Andric const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 67030b57cec5SDimitry Andric const RecordType *RT = nullptr; 67040b57cec5SDimitry Andric while (!RT) { 67050b57cec5SDimitry Andric switch (T->getTypeClass()) { 67060b57cec5SDimitry Andric case Type::Record: 67070b57cec5SDimitry Andric RT = cast<RecordType>(T); 67080b57cec5SDimitry Andric break; 67090b57cec5SDimitry Andric case Type::ConstantArray: 67100b57cec5SDimitry Andric case Type::IncompleteArray: 67110b57cec5SDimitry Andric case Type::VariableArray: 67120b57cec5SDimitry Andric case Type::DependentSizedArray: 67130b57cec5SDimitry Andric T = cast<ArrayType>(T)->getElementType().getTypePtr(); 67140b57cec5SDimitry Andric break; 67150b57cec5SDimitry Andric default: 67160b57cec5SDimitry Andric return E; 67170b57cec5SDimitry Andric } 67180b57cec5SDimitry Andric } 67190b57cec5SDimitry Andric 67200b57cec5SDimitry Andric // That should be enough to guarantee that this type is complete, if we're 67210b57cec5SDimitry Andric // not processing a decltype expression. 67220b57cec5SDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 67230b57cec5SDimitry Andric if (RD->isInvalidDecl() || RD->isDependentContext()) 67240b57cec5SDimitry Andric return E; 67250b57cec5SDimitry Andric 67260b57cec5SDimitry Andric bool IsDecltype = ExprEvalContexts.back().ExprContext == 67270b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Decltype; 67280b57cec5SDimitry Andric CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); 67290b57cec5SDimitry Andric 67300b57cec5SDimitry Andric if (Destructor) { 67310b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), Destructor); 67320b57cec5SDimitry Andric CheckDestructorAccess(E->getExprLoc(), Destructor, 67330b57cec5SDimitry Andric PDiag(diag::err_access_dtor_temp) 67340b57cec5SDimitry Andric << E->getType()); 67350b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 67360b57cec5SDimitry Andric return ExprError(); 67370b57cec5SDimitry Andric 67380b57cec5SDimitry Andric // If destructor is trivial, we can avoid the extra copy. 67390b57cec5SDimitry Andric if (Destructor->isTrivial()) 67400b57cec5SDimitry Andric return E; 67410b57cec5SDimitry Andric 67420b57cec5SDimitry Andric // We need a cleanup, but we don't need to remember the temporary. 67430b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 67440b57cec5SDimitry Andric } 67450b57cec5SDimitry Andric 67460b57cec5SDimitry Andric CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 67470b57cec5SDimitry Andric CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 67480b57cec5SDimitry Andric 67490b57cec5SDimitry Andric if (IsDecltype) 67500b57cec5SDimitry Andric ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 67510b57cec5SDimitry Andric 67520b57cec5SDimitry Andric return Bind; 67530b57cec5SDimitry Andric } 67540b57cec5SDimitry Andric 67550b57cec5SDimitry Andric ExprResult 67560b57cec5SDimitry Andric Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 67570b57cec5SDimitry Andric if (SubExpr.isInvalid()) 67580b57cec5SDimitry Andric return ExprError(); 67590b57cec5SDimitry Andric 67600b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(SubExpr.get()); 67610b57cec5SDimitry Andric } 67620b57cec5SDimitry Andric 67630b57cec5SDimitry Andric Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 67640b57cec5SDimitry Andric assert(SubExpr && "subexpression can't be null!"); 67650b57cec5SDimitry Andric 67660b57cec5SDimitry Andric CleanupVarDeclMarking(); 67670b57cec5SDimitry Andric 67680b57cec5SDimitry Andric unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 67690b57cec5SDimitry Andric assert(ExprCleanupObjects.size() >= FirstCleanup); 67700b57cec5SDimitry Andric assert(Cleanup.exprNeedsCleanups() || 67710b57cec5SDimitry Andric ExprCleanupObjects.size() == FirstCleanup); 67720b57cec5SDimitry Andric if (!Cleanup.exprNeedsCleanups()) 67730b57cec5SDimitry Andric return SubExpr; 67740b57cec5SDimitry Andric 67750b57cec5SDimitry Andric auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 67760b57cec5SDimitry Andric ExprCleanupObjects.size() - FirstCleanup); 67770b57cec5SDimitry Andric 67780b57cec5SDimitry Andric auto *E = ExprWithCleanups::Create( 67790b57cec5SDimitry Andric Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); 67800b57cec5SDimitry Andric DiscardCleanupsInEvaluationContext(); 67810b57cec5SDimitry Andric 67820b57cec5SDimitry Andric return E; 67830b57cec5SDimitry Andric } 67840b57cec5SDimitry Andric 67850b57cec5SDimitry Andric Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 67860b57cec5SDimitry Andric assert(SubStmt && "sub-statement can't be null!"); 67870b57cec5SDimitry Andric 67880b57cec5SDimitry Andric CleanupVarDeclMarking(); 67890b57cec5SDimitry Andric 67900b57cec5SDimitry Andric if (!Cleanup.exprNeedsCleanups()) 67910b57cec5SDimitry Andric return SubStmt; 67920b57cec5SDimitry Andric 67930b57cec5SDimitry Andric // FIXME: In order to attach the temporaries, wrap the statement into 67940b57cec5SDimitry Andric // a StmtExpr; currently this is only used for asm statements. 67950b57cec5SDimitry Andric // This is hacky, either create a new CXXStmtWithTemporaries statement or 67960b57cec5SDimitry Andric // a new AsmStmtWithTemporaries. 67970b57cec5SDimitry Andric CompoundStmt *CompStmt = CompoundStmt::Create( 67980b57cec5SDimitry Andric Context, SubStmt, SourceLocation(), SourceLocation()); 67998c27c554SDimitry Andric Expr *E = new (Context) 68008c27c554SDimitry Andric StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), 6801cd675bb6SDimitry Andric /*FIXME TemplateDepth=*/0); 68020b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(E); 68030b57cec5SDimitry Andric } 68040b57cec5SDimitry Andric 68050b57cec5SDimitry Andric /// Process the expression contained within a decltype. For such expressions, 68060b57cec5SDimitry Andric /// certain semantic checks on temporaries are delayed until this point, and 68070b57cec5SDimitry Andric /// are omitted for the 'topmost' call in the decltype expression. If the 68080b57cec5SDimitry Andric /// topmost call bound a temporary, strip that temporary off the expression. 68090b57cec5SDimitry Andric ExprResult Sema::ActOnDecltypeExpression(Expr *E) { 68100b57cec5SDimitry Andric assert(ExprEvalContexts.back().ExprContext == 68110b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Decltype && 68120b57cec5SDimitry Andric "not in a decltype expression"); 68130b57cec5SDimitry Andric 68140b57cec5SDimitry Andric ExprResult Result = CheckPlaceholderExpr(E); 68150b57cec5SDimitry Andric if (Result.isInvalid()) 68160b57cec5SDimitry Andric return ExprError(); 68170b57cec5SDimitry Andric E = Result.get(); 68180b57cec5SDimitry Andric 68190b57cec5SDimitry Andric // C++11 [expr.call]p11: 68200b57cec5SDimitry Andric // If a function call is a prvalue of object type, 68210b57cec5SDimitry Andric // -- if the function call is either 68220b57cec5SDimitry Andric // -- the operand of a decltype-specifier, or 68230b57cec5SDimitry Andric // -- the right operand of a comma operator that is the operand of a 68240b57cec5SDimitry Andric // decltype-specifier, 68250b57cec5SDimitry Andric // a temporary object is not introduced for the prvalue. 68260b57cec5SDimitry Andric 68270b57cec5SDimitry Andric // Recursively rebuild ParenExprs and comma expressions to strip out the 68280b57cec5SDimitry Andric // outermost CXXBindTemporaryExpr, if any. 68290b57cec5SDimitry Andric if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 68300b57cec5SDimitry Andric ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 68310b57cec5SDimitry Andric if (SubExpr.isInvalid()) 68320b57cec5SDimitry Andric return ExprError(); 68330b57cec5SDimitry Andric if (SubExpr.get() == PE->getSubExpr()) 68340b57cec5SDimitry Andric return E; 68350b57cec5SDimitry Andric return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 68360b57cec5SDimitry Andric } 68370b57cec5SDimitry Andric if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 68380b57cec5SDimitry Andric if (BO->getOpcode() == BO_Comma) { 68390b57cec5SDimitry Andric ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 68400b57cec5SDimitry Andric if (RHS.isInvalid()) 68410b57cec5SDimitry Andric return ExprError(); 68420b57cec5SDimitry Andric if (RHS.get() == BO->getRHS()) 68430b57cec5SDimitry Andric return E; 68440b57cec5SDimitry Andric return new (Context) BinaryOperator( 68450b57cec5SDimitry Andric BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(), 68460b57cec5SDimitry Andric BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures()); 68470b57cec5SDimitry Andric } 68480b57cec5SDimitry Andric } 68490b57cec5SDimitry Andric 68500b57cec5SDimitry Andric CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 68510b57cec5SDimitry Andric CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) 68520b57cec5SDimitry Andric : nullptr; 68530b57cec5SDimitry Andric if (TopCall) 68540b57cec5SDimitry Andric E = TopCall; 68550b57cec5SDimitry Andric else 68560b57cec5SDimitry Andric TopBind = nullptr; 68570b57cec5SDimitry Andric 68580b57cec5SDimitry Andric // Disable the special decltype handling now. 68590b57cec5SDimitry Andric ExprEvalContexts.back().ExprContext = 68600b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Other; 68610b57cec5SDimitry Andric 6862a7dea167SDimitry Andric Result = CheckUnevaluatedOperand(E); 6863a7dea167SDimitry Andric if (Result.isInvalid()) 6864a7dea167SDimitry Andric return ExprError(); 6865a7dea167SDimitry Andric E = Result.get(); 6866a7dea167SDimitry Andric 68670b57cec5SDimitry Andric // In MS mode, don't perform any extra checking of call return types within a 68680b57cec5SDimitry Andric // decltype expression. 68690b57cec5SDimitry Andric if (getLangOpts().MSVCCompat) 68700b57cec5SDimitry Andric return E; 68710b57cec5SDimitry Andric 68720b57cec5SDimitry Andric // Perform the semantic checks we delayed until this point. 68730b57cec5SDimitry Andric for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); 68740b57cec5SDimitry Andric I != N; ++I) { 68750b57cec5SDimitry Andric CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; 68760b57cec5SDimitry Andric if (Call == TopCall) 68770b57cec5SDimitry Andric continue; 68780b57cec5SDimitry Andric 68790b57cec5SDimitry Andric if (CheckCallReturnType(Call->getCallReturnType(Context), 68800b57cec5SDimitry Andric Call->getBeginLoc(), Call, Call->getDirectCallee())) 68810b57cec5SDimitry Andric return ExprError(); 68820b57cec5SDimitry Andric } 68830b57cec5SDimitry Andric 68840b57cec5SDimitry Andric // Now all relevant types are complete, check the destructors are accessible 68850b57cec5SDimitry Andric // and non-deleted, and annotate them on the temporaries. 68860b57cec5SDimitry Andric for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); 68870b57cec5SDimitry Andric I != N; ++I) { 68880b57cec5SDimitry Andric CXXBindTemporaryExpr *Bind = 68890b57cec5SDimitry Andric ExprEvalContexts.back().DelayedDecltypeBinds[I]; 68900b57cec5SDimitry Andric if (Bind == TopBind) 68910b57cec5SDimitry Andric continue; 68920b57cec5SDimitry Andric 68930b57cec5SDimitry Andric CXXTemporary *Temp = Bind->getTemporary(); 68940b57cec5SDimitry Andric 68950b57cec5SDimitry Andric CXXRecordDecl *RD = 68960b57cec5SDimitry Andric Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 68970b57cec5SDimitry Andric CXXDestructorDecl *Destructor = LookupDestructor(RD); 68980b57cec5SDimitry Andric Temp->setDestructor(Destructor); 68990b57cec5SDimitry Andric 69000b57cec5SDimitry Andric MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 69010b57cec5SDimitry Andric CheckDestructorAccess(Bind->getExprLoc(), Destructor, 69020b57cec5SDimitry Andric PDiag(diag::err_access_dtor_temp) 69030b57cec5SDimitry Andric << Bind->getType()); 69040b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) 69050b57cec5SDimitry Andric return ExprError(); 69060b57cec5SDimitry Andric 69070b57cec5SDimitry Andric // We need a cleanup, but we don't need to remember the temporary. 69080b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 69090b57cec5SDimitry Andric } 69100b57cec5SDimitry Andric 69110b57cec5SDimitry Andric // Possibly strip off the top CXXBindTemporaryExpr. 69120b57cec5SDimitry Andric return E; 69130b57cec5SDimitry Andric } 69140b57cec5SDimitry Andric 69150b57cec5SDimitry Andric /// Note a set of 'operator->' functions that were used for a member access. 69160b57cec5SDimitry Andric static void noteOperatorArrows(Sema &S, 69170b57cec5SDimitry Andric ArrayRef<FunctionDecl *> OperatorArrows) { 69180b57cec5SDimitry Andric unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; 69190b57cec5SDimitry Andric // FIXME: Make this configurable? 69200b57cec5SDimitry Andric unsigned Limit = 9; 69210b57cec5SDimitry Andric if (OperatorArrows.size() > Limit) { 69220b57cec5SDimitry Andric // Produce Limit-1 normal notes and one 'skipping' note. 69230b57cec5SDimitry Andric SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; 69240b57cec5SDimitry Andric SkipCount = OperatorArrows.size() - (Limit - 1); 69250b57cec5SDimitry Andric } 69260b57cec5SDimitry Andric 69270b57cec5SDimitry Andric for (unsigned I = 0; I < OperatorArrows.size(); /**/) { 69280b57cec5SDimitry Andric if (I == SkipStart) { 69290b57cec5SDimitry Andric S.Diag(OperatorArrows[I]->getLocation(), 69300b57cec5SDimitry Andric diag::note_operator_arrows_suppressed) 69310b57cec5SDimitry Andric << SkipCount; 69320b57cec5SDimitry Andric I += SkipCount; 69330b57cec5SDimitry Andric } else { 69340b57cec5SDimitry Andric S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) 69350b57cec5SDimitry Andric << OperatorArrows[I]->getCallResultType(); 69360b57cec5SDimitry Andric ++I; 69370b57cec5SDimitry Andric } 69380b57cec5SDimitry Andric } 69390b57cec5SDimitry Andric } 69400b57cec5SDimitry Andric 69410b57cec5SDimitry Andric ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, 69420b57cec5SDimitry Andric SourceLocation OpLoc, 69430b57cec5SDimitry Andric tok::TokenKind OpKind, 69440b57cec5SDimitry Andric ParsedType &ObjectType, 69450b57cec5SDimitry Andric bool &MayBePseudoDestructor) { 69460b57cec5SDimitry Andric // Since this might be a postfix expression, get rid of ParenListExprs. 69470b57cec5SDimitry Andric ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 69480b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 69490b57cec5SDimitry Andric Base = Result.get(); 69500b57cec5SDimitry Andric 69510b57cec5SDimitry Andric Result = CheckPlaceholderExpr(Base); 69520b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 69530b57cec5SDimitry Andric Base = Result.get(); 69540b57cec5SDimitry Andric 69550b57cec5SDimitry Andric QualType BaseType = Base->getType(); 69560b57cec5SDimitry Andric MayBePseudoDestructor = false; 69570b57cec5SDimitry Andric if (BaseType->isDependentType()) { 69580b57cec5SDimitry Andric // If we have a pointer to a dependent type and are using the -> operator, 69590b57cec5SDimitry Andric // the object type is the type that the pointer points to. We might still 69600b57cec5SDimitry Andric // have enough information about that type to do something useful. 69610b57cec5SDimitry Andric if (OpKind == tok::arrow) 69620b57cec5SDimitry Andric if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 69630b57cec5SDimitry Andric BaseType = Ptr->getPointeeType(); 69640b57cec5SDimitry Andric 69650b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 69660b57cec5SDimitry Andric MayBePseudoDestructor = true; 69670b57cec5SDimitry Andric return Base; 69680b57cec5SDimitry Andric } 69690b57cec5SDimitry Andric 69700b57cec5SDimitry Andric // C++ [over.match.oper]p8: 69710b57cec5SDimitry Andric // [...] When operator->returns, the operator-> is applied to the value 69720b57cec5SDimitry Andric // returned, with the original second operand. 69730b57cec5SDimitry Andric if (OpKind == tok::arrow) { 69740b57cec5SDimitry Andric QualType StartingType = BaseType; 69750b57cec5SDimitry Andric bool NoArrowOperatorFound = false; 69760b57cec5SDimitry Andric bool FirstIteration = true; 69770b57cec5SDimitry Andric FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); 69780b57cec5SDimitry Andric // The set of types we've considered so far. 69790b57cec5SDimitry Andric llvm::SmallPtrSet<CanQualType,8> CTypes; 69800b57cec5SDimitry Andric SmallVector<FunctionDecl*, 8> OperatorArrows; 69810b57cec5SDimitry Andric CTypes.insert(Context.getCanonicalType(BaseType)); 69820b57cec5SDimitry Andric 69830b57cec5SDimitry Andric while (BaseType->isRecordType()) { 69840b57cec5SDimitry Andric if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { 69850b57cec5SDimitry Andric Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) 69860b57cec5SDimitry Andric << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); 69870b57cec5SDimitry Andric noteOperatorArrows(*this, OperatorArrows); 69880b57cec5SDimitry Andric Diag(OpLoc, diag::note_operator_arrow_depth) 69890b57cec5SDimitry Andric << getLangOpts().ArrowDepth; 69900b57cec5SDimitry Andric return ExprError(); 69910b57cec5SDimitry Andric } 69920b57cec5SDimitry Andric 69930b57cec5SDimitry Andric Result = BuildOverloadedArrowExpr( 69940b57cec5SDimitry Andric S, Base, OpLoc, 69950b57cec5SDimitry Andric // When in a template specialization and on the first loop iteration, 69960b57cec5SDimitry Andric // potentially give the default diagnostic (with the fixit in a 69970b57cec5SDimitry Andric // separate note) instead of having the error reported back to here 69980b57cec5SDimitry Andric // and giving a diagnostic with a fixit attached to the error itself. 69990b57cec5SDimitry Andric (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) 70000b57cec5SDimitry Andric ? nullptr 70010b57cec5SDimitry Andric : &NoArrowOperatorFound); 70020b57cec5SDimitry Andric if (Result.isInvalid()) { 70030b57cec5SDimitry Andric if (NoArrowOperatorFound) { 70040b57cec5SDimitry Andric if (FirstIteration) { 70050b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 70060b57cec5SDimitry Andric << BaseType << 1 << Base->getSourceRange() 70070b57cec5SDimitry Andric << FixItHint::CreateReplacement(OpLoc, "."); 70080b57cec5SDimitry Andric OpKind = tok::period; 70090b57cec5SDimitry Andric break; 70100b57cec5SDimitry Andric } 70110b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 70120b57cec5SDimitry Andric << BaseType << Base->getSourceRange(); 70130b57cec5SDimitry Andric CallExpr *CE = dyn_cast<CallExpr>(Base); 70140b57cec5SDimitry Andric if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { 70150b57cec5SDimitry Andric Diag(CD->getBeginLoc(), 70160b57cec5SDimitry Andric diag::note_member_reference_arrow_from_operator_arrow); 70170b57cec5SDimitry Andric } 70180b57cec5SDimitry Andric } 70190b57cec5SDimitry Andric return ExprError(); 70200b57cec5SDimitry Andric } 70210b57cec5SDimitry Andric Base = Result.get(); 70220b57cec5SDimitry Andric if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 70230b57cec5SDimitry Andric OperatorArrows.push_back(OpCall->getDirectCallee()); 70240b57cec5SDimitry Andric BaseType = Base->getType(); 70250b57cec5SDimitry Andric CanQualType CBaseType = Context.getCanonicalType(BaseType); 70260b57cec5SDimitry Andric if (!CTypes.insert(CBaseType).second) { 70270b57cec5SDimitry Andric Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; 70280b57cec5SDimitry Andric noteOperatorArrows(*this, OperatorArrows); 70290b57cec5SDimitry Andric return ExprError(); 70300b57cec5SDimitry Andric } 70310b57cec5SDimitry Andric FirstIteration = false; 70320b57cec5SDimitry Andric } 70330b57cec5SDimitry Andric 70340b57cec5SDimitry Andric if (OpKind == tok::arrow) { 70350b57cec5SDimitry Andric if (BaseType->isPointerType()) 70360b57cec5SDimitry Andric BaseType = BaseType->getPointeeType(); 70370b57cec5SDimitry Andric else if (auto *AT = Context.getAsArrayType(BaseType)) 70380b57cec5SDimitry Andric BaseType = AT->getElementType(); 70390b57cec5SDimitry Andric } 70400b57cec5SDimitry Andric } 70410b57cec5SDimitry Andric 70420b57cec5SDimitry Andric // Objective-C properties allow "." access on Objective-C pointer types, 70430b57cec5SDimitry Andric // so adjust the base type to the object type itself. 70440b57cec5SDimitry Andric if (BaseType->isObjCObjectPointerType()) 70450b57cec5SDimitry Andric BaseType = BaseType->getPointeeType(); 70460b57cec5SDimitry Andric 70470b57cec5SDimitry Andric // C++ [basic.lookup.classref]p2: 70480b57cec5SDimitry Andric // [...] If the type of the object expression is of pointer to scalar 70490b57cec5SDimitry Andric // type, the unqualified-id is looked up in the context of the complete 70500b57cec5SDimitry Andric // postfix-expression. 70510b57cec5SDimitry Andric // 70520b57cec5SDimitry Andric // This also indicates that we could be parsing a pseudo-destructor-name. 70530b57cec5SDimitry Andric // Note that Objective-C class and object types can be pseudo-destructor 70540b57cec5SDimitry Andric // expressions or normal member (ivar or property) access expressions, and 70550b57cec5SDimitry Andric // it's legal for the type to be incomplete if this is a pseudo-destructor 70560b57cec5SDimitry Andric // call. We'll do more incomplete-type checks later in the lookup process, 70570b57cec5SDimitry Andric // so just skip this check for ObjC types. 70580b57cec5SDimitry Andric if (!BaseType->isRecordType()) { 70590b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 70600b57cec5SDimitry Andric MayBePseudoDestructor = true; 70610b57cec5SDimitry Andric return Base; 70620b57cec5SDimitry Andric } 70630b57cec5SDimitry Andric 70640b57cec5SDimitry Andric // The object type must be complete (or dependent), or 70650b57cec5SDimitry Andric // C++11 [expr.prim.general]p3: 70660b57cec5SDimitry Andric // Unlike the object expression in other contexts, *this is not required to 70670b57cec5SDimitry Andric // be of complete type for purposes of class member access (5.2.5) outside 70680b57cec5SDimitry Andric // the member function body. 70690b57cec5SDimitry Andric if (!BaseType->isDependentType() && 70700b57cec5SDimitry Andric !isThisOutsideMemberFunctionBody(BaseType) && 70710b57cec5SDimitry Andric RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access)) 70720b57cec5SDimitry Andric return ExprError(); 70730b57cec5SDimitry Andric 70740b57cec5SDimitry Andric // C++ [basic.lookup.classref]p2: 70750b57cec5SDimitry Andric // If the id-expression in a class member access (5.2.5) is an 70760b57cec5SDimitry Andric // unqualified-id, and the type of the object expression is of a class 70770b57cec5SDimitry Andric // type C (or of pointer to a class type C), the unqualified-id is looked 70780b57cec5SDimitry Andric // up in the scope of class C. [...] 70790b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 70800b57cec5SDimitry Andric return Base; 70810b57cec5SDimitry Andric } 70820b57cec5SDimitry Andric 70830b57cec5SDimitry Andric static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base, 70840b57cec5SDimitry Andric tok::TokenKind& OpKind, SourceLocation OpLoc) { 70850b57cec5SDimitry Andric if (Base->hasPlaceholderType()) { 70860b57cec5SDimitry Andric ExprResult result = S.CheckPlaceholderExpr(Base); 70870b57cec5SDimitry Andric if (result.isInvalid()) return true; 70880b57cec5SDimitry Andric Base = result.get(); 70890b57cec5SDimitry Andric } 70900b57cec5SDimitry Andric ObjectType = Base->getType(); 70910b57cec5SDimitry Andric 70920b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 70930b57cec5SDimitry Andric // The left-hand side of the dot operator shall be of scalar type. The 70940b57cec5SDimitry Andric // left-hand side of the arrow operator shall be of pointer to scalar type. 70950b57cec5SDimitry Andric // This scalar type is the object type. 70960b57cec5SDimitry Andric // Note that this is rather different from the normal handling for the 70970b57cec5SDimitry Andric // arrow operator. 70980b57cec5SDimitry Andric if (OpKind == tok::arrow) { 70990b57cec5SDimitry Andric if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 71000b57cec5SDimitry Andric ObjectType = Ptr->getPointeeType(); 71010b57cec5SDimitry Andric } else if (!Base->isTypeDependent()) { 71020b57cec5SDimitry Andric // The user wrote "p->" when they probably meant "p."; fix it. 71030b57cec5SDimitry Andric S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 71040b57cec5SDimitry Andric << ObjectType << true 71050b57cec5SDimitry Andric << FixItHint::CreateReplacement(OpLoc, "."); 71060b57cec5SDimitry Andric if (S.isSFINAEContext()) 71070b57cec5SDimitry Andric return true; 71080b57cec5SDimitry Andric 71090b57cec5SDimitry Andric OpKind = tok::period; 71100b57cec5SDimitry Andric } 71110b57cec5SDimitry Andric } 71120b57cec5SDimitry Andric 71130b57cec5SDimitry Andric return false; 71140b57cec5SDimitry Andric } 71150b57cec5SDimitry Andric 71160b57cec5SDimitry Andric /// Check if it's ok to try and recover dot pseudo destructor calls on 71170b57cec5SDimitry Andric /// pointer objects. 71180b57cec5SDimitry Andric static bool 71190b57cec5SDimitry Andric canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, 71200b57cec5SDimitry Andric QualType DestructedType) { 71210b57cec5SDimitry Andric // If this is a record type, check if its destructor is callable. 71220b57cec5SDimitry Andric if (auto *RD = DestructedType->getAsCXXRecordDecl()) { 71230b57cec5SDimitry Andric if (RD->hasDefinition()) 71240b57cec5SDimitry Andric if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) 71250b57cec5SDimitry Andric return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); 71260b57cec5SDimitry Andric return false; 71270b57cec5SDimitry Andric } 71280b57cec5SDimitry Andric 71290b57cec5SDimitry Andric // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. 71300b57cec5SDimitry Andric return DestructedType->isDependentType() || DestructedType->isScalarType() || 71310b57cec5SDimitry Andric DestructedType->isVectorType(); 71320b57cec5SDimitry Andric } 71330b57cec5SDimitry Andric 71340b57cec5SDimitry Andric ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 71350b57cec5SDimitry Andric SourceLocation OpLoc, 71360b57cec5SDimitry Andric tok::TokenKind OpKind, 71370b57cec5SDimitry Andric const CXXScopeSpec &SS, 71380b57cec5SDimitry Andric TypeSourceInfo *ScopeTypeInfo, 71390b57cec5SDimitry Andric SourceLocation CCLoc, 71400b57cec5SDimitry Andric SourceLocation TildeLoc, 71410b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed) { 71420b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 71430b57cec5SDimitry Andric 71440b57cec5SDimitry Andric QualType ObjectType; 71450b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 71460b57cec5SDimitry Andric return ExprError(); 71470b57cec5SDimitry Andric 71480b57cec5SDimitry Andric if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && 71490b57cec5SDimitry Andric !ObjectType->isVectorType()) { 71500b57cec5SDimitry Andric if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) 71510b57cec5SDimitry Andric Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 71520b57cec5SDimitry Andric else { 71530b57cec5SDimitry Andric Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 71540b57cec5SDimitry Andric << ObjectType << Base->getSourceRange(); 71550b57cec5SDimitry Andric return ExprError(); 71560b57cec5SDimitry Andric } 71570b57cec5SDimitry Andric } 71580b57cec5SDimitry Andric 71590b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 71600b57cec5SDimitry Andric // [...] The cv-unqualified versions of the object type and of the type 71610b57cec5SDimitry Andric // designated by the pseudo-destructor-name shall be the same type. 71620b57cec5SDimitry Andric if (DestructedTypeInfo) { 71630b57cec5SDimitry Andric QualType DestructedType = DestructedTypeInfo->getType(); 71640b57cec5SDimitry Andric SourceLocation DestructedTypeStart 71650b57cec5SDimitry Andric = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 71660b57cec5SDimitry Andric if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 71670b57cec5SDimitry Andric if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 71680b57cec5SDimitry Andric // Detect dot pseudo destructor calls on pointer objects, e.g.: 71690b57cec5SDimitry Andric // Foo *foo; 71700b57cec5SDimitry Andric // foo.~Foo(); 71710b57cec5SDimitry Andric if (OpKind == tok::period && ObjectType->isPointerType() && 71720b57cec5SDimitry Andric Context.hasSameUnqualifiedType(DestructedType, 71730b57cec5SDimitry Andric ObjectType->getPointeeType())) { 71740b57cec5SDimitry Andric auto Diagnostic = 71750b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 71760b57cec5SDimitry Andric << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); 71770b57cec5SDimitry Andric 71780b57cec5SDimitry Andric // Issue a fixit only when the destructor is valid. 71790b57cec5SDimitry Andric if (canRecoverDotPseudoDestructorCallsOnPointerObjects( 71800b57cec5SDimitry Andric *this, DestructedType)) 71810b57cec5SDimitry Andric Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); 71820b57cec5SDimitry Andric 71830b57cec5SDimitry Andric // Recover by setting the object type to the destructed type and the 71840b57cec5SDimitry Andric // operator to '->'. 71850b57cec5SDimitry Andric ObjectType = DestructedType; 71860b57cec5SDimitry Andric OpKind = tok::arrow; 71870b57cec5SDimitry Andric } else { 71880b57cec5SDimitry Andric Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 71890b57cec5SDimitry Andric << ObjectType << DestructedType << Base->getSourceRange() 71900b57cec5SDimitry Andric << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 71910b57cec5SDimitry Andric 71920b57cec5SDimitry Andric // Recover by setting the destructed type to the object type. 71930b57cec5SDimitry Andric DestructedType = ObjectType; 71940b57cec5SDimitry Andric DestructedTypeInfo = 71950b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); 71960b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 71970b57cec5SDimitry Andric } 71980b57cec5SDimitry Andric } else if (DestructedType.getObjCLifetime() != 71990b57cec5SDimitry Andric ObjectType.getObjCLifetime()) { 72000b57cec5SDimitry Andric 72010b57cec5SDimitry Andric if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 72020b57cec5SDimitry Andric // Okay: just pretend that the user provided the correctly-qualified 72030b57cec5SDimitry Andric // type. 72040b57cec5SDimitry Andric } else { 72050b57cec5SDimitry Andric Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 72060b57cec5SDimitry Andric << ObjectType << DestructedType << Base->getSourceRange() 72070b57cec5SDimitry Andric << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 72080b57cec5SDimitry Andric } 72090b57cec5SDimitry Andric 72100b57cec5SDimitry Andric // Recover by setting the destructed type to the object type. 72110b57cec5SDimitry Andric DestructedType = ObjectType; 72120b57cec5SDimitry Andric DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 72130b57cec5SDimitry Andric DestructedTypeStart); 72140b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 72150b57cec5SDimitry Andric } 72160b57cec5SDimitry Andric } 72170b57cec5SDimitry Andric } 72180b57cec5SDimitry Andric 72190b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 72200b57cec5SDimitry Andric // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 72210b57cec5SDimitry Andric // form 72220b57cec5SDimitry Andric // 72230b57cec5SDimitry Andric // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 72240b57cec5SDimitry Andric // 72250b57cec5SDimitry Andric // shall designate the same scalar type. 72260b57cec5SDimitry Andric if (ScopeTypeInfo) { 72270b57cec5SDimitry Andric QualType ScopeType = ScopeTypeInfo->getType(); 72280b57cec5SDimitry Andric if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 72290b57cec5SDimitry Andric !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 72300b57cec5SDimitry Andric 72310b57cec5SDimitry Andric Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 72320b57cec5SDimitry Andric diag::err_pseudo_dtor_type_mismatch) 72330b57cec5SDimitry Andric << ObjectType << ScopeType << Base->getSourceRange() 72340b57cec5SDimitry Andric << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 72350b57cec5SDimitry Andric 72360b57cec5SDimitry Andric ScopeType = QualType(); 72370b57cec5SDimitry Andric ScopeTypeInfo = nullptr; 72380b57cec5SDimitry Andric } 72390b57cec5SDimitry Andric } 72400b57cec5SDimitry Andric 72410b57cec5SDimitry Andric Expr *Result 72420b57cec5SDimitry Andric = new (Context) CXXPseudoDestructorExpr(Context, Base, 72430b57cec5SDimitry Andric OpKind == tok::arrow, OpLoc, 72440b57cec5SDimitry Andric SS.getWithLocInContext(Context), 72450b57cec5SDimitry Andric ScopeTypeInfo, 72460b57cec5SDimitry Andric CCLoc, 72470b57cec5SDimitry Andric TildeLoc, 72480b57cec5SDimitry Andric Destructed); 72490b57cec5SDimitry Andric 72500b57cec5SDimitry Andric return Result; 72510b57cec5SDimitry Andric } 72520b57cec5SDimitry Andric 72530b57cec5SDimitry Andric ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 72540b57cec5SDimitry Andric SourceLocation OpLoc, 72550b57cec5SDimitry Andric tok::TokenKind OpKind, 72560b57cec5SDimitry Andric CXXScopeSpec &SS, 72570b57cec5SDimitry Andric UnqualifiedId &FirstTypeName, 72580b57cec5SDimitry Andric SourceLocation CCLoc, 72590b57cec5SDimitry Andric SourceLocation TildeLoc, 72600b57cec5SDimitry Andric UnqualifiedId &SecondTypeName) { 72610b57cec5SDimitry Andric assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 72620b57cec5SDimitry Andric FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 72630b57cec5SDimitry Andric "Invalid first type name in pseudo-destructor"); 72640b57cec5SDimitry Andric assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 72650b57cec5SDimitry Andric SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 72660b57cec5SDimitry Andric "Invalid second type name in pseudo-destructor"); 72670b57cec5SDimitry Andric 72680b57cec5SDimitry Andric QualType ObjectType; 72690b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 72700b57cec5SDimitry Andric return ExprError(); 72710b57cec5SDimitry Andric 72720b57cec5SDimitry Andric // Compute the object type that we should use for name lookup purposes. Only 72730b57cec5SDimitry Andric // record types and dependent types matter. 72740b57cec5SDimitry Andric ParsedType ObjectTypePtrForLookup; 72750b57cec5SDimitry Andric if (!SS.isSet()) { 72760b57cec5SDimitry Andric if (ObjectType->isRecordType()) 72770b57cec5SDimitry Andric ObjectTypePtrForLookup = ParsedType::make(ObjectType); 72780b57cec5SDimitry Andric else if (ObjectType->isDependentType()) 72790b57cec5SDimitry Andric ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 72800b57cec5SDimitry Andric } 72810b57cec5SDimitry Andric 72820b57cec5SDimitry Andric // Convert the name of the type being destructed (following the ~) into a 72830b57cec5SDimitry Andric // type (with source-location information). 72840b57cec5SDimitry Andric QualType DestructedType; 72850b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = nullptr; 72860b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed; 72870b57cec5SDimitry Andric if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 72880b57cec5SDimitry Andric ParsedType T = getTypeName(*SecondTypeName.Identifier, 72890b57cec5SDimitry Andric SecondTypeName.StartLocation, 72900b57cec5SDimitry Andric S, &SS, true, false, ObjectTypePtrForLookup, 72910b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 72920b57cec5SDimitry Andric if (!T && 72930b57cec5SDimitry Andric ((SS.isSet() && !computeDeclContext(SS, false)) || 72940b57cec5SDimitry Andric (!SS.isSet() && ObjectType->isDependentType()))) { 72950b57cec5SDimitry Andric // The name of the type being destroyed is a dependent name, and we 72960b57cec5SDimitry Andric // couldn't find anything useful in scope. Just store the identifier and 72970b57cec5SDimitry Andric // it's location, and we'll perform (qualified) name lookup again at 72980b57cec5SDimitry Andric // template instantiation time. 72990b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 73000b57cec5SDimitry Andric SecondTypeName.StartLocation); 73010b57cec5SDimitry Andric } else if (!T) { 73020b57cec5SDimitry Andric Diag(SecondTypeName.StartLocation, 73030b57cec5SDimitry Andric diag::err_pseudo_dtor_destructor_non_type) 73040b57cec5SDimitry Andric << SecondTypeName.Identifier << ObjectType; 73050b57cec5SDimitry Andric if (isSFINAEContext()) 73060b57cec5SDimitry Andric return ExprError(); 73070b57cec5SDimitry Andric 73080b57cec5SDimitry Andric // Recover by assuming we had the right type all along. 73090b57cec5SDimitry Andric DestructedType = ObjectType; 73100b57cec5SDimitry Andric } else 73110b57cec5SDimitry Andric DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 73120b57cec5SDimitry Andric } else { 73130b57cec5SDimitry Andric // Resolve the template-id to a type. 73140b57cec5SDimitry Andric TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 73150b57cec5SDimitry Andric ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 73160b57cec5SDimitry Andric TemplateId->NumArgs); 73170b57cec5SDimitry Andric TypeResult T = ActOnTemplateIdType(S, 731855e4f9d5SDimitry Andric SS, 73190b57cec5SDimitry Andric TemplateId->TemplateKWLoc, 73200b57cec5SDimitry Andric TemplateId->Template, 73210b57cec5SDimitry Andric TemplateId->Name, 73220b57cec5SDimitry Andric TemplateId->TemplateNameLoc, 73230b57cec5SDimitry Andric TemplateId->LAngleLoc, 73240b57cec5SDimitry Andric TemplateArgsPtr, 73250b57cec5SDimitry Andric TemplateId->RAngleLoc, 73260b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 73270b57cec5SDimitry Andric if (T.isInvalid() || !T.get()) { 73280b57cec5SDimitry Andric // Recover by assuming we had the right type all along. 73290b57cec5SDimitry Andric DestructedType = ObjectType; 73300b57cec5SDimitry Andric } else 73310b57cec5SDimitry Andric DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 73320b57cec5SDimitry Andric } 73330b57cec5SDimitry Andric 73340b57cec5SDimitry Andric // If we've performed some kind of recovery, (re-)build the type source 73350b57cec5SDimitry Andric // information. 73360b57cec5SDimitry Andric if (!DestructedType.isNull()) { 73370b57cec5SDimitry Andric if (!DestructedTypeInfo) 73380b57cec5SDimitry Andric DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 73390b57cec5SDimitry Andric SecondTypeName.StartLocation); 73400b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 73410b57cec5SDimitry Andric } 73420b57cec5SDimitry Andric 73430b57cec5SDimitry Andric // Convert the name of the scope type (the type prior to '::') into a type. 73440b57cec5SDimitry Andric TypeSourceInfo *ScopeTypeInfo = nullptr; 73450b57cec5SDimitry Andric QualType ScopeType; 73460b57cec5SDimitry Andric if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 73470b57cec5SDimitry Andric FirstTypeName.Identifier) { 73480b57cec5SDimitry Andric if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 73490b57cec5SDimitry Andric ParsedType T = getTypeName(*FirstTypeName.Identifier, 73500b57cec5SDimitry Andric FirstTypeName.StartLocation, 73510b57cec5SDimitry Andric S, &SS, true, false, ObjectTypePtrForLookup, 73520b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 73530b57cec5SDimitry Andric if (!T) { 73540b57cec5SDimitry Andric Diag(FirstTypeName.StartLocation, 73550b57cec5SDimitry Andric diag::err_pseudo_dtor_destructor_non_type) 73560b57cec5SDimitry Andric << FirstTypeName.Identifier << ObjectType; 73570b57cec5SDimitry Andric 73580b57cec5SDimitry Andric if (isSFINAEContext()) 73590b57cec5SDimitry Andric return ExprError(); 73600b57cec5SDimitry Andric 73610b57cec5SDimitry Andric // Just drop this type. It's unnecessary anyway. 73620b57cec5SDimitry Andric ScopeType = QualType(); 73630b57cec5SDimitry Andric } else 73640b57cec5SDimitry Andric ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 73650b57cec5SDimitry Andric } else { 73660b57cec5SDimitry Andric // Resolve the template-id to a type. 73670b57cec5SDimitry Andric TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 73680b57cec5SDimitry Andric ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 73690b57cec5SDimitry Andric TemplateId->NumArgs); 73700b57cec5SDimitry Andric TypeResult T = ActOnTemplateIdType(S, 737155e4f9d5SDimitry Andric SS, 73720b57cec5SDimitry Andric TemplateId->TemplateKWLoc, 73730b57cec5SDimitry Andric TemplateId->Template, 73740b57cec5SDimitry Andric TemplateId->Name, 73750b57cec5SDimitry Andric TemplateId->TemplateNameLoc, 73760b57cec5SDimitry Andric TemplateId->LAngleLoc, 73770b57cec5SDimitry Andric TemplateArgsPtr, 73780b57cec5SDimitry Andric TemplateId->RAngleLoc, 73790b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 73800b57cec5SDimitry Andric if (T.isInvalid() || !T.get()) { 73810b57cec5SDimitry Andric // Recover by dropping this type. 73820b57cec5SDimitry Andric ScopeType = QualType(); 73830b57cec5SDimitry Andric } else 73840b57cec5SDimitry Andric ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 73850b57cec5SDimitry Andric } 73860b57cec5SDimitry Andric } 73870b57cec5SDimitry Andric 73880b57cec5SDimitry Andric if (!ScopeType.isNull() && !ScopeTypeInfo) 73890b57cec5SDimitry Andric ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 73900b57cec5SDimitry Andric FirstTypeName.StartLocation); 73910b57cec5SDimitry Andric 73920b57cec5SDimitry Andric 73930b57cec5SDimitry Andric return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 73940b57cec5SDimitry Andric ScopeTypeInfo, CCLoc, TildeLoc, 73950b57cec5SDimitry Andric Destructed); 73960b57cec5SDimitry Andric } 73970b57cec5SDimitry Andric 73980b57cec5SDimitry Andric ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 73990b57cec5SDimitry Andric SourceLocation OpLoc, 74000b57cec5SDimitry Andric tok::TokenKind OpKind, 74010b57cec5SDimitry Andric SourceLocation TildeLoc, 74020b57cec5SDimitry Andric const DeclSpec& DS) { 74030b57cec5SDimitry Andric QualType ObjectType; 74040b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 74050b57cec5SDimitry Andric return ExprError(); 74060b57cec5SDimitry Andric 74070b57cec5SDimitry Andric QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(), 74080b57cec5SDimitry Andric false); 74090b57cec5SDimitry Andric 74100b57cec5SDimitry Andric TypeLocBuilder TLB; 74110b57cec5SDimitry Andric DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 74120b57cec5SDimitry Andric DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc()); 74130b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 74140b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 74150b57cec5SDimitry Andric 74160b57cec5SDimitry Andric return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 74170b57cec5SDimitry Andric nullptr, SourceLocation(), TildeLoc, 74180b57cec5SDimitry Andric Destructed); 74190b57cec5SDimitry Andric } 74200b57cec5SDimitry Andric 74210b57cec5SDimitry Andric ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 74220b57cec5SDimitry Andric CXXConversionDecl *Method, 74230b57cec5SDimitry Andric bool HadMultipleCandidates) { 74240b57cec5SDimitry Andric // Convert the expression to match the conversion function's implicit object 74250b57cec5SDimitry Andric // parameter. 74260b57cec5SDimitry Andric ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr, 74270b57cec5SDimitry Andric FoundDecl, Method); 74280b57cec5SDimitry Andric if (Exp.isInvalid()) 74290b57cec5SDimitry Andric return true; 74300b57cec5SDimitry Andric 74310b57cec5SDimitry Andric if (Method->getParent()->isLambda() && 74320b57cec5SDimitry Andric Method->getConversionType()->isBlockPointerType()) { 7433a7dea167SDimitry Andric // This is a lambda conversion to block pointer; check if the argument 74340b57cec5SDimitry Andric // was a LambdaExpr. 74350b57cec5SDimitry Andric Expr *SubE = E; 74360b57cec5SDimitry Andric CastExpr *CE = dyn_cast<CastExpr>(SubE); 74370b57cec5SDimitry Andric if (CE && CE->getCastKind() == CK_NoOp) 74380b57cec5SDimitry Andric SubE = CE->getSubExpr(); 74390b57cec5SDimitry Andric SubE = SubE->IgnoreParens(); 74400b57cec5SDimitry Andric if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 74410b57cec5SDimitry Andric SubE = BE->getSubExpr(); 74420b57cec5SDimitry Andric if (isa<LambdaExpr>(SubE)) { 74430b57cec5SDimitry Andric // For the conversion to block pointer on a lambda expression, we 74440b57cec5SDimitry Andric // construct a special BlockLiteral instead; this doesn't really make 74450b57cec5SDimitry Andric // a difference in ARC, but outside of ARC the resulting block literal 74460b57cec5SDimitry Andric // follows the normal lifetime rules for block literals instead of being 74470b57cec5SDimitry Andric // autoreleased. 74480b57cec5SDimitry Andric DiagnosticErrorTrap Trap(Diags); 74490b57cec5SDimitry Andric PushExpressionEvaluationContext( 74500b57cec5SDimitry Andric ExpressionEvaluationContext::PotentiallyEvaluated); 74510b57cec5SDimitry Andric ExprResult BlockExp = BuildBlockForLambdaConversion( 74520b57cec5SDimitry Andric Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); 74530b57cec5SDimitry Andric PopExpressionEvaluationContext(); 74540b57cec5SDimitry Andric 74550b57cec5SDimitry Andric if (BlockExp.isInvalid()) 74560b57cec5SDimitry Andric Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); 74570b57cec5SDimitry Andric return BlockExp; 74580b57cec5SDimitry Andric } 74590b57cec5SDimitry Andric } 74600b57cec5SDimitry Andric 74610b57cec5SDimitry Andric MemberExpr *ME = 74620b57cec5SDimitry Andric BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), 74630b57cec5SDimitry Andric NestedNameSpecifierLoc(), SourceLocation(), Method, 74640b57cec5SDimitry Andric DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), 74650b57cec5SDimitry Andric HadMultipleCandidates, DeclarationNameInfo(), 74660b57cec5SDimitry Andric Context.BoundMemberTy, VK_RValue, OK_Ordinary); 74670b57cec5SDimitry Andric 74680b57cec5SDimitry Andric QualType ResultType = Method->getReturnType(); 74690b57cec5SDimitry Andric ExprValueKind VK = Expr::getValueKindForType(ResultType); 74700b57cec5SDimitry Andric ResultType = ResultType.getNonLValueExprType(Context); 74710b57cec5SDimitry Andric 74720b57cec5SDimitry Andric CXXMemberCallExpr *CE = CXXMemberCallExpr::Create( 74730b57cec5SDimitry Andric Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc()); 74740b57cec5SDimitry Andric 74750b57cec5SDimitry Andric if (CheckFunctionCall(Method, CE, 74760b57cec5SDimitry Andric Method->getType()->castAs<FunctionProtoType>())) 74770b57cec5SDimitry Andric return ExprError(); 74780b57cec5SDimitry Andric 74790b57cec5SDimitry Andric return CE; 74800b57cec5SDimitry Andric } 74810b57cec5SDimitry Andric 74820b57cec5SDimitry Andric ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 74830b57cec5SDimitry Andric SourceLocation RParen) { 74840b57cec5SDimitry Andric // If the operand is an unresolved lookup expression, the expression is ill- 74850b57cec5SDimitry Andric // formed per [over.over]p1, because overloaded function names cannot be used 74860b57cec5SDimitry Andric // without arguments except in explicit contexts. 74870b57cec5SDimitry Andric ExprResult R = CheckPlaceholderExpr(Operand); 74880b57cec5SDimitry Andric if (R.isInvalid()) 74890b57cec5SDimitry Andric return R; 74900b57cec5SDimitry Andric 7491a7dea167SDimitry Andric R = CheckUnevaluatedOperand(R.get()); 7492a7dea167SDimitry Andric if (R.isInvalid()) 7493a7dea167SDimitry Andric return ExprError(); 7494a7dea167SDimitry Andric 74950b57cec5SDimitry Andric Operand = R.get(); 74960b57cec5SDimitry Andric 74970b57cec5SDimitry Andric if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) { 74980b57cec5SDimitry Andric // The expression operand for noexcept is in an unevaluated expression 74990b57cec5SDimitry Andric // context, so side effects could result in unintended consequences. 75000b57cec5SDimitry Andric Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); 75010b57cec5SDimitry Andric } 75020b57cec5SDimitry Andric 75030b57cec5SDimitry Andric CanThrowResult CanThrow = canThrow(Operand); 75040b57cec5SDimitry Andric return new (Context) 75050b57cec5SDimitry Andric CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); 75060b57cec5SDimitry Andric } 75070b57cec5SDimitry Andric 75080b57cec5SDimitry Andric ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 75090b57cec5SDimitry Andric Expr *Operand, SourceLocation RParen) { 75100b57cec5SDimitry Andric return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 75110b57cec5SDimitry Andric } 75120b57cec5SDimitry Andric 75130b57cec5SDimitry Andric static bool IsSpecialDiscardedValue(Expr *E) { 75140b57cec5SDimitry Andric // In C++11, discarded-value expressions of a certain form are special, 75150b57cec5SDimitry Andric // according to [expr]p10: 75160b57cec5SDimitry Andric // The lvalue-to-rvalue conversion (4.1) is applied only if the 75170b57cec5SDimitry Andric // expression is an lvalue of volatile-qualified type and it has 75180b57cec5SDimitry Andric // one of the following forms: 75190b57cec5SDimitry Andric E = E->IgnoreParens(); 75200b57cec5SDimitry Andric 75210b57cec5SDimitry Andric // - id-expression (5.1.1), 75220b57cec5SDimitry Andric if (isa<DeclRefExpr>(E)) 75230b57cec5SDimitry Andric return true; 75240b57cec5SDimitry Andric 75250b57cec5SDimitry Andric // - subscripting (5.2.1), 75260b57cec5SDimitry Andric if (isa<ArraySubscriptExpr>(E)) 75270b57cec5SDimitry Andric return true; 75280b57cec5SDimitry Andric 75290b57cec5SDimitry Andric // - class member access (5.2.5), 75300b57cec5SDimitry Andric if (isa<MemberExpr>(E)) 75310b57cec5SDimitry Andric return true; 75320b57cec5SDimitry Andric 75330b57cec5SDimitry Andric // - indirection (5.3.1), 75340b57cec5SDimitry Andric if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) 75350b57cec5SDimitry Andric if (UO->getOpcode() == UO_Deref) 75360b57cec5SDimitry Andric return true; 75370b57cec5SDimitry Andric 75380b57cec5SDimitry Andric if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 75390b57cec5SDimitry Andric // - pointer-to-member operation (5.5), 75400b57cec5SDimitry Andric if (BO->isPtrMemOp()) 75410b57cec5SDimitry Andric return true; 75420b57cec5SDimitry Andric 75430b57cec5SDimitry Andric // - comma expression (5.18) where the right operand is one of the above. 75440b57cec5SDimitry Andric if (BO->getOpcode() == BO_Comma) 75450b57cec5SDimitry Andric return IsSpecialDiscardedValue(BO->getRHS()); 75460b57cec5SDimitry Andric } 75470b57cec5SDimitry Andric 75480b57cec5SDimitry Andric // - conditional expression (5.16) where both the second and the third 75490b57cec5SDimitry Andric // operands are one of the above, or 75500b57cec5SDimitry Andric if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) 75510b57cec5SDimitry Andric return IsSpecialDiscardedValue(CO->getTrueExpr()) && 75520b57cec5SDimitry Andric IsSpecialDiscardedValue(CO->getFalseExpr()); 75530b57cec5SDimitry Andric // The related edge case of "*x ?: *x". 75540b57cec5SDimitry Andric if (BinaryConditionalOperator *BCO = 75550b57cec5SDimitry Andric dyn_cast<BinaryConditionalOperator>(E)) { 75560b57cec5SDimitry Andric if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr())) 75570b57cec5SDimitry Andric return IsSpecialDiscardedValue(OVE->getSourceExpr()) && 75580b57cec5SDimitry Andric IsSpecialDiscardedValue(BCO->getFalseExpr()); 75590b57cec5SDimitry Andric } 75600b57cec5SDimitry Andric 75610b57cec5SDimitry Andric // Objective-C++ extensions to the rule. 75620b57cec5SDimitry Andric if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E)) 75630b57cec5SDimitry Andric return true; 75640b57cec5SDimitry Andric 75650b57cec5SDimitry Andric return false; 75660b57cec5SDimitry Andric } 75670b57cec5SDimitry Andric 75680b57cec5SDimitry Andric /// Perform the conversions required for an expression used in a 75690b57cec5SDimitry Andric /// context that ignores the result. 75700b57cec5SDimitry Andric ExprResult Sema::IgnoredValueConversions(Expr *E) { 75710b57cec5SDimitry Andric if (E->hasPlaceholderType()) { 75720b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(E); 75730b57cec5SDimitry Andric if (result.isInvalid()) return E; 75740b57cec5SDimitry Andric E = result.get(); 75750b57cec5SDimitry Andric } 75760b57cec5SDimitry Andric 75770b57cec5SDimitry Andric // C99 6.3.2.1: 75780b57cec5SDimitry Andric // [Except in specific positions,] an lvalue that does not have 75790b57cec5SDimitry Andric // array type is converted to the value stored in the 75800b57cec5SDimitry Andric // designated object (and is no longer an lvalue). 75810b57cec5SDimitry Andric if (E->isRValue()) { 75820b57cec5SDimitry Andric // In C, function designators (i.e. expressions of function type) 75830b57cec5SDimitry Andric // are r-values, but we still want to do function-to-pointer decay 75840b57cec5SDimitry Andric // on them. This is both technically correct and convenient for 75850b57cec5SDimitry Andric // some clients. 75860b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 75870b57cec5SDimitry Andric return DefaultFunctionArrayConversion(E); 75880b57cec5SDimitry Andric 75890b57cec5SDimitry Andric return E; 75900b57cec5SDimitry Andric } 75910b57cec5SDimitry Andric 75920b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 75930b57cec5SDimitry Andric // The C++11 standard defines the notion of a discarded-value expression; 75940b57cec5SDimitry Andric // normally, we don't need to do anything to handle it, but if it is a 75950b57cec5SDimitry Andric // volatile lvalue with a special form, we perform an lvalue-to-rvalue 75960b57cec5SDimitry Andric // conversion. 75970b57cec5SDimitry Andric if (getLangOpts().CPlusPlus11 && E->isGLValue() && 7598a7dea167SDimitry Andric E->getType().isVolatileQualified()) { 7599a7dea167SDimitry Andric if (IsSpecialDiscardedValue(E)) { 76000b57cec5SDimitry Andric ExprResult Res = DefaultLvalueConversion(E); 76010b57cec5SDimitry Andric if (Res.isInvalid()) 76020b57cec5SDimitry Andric return E; 76030b57cec5SDimitry Andric E = Res.get(); 7604a7dea167SDimitry Andric } else { 7605a7dea167SDimitry Andric // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 7606a7dea167SDimitry Andric // it occurs as a discarded-value expression. 7607a7dea167SDimitry Andric CheckUnusedVolatileAssignment(E); 7608a7dea167SDimitry Andric } 76090b57cec5SDimitry Andric } 76100b57cec5SDimitry Andric 76110b57cec5SDimitry Andric // C++1z: 76120b57cec5SDimitry Andric // If the expression is a prvalue after this optional conversion, the 76130b57cec5SDimitry Andric // temporary materialization conversion is applied. 76140b57cec5SDimitry Andric // 76150b57cec5SDimitry Andric // We skip this step: IR generation is able to synthesize the storage for 76160b57cec5SDimitry Andric // itself in the aggregate case, and adding the extra node to the AST is 76170b57cec5SDimitry Andric // just clutter. 76180b57cec5SDimitry Andric // FIXME: We don't emit lifetime markers for the temporaries due to this. 76190b57cec5SDimitry Andric // FIXME: Do any other AST consumers care about this? 76200b57cec5SDimitry Andric return E; 76210b57cec5SDimitry Andric } 76220b57cec5SDimitry Andric 76230b57cec5SDimitry Andric // GCC seems to also exclude expressions of incomplete enum type. 76240b57cec5SDimitry Andric if (const EnumType *T = E->getType()->getAs<EnumType>()) { 76250b57cec5SDimitry Andric if (!T->getDecl()->isComplete()) { 76260b57cec5SDimitry Andric // FIXME: stupid workaround for a codegen bug! 76270b57cec5SDimitry Andric E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); 76280b57cec5SDimitry Andric return E; 76290b57cec5SDimitry Andric } 76300b57cec5SDimitry Andric } 76310b57cec5SDimitry Andric 76320b57cec5SDimitry Andric ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 76330b57cec5SDimitry Andric if (Res.isInvalid()) 76340b57cec5SDimitry Andric return E; 76350b57cec5SDimitry Andric E = Res.get(); 76360b57cec5SDimitry Andric 76370b57cec5SDimitry Andric if (!E->getType()->isVoidType()) 76380b57cec5SDimitry Andric RequireCompleteType(E->getExprLoc(), E->getType(), 76390b57cec5SDimitry Andric diag::err_incomplete_type); 76400b57cec5SDimitry Andric return E; 76410b57cec5SDimitry Andric } 76420b57cec5SDimitry Andric 7643a7dea167SDimitry Andric ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { 7644a7dea167SDimitry Andric // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 7645a7dea167SDimitry Andric // it occurs as an unevaluated operand. 7646a7dea167SDimitry Andric CheckUnusedVolatileAssignment(E); 7647a7dea167SDimitry Andric 7648a7dea167SDimitry Andric return E; 7649a7dea167SDimitry Andric } 7650a7dea167SDimitry Andric 76510b57cec5SDimitry Andric // If we can unambiguously determine whether Var can never be used 76520b57cec5SDimitry Andric // in a constant expression, return true. 76530b57cec5SDimitry Andric // - if the variable and its initializer are non-dependent, then 76540b57cec5SDimitry Andric // we can unambiguously check if the variable is a constant expression. 76550b57cec5SDimitry Andric // - if the initializer is not value dependent - we can determine whether 76560b57cec5SDimitry Andric // it can be used to initialize a constant expression. If Init can not 76570b57cec5SDimitry Andric // be used to initialize a constant expression we conclude that Var can 76580b57cec5SDimitry Andric // never be a constant expression. 76590b57cec5SDimitry Andric // - FXIME: if the initializer is dependent, we can still do some analysis and 76600b57cec5SDimitry Andric // identify certain cases unambiguously as non-const by using a Visitor: 76610b57cec5SDimitry Andric // - such as those that involve odr-use of a ParmVarDecl, involve a new 76620b57cec5SDimitry Andric // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... 76630b57cec5SDimitry Andric static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 76640b57cec5SDimitry Andric ASTContext &Context) { 76650b57cec5SDimitry Andric if (isa<ParmVarDecl>(Var)) return true; 76660b57cec5SDimitry Andric const VarDecl *DefVD = nullptr; 76670b57cec5SDimitry Andric 76680b57cec5SDimitry Andric // If there is no initializer - this can not be a constant expression. 76690b57cec5SDimitry Andric if (!Var->getAnyInitializer(DefVD)) return true; 76700b57cec5SDimitry Andric assert(DefVD); 76710b57cec5SDimitry Andric if (DefVD->isWeak()) return false; 76720b57cec5SDimitry Andric EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 76730b57cec5SDimitry Andric 76740b57cec5SDimitry Andric Expr *Init = cast<Expr>(Eval->Value); 76750b57cec5SDimitry Andric 76760b57cec5SDimitry Andric if (Var->getType()->isDependentType() || Init->isValueDependent()) { 76770b57cec5SDimitry Andric // FIXME: Teach the constant evaluator to deal with the non-dependent parts 76780b57cec5SDimitry Andric // of value-dependent expressions, and use it here to determine whether the 76790b57cec5SDimitry Andric // initializer is a potential constant expression. 76800b57cec5SDimitry Andric return false; 76810b57cec5SDimitry Andric } 76820b57cec5SDimitry Andric 76830b57cec5SDimitry Andric return !Var->isUsableInConstantExpressions(Context); 76840b57cec5SDimitry Andric } 76850b57cec5SDimitry Andric 76860b57cec5SDimitry Andric /// Check if the current lambda has any potential captures 76870b57cec5SDimitry Andric /// that must be captured by any of its enclosing lambdas that are ready to 76880b57cec5SDimitry Andric /// capture. If there is a lambda that can capture a nested 76890b57cec5SDimitry Andric /// potential-capture, go ahead and do so. Also, check to see if any 76900b57cec5SDimitry Andric /// variables are uncaptureable or do not involve an odr-use so do not 76910b57cec5SDimitry Andric /// need to be captured. 76920b57cec5SDimitry Andric 76930b57cec5SDimitry Andric static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( 76940b57cec5SDimitry Andric Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { 76950b57cec5SDimitry Andric 76960b57cec5SDimitry Andric assert(!S.isUnevaluatedContext()); 76970b57cec5SDimitry Andric assert(S.CurContext->isDependentContext()); 76980b57cec5SDimitry Andric #ifndef NDEBUG 76990b57cec5SDimitry Andric DeclContext *DC = S.CurContext; 77000b57cec5SDimitry Andric while (DC && isa<CapturedDecl>(DC)) 77010b57cec5SDimitry Andric DC = DC->getParent(); 77020b57cec5SDimitry Andric assert( 77030b57cec5SDimitry Andric CurrentLSI->CallOperator == DC && 77040b57cec5SDimitry Andric "The current call operator must be synchronized with Sema's CurContext"); 77050b57cec5SDimitry Andric #endif // NDEBUG 77060b57cec5SDimitry Andric 77070b57cec5SDimitry Andric const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); 77080b57cec5SDimitry Andric 77090b57cec5SDimitry Andric // All the potentially captureable variables in the current nested 77100b57cec5SDimitry Andric // lambda (within a generic outer lambda), must be captured by an 77110b57cec5SDimitry Andric // outer lambda that is enclosed within a non-dependent context. 77120b57cec5SDimitry Andric CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) { 77130b57cec5SDimitry Andric // If the variable is clearly identified as non-odr-used and the full 77140b57cec5SDimitry Andric // expression is not instantiation dependent, only then do we not 77150b57cec5SDimitry Andric // need to check enclosing lambda's for speculative captures. 77160b57cec5SDimitry Andric // For e.g.: 77170b57cec5SDimitry Andric // Even though 'x' is not odr-used, it should be captured. 77180b57cec5SDimitry Andric // int test() { 77190b57cec5SDimitry Andric // const int x = 10; 77200b57cec5SDimitry Andric // auto L = [=](auto a) { 77210b57cec5SDimitry Andric // (void) +x + a; 77220b57cec5SDimitry Andric // }; 77230b57cec5SDimitry Andric // } 77240b57cec5SDimitry Andric if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && 77250b57cec5SDimitry Andric !IsFullExprInstantiationDependent) 77260b57cec5SDimitry Andric return; 77270b57cec5SDimitry Andric 77280b57cec5SDimitry Andric // If we have a capture-capable lambda for the variable, go ahead and 77290b57cec5SDimitry Andric // capture the variable in that lambda (and all its enclosing lambdas). 77300b57cec5SDimitry Andric if (const Optional<unsigned> Index = 77310b57cec5SDimitry Andric getStackIndexOfNearestEnclosingCaptureCapableLambda( 77320b57cec5SDimitry Andric S.FunctionScopes, Var, S)) 77330b57cec5SDimitry Andric S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), 77340b57cec5SDimitry Andric Index.getValue()); 77350b57cec5SDimitry Andric const bool IsVarNeverAConstantExpression = 77360b57cec5SDimitry Andric VariableCanNeverBeAConstantExpression(Var, S.Context); 77370b57cec5SDimitry Andric if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { 77380b57cec5SDimitry Andric // This full expression is not instantiation dependent or the variable 77390b57cec5SDimitry Andric // can not be used in a constant expression - which means 77400b57cec5SDimitry Andric // this variable must be odr-used here, so diagnose a 77410b57cec5SDimitry Andric // capture violation early, if the variable is un-captureable. 77420b57cec5SDimitry Andric // This is purely for diagnosing errors early. Otherwise, this 77430b57cec5SDimitry Andric // error would get diagnosed when the lambda becomes capture ready. 77440b57cec5SDimitry Andric QualType CaptureType, DeclRefType; 77450b57cec5SDimitry Andric SourceLocation ExprLoc = VarExpr->getExprLoc(); 77460b57cec5SDimitry Andric if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 77470b57cec5SDimitry Andric /*EllipsisLoc*/ SourceLocation(), 77480b57cec5SDimitry Andric /*BuildAndDiagnose*/false, CaptureType, 77490b57cec5SDimitry Andric DeclRefType, nullptr)) { 77500b57cec5SDimitry Andric // We will never be able to capture this variable, and we need 77510b57cec5SDimitry Andric // to be able to in any and all instantiations, so diagnose it. 77520b57cec5SDimitry Andric S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 77530b57cec5SDimitry Andric /*EllipsisLoc*/ SourceLocation(), 77540b57cec5SDimitry Andric /*BuildAndDiagnose*/true, CaptureType, 77550b57cec5SDimitry Andric DeclRefType, nullptr); 77560b57cec5SDimitry Andric } 77570b57cec5SDimitry Andric } 77580b57cec5SDimitry Andric }); 77590b57cec5SDimitry Andric 77600b57cec5SDimitry Andric // Check if 'this' needs to be captured. 77610b57cec5SDimitry Andric if (CurrentLSI->hasPotentialThisCapture()) { 77620b57cec5SDimitry Andric // If we have a capture-capable lambda for 'this', go ahead and capture 77630b57cec5SDimitry Andric // 'this' in that lambda (and all its enclosing lambdas). 77640b57cec5SDimitry Andric if (const Optional<unsigned> Index = 77650b57cec5SDimitry Andric getStackIndexOfNearestEnclosingCaptureCapableLambda( 77660b57cec5SDimitry Andric S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { 77670b57cec5SDimitry Andric const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue(); 77680b57cec5SDimitry Andric S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, 77690b57cec5SDimitry Andric /*Explicit*/ false, /*BuildAndDiagnose*/ true, 77700b57cec5SDimitry Andric &FunctionScopeIndexOfCapturableLambda); 77710b57cec5SDimitry Andric } 77720b57cec5SDimitry Andric } 77730b57cec5SDimitry Andric 77740b57cec5SDimitry Andric // Reset all the potential captures at the end of each full-expression. 77750b57cec5SDimitry Andric CurrentLSI->clearPotentialCaptures(); 77760b57cec5SDimitry Andric } 77770b57cec5SDimitry Andric 77780b57cec5SDimitry Andric static ExprResult attemptRecovery(Sema &SemaRef, 77790b57cec5SDimitry Andric const TypoCorrectionConsumer &Consumer, 77800b57cec5SDimitry Andric const TypoCorrection &TC) { 77810b57cec5SDimitry Andric LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), 77820b57cec5SDimitry Andric Consumer.getLookupResult().getLookupKind()); 77830b57cec5SDimitry Andric const CXXScopeSpec *SS = Consumer.getSS(); 77840b57cec5SDimitry Andric CXXScopeSpec NewSS; 77850b57cec5SDimitry Andric 77860b57cec5SDimitry Andric // Use an approprate CXXScopeSpec for building the expr. 77870b57cec5SDimitry Andric if (auto *NNS = TC.getCorrectionSpecifier()) 77880b57cec5SDimitry Andric NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); 77890b57cec5SDimitry Andric else if (SS && !TC.WillReplaceSpecifier()) 77900b57cec5SDimitry Andric NewSS = *SS; 77910b57cec5SDimitry Andric 77920b57cec5SDimitry Andric if (auto *ND = TC.getFoundDecl()) { 77930b57cec5SDimitry Andric R.setLookupName(ND->getDeclName()); 77940b57cec5SDimitry Andric R.addDecl(ND); 77950b57cec5SDimitry Andric if (ND->isCXXClassMember()) { 77960b57cec5SDimitry Andric // Figure out the correct naming class to add to the LookupResult. 77970b57cec5SDimitry Andric CXXRecordDecl *Record = nullptr; 77980b57cec5SDimitry Andric if (auto *NNS = TC.getCorrectionSpecifier()) 77990b57cec5SDimitry Andric Record = NNS->getAsType()->getAsCXXRecordDecl(); 78000b57cec5SDimitry Andric if (!Record) 78010b57cec5SDimitry Andric Record = 78020b57cec5SDimitry Andric dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); 78030b57cec5SDimitry Andric if (Record) 78040b57cec5SDimitry Andric R.setNamingClass(Record); 78050b57cec5SDimitry Andric 78060b57cec5SDimitry Andric // Detect and handle the case where the decl might be an implicit 78070b57cec5SDimitry Andric // member. 78080b57cec5SDimitry Andric bool MightBeImplicitMember; 78090b57cec5SDimitry Andric if (!Consumer.isAddressOfOperand()) 78100b57cec5SDimitry Andric MightBeImplicitMember = true; 78110b57cec5SDimitry Andric else if (!NewSS.isEmpty()) 78120b57cec5SDimitry Andric MightBeImplicitMember = false; 78130b57cec5SDimitry Andric else if (R.isOverloadedResult()) 78140b57cec5SDimitry Andric MightBeImplicitMember = false; 78150b57cec5SDimitry Andric else if (R.isUnresolvableResult()) 78160b57cec5SDimitry Andric MightBeImplicitMember = true; 78170b57cec5SDimitry Andric else 78180b57cec5SDimitry Andric MightBeImplicitMember = isa<FieldDecl>(ND) || 78190b57cec5SDimitry Andric isa<IndirectFieldDecl>(ND) || 78200b57cec5SDimitry Andric isa<MSPropertyDecl>(ND); 78210b57cec5SDimitry Andric 78220b57cec5SDimitry Andric if (MightBeImplicitMember) 78230b57cec5SDimitry Andric return SemaRef.BuildPossibleImplicitMemberExpr( 78240b57cec5SDimitry Andric NewSS, /*TemplateKWLoc*/ SourceLocation(), R, 78250b57cec5SDimitry Andric /*TemplateArgs*/ nullptr, /*S*/ nullptr); 78260b57cec5SDimitry Andric } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 78270b57cec5SDimitry Andric return SemaRef.LookupInObjCMethod(R, Consumer.getScope(), 78280b57cec5SDimitry Andric Ivar->getIdentifier()); 78290b57cec5SDimitry Andric } 78300b57cec5SDimitry Andric } 78310b57cec5SDimitry Andric 78320b57cec5SDimitry Andric return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, 78330b57cec5SDimitry Andric /*AcceptInvalidDecl*/ true); 78340b57cec5SDimitry Andric } 78350b57cec5SDimitry Andric 78360b57cec5SDimitry Andric namespace { 78370b57cec5SDimitry Andric class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { 78380b57cec5SDimitry Andric llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; 78390b57cec5SDimitry Andric 78400b57cec5SDimitry Andric public: 78410b57cec5SDimitry Andric explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) 78420b57cec5SDimitry Andric : TypoExprs(TypoExprs) {} 78430b57cec5SDimitry Andric bool VisitTypoExpr(TypoExpr *TE) { 78440b57cec5SDimitry Andric TypoExprs.insert(TE); 78450b57cec5SDimitry Andric return true; 78460b57cec5SDimitry Andric } 78470b57cec5SDimitry Andric }; 78480b57cec5SDimitry Andric 78490b57cec5SDimitry Andric class TransformTypos : public TreeTransform<TransformTypos> { 78500b57cec5SDimitry Andric typedef TreeTransform<TransformTypos> BaseTransform; 78510b57cec5SDimitry Andric 78520b57cec5SDimitry Andric VarDecl *InitDecl; // A decl to avoid as a correction because it is in the 78530b57cec5SDimitry Andric // process of being initialized. 78540b57cec5SDimitry Andric llvm::function_ref<ExprResult(Expr *)> ExprFilter; 78550b57cec5SDimitry Andric llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; 78560b57cec5SDimitry Andric llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; 78570b57cec5SDimitry Andric llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; 78580b57cec5SDimitry Andric 78590b57cec5SDimitry Andric /// Emit diagnostics for all of the TypoExprs encountered. 7860a7dea167SDimitry Andric /// 78610b57cec5SDimitry Andric /// If the TypoExprs were successfully corrected, then the diagnostics should 78620b57cec5SDimitry Andric /// suggest the corrections. Otherwise the diagnostics will not suggest 78630b57cec5SDimitry Andric /// anything (having been passed an empty TypoCorrection). 7864a7dea167SDimitry Andric /// 7865a7dea167SDimitry Andric /// If we've failed to correct due to ambiguous corrections, we need to 7866a7dea167SDimitry Andric /// be sure to pass empty corrections and replacements. Otherwise it's 7867a7dea167SDimitry Andric /// possible that the Consumer has a TypoCorrection that failed to ambiguity 7868a7dea167SDimitry Andric /// and we don't want to report those diagnostics. 7869a7dea167SDimitry Andric void EmitAllDiagnostics(bool IsAmbiguous) { 78700b57cec5SDimitry Andric for (TypoExpr *TE : TypoExprs) { 78710b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(TE); 78720b57cec5SDimitry Andric if (State.DiagHandler) { 7873a7dea167SDimitry Andric TypoCorrection TC = IsAmbiguous 7874a7dea167SDimitry Andric ? TypoCorrection() : State.Consumer->getCurrentCorrection(); 7875a7dea167SDimitry Andric ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; 78760b57cec5SDimitry Andric 78770b57cec5SDimitry Andric // Extract the NamedDecl from the transformed TypoExpr and add it to the 78780b57cec5SDimitry Andric // TypoCorrection, replacing the existing decls. This ensures the right 78790b57cec5SDimitry Andric // NamedDecl is used in diagnostics e.g. in the case where overload 78800b57cec5SDimitry Andric // resolution was used to select one from several possible decls that 78810b57cec5SDimitry Andric // had been stored in the TypoCorrection. 78820b57cec5SDimitry Andric if (auto *ND = getDeclFromExpr( 78830b57cec5SDimitry Andric Replacement.isInvalid() ? nullptr : Replacement.get())) 78840b57cec5SDimitry Andric TC.setCorrectionDecl(ND); 78850b57cec5SDimitry Andric 78860b57cec5SDimitry Andric State.DiagHandler(TC); 78870b57cec5SDimitry Andric } 78880b57cec5SDimitry Andric SemaRef.clearDelayedTypo(TE); 78890b57cec5SDimitry Andric } 78900b57cec5SDimitry Andric } 78910b57cec5SDimitry Andric 78920b57cec5SDimitry Andric /// If corrections for the first TypoExpr have been exhausted for a 78930b57cec5SDimitry Andric /// given combination of the other TypoExprs, retry those corrections against 78940b57cec5SDimitry Andric /// the next combination of substitutions for the other TypoExprs by advancing 78950b57cec5SDimitry Andric /// to the next potential correction of the second TypoExpr. For the second 78960b57cec5SDimitry Andric /// and subsequent TypoExprs, if its stream of corrections has been exhausted, 78970b57cec5SDimitry Andric /// the stream is reset and the next TypoExpr's stream is advanced by one (a 78980b57cec5SDimitry Andric /// TypoExpr's correction stream is advanced by removing the TypoExpr from the 78990b57cec5SDimitry Andric /// TransformCache). Returns true if there is still any untried combinations 79000b57cec5SDimitry Andric /// of corrections. 79010b57cec5SDimitry Andric bool CheckAndAdvanceTypoExprCorrectionStreams() { 79020b57cec5SDimitry Andric for (auto TE : TypoExprs) { 79030b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(TE); 79040b57cec5SDimitry Andric TransformCache.erase(TE); 79050b57cec5SDimitry Andric if (!State.Consumer->finished()) 79060b57cec5SDimitry Andric return true; 79070b57cec5SDimitry Andric State.Consumer->resetCorrectionStream(); 79080b57cec5SDimitry Andric } 79090b57cec5SDimitry Andric return false; 79100b57cec5SDimitry Andric } 79110b57cec5SDimitry Andric 79120b57cec5SDimitry Andric NamedDecl *getDeclFromExpr(Expr *E) { 79130b57cec5SDimitry Andric if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) 79140b57cec5SDimitry Andric E = OverloadResolution[OE]; 79150b57cec5SDimitry Andric 79160b57cec5SDimitry Andric if (!E) 79170b57cec5SDimitry Andric return nullptr; 79180b57cec5SDimitry Andric if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 79190b57cec5SDimitry Andric return DRE->getFoundDecl(); 79200b57cec5SDimitry Andric if (auto *ME = dyn_cast<MemberExpr>(E)) 79210b57cec5SDimitry Andric return ME->getFoundDecl(); 79220b57cec5SDimitry Andric // FIXME: Add any other expr types that could be be seen by the delayed typo 79230b57cec5SDimitry Andric // correction TreeTransform for which the corresponding TypoCorrection could 79240b57cec5SDimitry Andric // contain multiple decls. 79250b57cec5SDimitry Andric return nullptr; 79260b57cec5SDimitry Andric } 79270b57cec5SDimitry Andric 79280b57cec5SDimitry Andric ExprResult TryTransform(Expr *E) { 79290b57cec5SDimitry Andric Sema::SFINAETrap Trap(SemaRef); 79300b57cec5SDimitry Andric ExprResult Res = TransformExpr(E); 79310b57cec5SDimitry Andric if (Trap.hasErrorOccurred() || Res.isInvalid()) 79320b57cec5SDimitry Andric return ExprError(); 79330b57cec5SDimitry Andric 79340b57cec5SDimitry Andric return ExprFilter(Res.get()); 79350b57cec5SDimitry Andric } 79360b57cec5SDimitry Andric 7937a7dea167SDimitry Andric // Since correcting typos may intoduce new TypoExprs, this function 7938a7dea167SDimitry Andric // checks for new TypoExprs and recurses if it finds any. Note that it will 7939a7dea167SDimitry Andric // only succeed if it is able to correct all typos in the given expression. 7940a7dea167SDimitry Andric ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { 7941a7dea167SDimitry Andric if (Res.isInvalid()) { 7942a7dea167SDimitry Andric return Res; 7943a7dea167SDimitry Andric } 7944a7dea167SDimitry Andric // Check to see if any new TypoExprs were created. If so, we need to recurse 7945a7dea167SDimitry Andric // to check their validity. 7946a7dea167SDimitry Andric Expr *FixedExpr = Res.get(); 7947a7dea167SDimitry Andric 7948a7dea167SDimitry Andric auto SavedTypoExprs = std::move(TypoExprs); 7949a7dea167SDimitry Andric auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); 7950a7dea167SDimitry Andric TypoExprs.clear(); 7951a7dea167SDimitry Andric AmbiguousTypoExprs.clear(); 7952a7dea167SDimitry Andric 7953a7dea167SDimitry Andric FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); 7954a7dea167SDimitry Andric if (!TypoExprs.empty()) { 7955a7dea167SDimitry Andric // Recurse to handle newly created TypoExprs. If we're not able to 7956a7dea167SDimitry Andric // handle them, discard these TypoExprs. 7957a7dea167SDimitry Andric ExprResult RecurResult = 7958a7dea167SDimitry Andric RecursiveTransformLoop(FixedExpr, IsAmbiguous); 7959a7dea167SDimitry Andric if (RecurResult.isInvalid()) { 7960a7dea167SDimitry Andric Res = ExprError(); 7961a7dea167SDimitry Andric // Recursive corrections didn't work, wipe them away and don't add 7962a7dea167SDimitry Andric // them to the TypoExprs set. Remove them from Sema's TypoExpr list 7963a7dea167SDimitry Andric // since we don't want to clear them twice. Note: it's possible the 7964a7dea167SDimitry Andric // TypoExprs were created recursively and thus won't be in our 7965a7dea167SDimitry Andric // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. 7966a7dea167SDimitry Andric auto &SemaTypoExprs = SemaRef.TypoExprs; 7967a7dea167SDimitry Andric for (auto TE : TypoExprs) { 7968a7dea167SDimitry Andric TransformCache.erase(TE); 7969a7dea167SDimitry Andric SemaRef.clearDelayedTypo(TE); 7970a7dea167SDimitry Andric 7971a7dea167SDimitry Andric auto SI = find(SemaTypoExprs, TE); 7972a7dea167SDimitry Andric if (SI != SemaTypoExprs.end()) { 7973a7dea167SDimitry Andric SemaTypoExprs.erase(SI); 7974a7dea167SDimitry Andric } 7975a7dea167SDimitry Andric } 7976a7dea167SDimitry Andric } else { 7977a7dea167SDimitry Andric // TypoExpr is valid: add newly created TypoExprs since we were 7978a7dea167SDimitry Andric // able to correct them. 7979a7dea167SDimitry Andric Res = RecurResult; 7980a7dea167SDimitry Andric SavedTypoExprs.set_union(TypoExprs); 7981a7dea167SDimitry Andric } 7982a7dea167SDimitry Andric } 7983a7dea167SDimitry Andric 7984a7dea167SDimitry Andric TypoExprs = std::move(SavedTypoExprs); 7985a7dea167SDimitry Andric AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); 7986a7dea167SDimitry Andric 7987a7dea167SDimitry Andric return Res; 7988a7dea167SDimitry Andric } 7989a7dea167SDimitry Andric 7990a7dea167SDimitry Andric // Try to transform the given expression, looping through the correction 7991a7dea167SDimitry Andric // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. 7992a7dea167SDimitry Andric // 7993a7dea167SDimitry Andric // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to 7994a7dea167SDimitry Andric // true and this method immediately will return an `ExprError`. 7995a7dea167SDimitry Andric ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { 7996a7dea167SDimitry Andric ExprResult Res; 7997a7dea167SDimitry Andric auto SavedTypoExprs = std::move(SemaRef.TypoExprs); 7998a7dea167SDimitry Andric SemaRef.TypoExprs.clear(); 7999a7dea167SDimitry Andric 8000a7dea167SDimitry Andric while (true) { 8001a7dea167SDimitry Andric Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 8002a7dea167SDimitry Andric 8003a7dea167SDimitry Andric // Recursion encountered an ambiguous correction. This means that our 8004a7dea167SDimitry Andric // correction itself is ambiguous, so stop now. 8005a7dea167SDimitry Andric if (IsAmbiguous) 8006a7dea167SDimitry Andric break; 8007a7dea167SDimitry Andric 8008a7dea167SDimitry Andric // If the transform is still valid after checking for any new typos, 8009a7dea167SDimitry Andric // it's good to go. 8010a7dea167SDimitry Andric if (!Res.isInvalid()) 8011a7dea167SDimitry Andric break; 8012a7dea167SDimitry Andric 8013a7dea167SDimitry Andric // The transform was invalid, see if we have any TypoExprs with untried 8014a7dea167SDimitry Andric // correction candidates. 8015a7dea167SDimitry Andric if (!CheckAndAdvanceTypoExprCorrectionStreams()) 8016a7dea167SDimitry Andric break; 8017a7dea167SDimitry Andric } 8018a7dea167SDimitry Andric 8019a7dea167SDimitry Andric // If we found a valid result, double check to make sure it's not ambiguous. 8020a7dea167SDimitry Andric if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { 8021480093f4SDimitry Andric auto SavedTransformCache = 8022480093f4SDimitry Andric llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); 8023480093f4SDimitry Andric 8024a7dea167SDimitry Andric // Ensure none of the TypoExprs have multiple typo correction candidates 8025a7dea167SDimitry Andric // with the same edit length that pass all the checks and filters. 8026a7dea167SDimitry Andric while (!AmbiguousTypoExprs.empty()) { 8027a7dea167SDimitry Andric auto TE = AmbiguousTypoExprs.back(); 8028a7dea167SDimitry Andric 8029a7dea167SDimitry Andric // TryTransform itself can create new Typos, adding them to the TypoExpr map 8030a7dea167SDimitry Andric // and invalidating our TypoExprState, so always fetch it instead of storing. 8031a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); 8032a7dea167SDimitry Andric 8033a7dea167SDimitry Andric TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); 8034a7dea167SDimitry Andric TypoCorrection Next; 8035a7dea167SDimitry Andric do { 8036a7dea167SDimitry Andric // Fetch the next correction by erasing the typo from the cache and calling 8037a7dea167SDimitry Andric // `TryTransform` which will iterate through corrections in 8038a7dea167SDimitry Andric // `TransformTypoExpr`. 8039a7dea167SDimitry Andric TransformCache.erase(TE); 8040a7dea167SDimitry Andric ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 8041a7dea167SDimitry Andric 8042a7dea167SDimitry Andric if (!AmbigRes.isInvalid() || IsAmbiguous) { 8043a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); 8044a7dea167SDimitry Andric SavedTransformCache.erase(TE); 8045a7dea167SDimitry Andric Res = ExprError(); 8046a7dea167SDimitry Andric IsAmbiguous = true; 8047a7dea167SDimitry Andric break; 8048a7dea167SDimitry Andric } 8049a7dea167SDimitry Andric } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && 8050a7dea167SDimitry Andric Next.getEditDistance(false) == TC.getEditDistance(false)); 8051a7dea167SDimitry Andric 8052a7dea167SDimitry Andric if (IsAmbiguous) 8053a7dea167SDimitry Andric break; 8054a7dea167SDimitry Andric 8055a7dea167SDimitry Andric AmbiguousTypoExprs.remove(TE); 8056a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); 8057a7dea167SDimitry Andric } 8058a7dea167SDimitry Andric TransformCache = std::move(SavedTransformCache); 8059a7dea167SDimitry Andric } 8060a7dea167SDimitry Andric 8061a7dea167SDimitry Andric // Wipe away any newly created TypoExprs that we don't know about. Since we 8062a7dea167SDimitry Andric // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only 8063a7dea167SDimitry Andric // possible if a `TypoExpr` is created during a transformation but then 8064a7dea167SDimitry Andric // fails before we can discover it. 8065a7dea167SDimitry Andric auto &SemaTypoExprs = SemaRef.TypoExprs; 8066a7dea167SDimitry Andric for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { 8067a7dea167SDimitry Andric auto TE = *Iterator; 8068a7dea167SDimitry Andric auto FI = find(TypoExprs, TE); 8069a7dea167SDimitry Andric if (FI != TypoExprs.end()) { 8070a7dea167SDimitry Andric Iterator++; 8071a7dea167SDimitry Andric continue; 8072a7dea167SDimitry Andric } 8073a7dea167SDimitry Andric SemaRef.clearDelayedTypo(TE); 8074a7dea167SDimitry Andric Iterator = SemaTypoExprs.erase(Iterator); 8075a7dea167SDimitry Andric } 8076a7dea167SDimitry Andric SemaRef.TypoExprs = std::move(SavedTypoExprs); 8077a7dea167SDimitry Andric 8078a7dea167SDimitry Andric return Res; 8079a7dea167SDimitry Andric } 8080a7dea167SDimitry Andric 80810b57cec5SDimitry Andric public: 80820b57cec5SDimitry Andric TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) 80830b57cec5SDimitry Andric : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} 80840b57cec5SDimitry Andric 80850b57cec5SDimitry Andric ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, 80860b57cec5SDimitry Andric MultiExprArg Args, 80870b57cec5SDimitry Andric SourceLocation RParenLoc, 80880b57cec5SDimitry Andric Expr *ExecConfig = nullptr) { 80890b57cec5SDimitry Andric auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, 80900b57cec5SDimitry Andric RParenLoc, ExecConfig); 80910b57cec5SDimitry Andric if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { 80920b57cec5SDimitry Andric if (Result.isUsable()) { 80930b57cec5SDimitry Andric Expr *ResultCall = Result.get(); 80940b57cec5SDimitry Andric if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) 80950b57cec5SDimitry Andric ResultCall = BE->getSubExpr(); 80960b57cec5SDimitry Andric if (auto *CE = dyn_cast<CallExpr>(ResultCall)) 80970b57cec5SDimitry Andric OverloadResolution[OE] = CE->getCallee(); 80980b57cec5SDimitry Andric } 80990b57cec5SDimitry Andric } 81000b57cec5SDimitry Andric return Result; 81010b57cec5SDimitry Andric } 81020b57cec5SDimitry Andric 81030b57cec5SDimitry Andric ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } 81040b57cec5SDimitry Andric 81050b57cec5SDimitry Andric ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } 81060b57cec5SDimitry Andric 81070b57cec5SDimitry Andric ExprResult Transform(Expr *E) { 8108a7dea167SDimitry Andric bool IsAmbiguous = false; 8109a7dea167SDimitry Andric ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); 81100b57cec5SDimitry Andric 81110b57cec5SDimitry Andric if (!Res.isUsable()) 81120b57cec5SDimitry Andric FindTypoExprs(TypoExprs).TraverseStmt(E); 81130b57cec5SDimitry Andric 8114a7dea167SDimitry Andric EmitAllDiagnostics(IsAmbiguous); 81150b57cec5SDimitry Andric 81160b57cec5SDimitry Andric return Res; 81170b57cec5SDimitry Andric } 81180b57cec5SDimitry Andric 81190b57cec5SDimitry Andric ExprResult TransformTypoExpr(TypoExpr *E) { 81200b57cec5SDimitry Andric // If the TypoExpr hasn't been seen before, record it. Otherwise, return the 81210b57cec5SDimitry Andric // cached transformation result if there is one and the TypoExpr isn't the 81220b57cec5SDimitry Andric // first one that was encountered. 81230b57cec5SDimitry Andric auto &CacheEntry = TransformCache[E]; 81240b57cec5SDimitry Andric if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { 81250b57cec5SDimitry Andric return CacheEntry; 81260b57cec5SDimitry Andric } 81270b57cec5SDimitry Andric 81280b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(E); 81290b57cec5SDimitry Andric assert(State.Consumer && "Cannot transform a cleared TypoExpr"); 81300b57cec5SDimitry Andric 81310b57cec5SDimitry Andric // For the first TypoExpr and an uncached TypoExpr, find the next likely 81320b57cec5SDimitry Andric // typo correction and return it. 81330b57cec5SDimitry Andric while (TypoCorrection TC = State.Consumer->getNextCorrection()) { 81340b57cec5SDimitry Andric if (InitDecl && TC.getFoundDecl() == InitDecl) 81350b57cec5SDimitry Andric continue; 81360b57cec5SDimitry Andric // FIXME: If we would typo-correct to an invalid declaration, it's 81370b57cec5SDimitry Andric // probably best to just suppress all errors from this typo correction. 81380b57cec5SDimitry Andric ExprResult NE = State.RecoveryHandler ? 81390b57cec5SDimitry Andric State.RecoveryHandler(SemaRef, E, TC) : 81400b57cec5SDimitry Andric attemptRecovery(SemaRef, *State.Consumer, TC); 81410b57cec5SDimitry Andric if (!NE.isInvalid()) { 81420b57cec5SDimitry Andric // Check whether there may be a second viable correction with the same 81430b57cec5SDimitry Andric // edit distance; if so, remember this TypoExpr may have an ambiguous 81440b57cec5SDimitry Andric // correction so it can be more thoroughly vetted later. 81450b57cec5SDimitry Andric TypoCorrection Next; 81460b57cec5SDimitry Andric if ((Next = State.Consumer->peekNextCorrection()) && 81470b57cec5SDimitry Andric Next.getEditDistance(false) == TC.getEditDistance(false)) { 81480b57cec5SDimitry Andric AmbiguousTypoExprs.insert(E); 81490b57cec5SDimitry Andric } else { 81500b57cec5SDimitry Andric AmbiguousTypoExprs.remove(E); 81510b57cec5SDimitry Andric } 81520b57cec5SDimitry Andric assert(!NE.isUnset() && 81530b57cec5SDimitry Andric "Typo was transformed into a valid-but-null ExprResult"); 81540b57cec5SDimitry Andric return CacheEntry = NE; 81550b57cec5SDimitry Andric } 81560b57cec5SDimitry Andric } 81570b57cec5SDimitry Andric return CacheEntry = ExprError(); 81580b57cec5SDimitry Andric } 81590b57cec5SDimitry Andric }; 81600b57cec5SDimitry Andric } 81610b57cec5SDimitry Andric 81620b57cec5SDimitry Andric ExprResult 81630b57cec5SDimitry Andric Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, 81640b57cec5SDimitry Andric llvm::function_ref<ExprResult(Expr *)> Filter) { 81650b57cec5SDimitry Andric // If the current evaluation context indicates there are uncorrected typos 81660b57cec5SDimitry Andric // and the current expression isn't guaranteed to not have typos, try to 81670b57cec5SDimitry Andric // resolve any TypoExpr nodes that might be in the expression. 81680b57cec5SDimitry Andric if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && 81690b57cec5SDimitry Andric (E->isTypeDependent() || E->isValueDependent() || 81700b57cec5SDimitry Andric E->isInstantiationDependent())) { 81710b57cec5SDimitry Andric auto TyposResolved = DelayedTypos.size(); 81720b57cec5SDimitry Andric auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); 81730b57cec5SDimitry Andric TyposResolved -= DelayedTypos.size(); 81740b57cec5SDimitry Andric if (Result.isInvalid() || Result.get() != E) { 81750b57cec5SDimitry Andric ExprEvalContexts.back().NumTypos -= TyposResolved; 81760b57cec5SDimitry Andric return Result; 81770b57cec5SDimitry Andric } 81780b57cec5SDimitry Andric assert(TyposResolved == 0 && "Corrected typo but got same Expr back?"); 81790b57cec5SDimitry Andric } 81800b57cec5SDimitry Andric return E; 81810b57cec5SDimitry Andric } 81820b57cec5SDimitry Andric 81830b57cec5SDimitry Andric ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, 81840b57cec5SDimitry Andric bool DiscardedValue, 81850b57cec5SDimitry Andric bool IsConstexpr) { 81860b57cec5SDimitry Andric ExprResult FullExpr = FE; 81870b57cec5SDimitry Andric 81880b57cec5SDimitry Andric if (!FullExpr.get()) 81890b57cec5SDimitry Andric return ExprError(); 81900b57cec5SDimitry Andric 81910b57cec5SDimitry Andric if (DiagnoseUnexpandedParameterPack(FullExpr.get())) 81920b57cec5SDimitry Andric return ExprError(); 81930b57cec5SDimitry Andric 81940b57cec5SDimitry Andric if (DiscardedValue) { 81950b57cec5SDimitry Andric // Top-level expressions default to 'id' when we're in a debugger. 81960b57cec5SDimitry Andric if (getLangOpts().DebuggerCastResultToId && 81970b57cec5SDimitry Andric FullExpr.get()->getType() == Context.UnknownAnyTy) { 81980b57cec5SDimitry Andric FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); 81990b57cec5SDimitry Andric if (FullExpr.isInvalid()) 82000b57cec5SDimitry Andric return ExprError(); 82010b57cec5SDimitry Andric } 82020b57cec5SDimitry Andric 82030b57cec5SDimitry Andric FullExpr = CheckPlaceholderExpr(FullExpr.get()); 82040b57cec5SDimitry Andric if (FullExpr.isInvalid()) 82050b57cec5SDimitry Andric return ExprError(); 82060b57cec5SDimitry Andric 82070b57cec5SDimitry Andric FullExpr = IgnoredValueConversions(FullExpr.get()); 82080b57cec5SDimitry Andric if (FullExpr.isInvalid()) 82090b57cec5SDimitry Andric return ExprError(); 82100b57cec5SDimitry Andric 82110b57cec5SDimitry Andric DiagnoseUnusedExprResult(FullExpr.get()); 82120b57cec5SDimitry Andric } 82130b57cec5SDimitry Andric 82140b57cec5SDimitry Andric FullExpr = CorrectDelayedTyposInExpr(FullExpr.get()); 82150b57cec5SDimitry Andric if (FullExpr.isInvalid()) 82160b57cec5SDimitry Andric return ExprError(); 82170b57cec5SDimitry Andric 82180b57cec5SDimitry Andric CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); 82190b57cec5SDimitry Andric 82200b57cec5SDimitry Andric // At the end of this full expression (which could be a deeply nested 82210b57cec5SDimitry Andric // lambda), if there is a potential capture within the nested lambda, 82220b57cec5SDimitry Andric // have the outer capture-able lambda try and capture it. 82230b57cec5SDimitry Andric // Consider the following code: 82240b57cec5SDimitry Andric // void f(int, int); 82250b57cec5SDimitry Andric // void f(const int&, double); 82260b57cec5SDimitry Andric // void foo() { 82270b57cec5SDimitry Andric // const int x = 10, y = 20; 82280b57cec5SDimitry Andric // auto L = [=](auto a) { 82290b57cec5SDimitry Andric // auto M = [=](auto b) { 82300b57cec5SDimitry Andric // f(x, b); <-- requires x to be captured by L and M 82310b57cec5SDimitry Andric // f(y, a); <-- requires y to be captured by L, but not all Ms 82320b57cec5SDimitry Andric // }; 82330b57cec5SDimitry Andric // }; 82340b57cec5SDimitry Andric // } 82350b57cec5SDimitry Andric 82360b57cec5SDimitry Andric // FIXME: Also consider what happens for something like this that involves 82370b57cec5SDimitry Andric // the gnu-extension statement-expressions or even lambda-init-captures: 82380b57cec5SDimitry Andric // void f() { 82390b57cec5SDimitry Andric // const int n = 0; 82400b57cec5SDimitry Andric // auto L = [&](auto a) { 82410b57cec5SDimitry Andric // +n + ({ 0; a; }); 82420b57cec5SDimitry Andric // }; 82430b57cec5SDimitry Andric // } 82440b57cec5SDimitry Andric // 82450b57cec5SDimitry Andric // Here, we see +n, and then the full-expression 0; ends, so we don't 82460b57cec5SDimitry Andric // capture n (and instead remove it from our list of potential captures), 82470b57cec5SDimitry Andric // and then the full-expression +n + ({ 0; }); ends, but it's too late 82480b57cec5SDimitry Andric // for us to see that we need to capture n after all. 82490b57cec5SDimitry Andric 82500b57cec5SDimitry Andric LambdaScopeInfo *const CurrentLSI = 82510b57cec5SDimitry Andric getCurLambda(/*IgnoreCapturedRegions=*/true); 82520b57cec5SDimitry Andric // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 82530b57cec5SDimitry Andric // even if CurContext is not a lambda call operator. Refer to that Bug Report 82540b57cec5SDimitry Andric // for an example of the code that might cause this asynchrony. 82550b57cec5SDimitry Andric // By ensuring we are in the context of a lambda's call operator 82560b57cec5SDimitry Andric // we can fix the bug (we only need to check whether we need to capture 82570b57cec5SDimitry Andric // if we are within a lambda's body); but per the comments in that 82580b57cec5SDimitry Andric // PR, a proper fix would entail : 82590b57cec5SDimitry Andric // "Alternative suggestion: 82600b57cec5SDimitry Andric // - Add to Sema an integer holding the smallest (outermost) scope 82610b57cec5SDimitry Andric // index that we are *lexically* within, and save/restore/set to 82620b57cec5SDimitry Andric // FunctionScopes.size() in InstantiatingTemplate's 82630b57cec5SDimitry Andric // constructor/destructor. 82640b57cec5SDimitry Andric // - Teach the handful of places that iterate over FunctionScopes to 82650b57cec5SDimitry Andric // stop at the outermost enclosing lexical scope." 82660b57cec5SDimitry Andric DeclContext *DC = CurContext; 82670b57cec5SDimitry Andric while (DC && isa<CapturedDecl>(DC)) 82680b57cec5SDimitry Andric DC = DC->getParent(); 82690b57cec5SDimitry Andric const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); 82700b57cec5SDimitry Andric if (IsInLambdaDeclContext && CurrentLSI && 82710b57cec5SDimitry Andric CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) 82720b57cec5SDimitry Andric CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, 82730b57cec5SDimitry Andric *this); 82740b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(FullExpr); 82750b57cec5SDimitry Andric } 82760b57cec5SDimitry Andric 82770b57cec5SDimitry Andric StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 82780b57cec5SDimitry Andric if (!FullStmt) return StmtError(); 82790b57cec5SDimitry Andric 82800b57cec5SDimitry Andric return MaybeCreateStmtWithCleanups(FullStmt); 82810b57cec5SDimitry Andric } 82820b57cec5SDimitry Andric 82830b57cec5SDimitry Andric Sema::IfExistsResult 82840b57cec5SDimitry Andric Sema::CheckMicrosoftIfExistsSymbol(Scope *S, 82850b57cec5SDimitry Andric CXXScopeSpec &SS, 82860b57cec5SDimitry Andric const DeclarationNameInfo &TargetNameInfo) { 82870b57cec5SDimitry Andric DeclarationName TargetName = TargetNameInfo.getName(); 82880b57cec5SDimitry Andric if (!TargetName) 82890b57cec5SDimitry Andric return IER_DoesNotExist; 82900b57cec5SDimitry Andric 82910b57cec5SDimitry Andric // If the name itself is dependent, then the result is dependent. 82920b57cec5SDimitry Andric if (TargetName.isDependentName()) 82930b57cec5SDimitry Andric return IER_Dependent; 82940b57cec5SDimitry Andric 82950b57cec5SDimitry Andric // Do the redeclaration lookup in the current scope. 82960b57cec5SDimitry Andric LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 82970b57cec5SDimitry Andric Sema::NotForRedeclaration); 82980b57cec5SDimitry Andric LookupParsedName(R, S, &SS); 82990b57cec5SDimitry Andric R.suppressDiagnostics(); 83000b57cec5SDimitry Andric 83010b57cec5SDimitry Andric switch (R.getResultKind()) { 83020b57cec5SDimitry Andric case LookupResult::Found: 83030b57cec5SDimitry Andric case LookupResult::FoundOverloaded: 83040b57cec5SDimitry Andric case LookupResult::FoundUnresolvedValue: 83050b57cec5SDimitry Andric case LookupResult::Ambiguous: 83060b57cec5SDimitry Andric return IER_Exists; 83070b57cec5SDimitry Andric 83080b57cec5SDimitry Andric case LookupResult::NotFound: 83090b57cec5SDimitry Andric return IER_DoesNotExist; 83100b57cec5SDimitry Andric 83110b57cec5SDimitry Andric case LookupResult::NotFoundInCurrentInstantiation: 83120b57cec5SDimitry Andric return IER_Dependent; 83130b57cec5SDimitry Andric } 83140b57cec5SDimitry Andric 83150b57cec5SDimitry Andric llvm_unreachable("Invalid LookupResult Kind!"); 83160b57cec5SDimitry Andric } 83170b57cec5SDimitry Andric 83180b57cec5SDimitry Andric Sema::IfExistsResult 83190b57cec5SDimitry Andric Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 83200b57cec5SDimitry Andric bool IsIfExists, CXXScopeSpec &SS, 83210b57cec5SDimitry Andric UnqualifiedId &Name) { 83220b57cec5SDimitry Andric DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 83230b57cec5SDimitry Andric 83240b57cec5SDimitry Andric // Check for an unexpanded parameter pack. 83250b57cec5SDimitry Andric auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; 83260b57cec5SDimitry Andric if (DiagnoseUnexpandedParameterPack(SS, UPPC) || 83270b57cec5SDimitry Andric DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) 83280b57cec5SDimitry Andric return IER_Error; 83290b57cec5SDimitry Andric 83300b57cec5SDimitry Andric return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 83310b57cec5SDimitry Andric } 833255e4f9d5SDimitry Andric 833355e4f9d5SDimitry Andric concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { 833455e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/true, 833555e4f9d5SDimitry Andric /*NoexceptLoc=*/SourceLocation(), 833655e4f9d5SDimitry Andric /*ReturnTypeRequirement=*/{}); 833755e4f9d5SDimitry Andric } 833855e4f9d5SDimitry Andric 833955e4f9d5SDimitry Andric concepts::Requirement * 834055e4f9d5SDimitry Andric Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, 834155e4f9d5SDimitry Andric SourceLocation NameLoc, IdentifierInfo *TypeName, 834255e4f9d5SDimitry Andric TemplateIdAnnotation *TemplateId) { 834355e4f9d5SDimitry Andric assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) && 834455e4f9d5SDimitry Andric "Exactly one of TypeName and TemplateId must be specified."); 834555e4f9d5SDimitry Andric TypeSourceInfo *TSI = nullptr; 834655e4f9d5SDimitry Andric if (TypeName) { 834755e4f9d5SDimitry Andric QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc, 834855e4f9d5SDimitry Andric SS.getWithLocInContext(Context), *TypeName, 834955e4f9d5SDimitry Andric NameLoc, &TSI, /*DeducedTypeContext=*/false); 835055e4f9d5SDimitry Andric if (T.isNull()) 835155e4f9d5SDimitry Andric return nullptr; 835255e4f9d5SDimitry Andric } else { 835355e4f9d5SDimitry Andric ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), 835455e4f9d5SDimitry Andric TemplateId->NumArgs); 835555e4f9d5SDimitry Andric TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS, 835655e4f9d5SDimitry Andric TemplateId->TemplateKWLoc, 835755e4f9d5SDimitry Andric TemplateId->Template, TemplateId->Name, 835855e4f9d5SDimitry Andric TemplateId->TemplateNameLoc, 835955e4f9d5SDimitry Andric TemplateId->LAngleLoc, ArgsPtr, 836055e4f9d5SDimitry Andric TemplateId->RAngleLoc); 836155e4f9d5SDimitry Andric if (T.isInvalid()) 836255e4f9d5SDimitry Andric return nullptr; 836355e4f9d5SDimitry Andric if (GetTypeFromParser(T.get(), &TSI).isNull()) 836455e4f9d5SDimitry Andric return nullptr; 836555e4f9d5SDimitry Andric } 836655e4f9d5SDimitry Andric return BuildTypeRequirement(TSI); 836755e4f9d5SDimitry Andric } 836855e4f9d5SDimitry Andric 836955e4f9d5SDimitry Andric concepts::Requirement * 837055e4f9d5SDimitry Andric Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { 837155e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, 837255e4f9d5SDimitry Andric /*ReturnTypeRequirement=*/{}); 837355e4f9d5SDimitry Andric } 837455e4f9d5SDimitry Andric 837555e4f9d5SDimitry Andric concepts::Requirement * 837655e4f9d5SDimitry Andric Sema::ActOnCompoundRequirement( 837755e4f9d5SDimitry Andric Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 837855e4f9d5SDimitry Andric TemplateIdAnnotation *TypeConstraint, unsigned Depth) { 837955e4f9d5SDimitry Andric // C++2a [expr.prim.req.compound] p1.3.3 838055e4f9d5SDimitry Andric // [..] the expression is deduced against an invented function template 838155e4f9d5SDimitry Andric // F [...] F is a void function template with a single type template 838255e4f9d5SDimitry Andric // parameter T declared with the constrained-parameter. Form a new 838355e4f9d5SDimitry Andric // cv-qualifier-seq cv by taking the union of const and volatile specifiers 838455e4f9d5SDimitry Andric // around the constrained-parameter. F has a single parameter whose 838555e4f9d5SDimitry Andric // type-specifier is cv T followed by the abstract-declarator. [...] 838655e4f9d5SDimitry Andric // 838755e4f9d5SDimitry Andric // The cv part is done in the calling function - we get the concept with 838855e4f9d5SDimitry Andric // arguments and the abstract declarator with the correct CV qualification and 838955e4f9d5SDimitry Andric // have to synthesize T and the single parameter of F. 839055e4f9d5SDimitry Andric auto &II = Context.Idents.get("expr-type"); 839155e4f9d5SDimitry Andric auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext, 839255e4f9d5SDimitry Andric SourceLocation(), 839355e4f9d5SDimitry Andric SourceLocation(), Depth, 839455e4f9d5SDimitry Andric /*Index=*/0, &II, 839555e4f9d5SDimitry Andric /*Typename=*/true, 839655e4f9d5SDimitry Andric /*ParameterPack=*/false, 839755e4f9d5SDimitry Andric /*HasTypeConstraint=*/true); 839855e4f9d5SDimitry Andric 839955e4f9d5SDimitry Andric if (ActOnTypeConstraint(SS, TypeConstraint, TParam, 840055e4f9d5SDimitry Andric /*EllpsisLoc=*/SourceLocation())) 840155e4f9d5SDimitry Andric // Just produce a requirement with no type requirements. 840255e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {}); 840355e4f9d5SDimitry Andric 840455e4f9d5SDimitry Andric auto *TPL = TemplateParameterList::Create(Context, SourceLocation(), 840555e4f9d5SDimitry Andric SourceLocation(), 840655e4f9d5SDimitry Andric ArrayRef<NamedDecl *>(TParam), 840755e4f9d5SDimitry Andric SourceLocation(), 840855e4f9d5SDimitry Andric /*RequiresClause=*/nullptr); 840955e4f9d5SDimitry Andric return BuildExprRequirement( 841055e4f9d5SDimitry Andric E, /*IsSimple=*/false, NoexceptLoc, 841155e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement(TPL)); 841255e4f9d5SDimitry Andric } 841355e4f9d5SDimitry Andric 841455e4f9d5SDimitry Andric concepts::ExprRequirement * 841555e4f9d5SDimitry Andric Sema::BuildExprRequirement( 841655e4f9d5SDimitry Andric Expr *E, bool IsSimple, SourceLocation NoexceptLoc, 841755e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 841855e4f9d5SDimitry Andric auto Status = concepts::ExprRequirement::SS_Satisfied; 841955e4f9d5SDimitry Andric ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; 842055e4f9d5SDimitry Andric if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent()) 842155e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_Dependent; 842255e4f9d5SDimitry Andric else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) 842355e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_NoexceptNotMet; 842455e4f9d5SDimitry Andric else if (ReturnTypeRequirement.isSubstitutionFailure()) 842555e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; 842655e4f9d5SDimitry Andric else if (ReturnTypeRequirement.isTypeConstraint()) { 842755e4f9d5SDimitry Andric // C++2a [expr.prim.req]p1.3.3 842855e4f9d5SDimitry Andric // The immediately-declared constraint ([temp]) of decltype((E)) shall 842955e4f9d5SDimitry Andric // be satisfied. 843055e4f9d5SDimitry Andric TemplateParameterList *TPL = 843155e4f9d5SDimitry Andric ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); 843255e4f9d5SDimitry Andric QualType MatchedType = 843355e4f9d5SDimitry Andric BuildDecltypeType(E, E->getBeginLoc()).getCanonicalType(); 843455e4f9d5SDimitry Andric llvm::SmallVector<TemplateArgument, 1> Args; 843555e4f9d5SDimitry Andric Args.push_back(TemplateArgument(MatchedType)); 843655e4f9d5SDimitry Andric TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args); 843755e4f9d5SDimitry Andric MultiLevelTemplateArgumentList MLTAL(TAL); 843855e4f9d5SDimitry Andric for (unsigned I = 0; I < TPL->getDepth(); ++I) 843955e4f9d5SDimitry Andric MLTAL.addOuterRetainedLevel(); 844055e4f9d5SDimitry Andric Expr *IDC = 844155e4f9d5SDimitry Andric cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint() 844255e4f9d5SDimitry Andric ->getImmediatelyDeclaredConstraint(); 844355e4f9d5SDimitry Andric ExprResult Constraint = SubstExpr(IDC, MLTAL); 844455e4f9d5SDimitry Andric assert(!Constraint.isInvalid() && 844555e4f9d5SDimitry Andric "Substitution cannot fail as it is simply putting a type template " 844655e4f9d5SDimitry Andric "argument into a concept specialization expression's parameter."); 844755e4f9d5SDimitry Andric 844855e4f9d5SDimitry Andric SubstitutedConstraintExpr = 844955e4f9d5SDimitry Andric cast<ConceptSpecializationExpr>(Constraint.get()); 845055e4f9d5SDimitry Andric if (!SubstitutedConstraintExpr->isSatisfied()) 845155e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; 845255e4f9d5SDimitry Andric } 845355e4f9d5SDimitry Andric return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, 845455e4f9d5SDimitry Andric ReturnTypeRequirement, Status, 845555e4f9d5SDimitry Andric SubstitutedConstraintExpr); 845655e4f9d5SDimitry Andric } 845755e4f9d5SDimitry Andric 845855e4f9d5SDimitry Andric concepts::ExprRequirement * 845955e4f9d5SDimitry Andric Sema::BuildExprRequirement( 846055e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, 846155e4f9d5SDimitry Andric bool IsSimple, SourceLocation NoexceptLoc, 846255e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 846355e4f9d5SDimitry Andric return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, 846455e4f9d5SDimitry Andric IsSimple, NoexceptLoc, 846555e4f9d5SDimitry Andric ReturnTypeRequirement); 846655e4f9d5SDimitry Andric } 846755e4f9d5SDimitry Andric 846855e4f9d5SDimitry Andric concepts::TypeRequirement * 846955e4f9d5SDimitry Andric Sema::BuildTypeRequirement(TypeSourceInfo *Type) { 847055e4f9d5SDimitry Andric return new (Context) concepts::TypeRequirement(Type); 847155e4f9d5SDimitry Andric } 847255e4f9d5SDimitry Andric 847355e4f9d5SDimitry Andric concepts::TypeRequirement * 847455e4f9d5SDimitry Andric Sema::BuildTypeRequirement( 847555e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { 847655e4f9d5SDimitry Andric return new (Context) concepts::TypeRequirement(SubstDiag); 847755e4f9d5SDimitry Andric } 847855e4f9d5SDimitry Andric 847955e4f9d5SDimitry Andric concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { 848055e4f9d5SDimitry Andric return BuildNestedRequirement(Constraint); 848155e4f9d5SDimitry Andric } 848255e4f9d5SDimitry Andric 848355e4f9d5SDimitry Andric concepts::NestedRequirement * 848455e4f9d5SDimitry Andric Sema::BuildNestedRequirement(Expr *Constraint) { 848555e4f9d5SDimitry Andric ConstraintSatisfaction Satisfaction; 848655e4f9d5SDimitry Andric if (!Constraint->isInstantiationDependent() && 848713138422SDimitry Andric CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{}, 848813138422SDimitry Andric Constraint->getSourceRange(), Satisfaction)) 848955e4f9d5SDimitry Andric return nullptr; 849055e4f9d5SDimitry Andric return new (Context) concepts::NestedRequirement(Context, Constraint, 849155e4f9d5SDimitry Andric Satisfaction); 849255e4f9d5SDimitry Andric } 849355e4f9d5SDimitry Andric 849455e4f9d5SDimitry Andric concepts::NestedRequirement * 849555e4f9d5SDimitry Andric Sema::BuildNestedRequirement( 849655e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { 849755e4f9d5SDimitry Andric return new (Context) concepts::NestedRequirement(SubstDiag); 849855e4f9d5SDimitry Andric } 849955e4f9d5SDimitry Andric 850055e4f9d5SDimitry Andric RequiresExprBodyDecl * 850155e4f9d5SDimitry Andric Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 850255e4f9d5SDimitry Andric ArrayRef<ParmVarDecl *> LocalParameters, 850355e4f9d5SDimitry Andric Scope *BodyScope) { 850455e4f9d5SDimitry Andric assert(BodyScope); 850555e4f9d5SDimitry Andric 850655e4f9d5SDimitry Andric RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext, 850755e4f9d5SDimitry Andric RequiresKWLoc); 850855e4f9d5SDimitry Andric 850955e4f9d5SDimitry Andric PushDeclContext(BodyScope, Body); 851055e4f9d5SDimitry Andric 851155e4f9d5SDimitry Andric for (ParmVarDecl *Param : LocalParameters) { 851255e4f9d5SDimitry Andric if (Param->hasDefaultArg()) 851355e4f9d5SDimitry Andric // C++2a [expr.prim.req] p4 851455e4f9d5SDimitry Andric // [...] A local parameter of a requires-expression shall not have a 851555e4f9d5SDimitry Andric // default argument. [...] 851655e4f9d5SDimitry Andric Diag(Param->getDefaultArgRange().getBegin(), 851755e4f9d5SDimitry Andric diag::err_requires_expr_local_parameter_default_argument); 851855e4f9d5SDimitry Andric // Ignore default argument and move on 851955e4f9d5SDimitry Andric 852055e4f9d5SDimitry Andric Param->setDeclContext(Body); 852155e4f9d5SDimitry Andric // If this has an identifier, add it to the scope stack. 852255e4f9d5SDimitry Andric if (Param->getIdentifier()) { 852355e4f9d5SDimitry Andric CheckShadow(BodyScope, Param); 852455e4f9d5SDimitry Andric PushOnScopeChains(Param, BodyScope); 852555e4f9d5SDimitry Andric } 852655e4f9d5SDimitry Andric } 852755e4f9d5SDimitry Andric return Body; 852855e4f9d5SDimitry Andric } 852955e4f9d5SDimitry Andric 853055e4f9d5SDimitry Andric void Sema::ActOnFinishRequiresExpr() { 853155e4f9d5SDimitry Andric assert(CurContext && "DeclContext imbalance!"); 853255e4f9d5SDimitry Andric CurContext = CurContext->getLexicalParent(); 853355e4f9d5SDimitry Andric assert(CurContext && "Popped translation unit!"); 853455e4f9d5SDimitry Andric } 853555e4f9d5SDimitry Andric 853655e4f9d5SDimitry Andric ExprResult 853755e4f9d5SDimitry Andric Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc, 853855e4f9d5SDimitry Andric RequiresExprBodyDecl *Body, 853955e4f9d5SDimitry Andric ArrayRef<ParmVarDecl *> LocalParameters, 854055e4f9d5SDimitry Andric ArrayRef<concepts::Requirement *> Requirements, 854155e4f9d5SDimitry Andric SourceLocation ClosingBraceLoc) { 854255e4f9d5SDimitry Andric return RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters, 854355e4f9d5SDimitry Andric Requirements, ClosingBraceLoc); 854455e4f9d5SDimitry Andric } 8545