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. 1595ffd83dbSDimitry Andric // 1605ffd83dbSDimitry Andric // For now, we accept all the cases in which the name given could plausibly 1615ffd83dbSDimitry Andric // be interpreted as a correct destructor name, issuing off-by-default 1625ffd83dbSDimitry Andric // extension diagnostics on the cases that don't strictly conform to the 1635ffd83dbSDimitry Andric // C++20 rules. This basically means we always consider looking in the 1645ffd83dbSDimitry Andric // nested-name-specifier prefix, the complete nested-name-specifier, and 1655ffd83dbSDimitry Andric // the scope, and accept if we find the expected type in any of the three 1665ffd83dbSDimitry Andric // places. 1670b57cec5SDimitry Andric 1680b57cec5SDimitry Andric if (SS.isInvalid()) 1690b57cec5SDimitry Andric return nullptr; 1700b57cec5SDimitry Andric 1715ffd83dbSDimitry Andric // Whether we've failed with a diagnostic already. 1725ffd83dbSDimitry Andric bool Failed = false; 1735ffd83dbSDimitry Andric 1745ffd83dbSDimitry Andric llvm::SmallVector<NamedDecl*, 8> FoundDecls; 175e8d8bef9SDimitry Andric llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; 1765ffd83dbSDimitry Andric 1770b57cec5SDimitry Andric // If we have an object type, it's because we are in a 1780b57cec5SDimitry Andric // pseudo-destructor-expression or a member access expression, and 1790b57cec5SDimitry Andric // we know what type we're looking for. 1805ffd83dbSDimitry Andric QualType SearchType = 1815ffd83dbSDimitry Andric ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType(); 1820b57cec5SDimitry Andric 1835ffd83dbSDimitry Andric auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType { 1845ffd83dbSDimitry Andric auto IsAcceptableResult = [&](NamedDecl *D) -> bool { 1855ffd83dbSDimitry Andric auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl()); 1865ffd83dbSDimitry Andric if (!Type) 1875ffd83dbSDimitry Andric return false; 1880b57cec5SDimitry Andric 1895ffd83dbSDimitry Andric if (SearchType.isNull() || SearchType->isDependentType()) 1905ffd83dbSDimitry Andric return true; 1915ffd83dbSDimitry Andric 1925ffd83dbSDimitry Andric QualType T = Context.getTypeDeclType(Type); 1935ffd83dbSDimitry Andric return Context.hasSameUnqualifiedType(T, SearchType); 1945ffd83dbSDimitry Andric }; 1955ffd83dbSDimitry Andric 1965ffd83dbSDimitry Andric unsigned NumAcceptableResults = 0; 1975ffd83dbSDimitry Andric for (NamedDecl *D : Found) { 1985ffd83dbSDimitry Andric if (IsAcceptableResult(D)) 1995ffd83dbSDimitry Andric ++NumAcceptableResults; 2005ffd83dbSDimitry Andric 2015ffd83dbSDimitry Andric // Don't list a class twice in the lookup failure diagnostic if it's 2025ffd83dbSDimitry Andric // found by both its injected-class-name and by the name in the enclosing 2035ffd83dbSDimitry Andric // scope. 2045ffd83dbSDimitry Andric if (auto *RD = dyn_cast<CXXRecordDecl>(D)) 2055ffd83dbSDimitry Andric if (RD->isInjectedClassName()) 2065ffd83dbSDimitry Andric D = cast<NamedDecl>(RD->getParent()); 2075ffd83dbSDimitry Andric 2085ffd83dbSDimitry Andric if (FoundDeclSet.insert(D).second) 2095ffd83dbSDimitry Andric FoundDecls.push_back(D); 2100b57cec5SDimitry Andric } 2110b57cec5SDimitry Andric 2125ffd83dbSDimitry Andric // As an extension, attempt to "fix" an ambiguity by erasing all non-type 2135ffd83dbSDimitry Andric // results, and all non-matching results if we have a search type. It's not 2145ffd83dbSDimitry Andric // clear what the right behavior is if destructor lookup hits an ambiguity, 2155ffd83dbSDimitry Andric // but other compilers do generally accept at least some kinds of 2165ffd83dbSDimitry Andric // ambiguity. 2175ffd83dbSDimitry Andric if (Found.isAmbiguous() && NumAcceptableResults == 1) { 2185ffd83dbSDimitry Andric Diag(NameLoc, diag::ext_dtor_name_ambiguous); 2195ffd83dbSDimitry Andric LookupResult::Filter F = Found.makeFilter(); 2205ffd83dbSDimitry Andric while (F.hasNext()) { 2215ffd83dbSDimitry Andric NamedDecl *D = F.next(); 2225ffd83dbSDimitry Andric if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) 2235ffd83dbSDimitry Andric Diag(D->getLocation(), diag::note_destructor_type_here) 2245ffd83dbSDimitry Andric << Context.getTypeDeclType(TD); 2255ffd83dbSDimitry Andric else 2265ffd83dbSDimitry Andric Diag(D->getLocation(), diag::note_destructor_nontype_here); 2275ffd83dbSDimitry Andric 2285ffd83dbSDimitry Andric if (!IsAcceptableResult(D)) 2295ffd83dbSDimitry Andric F.erase(); 2300b57cec5SDimitry Andric } 2315ffd83dbSDimitry Andric F.done(); 2325ffd83dbSDimitry Andric } 2335ffd83dbSDimitry Andric 2345ffd83dbSDimitry Andric if (Found.isAmbiguous()) 2355ffd83dbSDimitry Andric Failed = true; 2365ffd83dbSDimitry Andric 2375ffd83dbSDimitry Andric if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { 2385ffd83dbSDimitry Andric if (IsAcceptableResult(Type)) { 2395ffd83dbSDimitry Andric QualType T = Context.getTypeDeclType(Type); 2405ffd83dbSDimitry Andric MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 2415ffd83dbSDimitry Andric return CreateParsedType(T, 2425ffd83dbSDimitry Andric Context.getTrivialTypeSourceInfo(T, NameLoc)); 2435ffd83dbSDimitry Andric } 2445ffd83dbSDimitry Andric } 2455ffd83dbSDimitry Andric 2465ffd83dbSDimitry Andric return nullptr; 2475ffd83dbSDimitry Andric }; 2485ffd83dbSDimitry Andric 2495ffd83dbSDimitry Andric bool IsDependent = false; 2505ffd83dbSDimitry Andric 2515ffd83dbSDimitry Andric auto LookupInObjectType = [&]() -> ParsedType { 2525ffd83dbSDimitry Andric if (Failed || SearchType.isNull()) 2535ffd83dbSDimitry Andric return nullptr; 2545ffd83dbSDimitry Andric 2555ffd83dbSDimitry Andric IsDependent |= SearchType->isDependentType(); 2565ffd83dbSDimitry Andric 2575ffd83dbSDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 2585ffd83dbSDimitry Andric DeclContext *LookupCtx = computeDeclContext(SearchType); 2595ffd83dbSDimitry Andric if (!LookupCtx) 2605ffd83dbSDimitry Andric return nullptr; 2615ffd83dbSDimitry Andric LookupQualifiedName(Found, LookupCtx); 2625ffd83dbSDimitry Andric return CheckLookupResult(Found); 2635ffd83dbSDimitry Andric }; 2645ffd83dbSDimitry Andric 2655ffd83dbSDimitry Andric auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType { 2665ffd83dbSDimitry Andric if (Failed) 2675ffd83dbSDimitry Andric return nullptr; 2685ffd83dbSDimitry Andric 2695ffd83dbSDimitry Andric IsDependent |= isDependentScopeSpecifier(LookupSS); 2705ffd83dbSDimitry Andric DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext); 2715ffd83dbSDimitry Andric if (!LookupCtx) 2725ffd83dbSDimitry Andric return nullptr; 2735ffd83dbSDimitry Andric 2745ffd83dbSDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 2755ffd83dbSDimitry Andric if (RequireCompleteDeclContext(LookupSS, LookupCtx)) { 2765ffd83dbSDimitry Andric Failed = true; 2775ffd83dbSDimitry Andric return nullptr; 2785ffd83dbSDimitry Andric } 2795ffd83dbSDimitry Andric LookupQualifiedName(Found, LookupCtx); 2805ffd83dbSDimitry Andric return CheckLookupResult(Found); 2815ffd83dbSDimitry Andric }; 2825ffd83dbSDimitry Andric 2835ffd83dbSDimitry Andric auto LookupInScope = [&]() -> ParsedType { 2845ffd83dbSDimitry Andric if (Failed || !S) 2855ffd83dbSDimitry Andric return nullptr; 2865ffd83dbSDimitry Andric 2875ffd83dbSDimitry Andric LookupResult Found(*this, &II, NameLoc, LookupDestructorName); 2885ffd83dbSDimitry Andric LookupName(Found, S); 2895ffd83dbSDimitry Andric return CheckLookupResult(Found); 2905ffd83dbSDimitry Andric }; 2915ffd83dbSDimitry Andric 2925ffd83dbSDimitry Andric // C++2a [basic.lookup.qual]p6: 2935ffd83dbSDimitry Andric // In a qualified-id of the form 2945ffd83dbSDimitry Andric // 2955ffd83dbSDimitry Andric // nested-name-specifier[opt] type-name :: ~ type-name 2965ffd83dbSDimitry Andric // 2975ffd83dbSDimitry Andric // the second type-name is looked up in the same scope as the first. 2985ffd83dbSDimitry Andric // 2995ffd83dbSDimitry Andric // We interpret this as meaning that if you do a dual-scope lookup for the 3005ffd83dbSDimitry Andric // first name, you also do a dual-scope lookup for the second name, per 3015ffd83dbSDimitry Andric // C++ [basic.lookup.classref]p4: 3025ffd83dbSDimitry Andric // 3035ffd83dbSDimitry Andric // If the id-expression in a class member access is a qualified-id of the 3045ffd83dbSDimitry Andric // form 3055ffd83dbSDimitry Andric // 3065ffd83dbSDimitry Andric // class-name-or-namespace-name :: ... 3075ffd83dbSDimitry Andric // 3085ffd83dbSDimitry Andric // the class-name-or-namespace-name following the . or -> is first looked 3095ffd83dbSDimitry Andric // up in the class of the object expression and the name, if found, is used. 3105ffd83dbSDimitry Andric // Otherwise, it is looked up in the context of the entire 3115ffd83dbSDimitry Andric // postfix-expression. 3125ffd83dbSDimitry Andric // 3135ffd83dbSDimitry Andric // This looks in the same scopes as for an unqualified destructor name: 3145ffd83dbSDimitry Andric // 3150b57cec5SDimitry Andric // C++ [basic.lookup.classref]p3: 3160b57cec5SDimitry Andric // If the unqualified-id is ~ type-name, the type-name is looked up 3170b57cec5SDimitry Andric // in the context of the entire postfix-expression. If the type T 3180b57cec5SDimitry Andric // of the object expression is of a class type C, the type-name is 3190b57cec5SDimitry Andric // also looked up in the scope of class C. At least one of the 3205ffd83dbSDimitry Andric // lookups shall find a name that refers to cv T. 3215ffd83dbSDimitry Andric // 3225ffd83dbSDimitry Andric // FIXME: The intent is unclear here. Should type-name::~type-name look in 3235ffd83dbSDimitry Andric // the scope anyway if it finds a non-matching name declared in the class? 3245ffd83dbSDimitry Andric // If both lookups succeed and find a dependent result, which result should 3255ffd83dbSDimitry Andric // we retain? (Same question for p->~type-name().) 3260b57cec5SDimitry Andric 3275ffd83dbSDimitry Andric if (NestedNameSpecifier *Prefix = 3285ffd83dbSDimitry Andric SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) { 3295ffd83dbSDimitry Andric // This is 3305ffd83dbSDimitry Andric // 3315ffd83dbSDimitry Andric // nested-name-specifier type-name :: ~ type-name 3325ffd83dbSDimitry Andric // 3335ffd83dbSDimitry Andric // Look for the second type-name in the nested-name-specifier. 3345ffd83dbSDimitry Andric CXXScopeSpec PrefixSS; 3355ffd83dbSDimitry Andric PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); 3365ffd83dbSDimitry Andric if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) 3375ffd83dbSDimitry Andric return T; 3380b57cec5SDimitry Andric } else { 3395ffd83dbSDimitry Andric // This is one of 3405ffd83dbSDimitry Andric // 3415ffd83dbSDimitry Andric // type-name :: ~ type-name 3425ffd83dbSDimitry Andric // ~ type-name 3435ffd83dbSDimitry Andric // 3445ffd83dbSDimitry Andric // Look in the scope and (if any) the object type. 3455ffd83dbSDimitry Andric if (ParsedType T = LookupInScope()) 3465ffd83dbSDimitry Andric return T; 3475ffd83dbSDimitry Andric if (ParsedType T = LookupInObjectType()) 3485ffd83dbSDimitry Andric return T; 3490b57cec5SDimitry Andric } 3500b57cec5SDimitry Andric 3515ffd83dbSDimitry Andric if (Failed) 3520b57cec5SDimitry Andric return nullptr; 3530b57cec5SDimitry Andric 3545ffd83dbSDimitry Andric if (IsDependent) { 3555ffd83dbSDimitry Andric // We didn't find our type, but that's OK: it's dependent anyway. 3560b57cec5SDimitry Andric 3570b57cec5SDimitry Andric // FIXME: What if we have no nested-name-specifier? 3580b57cec5SDimitry Andric QualType T = CheckTypenameType(ETK_None, SourceLocation(), 3590b57cec5SDimitry Andric SS.getWithLocInContext(Context), 3600b57cec5SDimitry Andric II, NameLoc); 3610b57cec5SDimitry Andric return ParsedType::make(T); 3620b57cec5SDimitry Andric } 3630b57cec5SDimitry Andric 3645ffd83dbSDimitry Andric // The remaining cases are all non-standard extensions imitating the behavior 3655ffd83dbSDimitry Andric // of various other compilers. 3665ffd83dbSDimitry Andric unsigned NumNonExtensionDecls = FoundDecls.size(); 3675ffd83dbSDimitry Andric 3685ffd83dbSDimitry Andric if (SS.isSet()) { 3695ffd83dbSDimitry Andric // For compatibility with older broken C++ rules and existing code, 3705ffd83dbSDimitry Andric // 3715ffd83dbSDimitry Andric // nested-name-specifier :: ~ type-name 3725ffd83dbSDimitry Andric // 3735ffd83dbSDimitry Andric // also looks for type-name within the nested-name-specifier. 3745ffd83dbSDimitry Andric if (ParsedType T = LookupInNestedNameSpec(SS)) { 3755ffd83dbSDimitry Andric Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope) 3765ffd83dbSDimitry Andric << SS.getRange() 3775ffd83dbSDimitry Andric << FixItHint::CreateInsertion(SS.getEndLoc(), 3785ffd83dbSDimitry Andric ("::" + II.getName()).str()); 3795ffd83dbSDimitry Andric return T; 3800b57cec5SDimitry Andric } 3815ffd83dbSDimitry Andric 3825ffd83dbSDimitry Andric // For compatibility with other compilers and older versions of Clang, 3835ffd83dbSDimitry Andric // 3845ffd83dbSDimitry Andric // nested-name-specifier type-name :: ~ type-name 3855ffd83dbSDimitry Andric // 3865ffd83dbSDimitry Andric // also looks for type-name in the scope. Unfortunately, we can't 3875ffd83dbSDimitry Andric // reasonably apply this fallback for dependent nested-name-specifiers. 3885ffd83dbSDimitry Andric if (SS.getScopeRep()->getPrefix()) { 3895ffd83dbSDimitry Andric if (ParsedType T = LookupInScope()) { 3905ffd83dbSDimitry Andric Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope) 3915ffd83dbSDimitry Andric << FixItHint::CreateRemoval(SS.getRange()); 3925ffd83dbSDimitry Andric Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here) 3935ffd83dbSDimitry Andric << GetTypeFromParser(T); 3945ffd83dbSDimitry Andric return T; 3955ffd83dbSDimitry Andric } 3965ffd83dbSDimitry Andric } 3975ffd83dbSDimitry Andric } 3985ffd83dbSDimitry Andric 3995ffd83dbSDimitry Andric // We didn't find anything matching; tell the user what we did find (if 4005ffd83dbSDimitry Andric // anything). 4015ffd83dbSDimitry Andric 4025ffd83dbSDimitry Andric // Don't tell the user about declarations we shouldn't have found. 4035ffd83dbSDimitry Andric FoundDecls.resize(NumNonExtensionDecls); 4045ffd83dbSDimitry Andric 4055ffd83dbSDimitry Andric // List types before non-types. 4065ffd83dbSDimitry Andric std::stable_sort(FoundDecls.begin(), FoundDecls.end(), 4075ffd83dbSDimitry Andric [](NamedDecl *A, NamedDecl *B) { 4085ffd83dbSDimitry Andric return isa<TypeDecl>(A->getUnderlyingDecl()) > 4095ffd83dbSDimitry Andric isa<TypeDecl>(B->getUnderlyingDecl()); 4105ffd83dbSDimitry Andric }); 4115ffd83dbSDimitry Andric 4125ffd83dbSDimitry Andric // Suggest a fixit to properly name the destroyed type. 4135ffd83dbSDimitry Andric auto MakeFixItHint = [&]{ 4145ffd83dbSDimitry Andric const CXXRecordDecl *Destroyed = nullptr; 4155ffd83dbSDimitry Andric // FIXME: If we have a scope specifier, suggest its last component? 4165ffd83dbSDimitry Andric if (!SearchType.isNull()) 4175ffd83dbSDimitry Andric Destroyed = SearchType->getAsCXXRecordDecl(); 4185ffd83dbSDimitry Andric else if (S) 4195ffd83dbSDimitry Andric Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity()); 4205ffd83dbSDimitry Andric if (Destroyed) 4215ffd83dbSDimitry Andric return FixItHint::CreateReplacement(SourceRange(NameLoc), 4225ffd83dbSDimitry Andric Destroyed->getNameAsString()); 4235ffd83dbSDimitry Andric return FixItHint(); 4245ffd83dbSDimitry Andric }; 4255ffd83dbSDimitry Andric 4265ffd83dbSDimitry Andric if (FoundDecls.empty()) { 4275ffd83dbSDimitry Andric // FIXME: Attempt typo-correction? 4285ffd83dbSDimitry Andric Diag(NameLoc, diag::err_undeclared_destructor_name) 4295ffd83dbSDimitry Andric << &II << MakeFixItHint(); 4305ffd83dbSDimitry Andric } else if (!SearchType.isNull() && FoundDecls.size() == 1) { 4315ffd83dbSDimitry Andric if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) { 4325ffd83dbSDimitry Andric assert(!SearchType.isNull() && 4335ffd83dbSDimitry Andric "should only reject a type result if we have a search type"); 4345ffd83dbSDimitry Andric QualType T = Context.getTypeDeclType(TD); 4355ffd83dbSDimitry Andric Diag(NameLoc, diag::err_destructor_expr_type_mismatch) 4365ffd83dbSDimitry Andric << T << SearchType << MakeFixItHint(); 4375ffd83dbSDimitry Andric } else { 4385ffd83dbSDimitry Andric Diag(NameLoc, diag::err_destructor_expr_nontype) 4395ffd83dbSDimitry Andric << &II << MakeFixItHint(); 4405ffd83dbSDimitry Andric } 4415ffd83dbSDimitry Andric } else { 4425ffd83dbSDimitry Andric Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype 4435ffd83dbSDimitry Andric : diag::err_destructor_expr_mismatch) 4445ffd83dbSDimitry Andric << &II << SearchType << MakeFixItHint(); 4455ffd83dbSDimitry Andric } 4465ffd83dbSDimitry Andric 4475ffd83dbSDimitry Andric for (NamedDecl *FoundD : FoundDecls) { 4485ffd83dbSDimitry Andric if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl())) 4495ffd83dbSDimitry Andric Diag(FoundD->getLocation(), diag::note_destructor_type_here) 4505ffd83dbSDimitry Andric << Context.getTypeDeclType(TD); 4515ffd83dbSDimitry Andric else 4525ffd83dbSDimitry Andric Diag(FoundD->getLocation(), diag::note_destructor_nontype_here) 4535ffd83dbSDimitry Andric << FoundD; 4540b57cec5SDimitry Andric } 4550b57cec5SDimitry Andric 4560b57cec5SDimitry Andric return nullptr; 4570b57cec5SDimitry Andric } 4580b57cec5SDimitry Andric 4590b57cec5SDimitry Andric ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, 4600b57cec5SDimitry Andric ParsedType ObjectType) { 4610b57cec5SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_error) 4620b57cec5SDimitry Andric return nullptr; 4630b57cec5SDimitry Andric 4640b57cec5SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { 4650b57cec5SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 4660b57cec5SDimitry Andric return nullptr; 4670b57cec5SDimitry Andric } 4680b57cec5SDimitry Andric 4690b57cec5SDimitry Andric assert(DS.getTypeSpecType() == DeclSpec::TST_decltype && 4700b57cec5SDimitry Andric "unexpected type in getDestructorType"); 471349cc55cSDimitry Andric QualType T = BuildDecltypeType(DS.getRepAsExpr()); 4720b57cec5SDimitry Andric 4730b57cec5SDimitry Andric // If we know the type of the object, check that the correct destructor 4740b57cec5SDimitry Andric // type was named now; we can give better diagnostics this way. 4750b57cec5SDimitry Andric QualType SearchType = GetTypeFromParser(ObjectType); 4760b57cec5SDimitry Andric if (!SearchType.isNull() && !SearchType->isDependentType() && 4770b57cec5SDimitry Andric !Context.hasSameUnqualifiedType(T, SearchType)) { 4780b57cec5SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) 4790b57cec5SDimitry Andric << T << SearchType; 4800b57cec5SDimitry Andric return nullptr; 4810b57cec5SDimitry Andric } 4820b57cec5SDimitry Andric 4830b57cec5SDimitry Andric return ParsedType::make(T); 4840b57cec5SDimitry Andric } 4850b57cec5SDimitry Andric 4860b57cec5SDimitry Andric bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, 487fe6060f1SDimitry Andric const UnqualifiedId &Name, bool IsUDSuffix) { 4880b57cec5SDimitry Andric assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId); 489fe6060f1SDimitry Andric if (!IsUDSuffix) { 490fe6060f1SDimitry Andric // [over.literal] p8 491fe6060f1SDimitry Andric // 492fe6060f1SDimitry Andric // double operator""_Bq(long double); // OK: not a reserved identifier 493fe6060f1SDimitry Andric // double operator"" _Bq(long double); // ill-formed, no diagnostic required 494fe6060f1SDimitry Andric IdentifierInfo *II = Name.Identifier; 495fe6060f1SDimitry Andric ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts()); 496fe6060f1SDimitry Andric SourceLocation Loc = Name.getEndLoc(); 497349cc55cSDimitry Andric if (isReservedInAllContexts(Status) && 498fe6060f1SDimitry Andric !PP.getSourceManager().isInSystemHeader(Loc)) { 499fe6060f1SDimitry Andric Diag(Loc, diag::warn_reserved_extern_symbol) 500fe6060f1SDimitry Andric << II << static_cast<int>(Status) 501fe6060f1SDimitry Andric << FixItHint::CreateReplacement( 502fe6060f1SDimitry Andric Name.getSourceRange(), 503fe6060f1SDimitry Andric (StringRef("operator\"\"") + II->getName()).str()); 504fe6060f1SDimitry Andric } 505fe6060f1SDimitry Andric } 5060b57cec5SDimitry Andric 5070b57cec5SDimitry Andric if (!SS.isValid()) 5080b57cec5SDimitry Andric return false; 5090b57cec5SDimitry Andric 5100b57cec5SDimitry Andric switch (SS.getScopeRep()->getKind()) { 5110b57cec5SDimitry Andric case NestedNameSpecifier::Identifier: 5120b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpec: 5130b57cec5SDimitry Andric case NestedNameSpecifier::TypeSpecWithTemplate: 5140b57cec5SDimitry Andric // Per C++11 [over.literal]p2, literal operators can only be declared at 5150b57cec5SDimitry Andric // namespace scope. Therefore, this unqualified-id cannot name anything. 5160b57cec5SDimitry Andric // Reject it early, because we have no AST representation for this in the 5170b57cec5SDimitry Andric // case where the scope is dependent. 5180b57cec5SDimitry Andric Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) 5190b57cec5SDimitry Andric << SS.getScopeRep(); 5200b57cec5SDimitry Andric return true; 5210b57cec5SDimitry Andric 5220b57cec5SDimitry Andric case NestedNameSpecifier::Global: 5230b57cec5SDimitry Andric case NestedNameSpecifier::Super: 5240b57cec5SDimitry Andric case NestedNameSpecifier::Namespace: 5250b57cec5SDimitry Andric case NestedNameSpecifier::NamespaceAlias: 5260b57cec5SDimitry Andric return false; 5270b57cec5SDimitry Andric } 5280b57cec5SDimitry Andric 5290b57cec5SDimitry Andric llvm_unreachable("unknown nested name specifier kind"); 5300b57cec5SDimitry Andric } 5310b57cec5SDimitry Andric 5320b57cec5SDimitry Andric /// Build a C++ typeid expression with a type operand. 5330b57cec5SDimitry Andric ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 5340b57cec5SDimitry Andric SourceLocation TypeidLoc, 5350b57cec5SDimitry Andric TypeSourceInfo *Operand, 5360b57cec5SDimitry Andric SourceLocation RParenLoc) { 5370b57cec5SDimitry Andric // C++ [expr.typeid]p4: 5380b57cec5SDimitry Andric // The top-level cv-qualifiers of the lvalue expression or the type-id 5390b57cec5SDimitry Andric // that is the operand of typeid are always ignored. 5400b57cec5SDimitry Andric // If the type of the type-id is a class type or a reference to a class 5410b57cec5SDimitry Andric // type, the class shall be completely-defined. 5420b57cec5SDimitry Andric Qualifiers Quals; 5430b57cec5SDimitry Andric QualType T 5440b57cec5SDimitry Andric = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), 5450b57cec5SDimitry Andric Quals); 5460b57cec5SDimitry Andric if (T->getAs<RecordType>() && 5470b57cec5SDimitry Andric RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 5480b57cec5SDimitry Andric return ExprError(); 5490b57cec5SDimitry Andric 5500b57cec5SDimitry Andric if (T->isVariablyModifiedType()) 5510b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); 5520b57cec5SDimitry Andric 553a7dea167SDimitry Andric if (CheckQualifiedFunctionForTypeId(T, TypeidLoc)) 554a7dea167SDimitry Andric return ExprError(); 555a7dea167SDimitry Andric 5560b57cec5SDimitry Andric return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, 5570b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 5580b57cec5SDimitry Andric } 5590b57cec5SDimitry Andric 5600b57cec5SDimitry Andric /// Build a C++ typeid expression with an expression operand. 5610b57cec5SDimitry Andric ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, 5620b57cec5SDimitry Andric SourceLocation TypeidLoc, 5630b57cec5SDimitry Andric Expr *E, 5640b57cec5SDimitry Andric SourceLocation RParenLoc) { 5650b57cec5SDimitry Andric bool WasEvaluated = false; 5660b57cec5SDimitry Andric if (E && !E->isTypeDependent()) { 5670b57cec5SDimitry Andric if (E->getType()->isPlaceholderType()) { 5680b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(E); 5690b57cec5SDimitry Andric if (result.isInvalid()) return ExprError(); 5700b57cec5SDimitry Andric E = result.get(); 5710b57cec5SDimitry Andric } 5720b57cec5SDimitry Andric 5730b57cec5SDimitry Andric QualType T = E->getType(); 5740b57cec5SDimitry Andric if (const RecordType *RecordT = T->getAs<RecordType>()) { 5750b57cec5SDimitry Andric CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl()); 5760b57cec5SDimitry Andric // C++ [expr.typeid]p3: 5770b57cec5SDimitry Andric // [...] If the type of the expression is a class type, the class 5780b57cec5SDimitry Andric // shall be completely-defined. 5790b57cec5SDimitry Andric if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) 5800b57cec5SDimitry Andric return ExprError(); 5810b57cec5SDimitry Andric 5820b57cec5SDimitry Andric // C++ [expr.typeid]p3: 5830b57cec5SDimitry Andric // When typeid is applied to an expression other than an glvalue of a 5840b57cec5SDimitry Andric // polymorphic class type [...] [the] expression is an unevaluated 5850b57cec5SDimitry Andric // operand. [...] 5860b57cec5SDimitry Andric if (RecordD->isPolymorphic() && E->isGLValue()) { 587fe6060f1SDimitry Andric if (isUnevaluatedContext()) { 588fe6060f1SDimitry Andric // The operand was processed in unevaluated context, switch the 589fe6060f1SDimitry Andric // context and recheck the subexpression. 5900b57cec5SDimitry Andric ExprResult Result = TransformToPotentiallyEvaluated(E); 591fe6060f1SDimitry Andric if (Result.isInvalid()) 592fe6060f1SDimitry Andric return ExprError(); 5930b57cec5SDimitry Andric E = Result.get(); 594fe6060f1SDimitry Andric } 5950b57cec5SDimitry Andric 5960b57cec5SDimitry Andric // We require a vtable to query the type at run time. 5970b57cec5SDimitry Andric MarkVTableUsed(TypeidLoc, RecordD); 5980b57cec5SDimitry Andric WasEvaluated = true; 5990b57cec5SDimitry Andric } 6000b57cec5SDimitry Andric } 6010b57cec5SDimitry Andric 602a7dea167SDimitry Andric ExprResult Result = CheckUnevaluatedOperand(E); 603a7dea167SDimitry Andric if (Result.isInvalid()) 604a7dea167SDimitry Andric return ExprError(); 605a7dea167SDimitry Andric E = Result.get(); 606a7dea167SDimitry Andric 6070b57cec5SDimitry Andric // C++ [expr.typeid]p4: 6080b57cec5SDimitry Andric // [...] If the type of the type-id is a reference to a possibly 6090b57cec5SDimitry Andric // cv-qualified type, the result of the typeid expression refers to a 6100b57cec5SDimitry Andric // std::type_info object representing the cv-unqualified referenced 6110b57cec5SDimitry Andric // type. 6120b57cec5SDimitry Andric Qualifiers Quals; 6130b57cec5SDimitry Andric QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); 6140b57cec5SDimitry Andric if (!Context.hasSameType(T, UnqualT)) { 6150b57cec5SDimitry Andric T = UnqualT; 6160b57cec5SDimitry Andric E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); 6170b57cec5SDimitry Andric } 6180b57cec5SDimitry Andric } 6190b57cec5SDimitry Andric 6200b57cec5SDimitry Andric if (E->getType()->isVariablyModifiedType()) 6210b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) 6220b57cec5SDimitry Andric << E->getType()); 6230b57cec5SDimitry Andric else if (!inTemplateInstantiation() && 6240b57cec5SDimitry Andric E->HasSideEffects(Context, WasEvaluated)) { 6250b57cec5SDimitry Andric // The expression operand for typeid is in an unevaluated expression 6260b57cec5SDimitry Andric // context, so side effects could result in unintended consequences. 6270b57cec5SDimitry Andric Diag(E->getExprLoc(), WasEvaluated 6280b57cec5SDimitry Andric ? diag::warn_side_effects_typeid 6290b57cec5SDimitry Andric : diag::warn_side_effects_unevaluated_context); 6300b57cec5SDimitry Andric } 6310b57cec5SDimitry Andric 6320b57cec5SDimitry Andric return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, 6330b57cec5SDimitry Andric SourceRange(TypeidLoc, RParenLoc)); 6340b57cec5SDimitry Andric } 6350b57cec5SDimitry Andric 6360b57cec5SDimitry Andric /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); 6370b57cec5SDimitry Andric ExprResult 6380b57cec5SDimitry Andric Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, 6390b57cec5SDimitry Andric bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 6400b57cec5SDimitry Andric // typeid is not supported in OpenCL. 6410b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) { 6420b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) 6430b57cec5SDimitry Andric << "typeid"); 6440b57cec5SDimitry Andric } 6450b57cec5SDimitry Andric 6460b57cec5SDimitry Andric // Find the std::type_info type. 6470b57cec5SDimitry Andric if (!getStdNamespace()) 6480b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 6490b57cec5SDimitry Andric 6500b57cec5SDimitry Andric if (!CXXTypeInfoDecl) { 6510b57cec5SDimitry Andric IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); 6520b57cec5SDimitry Andric LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); 6530b57cec5SDimitry Andric LookupQualifiedName(R, getStdNamespace()); 6540b57cec5SDimitry Andric CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 6550b57cec5SDimitry Andric // Microsoft's typeinfo doesn't have type_info in std but in the global 6560b57cec5SDimitry Andric // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. 6570b57cec5SDimitry Andric if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { 6580b57cec5SDimitry Andric LookupQualifiedName(R, Context.getTranslationUnitDecl()); 6590b57cec5SDimitry Andric CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); 6600b57cec5SDimitry Andric } 6610b57cec5SDimitry Andric if (!CXXTypeInfoDecl) 6620b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); 6630b57cec5SDimitry Andric } 6640b57cec5SDimitry Andric 6650b57cec5SDimitry Andric if (!getLangOpts().RTTI) { 6660b57cec5SDimitry Andric return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); 6670b57cec5SDimitry Andric } 6680b57cec5SDimitry Andric 6690b57cec5SDimitry Andric QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); 6700b57cec5SDimitry Andric 6710b57cec5SDimitry Andric if (isType) { 6720b57cec5SDimitry Andric // The operand is a type; handle it as such. 6730b57cec5SDimitry Andric TypeSourceInfo *TInfo = nullptr; 6740b57cec5SDimitry Andric QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 6750b57cec5SDimitry Andric &TInfo); 6760b57cec5SDimitry Andric if (T.isNull()) 6770b57cec5SDimitry Andric return ExprError(); 6780b57cec5SDimitry Andric 6790b57cec5SDimitry Andric if (!TInfo) 6800b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 6810b57cec5SDimitry Andric 6820b57cec5SDimitry Andric return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); 6830b57cec5SDimitry Andric } 6840b57cec5SDimitry Andric 6850b57cec5SDimitry Andric // The operand is an expression. 686e8d8bef9SDimitry Andric ExprResult Result = 687e8d8bef9SDimitry Andric BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc); 688e8d8bef9SDimitry Andric 689e8d8bef9SDimitry Andric if (!getLangOpts().RTTIData && !Result.isInvalid()) 690e8d8bef9SDimitry Andric if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get())) 691e8d8bef9SDimitry Andric if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context)) 692e8d8bef9SDimitry Andric Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled) 693e8d8bef9SDimitry Andric << (getDiagnostics().getDiagnosticOptions().getFormat() == 694e8d8bef9SDimitry Andric DiagnosticOptions::MSVC); 695e8d8bef9SDimitry Andric return Result; 6960b57cec5SDimitry Andric } 6970b57cec5SDimitry Andric 6980b57cec5SDimitry Andric /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to 6990b57cec5SDimitry Andric /// a single GUID. 7000b57cec5SDimitry Andric static void 7010b57cec5SDimitry Andric getUuidAttrOfType(Sema &SemaRef, QualType QT, 7020b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { 7030b57cec5SDimitry Andric // Optionally remove one level of pointer, reference or array indirection. 7040b57cec5SDimitry Andric const Type *Ty = QT.getTypePtr(); 7050b57cec5SDimitry Andric if (QT->isPointerType() || QT->isReferenceType()) 7060b57cec5SDimitry Andric Ty = QT->getPointeeType().getTypePtr(); 7070b57cec5SDimitry Andric else if (QT->isArrayType()) 7080b57cec5SDimitry Andric Ty = Ty->getBaseElementTypeUnsafe(); 7090b57cec5SDimitry Andric 7100b57cec5SDimitry Andric const auto *TD = Ty->getAsTagDecl(); 7110b57cec5SDimitry Andric if (!TD) 7120b57cec5SDimitry Andric return; 7130b57cec5SDimitry Andric 7140b57cec5SDimitry Andric if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { 7150b57cec5SDimitry Andric UuidAttrs.insert(Uuid); 7160b57cec5SDimitry Andric return; 7170b57cec5SDimitry Andric } 7180b57cec5SDimitry Andric 7190b57cec5SDimitry Andric // __uuidof can grab UUIDs from template arguments. 7200b57cec5SDimitry Andric if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) { 7210b57cec5SDimitry Andric const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); 7220b57cec5SDimitry Andric for (const TemplateArgument &TA : TAL.asArray()) { 7230b57cec5SDimitry Andric const UuidAttr *UuidForTA = nullptr; 7240b57cec5SDimitry Andric if (TA.getKind() == TemplateArgument::Type) 7250b57cec5SDimitry Andric getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); 7260b57cec5SDimitry Andric else if (TA.getKind() == TemplateArgument::Declaration) 7270b57cec5SDimitry Andric getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); 7280b57cec5SDimitry Andric 7290b57cec5SDimitry Andric if (UuidForTA) 7300b57cec5SDimitry Andric UuidAttrs.insert(UuidForTA); 7310b57cec5SDimitry Andric } 7320b57cec5SDimitry Andric } 7330b57cec5SDimitry Andric } 7340b57cec5SDimitry Andric 7350b57cec5SDimitry Andric /// Build a Microsoft __uuidof expression with a type operand. 7365ffd83dbSDimitry Andric ExprResult Sema::BuildCXXUuidof(QualType Type, 7370b57cec5SDimitry Andric SourceLocation TypeidLoc, 7380b57cec5SDimitry Andric TypeSourceInfo *Operand, 7390b57cec5SDimitry Andric SourceLocation RParenLoc) { 7405ffd83dbSDimitry Andric MSGuidDecl *Guid = nullptr; 7410b57cec5SDimitry Andric if (!Operand->getType()->isDependentType()) { 7420b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 7430b57cec5SDimitry Andric getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); 7440b57cec5SDimitry Andric if (UuidAttrs.empty()) 7450b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 7460b57cec5SDimitry Andric if (UuidAttrs.size() > 1) 7470b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 7485ffd83dbSDimitry Andric Guid = UuidAttrs.back()->getGuidDecl(); 7490b57cec5SDimitry Andric } 7500b57cec5SDimitry Andric 7515ffd83dbSDimitry Andric return new (Context) 7525ffd83dbSDimitry Andric CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc)); 7530b57cec5SDimitry Andric } 7540b57cec5SDimitry Andric 7550b57cec5SDimitry Andric /// Build a Microsoft __uuidof expression with an expression operand. 7565ffd83dbSDimitry Andric ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc, 7575ffd83dbSDimitry Andric Expr *E, SourceLocation RParenLoc) { 7585ffd83dbSDimitry Andric MSGuidDecl *Guid = nullptr; 7590b57cec5SDimitry Andric if (!E->getType()->isDependentType()) { 7600b57cec5SDimitry Andric if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 7615ffd83dbSDimitry Andric // A null pointer results in {00000000-0000-0000-0000-000000000000}. 7625ffd83dbSDimitry Andric Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{}); 7630b57cec5SDimitry Andric } else { 7640b57cec5SDimitry Andric llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; 7650b57cec5SDimitry Andric getUuidAttrOfType(*this, E->getType(), UuidAttrs); 7660b57cec5SDimitry Andric if (UuidAttrs.empty()) 7670b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); 7680b57cec5SDimitry Andric if (UuidAttrs.size() > 1) 7690b57cec5SDimitry Andric return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); 7705ffd83dbSDimitry Andric Guid = UuidAttrs.back()->getGuidDecl(); 7710b57cec5SDimitry Andric } 7720b57cec5SDimitry Andric } 7730b57cec5SDimitry Andric 7745ffd83dbSDimitry Andric return new (Context) 7755ffd83dbSDimitry Andric CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc)); 7760b57cec5SDimitry Andric } 7770b57cec5SDimitry Andric 7780b57cec5SDimitry Andric /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); 7790b57cec5SDimitry Andric ExprResult 7800b57cec5SDimitry Andric Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, 7810b57cec5SDimitry Andric bool isType, void *TyOrExpr, SourceLocation RParenLoc) { 7825ffd83dbSDimitry Andric QualType GuidType = Context.getMSGuidType(); 7835ffd83dbSDimitry Andric GuidType.addConst(); 7840b57cec5SDimitry Andric 7850b57cec5SDimitry Andric if (isType) { 7860b57cec5SDimitry Andric // The operand is a type; handle it as such. 7870b57cec5SDimitry Andric TypeSourceInfo *TInfo = nullptr; 7880b57cec5SDimitry Andric QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), 7890b57cec5SDimitry Andric &TInfo); 7900b57cec5SDimitry Andric if (T.isNull()) 7910b57cec5SDimitry Andric return ExprError(); 7920b57cec5SDimitry Andric 7930b57cec5SDimitry Andric if (!TInfo) 7940b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); 7950b57cec5SDimitry Andric 7960b57cec5SDimitry Andric return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); 7970b57cec5SDimitry Andric } 7980b57cec5SDimitry Andric 7990b57cec5SDimitry Andric // The operand is an expression. 8000b57cec5SDimitry Andric return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); 8010b57cec5SDimitry Andric } 8020b57cec5SDimitry Andric 8030b57cec5SDimitry Andric /// ActOnCXXBoolLiteral - Parse {true,false} literals. 8040b57cec5SDimitry Andric ExprResult 8050b57cec5SDimitry Andric Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { 8060b57cec5SDimitry Andric assert((Kind == tok::kw_true || Kind == tok::kw_false) && 8070b57cec5SDimitry Andric "Unknown C++ Boolean value!"); 8080b57cec5SDimitry Andric return new (Context) 8090b57cec5SDimitry Andric CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); 8100b57cec5SDimitry Andric } 8110b57cec5SDimitry Andric 8120b57cec5SDimitry Andric /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 8130b57cec5SDimitry Andric ExprResult 8140b57cec5SDimitry Andric Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { 8150b57cec5SDimitry Andric return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 8160b57cec5SDimitry Andric } 8170b57cec5SDimitry Andric 8180b57cec5SDimitry Andric /// ActOnCXXThrow - Parse throw expressions. 8190b57cec5SDimitry Andric ExprResult 8200b57cec5SDimitry Andric Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { 8210b57cec5SDimitry Andric bool IsThrownVarInScope = false; 8220b57cec5SDimitry Andric if (Ex) { 8230b57cec5SDimitry Andric // C++0x [class.copymove]p31: 8240b57cec5SDimitry Andric // When certain criteria are met, an implementation is allowed to omit the 8250b57cec5SDimitry Andric // copy/move construction of a class object [...] 8260b57cec5SDimitry Andric // 8270b57cec5SDimitry Andric // - in a throw-expression, when the operand is the name of a 8280b57cec5SDimitry Andric // non-volatile automatic object (other than a function or catch- 8290b57cec5SDimitry Andric // clause parameter) whose scope does not extend beyond the end of the 8300b57cec5SDimitry Andric // innermost enclosing try-block (if there is one), the copy/move 8310b57cec5SDimitry Andric // operation from the operand to the exception object (15.1) can be 8320b57cec5SDimitry Andric // omitted by constructing the automatic object directly into the 8330b57cec5SDimitry Andric // exception object 8340b57cec5SDimitry Andric if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) 8350b57cec5SDimitry Andric if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 8360b57cec5SDimitry Andric if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) { 8370b57cec5SDimitry Andric for( ; S; S = S->getParent()) { 8380b57cec5SDimitry Andric if (S->isDeclScope(Var)) { 8390b57cec5SDimitry Andric IsThrownVarInScope = true; 8400b57cec5SDimitry Andric break; 8410b57cec5SDimitry Andric } 8420b57cec5SDimitry Andric 8430b57cec5SDimitry Andric if (S->getFlags() & 8440b57cec5SDimitry Andric (Scope::FnScope | Scope::ClassScope | Scope::BlockScope | 8450b57cec5SDimitry Andric Scope::FunctionPrototypeScope | Scope::ObjCMethodScope | 8460b57cec5SDimitry Andric Scope::TryScope)) 8470b57cec5SDimitry Andric break; 8480b57cec5SDimitry Andric } 8490b57cec5SDimitry Andric } 8500b57cec5SDimitry Andric } 8510b57cec5SDimitry Andric } 8520b57cec5SDimitry Andric 8530b57cec5SDimitry Andric return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); 8540b57cec5SDimitry Andric } 8550b57cec5SDimitry Andric 8560b57cec5SDimitry Andric ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 8570b57cec5SDimitry Andric bool IsThrownVarInScope) { 8580b57cec5SDimitry Andric // Don't report an error if 'throw' is used in system headers. 8590b57cec5SDimitry Andric if (!getLangOpts().CXXExceptions && 8600b57cec5SDimitry Andric !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) { 8610b57cec5SDimitry Andric // Delay error emission for the OpenMP device code. 8620b57cec5SDimitry Andric targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw"; 8630b57cec5SDimitry Andric } 8640b57cec5SDimitry Andric 8650b57cec5SDimitry Andric // Exceptions aren't allowed in CUDA device code. 8660b57cec5SDimitry Andric if (getLangOpts().CUDA) 8670b57cec5SDimitry Andric CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) 8680b57cec5SDimitry Andric << "throw" << CurrentCUDATarget(); 8690b57cec5SDimitry Andric 8700b57cec5SDimitry Andric if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) 8710b57cec5SDimitry Andric Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; 8720b57cec5SDimitry Andric 8730b57cec5SDimitry Andric if (Ex && !Ex->isTypeDependent()) { 8740b57cec5SDimitry Andric // Initialize the exception result. This implicitly weeds out 8750b57cec5SDimitry Andric // abstract types or types with inaccessible copy constructors. 8760b57cec5SDimitry Andric 8770b57cec5SDimitry Andric // C++0x [class.copymove]p31: 8780b57cec5SDimitry Andric // When certain criteria are met, an implementation is allowed to omit the 8790b57cec5SDimitry Andric // copy/move construction of a class object [...] 8800b57cec5SDimitry Andric // 8810b57cec5SDimitry Andric // - in a throw-expression, when the operand is the name of a 8820b57cec5SDimitry Andric // non-volatile automatic object (other than a function or 8830b57cec5SDimitry Andric // catch-clause 8840b57cec5SDimitry Andric // parameter) whose scope does not extend beyond the end of the 8850b57cec5SDimitry Andric // innermost enclosing try-block (if there is one), the copy/move 8860b57cec5SDimitry Andric // operation from the operand to the exception object (15.1) can be 8870b57cec5SDimitry Andric // omitted by constructing the automatic object directly into the 8880b57cec5SDimitry Andric // exception object 889fe6060f1SDimitry Andric NamedReturnInfo NRInfo = 890fe6060f1SDimitry Andric IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo(); 891fe6060f1SDimitry Andric 892fe6060f1SDimitry Andric QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); 893fe6060f1SDimitry Andric if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) 894fe6060f1SDimitry Andric return ExprError(); 8950b57cec5SDimitry Andric 89628a41182SDimitry Andric InitializedEntity Entity = 89728a41182SDimitry Andric InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy); 898fe6060f1SDimitry Andric ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex); 8990b57cec5SDimitry Andric if (Res.isInvalid()) 9000b57cec5SDimitry Andric return ExprError(); 9010b57cec5SDimitry Andric Ex = Res.get(); 9020b57cec5SDimitry Andric } 9030b57cec5SDimitry Andric 904e8d8bef9SDimitry Andric // PPC MMA non-pointer types are not allowed as throw expr types. 905e8d8bef9SDimitry Andric if (Ex && Context.getTargetInfo().getTriple().isPPC64()) 906e8d8bef9SDimitry Andric CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc()); 907e8d8bef9SDimitry Andric 9080b57cec5SDimitry Andric return new (Context) 9090b57cec5SDimitry Andric CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); 9100b57cec5SDimitry Andric } 9110b57cec5SDimitry Andric 9120b57cec5SDimitry Andric static void 9130b57cec5SDimitry Andric collectPublicBases(CXXRecordDecl *RD, 9140b57cec5SDimitry Andric llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, 9150b57cec5SDimitry Andric llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, 9160b57cec5SDimitry Andric llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, 9170b57cec5SDimitry Andric bool ParentIsPublic) { 9180b57cec5SDimitry Andric for (const CXXBaseSpecifier &BS : RD->bases()) { 9190b57cec5SDimitry Andric CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); 9200b57cec5SDimitry Andric bool NewSubobject; 9210b57cec5SDimitry Andric // Virtual bases constitute the same subobject. Non-virtual bases are 9220b57cec5SDimitry Andric // always distinct subobjects. 9230b57cec5SDimitry Andric if (BS.isVirtual()) 9240b57cec5SDimitry Andric NewSubobject = VBases.insert(BaseDecl).second; 9250b57cec5SDimitry Andric else 9260b57cec5SDimitry Andric NewSubobject = true; 9270b57cec5SDimitry Andric 9280b57cec5SDimitry Andric if (NewSubobject) 9290b57cec5SDimitry Andric ++SubobjectsSeen[BaseDecl]; 9300b57cec5SDimitry Andric 9310b57cec5SDimitry Andric // Only add subobjects which have public access throughout the entire chain. 9320b57cec5SDimitry Andric bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; 9330b57cec5SDimitry Andric if (PublicPath) 9340b57cec5SDimitry Andric PublicSubobjectsSeen.insert(BaseDecl); 9350b57cec5SDimitry Andric 9360b57cec5SDimitry Andric // Recurse on to each base subobject. 9370b57cec5SDimitry Andric collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, 9380b57cec5SDimitry Andric PublicPath); 9390b57cec5SDimitry Andric } 9400b57cec5SDimitry Andric } 9410b57cec5SDimitry Andric 9420b57cec5SDimitry Andric static void getUnambiguousPublicSubobjects( 9430b57cec5SDimitry Andric CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { 9440b57cec5SDimitry Andric llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; 9450b57cec5SDimitry Andric llvm::SmallSet<CXXRecordDecl *, 2> VBases; 9460b57cec5SDimitry Andric llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; 9470b57cec5SDimitry Andric SubobjectsSeen[RD] = 1; 9480b57cec5SDimitry Andric PublicSubobjectsSeen.insert(RD); 9490b57cec5SDimitry Andric collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, 9500b57cec5SDimitry Andric /*ParentIsPublic=*/true); 9510b57cec5SDimitry Andric 9520b57cec5SDimitry Andric for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { 9530b57cec5SDimitry Andric // Skip ambiguous objects. 9540b57cec5SDimitry Andric if (SubobjectsSeen[PublicSubobject] > 1) 9550b57cec5SDimitry Andric continue; 9560b57cec5SDimitry Andric 9570b57cec5SDimitry Andric Objects.push_back(PublicSubobject); 9580b57cec5SDimitry Andric } 9590b57cec5SDimitry Andric } 9600b57cec5SDimitry Andric 9610b57cec5SDimitry Andric /// CheckCXXThrowOperand - Validate the operand of a throw. 9620b57cec5SDimitry Andric bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, 9630b57cec5SDimitry Andric QualType ExceptionObjectTy, Expr *E) { 9640b57cec5SDimitry Andric // If the type of the exception would be an incomplete type or a pointer 9650b57cec5SDimitry Andric // to an incomplete type other than (cv) void the program is ill-formed. 9660b57cec5SDimitry Andric QualType Ty = ExceptionObjectTy; 9670b57cec5SDimitry Andric bool isPointer = false; 9680b57cec5SDimitry Andric if (const PointerType* Ptr = Ty->getAs<PointerType>()) { 9690b57cec5SDimitry Andric Ty = Ptr->getPointeeType(); 9700b57cec5SDimitry Andric isPointer = true; 9710b57cec5SDimitry Andric } 9720b57cec5SDimitry Andric if (!isPointer || !Ty->isVoidType()) { 9730b57cec5SDimitry Andric if (RequireCompleteType(ThrowLoc, Ty, 9740b57cec5SDimitry Andric isPointer ? diag::err_throw_incomplete_ptr 9750b57cec5SDimitry Andric : diag::err_throw_incomplete, 9760b57cec5SDimitry Andric E->getSourceRange())) 9770b57cec5SDimitry Andric return true; 9780b57cec5SDimitry Andric 9795ffd83dbSDimitry Andric if (!isPointer && Ty->isSizelessType()) { 9805ffd83dbSDimitry Andric Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange(); 9815ffd83dbSDimitry Andric return true; 9825ffd83dbSDimitry Andric } 9835ffd83dbSDimitry Andric 9840b57cec5SDimitry Andric if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, 9850b57cec5SDimitry Andric diag::err_throw_abstract_type, E)) 9860b57cec5SDimitry Andric return true; 9870b57cec5SDimitry Andric } 9880b57cec5SDimitry Andric 9890b57cec5SDimitry Andric // If the exception has class type, we need additional handling. 9900b57cec5SDimitry Andric CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9910b57cec5SDimitry Andric if (!RD) 9920b57cec5SDimitry Andric return false; 9930b57cec5SDimitry Andric 9940b57cec5SDimitry Andric // If we are throwing a polymorphic class type or pointer thereof, 9950b57cec5SDimitry Andric // exception handling will make use of the vtable. 9960b57cec5SDimitry Andric MarkVTableUsed(ThrowLoc, RD); 9970b57cec5SDimitry Andric 9980b57cec5SDimitry Andric // If a pointer is thrown, the referenced object will not be destroyed. 9990b57cec5SDimitry Andric if (isPointer) 10000b57cec5SDimitry Andric return false; 10010b57cec5SDimitry Andric 10020b57cec5SDimitry Andric // If the class has a destructor, we must be able to call it. 10030b57cec5SDimitry Andric if (!RD->hasIrrelevantDestructor()) { 10040b57cec5SDimitry Andric if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { 10050b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), Destructor); 10060b57cec5SDimitry Andric CheckDestructorAccess(E->getExprLoc(), Destructor, 10070b57cec5SDimitry Andric PDiag(diag::err_access_dtor_exception) << Ty); 10080b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 10090b57cec5SDimitry Andric return true; 10100b57cec5SDimitry Andric } 10110b57cec5SDimitry Andric } 10120b57cec5SDimitry Andric 10130b57cec5SDimitry Andric // The MSVC ABI creates a list of all types which can catch the exception 10140b57cec5SDimitry Andric // object. This list also references the appropriate copy constructor to call 10150b57cec5SDimitry Andric // if the object is caught by value and has a non-trivial copy constructor. 10160b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 10170b57cec5SDimitry Andric // We are only interested in the public, unambiguous bases contained within 10180b57cec5SDimitry Andric // the exception object. Bases which are ambiguous or otherwise 10190b57cec5SDimitry Andric // inaccessible are not catchable types. 10200b57cec5SDimitry Andric llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; 10210b57cec5SDimitry Andric getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); 10220b57cec5SDimitry Andric 10230b57cec5SDimitry Andric for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { 10240b57cec5SDimitry Andric // Attempt to lookup the copy constructor. Various pieces of machinery 10250b57cec5SDimitry Andric // will spring into action, like template instantiation, which means this 10260b57cec5SDimitry Andric // cannot be a simple walk of the class's decls. Instead, we must perform 10270b57cec5SDimitry Andric // lookup and overload resolution. 10280b57cec5SDimitry Andric CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); 1029480093f4SDimitry Andric if (!CD || CD->isDeleted()) 10300b57cec5SDimitry Andric continue; 10310b57cec5SDimitry Andric 10320b57cec5SDimitry Andric // Mark the constructor referenced as it is used by this throw expression. 10330b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), CD); 10340b57cec5SDimitry Andric 10350b57cec5SDimitry Andric // Skip this copy constructor if it is trivial, we don't need to record it 10360b57cec5SDimitry Andric // in the catchable type data. 10370b57cec5SDimitry Andric if (CD->isTrivial()) 10380b57cec5SDimitry Andric continue; 10390b57cec5SDimitry Andric 10400b57cec5SDimitry Andric // The copy constructor is non-trivial, create a mapping from this class 10410b57cec5SDimitry Andric // type to this constructor. 10420b57cec5SDimitry Andric // N.B. The selection of copy constructor is not sensitive to this 10430b57cec5SDimitry Andric // particular throw-site. Lookup will be performed at the catch-site to 10440b57cec5SDimitry Andric // ensure that the copy constructor is, in fact, accessible (via 10450b57cec5SDimitry Andric // friendship or any other means). 10460b57cec5SDimitry Andric Context.addCopyConstructorForExceptionObject(Subobject, CD); 10470b57cec5SDimitry Andric 10480b57cec5SDimitry Andric // We don't keep the instantiated default argument expressions around so 10490b57cec5SDimitry Andric // we must rebuild them here. 10500b57cec5SDimitry Andric for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { 10510b57cec5SDimitry Andric if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I))) 10520b57cec5SDimitry Andric return true; 10530b57cec5SDimitry Andric } 10540b57cec5SDimitry Andric } 10550b57cec5SDimitry Andric } 10560b57cec5SDimitry Andric 10570b57cec5SDimitry Andric // Under the Itanium C++ ABI, memory for the exception object is allocated by 10580b57cec5SDimitry Andric // the runtime with no ability for the compiler to request additional 10590b57cec5SDimitry Andric // alignment. Warn if the exception type requires alignment beyond the minimum 10600b57cec5SDimitry Andric // guaranteed by the target C++ runtime. 10610b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { 10620b57cec5SDimitry Andric CharUnits TypeAlign = Context.getTypeAlignInChars(Ty); 10630b57cec5SDimitry Andric CharUnits ExnObjAlign = Context.getExnObjectAlignment(); 10640b57cec5SDimitry Andric if (ExnObjAlign < TypeAlign) { 10650b57cec5SDimitry Andric Diag(ThrowLoc, diag::warn_throw_underaligned_obj); 10660b57cec5SDimitry Andric Diag(ThrowLoc, diag::note_throw_underaligned_obj) 10670b57cec5SDimitry Andric << Ty << (unsigned)TypeAlign.getQuantity() 10680b57cec5SDimitry Andric << (unsigned)ExnObjAlign.getQuantity(); 10690b57cec5SDimitry Andric } 10700b57cec5SDimitry Andric } 10710b57cec5SDimitry Andric 10720b57cec5SDimitry Andric return false; 10730b57cec5SDimitry Andric } 10740b57cec5SDimitry Andric 10750b57cec5SDimitry Andric static QualType adjustCVQualifiersForCXXThisWithinLambda( 10760b57cec5SDimitry Andric ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, 10770b57cec5SDimitry Andric DeclContext *CurSemaContext, ASTContext &ASTCtx) { 10780b57cec5SDimitry Andric 10790b57cec5SDimitry Andric QualType ClassType = ThisTy->getPointeeType(); 10800b57cec5SDimitry Andric LambdaScopeInfo *CurLSI = nullptr; 10810b57cec5SDimitry Andric DeclContext *CurDC = CurSemaContext; 10820b57cec5SDimitry Andric 10830b57cec5SDimitry Andric // Iterate through the stack of lambdas starting from the innermost lambda to 10840b57cec5SDimitry Andric // the outermost lambda, checking if '*this' is ever captured by copy - since 10850b57cec5SDimitry Andric // that could change the cv-qualifiers of the '*this' object. 10860b57cec5SDimitry Andric // The object referred to by '*this' starts out with the cv-qualifiers of its 10870b57cec5SDimitry Andric // member function. We then start with the innermost lambda and iterate 10880b57cec5SDimitry Andric // outward checking to see if any lambda performs a by-copy capture of '*this' 10890b57cec5SDimitry Andric // - and if so, any nested lambda must respect the 'constness' of that 10900b57cec5SDimitry Andric // capturing lamdbda's call operator. 10910b57cec5SDimitry Andric // 10920b57cec5SDimitry Andric 10930b57cec5SDimitry Andric // Since the FunctionScopeInfo stack is representative of the lexical 10940b57cec5SDimitry Andric // nesting of the lambda expressions during initial parsing (and is the best 10950b57cec5SDimitry Andric // place for querying information about captures about lambdas that are 10960b57cec5SDimitry Andric // partially processed) and perhaps during instantiation of function templates 10970b57cec5SDimitry Andric // that contain lambda expressions that need to be transformed BUT not 10980b57cec5SDimitry Andric // necessarily during instantiation of a nested generic lambda's function call 10990b57cec5SDimitry Andric // operator (which might even be instantiated at the end of the TU) - at which 11000b57cec5SDimitry Andric // time the DeclContext tree is mature enough to query capture information 11010b57cec5SDimitry Andric // reliably - we use a two pronged approach to walk through all the lexically 11020b57cec5SDimitry Andric // enclosing lambda expressions: 11030b57cec5SDimitry Andric // 11040b57cec5SDimitry Andric // 1) Climb down the FunctionScopeInfo stack as long as each item represents 11050b57cec5SDimitry Andric // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically 11060b57cec5SDimitry Andric // enclosed by the call-operator of the LSI below it on the stack (while 11070b57cec5SDimitry Andric // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on 11080b57cec5SDimitry Andric // the stack represents the innermost lambda. 11090b57cec5SDimitry Andric // 11100b57cec5SDimitry Andric // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext 11110b57cec5SDimitry Andric // represents a lambda's call operator. If it does, we must be instantiating 11120b57cec5SDimitry Andric // a generic lambda's call operator (represented by the Current LSI, and 11130b57cec5SDimitry Andric // should be the only scenario where an inconsistency between the LSI and the 11140b57cec5SDimitry Andric // DeclContext should occur), so climb out the DeclContexts if they 11150b57cec5SDimitry Andric // represent lambdas, while querying the corresponding closure types 11160b57cec5SDimitry Andric // regarding capture information. 11170b57cec5SDimitry Andric 11180b57cec5SDimitry Andric // 1) Climb down the function scope info stack. 11190b57cec5SDimitry Andric for (int I = FunctionScopes.size(); 11200b57cec5SDimitry Andric I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) && 11210b57cec5SDimitry Andric (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == 11220b57cec5SDimitry Andric cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator); 11230b57cec5SDimitry Andric CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { 11240b57cec5SDimitry Andric CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); 11250b57cec5SDimitry Andric 11260b57cec5SDimitry Andric if (!CurLSI->isCXXThisCaptured()) 11270b57cec5SDimitry Andric continue; 11280b57cec5SDimitry Andric 11290b57cec5SDimitry Andric auto C = CurLSI->getCXXThisCapture(); 11300b57cec5SDimitry Andric 11310b57cec5SDimitry Andric if (C.isCopyCapture()) { 11320b57cec5SDimitry Andric ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 11330b57cec5SDimitry Andric if (CurLSI->CallOperator->isConst()) 11340b57cec5SDimitry Andric ClassType.addConst(); 11350b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 11360b57cec5SDimitry Andric } 11370b57cec5SDimitry Andric } 11380b57cec5SDimitry Andric 1139349cc55cSDimitry Andric // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which 1140349cc55cSDimitry Andric // can happen during instantiation of its nested generic lambda call 1141349cc55cSDimitry Andric // operator); 2. if we're in a lambda scope (lambda body). 1142349cc55cSDimitry Andric if (CurLSI && isLambdaCallOperator(CurDC)) { 11430b57cec5SDimitry Andric assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && 11440b57cec5SDimitry Andric "While computing 'this' capture-type for a generic lambda, when we " 11450b57cec5SDimitry Andric "run out of enclosing LSI's, yet the enclosing DC is a " 11460b57cec5SDimitry Andric "lambda-call-operator we must be (i.e. Current LSI) in a generic " 11470b57cec5SDimitry Andric "lambda call oeprator"); 11480b57cec5SDimitry Andric assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); 11490b57cec5SDimitry Andric 11500b57cec5SDimitry Andric auto IsThisCaptured = 11510b57cec5SDimitry Andric [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { 11520b57cec5SDimitry Andric IsConst = false; 11530b57cec5SDimitry Andric IsByCopy = false; 11540b57cec5SDimitry Andric for (auto &&C : Closure->captures()) { 11550b57cec5SDimitry Andric if (C.capturesThis()) { 11560b57cec5SDimitry Andric if (C.getCaptureKind() == LCK_StarThis) 11570b57cec5SDimitry Andric IsByCopy = true; 11580b57cec5SDimitry Andric if (Closure->getLambdaCallOperator()->isConst()) 11590b57cec5SDimitry Andric IsConst = true; 11600b57cec5SDimitry Andric return true; 11610b57cec5SDimitry Andric } 11620b57cec5SDimitry Andric } 11630b57cec5SDimitry Andric return false; 11640b57cec5SDimitry Andric }; 11650b57cec5SDimitry Andric 11660b57cec5SDimitry Andric bool IsByCopyCapture = false; 11670b57cec5SDimitry Andric bool IsConstCapture = false; 11680b57cec5SDimitry Andric CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); 11690b57cec5SDimitry Andric while (Closure && 11700b57cec5SDimitry Andric IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { 11710b57cec5SDimitry Andric if (IsByCopyCapture) { 11720b57cec5SDimitry Andric ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 11730b57cec5SDimitry Andric if (IsConstCapture) 11740b57cec5SDimitry Andric ClassType.addConst(); 11750b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 11760b57cec5SDimitry Andric } 11770b57cec5SDimitry Andric Closure = isLambdaCallOperator(Closure->getParent()) 11780b57cec5SDimitry Andric ? cast<CXXRecordDecl>(Closure->getParent()->getParent()) 11790b57cec5SDimitry Andric : nullptr; 11800b57cec5SDimitry Andric } 11810b57cec5SDimitry Andric } 11820b57cec5SDimitry Andric return ASTCtx.getPointerType(ClassType); 11830b57cec5SDimitry Andric } 11840b57cec5SDimitry Andric 11850b57cec5SDimitry Andric QualType Sema::getCurrentThisType() { 11860b57cec5SDimitry Andric DeclContext *DC = getFunctionLevelDeclContext(); 11870b57cec5SDimitry Andric QualType ThisTy = CXXThisTypeOverride; 11880b57cec5SDimitry Andric 11890b57cec5SDimitry Andric if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { 11900b57cec5SDimitry Andric if (method && method->isInstance()) 11910b57cec5SDimitry Andric ThisTy = method->getThisType(); 11920b57cec5SDimitry Andric } 11930b57cec5SDimitry Andric 11940b57cec5SDimitry Andric if (ThisTy.isNull() && isLambdaCallOperator(CurContext) && 1195fe6060f1SDimitry Andric inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) { 11960b57cec5SDimitry Andric 11970b57cec5SDimitry Andric // This is a lambda call operator that is being instantiated as a default 11980b57cec5SDimitry Andric // initializer. DC must point to the enclosing class type, so we can recover 11990b57cec5SDimitry Andric // the 'this' type from it. 12000b57cec5SDimitry Andric QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); 12010b57cec5SDimitry Andric // There are no cv-qualifiers for 'this' within default initializers, 12020b57cec5SDimitry Andric // per [expr.prim.general]p4. 12030b57cec5SDimitry Andric ThisTy = Context.getPointerType(ClassTy); 12040b57cec5SDimitry Andric } 12050b57cec5SDimitry Andric 12060b57cec5SDimitry Andric // If we are within a lambda's call operator, the cv-qualifiers of 'this' 12070b57cec5SDimitry Andric // might need to be adjusted if the lambda or any of its enclosing lambda's 12080b57cec5SDimitry Andric // captures '*this' by copy. 12090b57cec5SDimitry Andric if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) 12100b57cec5SDimitry Andric return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, 12110b57cec5SDimitry Andric CurContext, Context); 12120b57cec5SDimitry Andric return ThisTy; 12130b57cec5SDimitry Andric } 12140b57cec5SDimitry Andric 12150b57cec5SDimitry Andric Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, 12160b57cec5SDimitry Andric Decl *ContextDecl, 12170b57cec5SDimitry Andric Qualifiers CXXThisTypeQuals, 12180b57cec5SDimitry Andric bool Enabled) 12190b57cec5SDimitry Andric : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) 12200b57cec5SDimitry Andric { 12210b57cec5SDimitry Andric if (!Enabled || !ContextDecl) 12220b57cec5SDimitry Andric return; 12230b57cec5SDimitry Andric 12240b57cec5SDimitry Andric CXXRecordDecl *Record = nullptr; 12250b57cec5SDimitry Andric if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) 12260b57cec5SDimitry Andric Record = Template->getTemplatedDecl(); 12270b57cec5SDimitry Andric else 12280b57cec5SDimitry Andric Record = cast<CXXRecordDecl>(ContextDecl); 12290b57cec5SDimitry Andric 12300b57cec5SDimitry Andric QualType T = S.Context.getRecordType(Record); 12310b57cec5SDimitry Andric T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals); 12320b57cec5SDimitry Andric 12330b57cec5SDimitry Andric S.CXXThisTypeOverride = S.Context.getPointerType(T); 12340b57cec5SDimitry Andric 12350b57cec5SDimitry Andric this->Enabled = true; 12360b57cec5SDimitry Andric } 12370b57cec5SDimitry Andric 12380b57cec5SDimitry Andric 12390b57cec5SDimitry Andric Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { 12400b57cec5SDimitry Andric if (Enabled) { 12410b57cec5SDimitry Andric S.CXXThisTypeOverride = OldCXXThisTypeOverride; 12420b57cec5SDimitry Andric } 12430b57cec5SDimitry Andric } 12440b57cec5SDimitry Andric 1245fe6060f1SDimitry Andric static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) { 1246fe6060f1SDimitry Andric SourceLocation DiagLoc = LSI->IntroducerRange.getEnd(); 1247fe6060f1SDimitry Andric assert(!LSI->isCXXThisCaptured()); 1248fe6060f1SDimitry Andric // [=, this] {}; // until C++20: Error: this when = is the default 1249fe6060f1SDimitry Andric if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval && 1250fe6060f1SDimitry Andric !Sema.getLangOpts().CPlusPlus20) 1251fe6060f1SDimitry Andric return; 1252fe6060f1SDimitry Andric Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit) 1253fe6060f1SDimitry Andric << FixItHint::CreateInsertion( 1254fe6060f1SDimitry Andric DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this"); 1255fe6060f1SDimitry Andric } 1256fe6060f1SDimitry Andric 12570b57cec5SDimitry Andric bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, 12580b57cec5SDimitry Andric bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, 12590b57cec5SDimitry Andric const bool ByCopy) { 12600b57cec5SDimitry Andric // We don't need to capture this in an unevaluated context. 12610b57cec5SDimitry Andric if (isUnevaluatedContext() && !Explicit) 12620b57cec5SDimitry Andric return true; 12630b57cec5SDimitry Andric 12640b57cec5SDimitry Andric assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value"); 12650b57cec5SDimitry Andric 12660b57cec5SDimitry Andric const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt 12670b57cec5SDimitry Andric ? *FunctionScopeIndexToStopAt 12680b57cec5SDimitry Andric : FunctionScopes.size() - 1; 12690b57cec5SDimitry Andric 12700b57cec5SDimitry Andric // Check that we can capture the *enclosing object* (referred to by '*this') 12710b57cec5SDimitry Andric // by the capturing-entity/closure (lambda/block/etc) at 12720b57cec5SDimitry Andric // MaxFunctionScopesIndex-deep on the FunctionScopes stack. 12730b57cec5SDimitry Andric 12740b57cec5SDimitry Andric // Note: The *enclosing object* can only be captured by-value by a 12750b57cec5SDimitry Andric // closure that is a lambda, using the explicit notation: 12760b57cec5SDimitry Andric // [*this] { ... }. 12770b57cec5SDimitry Andric // Every other capture of the *enclosing object* results in its by-reference 12780b57cec5SDimitry Andric // capture. 12790b57cec5SDimitry Andric 12800b57cec5SDimitry Andric // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes 12810b57cec5SDimitry Andric // stack), we can capture the *enclosing object* only if: 12820b57cec5SDimitry Andric // - 'L' has an explicit byref or byval capture of the *enclosing object* 12830b57cec5SDimitry Andric // - or, 'L' has an implicit capture. 12840b57cec5SDimitry Andric // AND 12850b57cec5SDimitry Andric // -- there is no enclosing closure 12860b57cec5SDimitry Andric // -- or, there is some enclosing closure 'E' that has already captured the 12870b57cec5SDimitry Andric // *enclosing object*, and every intervening closure (if any) between 'E' 12880b57cec5SDimitry Andric // and 'L' can implicitly capture the *enclosing object*. 12890b57cec5SDimitry Andric // -- or, every enclosing closure can implicitly capture the 12900b57cec5SDimitry Andric // *enclosing object* 12910b57cec5SDimitry Andric 12920b57cec5SDimitry Andric 12930b57cec5SDimitry Andric unsigned NumCapturingClosures = 0; 12940b57cec5SDimitry Andric for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { 12950b57cec5SDimitry Andric if (CapturingScopeInfo *CSI = 12960b57cec5SDimitry Andric dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { 12970b57cec5SDimitry Andric if (CSI->CXXThisCaptureIndex != 0) { 12980b57cec5SDimitry Andric // 'this' is already being captured; there isn't anything more to do. 12990b57cec5SDimitry Andric CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); 13000b57cec5SDimitry Andric break; 13010b57cec5SDimitry Andric } 13020b57cec5SDimitry Andric LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); 13030b57cec5SDimitry Andric if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { 13040b57cec5SDimitry Andric // This context can't implicitly capture 'this'; fail out. 1305fe6060f1SDimitry Andric if (BuildAndDiagnose) { 13060b57cec5SDimitry Andric Diag(Loc, diag::err_this_capture) 13070b57cec5SDimitry Andric << (Explicit && idx == MaxFunctionScopesIndex); 1308fe6060f1SDimitry Andric if (!Explicit) 1309fe6060f1SDimitry Andric buildLambdaThisCaptureFixit(*this, LSI); 1310fe6060f1SDimitry Andric } 13110b57cec5SDimitry Andric return true; 13120b57cec5SDimitry Andric } 13130b57cec5SDimitry Andric if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || 13140b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || 13150b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || 13160b57cec5SDimitry Andric CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || 13170b57cec5SDimitry Andric (Explicit && idx == MaxFunctionScopesIndex)) { 13180b57cec5SDimitry Andric // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first 13190b57cec5SDimitry Andric // iteration through can be an explicit capture, all enclosing closures, 13200b57cec5SDimitry Andric // if any, must perform implicit captures. 13210b57cec5SDimitry Andric 13220b57cec5SDimitry Andric // This closure can capture 'this'; continue looking upwards. 13230b57cec5SDimitry Andric NumCapturingClosures++; 13240b57cec5SDimitry Andric continue; 13250b57cec5SDimitry Andric } 13260b57cec5SDimitry Andric // This context can't implicitly capture 'this'; fail out. 13270b57cec5SDimitry Andric if (BuildAndDiagnose) 13280b57cec5SDimitry Andric Diag(Loc, diag::err_this_capture) 13290b57cec5SDimitry Andric << (Explicit && idx == MaxFunctionScopesIndex); 1330fe6060f1SDimitry Andric 1331fe6060f1SDimitry Andric if (!Explicit) 1332fe6060f1SDimitry Andric buildLambdaThisCaptureFixit(*this, LSI); 13330b57cec5SDimitry Andric return true; 13340b57cec5SDimitry Andric } 13350b57cec5SDimitry Andric break; 13360b57cec5SDimitry Andric } 13370b57cec5SDimitry Andric if (!BuildAndDiagnose) return false; 13380b57cec5SDimitry Andric 13390b57cec5SDimitry Andric // If we got here, then the closure at MaxFunctionScopesIndex on the 13400b57cec5SDimitry Andric // FunctionScopes stack, can capture the *enclosing object*, so capture it 13410b57cec5SDimitry Andric // (including implicit by-reference captures in any enclosing closures). 13420b57cec5SDimitry Andric 13430b57cec5SDimitry Andric // In the loop below, respect the ByCopy flag only for the closure requesting 13440b57cec5SDimitry Andric // the capture (i.e. first iteration through the loop below). Ignore it for 13450b57cec5SDimitry Andric // all enclosing closure's up to NumCapturingClosures (since they must be 13460b57cec5SDimitry Andric // implicitly capturing the *enclosing object* by reference (see loop 13470b57cec5SDimitry Andric // above)). 13480b57cec5SDimitry Andric assert((!ByCopy || 13490eae32dcSDimitry Andric isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && 13500b57cec5SDimitry Andric "Only a lambda can capture the enclosing object (referred to by " 13510b57cec5SDimitry Andric "*this) by copy"); 13520b57cec5SDimitry Andric QualType ThisTy = getCurrentThisType(); 13530b57cec5SDimitry Andric for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; 13540b57cec5SDimitry Andric --idx, --NumCapturingClosures) { 13550b57cec5SDimitry Andric CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); 13560b57cec5SDimitry Andric 13570b57cec5SDimitry Andric // The type of the corresponding data member (not a 'this' pointer if 'by 13580b57cec5SDimitry Andric // copy'). 13590b57cec5SDimitry Andric QualType CaptureType = ThisTy; 13600b57cec5SDimitry Andric if (ByCopy) { 13610b57cec5SDimitry Andric // If we are capturing the object referred to by '*this' by copy, ignore 13620b57cec5SDimitry Andric // any cv qualifiers inherited from the type of the member function for 13630b57cec5SDimitry Andric // the type of the closure-type's corresponding data member and any use 13640b57cec5SDimitry Andric // of 'this'. 13650b57cec5SDimitry Andric CaptureType = ThisTy->getPointeeType(); 13660b57cec5SDimitry Andric CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask); 13670b57cec5SDimitry Andric } 13680b57cec5SDimitry Andric 13690b57cec5SDimitry Andric bool isNested = NumCapturingClosures > 1; 13700b57cec5SDimitry Andric CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); 13710b57cec5SDimitry Andric } 13720b57cec5SDimitry Andric return false; 13730b57cec5SDimitry Andric } 13740b57cec5SDimitry Andric 13750b57cec5SDimitry Andric ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { 13760b57cec5SDimitry Andric /// C++ 9.3.2: In the body of a non-static member function, the keyword this 13770b57cec5SDimitry Andric /// is a non-lvalue expression whose value is the address of the object for 13780b57cec5SDimitry Andric /// which the function is called. 13790b57cec5SDimitry Andric 13800b57cec5SDimitry Andric QualType ThisTy = getCurrentThisType(); 13810b57cec5SDimitry Andric if (ThisTy.isNull()) 13820b57cec5SDimitry Andric return Diag(Loc, diag::err_invalid_this_use); 13830b57cec5SDimitry Andric return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); 13840b57cec5SDimitry Andric } 13850b57cec5SDimitry Andric 13860b57cec5SDimitry Andric Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, 13870b57cec5SDimitry Andric bool IsImplicit) { 13880b57cec5SDimitry Andric auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit); 13890b57cec5SDimitry Andric MarkThisReferenced(This); 13900b57cec5SDimitry Andric return This; 13910b57cec5SDimitry Andric } 13920b57cec5SDimitry Andric 13930b57cec5SDimitry Andric void Sema::MarkThisReferenced(CXXThisExpr *This) { 13940b57cec5SDimitry Andric CheckCXXThisCapture(This->getExprLoc()); 13950b57cec5SDimitry Andric } 13960b57cec5SDimitry Andric 13970b57cec5SDimitry Andric bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { 13980b57cec5SDimitry Andric // If we're outside the body of a member function, then we'll have a specified 13990b57cec5SDimitry Andric // type for 'this'. 14000b57cec5SDimitry Andric if (CXXThisTypeOverride.isNull()) 14010b57cec5SDimitry Andric return false; 14020b57cec5SDimitry Andric 14030b57cec5SDimitry Andric // Determine whether we're looking into a class that's currently being 14040b57cec5SDimitry Andric // defined. 14050b57cec5SDimitry Andric CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); 14060b57cec5SDimitry Andric return Class && Class->isBeingDefined(); 14070b57cec5SDimitry Andric } 14080b57cec5SDimitry Andric 14090b57cec5SDimitry Andric /// Parse construction of a specified type. 14100b57cec5SDimitry Andric /// Can be interpreted either as function-style casting ("int(x)") 14110b57cec5SDimitry Andric /// or class type construction ("ClassType(x,y,z)") 14120b57cec5SDimitry Andric /// or creation of a value-initialized type ("int()"). 14130b57cec5SDimitry Andric ExprResult 14140b57cec5SDimitry Andric Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, 14150b57cec5SDimitry Andric SourceLocation LParenOrBraceLoc, 14160b57cec5SDimitry Andric MultiExprArg exprs, 14170b57cec5SDimitry Andric SourceLocation RParenOrBraceLoc, 14180b57cec5SDimitry Andric bool ListInitialization) { 14190b57cec5SDimitry Andric if (!TypeRep) 14200b57cec5SDimitry Andric return ExprError(); 14210b57cec5SDimitry Andric 14220b57cec5SDimitry Andric TypeSourceInfo *TInfo; 14230b57cec5SDimitry Andric QualType Ty = GetTypeFromParser(TypeRep, &TInfo); 14240b57cec5SDimitry Andric if (!TInfo) 14250b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); 14260b57cec5SDimitry Andric 14270b57cec5SDimitry Andric auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, 14280b57cec5SDimitry Andric RParenOrBraceLoc, ListInitialization); 14290b57cec5SDimitry Andric // Avoid creating a non-type-dependent expression that contains typos. 14300b57cec5SDimitry Andric // Non-type-dependent expressions are liable to be discarded without 14310b57cec5SDimitry Andric // checking for embedded typos. 14320b57cec5SDimitry Andric if (!Result.isInvalid() && Result.get()->isInstantiationDependent() && 14330b57cec5SDimitry Andric !Result.get()->isTypeDependent()) 14340b57cec5SDimitry Andric Result = CorrectDelayedTyposInExpr(Result.get()); 1435e8d8bef9SDimitry Andric else if (Result.isInvalid()) 1436e8d8bef9SDimitry Andric Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(), 1437e8d8bef9SDimitry Andric RParenOrBraceLoc, exprs, Ty); 14380b57cec5SDimitry Andric return Result; 14390b57cec5SDimitry Andric } 14400b57cec5SDimitry Andric 14410b57cec5SDimitry Andric ExprResult 14420b57cec5SDimitry Andric Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, 14430b57cec5SDimitry Andric SourceLocation LParenOrBraceLoc, 14440b57cec5SDimitry Andric MultiExprArg Exprs, 14450b57cec5SDimitry Andric SourceLocation RParenOrBraceLoc, 14460b57cec5SDimitry Andric bool ListInitialization) { 14470b57cec5SDimitry Andric QualType Ty = TInfo->getType(); 14480b57cec5SDimitry Andric SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); 14490b57cec5SDimitry Andric 14500b57cec5SDimitry Andric assert((!ListInitialization || 14510b57cec5SDimitry Andric (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && 14520b57cec5SDimitry Andric "List initialization must have initializer list as expression."); 14530b57cec5SDimitry Andric SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); 14540b57cec5SDimitry Andric 1455349cc55cSDimitry Andric InitializedEntity Entity = 1456349cc55cSDimitry Andric InitializedEntity::InitializeTemporary(Context, TInfo); 14570b57cec5SDimitry Andric InitializationKind Kind = 14580b57cec5SDimitry Andric Exprs.size() 14590b57cec5SDimitry Andric ? ListInitialization 14600b57cec5SDimitry Andric ? InitializationKind::CreateDirectList( 14610b57cec5SDimitry Andric TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) 14620b57cec5SDimitry Andric : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, 14630b57cec5SDimitry Andric RParenOrBraceLoc) 14640b57cec5SDimitry Andric : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, 14650b57cec5SDimitry Andric RParenOrBraceLoc); 14660b57cec5SDimitry Andric 14670b57cec5SDimitry Andric // C++1z [expr.type.conv]p1: 14680b57cec5SDimitry Andric // If the type is a placeholder for a deduced class type, [...perform class 14690b57cec5SDimitry Andric // template argument deduction...] 14700b57cec5SDimitry Andric DeducedType *Deduced = Ty->getContainedDeducedType(); 14710b57cec5SDimitry Andric if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 14720b57cec5SDimitry Andric Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, 14730b57cec5SDimitry Andric Kind, Exprs); 14740b57cec5SDimitry Andric if (Ty.isNull()) 14750b57cec5SDimitry Andric return ExprError(); 14760b57cec5SDimitry Andric Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); 14770b57cec5SDimitry Andric } 14780b57cec5SDimitry Andric 1479e8d8bef9SDimitry Andric if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) { 1480e8d8bef9SDimitry Andric // FIXME: CXXUnresolvedConstructExpr does not model list-initialization 1481e8d8bef9SDimitry Andric // directly. We work around this by dropping the locations of the braces. 1482e8d8bef9SDimitry Andric SourceRange Locs = ListInitialization 1483e8d8bef9SDimitry Andric ? SourceRange() 1484e8d8bef9SDimitry Andric : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 1485e8d8bef9SDimitry Andric return CXXUnresolvedConstructExpr::Create(Context, Ty.getNonReferenceType(), 1486e8d8bef9SDimitry Andric TInfo, Locs.getBegin(), Exprs, 1487e8d8bef9SDimitry Andric Locs.getEnd()); 1488e8d8bef9SDimitry Andric } 1489e8d8bef9SDimitry Andric 14900b57cec5SDimitry Andric // C++ [expr.type.conv]p1: 14910b57cec5SDimitry Andric // If the expression list is a parenthesized single expression, the type 14920b57cec5SDimitry Andric // conversion expression is equivalent (in definedness, and if defined in 14930b57cec5SDimitry Andric // meaning) to the corresponding cast expression. 14940b57cec5SDimitry Andric if (Exprs.size() == 1 && !ListInitialization && 14950b57cec5SDimitry Andric !isa<InitListExpr>(Exprs[0])) { 14960b57cec5SDimitry Andric Expr *Arg = Exprs[0]; 14970b57cec5SDimitry Andric return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, 14980b57cec5SDimitry Andric RParenOrBraceLoc); 14990b57cec5SDimitry Andric } 15000b57cec5SDimitry Andric 15010b57cec5SDimitry Andric // For an expression of the form T(), T shall not be an array type. 15020b57cec5SDimitry Andric QualType ElemTy = Ty; 15030b57cec5SDimitry Andric if (Ty->isArrayType()) { 15040b57cec5SDimitry Andric if (!ListInitialization) 15050b57cec5SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) 15060b57cec5SDimitry Andric << FullRange); 15070b57cec5SDimitry Andric ElemTy = Context.getBaseElementType(Ty); 15080b57cec5SDimitry Andric } 15090b57cec5SDimitry Andric 15105e801ac6SDimitry Andric // Only construct objects with object types. 15114824e7fdSDimitry Andric // The standard doesn't explicitly forbid function types here, but that's an 15124824e7fdSDimitry Andric // obvious oversight, as there's no way to dynamically construct a function 15134824e7fdSDimitry Andric // in general. 15140b57cec5SDimitry Andric if (Ty->isFunctionType()) 15150b57cec5SDimitry Andric return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) 15160b57cec5SDimitry Andric << Ty << FullRange); 15170b57cec5SDimitry Andric 15180b57cec5SDimitry Andric // C++17 [expr.type.conv]p2: 15190b57cec5SDimitry Andric // If the type is cv void and the initializer is (), the expression is a 15200b57cec5SDimitry Andric // prvalue of the specified type that performs no initialization. 15210b57cec5SDimitry Andric if (!Ty->isVoidType() && 15220b57cec5SDimitry Andric RequireCompleteType(TyBeginLoc, ElemTy, 15230b57cec5SDimitry Andric diag::err_invalid_incomplete_type_use, FullRange)) 15240b57cec5SDimitry Andric return ExprError(); 15250b57cec5SDimitry Andric 15260b57cec5SDimitry Andric // Otherwise, the expression is a prvalue of the specified type whose 15270b57cec5SDimitry Andric // result object is direct-initialized (11.6) with the initializer. 15280b57cec5SDimitry Andric InitializationSequence InitSeq(*this, Entity, Kind, Exprs); 15290b57cec5SDimitry Andric ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); 15300b57cec5SDimitry Andric 15310b57cec5SDimitry Andric if (Result.isInvalid()) 15320b57cec5SDimitry Andric return Result; 15330b57cec5SDimitry Andric 15340b57cec5SDimitry Andric Expr *Inner = Result.get(); 15350b57cec5SDimitry Andric if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) 15360b57cec5SDimitry Andric Inner = BTE->getSubExpr(); 15370b57cec5SDimitry Andric if (!isa<CXXTemporaryObjectExpr>(Inner) && 15380b57cec5SDimitry Andric !isa<CXXScalarValueInitExpr>(Inner)) { 15390b57cec5SDimitry Andric // If we created a CXXTemporaryObjectExpr, that node also represents the 15400b57cec5SDimitry Andric // functional cast. Otherwise, create an explicit cast to represent 15410b57cec5SDimitry Andric // the syntactic form of a functional-style cast that was used here. 15420b57cec5SDimitry Andric // 15430b57cec5SDimitry Andric // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr 15440b57cec5SDimitry Andric // would give a more consistent AST representation than using a 15450b57cec5SDimitry Andric // CXXTemporaryObjectExpr. It's also weird that the functional cast 15460b57cec5SDimitry Andric // is sometimes handled by initialization and sometimes not. 15470b57cec5SDimitry Andric QualType ResultType = Result.get()->getType(); 15480b57cec5SDimitry Andric SourceRange Locs = ListInitialization 15490b57cec5SDimitry Andric ? SourceRange() 15500b57cec5SDimitry Andric : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); 15510b57cec5SDimitry Andric Result = CXXFunctionalCastExpr::Create( 15520b57cec5SDimitry Andric Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, 1553e8d8bef9SDimitry Andric Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(), 1554e8d8bef9SDimitry Andric Locs.getBegin(), Locs.getEnd()); 15550b57cec5SDimitry Andric } 15560b57cec5SDimitry Andric 15570b57cec5SDimitry Andric return Result; 15580b57cec5SDimitry Andric } 15590b57cec5SDimitry Andric 15600b57cec5SDimitry Andric bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { 15610b57cec5SDimitry Andric // [CUDA] Ignore this function, if we can't call it. 15620b57cec5SDimitry Andric const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext); 1563e8d8bef9SDimitry Andric if (getLangOpts().CUDA) { 1564e8d8bef9SDimitry Andric auto CallPreference = IdentifyCUDAPreference(Caller, Method); 1565e8d8bef9SDimitry Andric // If it's not callable at all, it's not the right function. 1566e8d8bef9SDimitry Andric if (CallPreference < CFP_WrongSide) 15670b57cec5SDimitry Andric return false; 1568e8d8bef9SDimitry Andric if (CallPreference == CFP_WrongSide) { 1569e8d8bef9SDimitry Andric // Maybe. We have to check if there are better alternatives. 1570e8d8bef9SDimitry Andric DeclContext::lookup_result R = 1571e8d8bef9SDimitry Andric Method->getDeclContext()->lookup(Method->getDeclName()); 1572e8d8bef9SDimitry Andric for (const auto *D : R) { 1573e8d8bef9SDimitry Andric if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1574e8d8bef9SDimitry Andric if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide) 1575e8d8bef9SDimitry Andric return false; 1576e8d8bef9SDimitry Andric } 1577e8d8bef9SDimitry Andric } 1578e8d8bef9SDimitry Andric // We've found no better variants. 1579e8d8bef9SDimitry Andric } 1580e8d8bef9SDimitry Andric } 15810b57cec5SDimitry Andric 15820b57cec5SDimitry Andric SmallVector<const FunctionDecl*, 4> PreventedBy; 15830b57cec5SDimitry Andric bool Result = Method->isUsualDeallocationFunction(PreventedBy); 15840b57cec5SDimitry Andric 15850b57cec5SDimitry Andric if (Result || !getLangOpts().CUDA || PreventedBy.empty()) 15860b57cec5SDimitry Andric return Result; 15870b57cec5SDimitry Andric 15880b57cec5SDimitry Andric // In case of CUDA, return true if none of the 1-argument deallocator 15890b57cec5SDimitry Andric // functions are actually callable. 15900b57cec5SDimitry Andric return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { 15910b57cec5SDimitry Andric assert(FD->getNumParams() == 1 && 15920b57cec5SDimitry Andric "Only single-operand functions should be in PreventedBy"); 15930b57cec5SDimitry Andric return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; 15940b57cec5SDimitry Andric }); 15950b57cec5SDimitry Andric } 15960b57cec5SDimitry Andric 15970b57cec5SDimitry Andric /// Determine whether the given function is a non-placement 15980b57cec5SDimitry Andric /// deallocation function. 15990b57cec5SDimitry Andric static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { 16000b57cec5SDimitry Andric if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) 16010b57cec5SDimitry Andric return S.isUsualDeallocationFunction(Method); 16020b57cec5SDimitry Andric 16030b57cec5SDimitry Andric if (FD->getOverloadedOperator() != OO_Delete && 16040b57cec5SDimitry Andric FD->getOverloadedOperator() != OO_Array_Delete) 16050b57cec5SDimitry Andric return false; 16060b57cec5SDimitry Andric 16070b57cec5SDimitry Andric unsigned UsualParams = 1; 16080b57cec5SDimitry Andric 16090b57cec5SDimitry Andric if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && 16100b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 16110b57cec5SDimitry Andric FD->getParamDecl(UsualParams)->getType(), 16120b57cec5SDimitry Andric S.Context.getSizeType())) 16130b57cec5SDimitry Andric ++UsualParams; 16140b57cec5SDimitry Andric 16150b57cec5SDimitry Andric if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && 16160b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 16170b57cec5SDimitry Andric FD->getParamDecl(UsualParams)->getType(), 16180b57cec5SDimitry Andric S.Context.getTypeDeclType(S.getStdAlignValT()))) 16190b57cec5SDimitry Andric ++UsualParams; 16200b57cec5SDimitry Andric 16210b57cec5SDimitry Andric return UsualParams == FD->getNumParams(); 16220b57cec5SDimitry Andric } 16230b57cec5SDimitry Andric 16240b57cec5SDimitry Andric namespace { 16250b57cec5SDimitry Andric struct UsualDeallocFnInfo { 16260b57cec5SDimitry Andric UsualDeallocFnInfo() : Found(), FD(nullptr) {} 16270b57cec5SDimitry Andric UsualDeallocFnInfo(Sema &S, DeclAccessPair Found) 16280b57cec5SDimitry Andric : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), 16290b57cec5SDimitry Andric Destroying(false), HasSizeT(false), HasAlignValT(false), 16300b57cec5SDimitry Andric CUDAPref(Sema::CFP_Native) { 16310b57cec5SDimitry Andric // A function template declaration is never a usual deallocation function. 16320b57cec5SDimitry Andric if (!FD) 16330b57cec5SDimitry Andric return; 16340b57cec5SDimitry Andric unsigned NumBaseParams = 1; 16350b57cec5SDimitry Andric if (FD->isDestroyingOperatorDelete()) { 16360b57cec5SDimitry Andric Destroying = true; 16370b57cec5SDimitry Andric ++NumBaseParams; 16380b57cec5SDimitry Andric } 16390b57cec5SDimitry Andric 16400b57cec5SDimitry Andric if (NumBaseParams < FD->getNumParams() && 16410b57cec5SDimitry Andric S.Context.hasSameUnqualifiedType( 16420b57cec5SDimitry Andric FD->getParamDecl(NumBaseParams)->getType(), 16430b57cec5SDimitry Andric S.Context.getSizeType())) { 16440b57cec5SDimitry Andric ++NumBaseParams; 16450b57cec5SDimitry Andric HasSizeT = true; 16460b57cec5SDimitry Andric } 16470b57cec5SDimitry Andric 16480b57cec5SDimitry Andric if (NumBaseParams < FD->getNumParams() && 16490b57cec5SDimitry Andric FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { 16500b57cec5SDimitry Andric ++NumBaseParams; 16510b57cec5SDimitry Andric HasAlignValT = true; 16520b57cec5SDimitry Andric } 16530b57cec5SDimitry Andric 16540b57cec5SDimitry Andric // In CUDA, determine how much we'd like / dislike to call this. 16550b57cec5SDimitry Andric if (S.getLangOpts().CUDA) 16560b57cec5SDimitry Andric if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 16570b57cec5SDimitry Andric CUDAPref = S.IdentifyCUDAPreference(Caller, FD); 16580b57cec5SDimitry Andric } 16590b57cec5SDimitry Andric 16600b57cec5SDimitry Andric explicit operator bool() const { return FD; } 16610b57cec5SDimitry Andric 16620b57cec5SDimitry Andric bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize, 16630b57cec5SDimitry Andric bool WantAlign) const { 16640b57cec5SDimitry Andric // C++ P0722: 16650b57cec5SDimitry Andric // A destroying operator delete is preferred over a non-destroying 16660b57cec5SDimitry Andric // operator delete. 16670b57cec5SDimitry Andric if (Destroying != Other.Destroying) 16680b57cec5SDimitry Andric return Destroying; 16690b57cec5SDimitry Andric 16700b57cec5SDimitry Andric // C++17 [expr.delete]p10: 16710b57cec5SDimitry Andric // If the type has new-extended alignment, a function with a parameter 16720b57cec5SDimitry Andric // of type std::align_val_t is preferred; otherwise a function without 16730b57cec5SDimitry Andric // such a parameter is preferred 16740b57cec5SDimitry Andric if (HasAlignValT != Other.HasAlignValT) 16750b57cec5SDimitry Andric return HasAlignValT == WantAlign; 16760b57cec5SDimitry Andric 16770b57cec5SDimitry Andric if (HasSizeT != Other.HasSizeT) 16780b57cec5SDimitry Andric return HasSizeT == WantSize; 16790b57cec5SDimitry Andric 16800b57cec5SDimitry Andric // Use CUDA call preference as a tiebreaker. 16810b57cec5SDimitry Andric return CUDAPref > Other.CUDAPref; 16820b57cec5SDimitry Andric } 16830b57cec5SDimitry Andric 16840b57cec5SDimitry Andric DeclAccessPair Found; 16850b57cec5SDimitry Andric FunctionDecl *FD; 16860b57cec5SDimitry Andric bool Destroying, HasSizeT, HasAlignValT; 16870b57cec5SDimitry Andric Sema::CUDAFunctionPreference CUDAPref; 16880b57cec5SDimitry Andric }; 16890b57cec5SDimitry Andric } 16900b57cec5SDimitry Andric 16910b57cec5SDimitry Andric /// Determine whether a type has new-extended alignment. This may be called when 16920b57cec5SDimitry Andric /// the type is incomplete (for a delete-expression with an incomplete pointee 16930b57cec5SDimitry Andric /// type), in which case it will conservatively return false if the alignment is 16940b57cec5SDimitry Andric /// not known. 16950b57cec5SDimitry Andric static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { 16960b57cec5SDimitry Andric return S.getLangOpts().AlignedAllocation && 16970b57cec5SDimitry Andric S.getASTContext().getTypeAlignIfKnown(AllocType) > 16980b57cec5SDimitry Andric S.getASTContext().getTargetInfo().getNewAlign(); 16990b57cec5SDimitry Andric } 17000b57cec5SDimitry Andric 17010b57cec5SDimitry Andric /// Select the correct "usual" deallocation function to use from a selection of 17020b57cec5SDimitry Andric /// deallocation functions (either global or class-scope). 17030b57cec5SDimitry Andric static UsualDeallocFnInfo resolveDeallocationOverload( 17040b57cec5SDimitry Andric Sema &S, LookupResult &R, bool WantSize, bool WantAlign, 17050b57cec5SDimitry Andric llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { 17060b57cec5SDimitry Andric UsualDeallocFnInfo Best; 17070b57cec5SDimitry Andric 17080b57cec5SDimitry Andric for (auto I = R.begin(), E = R.end(); I != E; ++I) { 17090b57cec5SDimitry Andric UsualDeallocFnInfo Info(S, I.getPair()); 17100b57cec5SDimitry Andric if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || 17110b57cec5SDimitry Andric Info.CUDAPref == Sema::CFP_Never) 17120b57cec5SDimitry Andric continue; 17130b57cec5SDimitry Andric 17140b57cec5SDimitry Andric if (!Best) { 17150b57cec5SDimitry Andric Best = Info; 17160b57cec5SDimitry Andric if (BestFns) 17170b57cec5SDimitry Andric BestFns->push_back(Info); 17180b57cec5SDimitry Andric continue; 17190b57cec5SDimitry Andric } 17200b57cec5SDimitry Andric 17210b57cec5SDimitry Andric if (Best.isBetterThan(Info, WantSize, WantAlign)) 17220b57cec5SDimitry Andric continue; 17230b57cec5SDimitry Andric 17240b57cec5SDimitry Andric // If more than one preferred function is found, all non-preferred 17250b57cec5SDimitry Andric // functions are eliminated from further consideration. 17260b57cec5SDimitry Andric if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign)) 17270b57cec5SDimitry Andric BestFns->clear(); 17280b57cec5SDimitry Andric 17290b57cec5SDimitry Andric Best = Info; 17300b57cec5SDimitry Andric if (BestFns) 17310b57cec5SDimitry Andric BestFns->push_back(Info); 17320b57cec5SDimitry Andric } 17330b57cec5SDimitry Andric 17340b57cec5SDimitry Andric return Best; 17350b57cec5SDimitry Andric } 17360b57cec5SDimitry Andric 17370b57cec5SDimitry Andric /// Determine whether a given type is a class for which 'delete[]' would call 17380b57cec5SDimitry Andric /// a member 'operator delete[]' with a 'size_t' parameter. This implies that 17390b57cec5SDimitry Andric /// we need to store the array size (even if the type is 17400b57cec5SDimitry Andric /// trivially-destructible). 17410b57cec5SDimitry Andric static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, 17420b57cec5SDimitry Andric QualType allocType) { 17430b57cec5SDimitry Andric const RecordType *record = 17440b57cec5SDimitry Andric allocType->getBaseElementTypeUnsafe()->getAs<RecordType>(); 17450b57cec5SDimitry Andric if (!record) return false; 17460b57cec5SDimitry Andric 17470b57cec5SDimitry Andric // Try to find an operator delete[] in class scope. 17480b57cec5SDimitry Andric 17490b57cec5SDimitry Andric DeclarationName deleteName = 17500b57cec5SDimitry Andric S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); 17510b57cec5SDimitry Andric LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); 17520b57cec5SDimitry Andric S.LookupQualifiedName(ops, record->getDecl()); 17530b57cec5SDimitry Andric 17540b57cec5SDimitry Andric // We're just doing this for information. 17550b57cec5SDimitry Andric ops.suppressDiagnostics(); 17560b57cec5SDimitry Andric 17570b57cec5SDimitry Andric // Very likely: there's no operator delete[]. 17580b57cec5SDimitry Andric if (ops.empty()) return false; 17590b57cec5SDimitry Andric 17600b57cec5SDimitry Andric // If it's ambiguous, it should be illegal to call operator delete[] 17610b57cec5SDimitry Andric // on this thing, so it doesn't matter if we allocate extra space or not. 17620b57cec5SDimitry Andric if (ops.isAmbiguous()) return false; 17630b57cec5SDimitry Andric 17640b57cec5SDimitry Andric // C++17 [expr.delete]p10: 17650b57cec5SDimitry Andric // If the deallocation functions have class scope, the one without a 17660b57cec5SDimitry Andric // parameter of type std::size_t is selected. 17670b57cec5SDimitry Andric auto Best = resolveDeallocationOverload( 17680b57cec5SDimitry Andric S, ops, /*WantSize*/false, 17690b57cec5SDimitry Andric /*WantAlign*/hasNewExtendedAlignment(S, allocType)); 17700b57cec5SDimitry Andric return Best && Best.HasSizeT; 17710b57cec5SDimitry Andric } 17720b57cec5SDimitry Andric 17730b57cec5SDimitry Andric /// Parsed a C++ 'new' expression (C++ 5.3.4). 17740b57cec5SDimitry Andric /// 17750b57cec5SDimitry Andric /// E.g.: 17760b57cec5SDimitry Andric /// @code new (memory) int[size][4] @endcode 17770b57cec5SDimitry Andric /// or 17780b57cec5SDimitry Andric /// @code ::new Foo(23, "hello") @endcode 17790b57cec5SDimitry Andric /// 17800b57cec5SDimitry Andric /// \param StartLoc The first location of the expression. 17810b57cec5SDimitry Andric /// \param UseGlobal True if 'new' was prefixed with '::'. 17820b57cec5SDimitry Andric /// \param PlacementLParen Opening paren of the placement arguments. 17830b57cec5SDimitry Andric /// \param PlacementArgs Placement new arguments. 17840b57cec5SDimitry Andric /// \param PlacementRParen Closing paren of the placement arguments. 17850b57cec5SDimitry Andric /// \param TypeIdParens If the type is in parens, the source range. 17860b57cec5SDimitry Andric /// \param D The type to be allocated, as well as array dimensions. 17870b57cec5SDimitry Andric /// \param Initializer The initializing expression or initializer-list, or null 17880b57cec5SDimitry Andric /// if there is none. 17890b57cec5SDimitry Andric ExprResult 17900b57cec5SDimitry Andric Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 17910b57cec5SDimitry Andric SourceLocation PlacementLParen, MultiExprArg PlacementArgs, 17920b57cec5SDimitry Andric SourceLocation PlacementRParen, SourceRange TypeIdParens, 17930b57cec5SDimitry Andric Declarator &D, Expr *Initializer) { 17940b57cec5SDimitry Andric Optional<Expr *> ArraySize; 17950b57cec5SDimitry Andric // If the specified type is an array, unwrap it and save the expression. 17960b57cec5SDimitry Andric if (D.getNumTypeObjects() > 0 && 17970b57cec5SDimitry Andric D.getTypeObject(0).Kind == DeclaratorChunk::Array) { 17980b57cec5SDimitry Andric DeclaratorChunk &Chunk = D.getTypeObject(0); 17990b57cec5SDimitry Andric if (D.getDeclSpec().hasAutoTypeSpec()) 18000b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) 18010b57cec5SDimitry Andric << D.getSourceRange()); 18020b57cec5SDimitry Andric if (Chunk.Arr.hasStatic) 18030b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) 18040b57cec5SDimitry Andric << D.getSourceRange()); 18050b57cec5SDimitry Andric if (!Chunk.Arr.NumElts && !Initializer) 18060b57cec5SDimitry Andric return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) 18070b57cec5SDimitry Andric << D.getSourceRange()); 18080b57cec5SDimitry Andric 18090b57cec5SDimitry Andric ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts); 18100b57cec5SDimitry Andric D.DropFirstTypeObject(); 18110b57cec5SDimitry Andric } 18120b57cec5SDimitry Andric 18130b57cec5SDimitry Andric // Every dimension shall be of constant size. 18140b57cec5SDimitry Andric if (ArraySize) { 18150b57cec5SDimitry Andric for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { 18160b57cec5SDimitry Andric if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) 18170b57cec5SDimitry Andric break; 18180b57cec5SDimitry Andric 18190b57cec5SDimitry Andric DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; 18200b57cec5SDimitry Andric if (Expr *NumElts = (Expr *)Array.NumElts) { 18210b57cec5SDimitry Andric if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { 1822e8d8bef9SDimitry Andric // FIXME: GCC permits constant folding here. We should either do so consistently 1823e8d8bef9SDimitry Andric // or not do so at all, rather than changing behavior in C++14 onwards. 18240b57cec5SDimitry Andric if (getLangOpts().CPlusPlus14) { 18250b57cec5SDimitry Andric // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator 18260b57cec5SDimitry Andric // shall be a converted constant expression (5.19) of type std::size_t 18270b57cec5SDimitry Andric // and shall evaluate to a strictly positive value. 1828e8d8bef9SDimitry Andric llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); 18290b57cec5SDimitry Andric Array.NumElts 18300b57cec5SDimitry Andric = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value, 1831e8d8bef9SDimitry Andric CCEK_ArrayBound) 18320b57cec5SDimitry Andric .get(); 18330b57cec5SDimitry Andric } else { 1834e8d8bef9SDimitry Andric Array.NumElts = 1835e8d8bef9SDimitry Andric VerifyIntegerConstantExpression( 1836e8d8bef9SDimitry Andric NumElts, nullptr, diag::err_new_array_nonconst, AllowFold) 18370b57cec5SDimitry Andric .get(); 18380b57cec5SDimitry Andric } 18390b57cec5SDimitry Andric if (!Array.NumElts) 18400b57cec5SDimitry Andric return ExprError(); 18410b57cec5SDimitry Andric } 18420b57cec5SDimitry Andric } 18430b57cec5SDimitry Andric } 18440b57cec5SDimitry Andric } 18450b57cec5SDimitry Andric 18460b57cec5SDimitry Andric TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr); 18470b57cec5SDimitry Andric QualType AllocType = TInfo->getType(); 18480b57cec5SDimitry Andric if (D.isInvalidType()) 18490b57cec5SDimitry Andric return ExprError(); 18500b57cec5SDimitry Andric 18510b57cec5SDimitry Andric SourceRange DirectInitRange; 18520b57cec5SDimitry Andric if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) 18530b57cec5SDimitry Andric DirectInitRange = List->getSourceRange(); 18540b57cec5SDimitry Andric 18550b57cec5SDimitry Andric return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, 18560b57cec5SDimitry Andric PlacementLParen, PlacementArgs, PlacementRParen, 18570b57cec5SDimitry Andric TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, 18580b57cec5SDimitry Andric Initializer); 18590b57cec5SDimitry Andric } 18600b57cec5SDimitry Andric 18610b57cec5SDimitry Andric static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style, 18620b57cec5SDimitry Andric Expr *Init) { 18630b57cec5SDimitry Andric if (!Init) 18640b57cec5SDimitry Andric return true; 18650b57cec5SDimitry Andric if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) 18660b57cec5SDimitry Andric return PLE->getNumExprs() == 0; 18670b57cec5SDimitry Andric if (isa<ImplicitValueInitExpr>(Init)) 18680b57cec5SDimitry Andric return true; 18690b57cec5SDimitry Andric else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) 18700b57cec5SDimitry Andric return !CCE->isListInitialization() && 18710b57cec5SDimitry Andric CCE->getConstructor()->isDefaultConstructor(); 18720b57cec5SDimitry Andric else if (Style == CXXNewExpr::ListInit) { 18730b57cec5SDimitry Andric assert(isa<InitListExpr>(Init) && 18740b57cec5SDimitry Andric "Shouldn't create list CXXConstructExprs for arrays."); 18750b57cec5SDimitry Andric return true; 18760b57cec5SDimitry Andric } 18770b57cec5SDimitry Andric return false; 18780b57cec5SDimitry Andric } 18790b57cec5SDimitry Andric 18800b57cec5SDimitry Andric bool 18810b57cec5SDimitry Andric Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { 18820b57cec5SDimitry Andric if (!getLangOpts().AlignedAllocationUnavailable) 18830b57cec5SDimitry Andric return false; 18840b57cec5SDimitry Andric if (FD.isDefined()) 18850b57cec5SDimitry Andric return false; 18865ffd83dbSDimitry Andric Optional<unsigned> AlignmentParam; 18875ffd83dbSDimitry Andric if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && 18885ffd83dbSDimitry Andric AlignmentParam.hasValue()) 18890b57cec5SDimitry Andric return true; 18900b57cec5SDimitry Andric return false; 18910b57cec5SDimitry Andric } 18920b57cec5SDimitry Andric 18930b57cec5SDimitry Andric // Emit a diagnostic if an aligned allocation/deallocation function that is not 18940b57cec5SDimitry Andric // implemented in the standard library is selected. 18950b57cec5SDimitry Andric void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, 18960b57cec5SDimitry Andric SourceLocation Loc) { 18970b57cec5SDimitry Andric if (isUnavailableAlignedAllocationFunction(FD)) { 18980b57cec5SDimitry Andric const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); 18990b57cec5SDimitry Andric StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( 19000b57cec5SDimitry Andric getASTContext().getTargetInfo().getPlatformName()); 1901e8d8bef9SDimitry Andric VersionTuple OSVersion = alignedAllocMinVersion(T.getOS()); 19020b57cec5SDimitry Andric 19030b57cec5SDimitry Andric OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator(); 19040b57cec5SDimitry Andric bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete; 19050b57cec5SDimitry Andric Diag(Loc, diag::err_aligned_allocation_unavailable) 19060b57cec5SDimitry Andric << IsDelete << FD.getType().getAsString() << OSName 1907e8d8bef9SDimitry Andric << OSVersion.getAsString() << OSVersion.empty(); 19080b57cec5SDimitry Andric Diag(Loc, diag::note_silence_aligned_allocation_unavailable); 19090b57cec5SDimitry Andric } 19100b57cec5SDimitry Andric } 19110b57cec5SDimitry Andric 19120b57cec5SDimitry Andric ExprResult 19130b57cec5SDimitry Andric Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, 19140b57cec5SDimitry Andric SourceLocation PlacementLParen, 19150b57cec5SDimitry Andric MultiExprArg PlacementArgs, 19160b57cec5SDimitry Andric SourceLocation PlacementRParen, 19170b57cec5SDimitry Andric SourceRange TypeIdParens, 19180b57cec5SDimitry Andric QualType AllocType, 19190b57cec5SDimitry Andric TypeSourceInfo *AllocTypeInfo, 19200b57cec5SDimitry Andric Optional<Expr *> ArraySize, 19210b57cec5SDimitry Andric SourceRange DirectInitRange, 19220b57cec5SDimitry Andric Expr *Initializer) { 19230b57cec5SDimitry Andric SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); 19240b57cec5SDimitry Andric SourceLocation StartLoc = Range.getBegin(); 19250b57cec5SDimitry Andric 19260b57cec5SDimitry Andric CXXNewExpr::InitializationStyle initStyle; 19270b57cec5SDimitry Andric if (DirectInitRange.isValid()) { 19280b57cec5SDimitry Andric assert(Initializer && "Have parens but no initializer."); 19290b57cec5SDimitry Andric initStyle = CXXNewExpr::CallInit; 19300b57cec5SDimitry Andric } else if (Initializer && isa<InitListExpr>(Initializer)) 19310b57cec5SDimitry Andric initStyle = CXXNewExpr::ListInit; 19320b57cec5SDimitry Andric else { 19330b57cec5SDimitry Andric assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || 19340b57cec5SDimitry Andric isa<CXXConstructExpr>(Initializer)) && 19350b57cec5SDimitry Andric "Initializer expression that cannot have been implicitly created."); 19360b57cec5SDimitry Andric initStyle = CXXNewExpr::NoInit; 19370b57cec5SDimitry Andric } 19380b57cec5SDimitry Andric 19390b57cec5SDimitry Andric Expr **Inits = &Initializer; 19400b57cec5SDimitry Andric unsigned NumInits = Initializer ? 1 : 0; 19410b57cec5SDimitry Andric if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { 19420b57cec5SDimitry Andric assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init"); 19430b57cec5SDimitry Andric Inits = List->getExprs(); 19440b57cec5SDimitry Andric NumInits = List->getNumExprs(); 19450b57cec5SDimitry Andric } 19460b57cec5SDimitry Andric 19470b57cec5SDimitry Andric // C++11 [expr.new]p15: 19480b57cec5SDimitry Andric // A new-expression that creates an object of type T initializes that 19490b57cec5SDimitry Andric // object as follows: 19500b57cec5SDimitry Andric InitializationKind Kind 19510b57cec5SDimitry Andric // - If the new-initializer is omitted, the object is default- 19520b57cec5SDimitry Andric // initialized (8.5); if no initialization is performed, 19530b57cec5SDimitry Andric // the object has indeterminate value 19540b57cec5SDimitry Andric = initStyle == CXXNewExpr::NoInit 19550b57cec5SDimitry Andric ? InitializationKind::CreateDefault(TypeRange.getBegin()) 19560b57cec5SDimitry Andric // - Otherwise, the new-initializer is interpreted according to 19570b57cec5SDimitry Andric // the 19580b57cec5SDimitry Andric // initialization rules of 8.5 for direct-initialization. 19590b57cec5SDimitry Andric : initStyle == CXXNewExpr::ListInit 19600b57cec5SDimitry Andric ? InitializationKind::CreateDirectList( 19610b57cec5SDimitry Andric TypeRange.getBegin(), Initializer->getBeginLoc(), 19620b57cec5SDimitry Andric Initializer->getEndLoc()) 19630b57cec5SDimitry Andric : InitializationKind::CreateDirect(TypeRange.getBegin(), 19640b57cec5SDimitry Andric DirectInitRange.getBegin(), 19650b57cec5SDimitry Andric DirectInitRange.getEnd()); 19660b57cec5SDimitry Andric 19670b57cec5SDimitry Andric // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. 19680b57cec5SDimitry Andric auto *Deduced = AllocType->getContainedDeducedType(); 19690b57cec5SDimitry Andric if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) { 19700b57cec5SDimitry Andric if (ArraySize) 19710b57cec5SDimitry Andric return ExprError( 1972349cc55cSDimitry Andric Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), 19730b57cec5SDimitry Andric diag::err_deduced_class_template_compound_type) 19740b57cec5SDimitry Andric << /*array*/ 2 1975349cc55cSDimitry Andric << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); 19760b57cec5SDimitry Andric 19770b57cec5SDimitry Andric InitializedEntity Entity 19780b57cec5SDimitry Andric = InitializedEntity::InitializeNew(StartLoc, AllocType); 19790b57cec5SDimitry Andric AllocType = DeduceTemplateSpecializationFromInitializer( 19800b57cec5SDimitry Andric AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits)); 19810b57cec5SDimitry Andric if (AllocType.isNull()) 19820b57cec5SDimitry Andric return ExprError(); 19830b57cec5SDimitry Andric } else if (Deduced) { 19840b57cec5SDimitry Andric bool Braced = (initStyle == CXXNewExpr::ListInit); 19850b57cec5SDimitry Andric if (NumInits == 1) { 19860b57cec5SDimitry Andric if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) { 19870b57cec5SDimitry Andric Inits = p->getInits(); 19880b57cec5SDimitry Andric NumInits = p->getNumInits(); 19890b57cec5SDimitry Andric Braced = true; 19900b57cec5SDimitry Andric } 19910b57cec5SDimitry Andric } 19920b57cec5SDimitry Andric 19930b57cec5SDimitry Andric if (initStyle == CXXNewExpr::NoInit || NumInits == 0) 19940b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) 19950b57cec5SDimitry Andric << AllocType << TypeRange); 19960b57cec5SDimitry Andric if (NumInits > 1) { 19970b57cec5SDimitry Andric Expr *FirstBad = Inits[1]; 19980b57cec5SDimitry Andric return ExprError(Diag(FirstBad->getBeginLoc(), 19990b57cec5SDimitry Andric diag::err_auto_new_ctor_multiple_expressions) 20000b57cec5SDimitry Andric << AllocType << TypeRange); 20010b57cec5SDimitry Andric } 20020b57cec5SDimitry Andric if (Braced && !getLangOpts().CPlusPlus17) 20030b57cec5SDimitry Andric Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) 20040b57cec5SDimitry Andric << AllocType << TypeRange; 20050b57cec5SDimitry Andric Expr *Deduce = Inits[0]; 20060b57cec5SDimitry Andric QualType DeducedType; 20070b57cec5SDimitry Andric if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed) 20080b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) 20090b57cec5SDimitry Andric << AllocType << Deduce->getType() 20100b57cec5SDimitry Andric << TypeRange << Deduce->getSourceRange()); 20110b57cec5SDimitry Andric if (DeducedType.isNull()) 20120b57cec5SDimitry Andric return ExprError(); 20130b57cec5SDimitry Andric AllocType = DeducedType; 20140b57cec5SDimitry Andric } 20150b57cec5SDimitry Andric 20160b57cec5SDimitry Andric // Per C++0x [expr.new]p5, the type being constructed may be a 20170b57cec5SDimitry Andric // typedef of an array type. 20180b57cec5SDimitry Andric if (!ArraySize) { 20190b57cec5SDimitry Andric if (const ConstantArrayType *Array 20200b57cec5SDimitry Andric = Context.getAsConstantArrayType(AllocType)) { 20210b57cec5SDimitry Andric ArraySize = IntegerLiteral::Create(Context, Array->getSize(), 20220b57cec5SDimitry Andric Context.getSizeType(), 20230b57cec5SDimitry Andric TypeRange.getEnd()); 20240b57cec5SDimitry Andric AllocType = Array->getElementType(); 20250b57cec5SDimitry Andric } 20260b57cec5SDimitry Andric } 20270b57cec5SDimitry Andric 20280b57cec5SDimitry Andric if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) 20290b57cec5SDimitry Andric return ExprError(); 20300b57cec5SDimitry Andric 20310b57cec5SDimitry Andric // In ARC, infer 'retaining' for the allocated 20320b57cec5SDimitry Andric if (getLangOpts().ObjCAutoRefCount && 20330b57cec5SDimitry Andric AllocType.getObjCLifetime() == Qualifiers::OCL_None && 20340b57cec5SDimitry Andric AllocType->isObjCLifetimeType()) { 20350b57cec5SDimitry Andric AllocType = Context.getLifetimeQualifiedType(AllocType, 20360b57cec5SDimitry Andric AllocType->getObjCARCImplicitLifetime()); 20370b57cec5SDimitry Andric } 20380b57cec5SDimitry Andric 20390b57cec5SDimitry Andric QualType ResultType = Context.getPointerType(AllocType); 20400b57cec5SDimitry Andric 20410b57cec5SDimitry Andric if (ArraySize && *ArraySize && 20420b57cec5SDimitry Andric (*ArraySize)->getType()->isNonOverloadPlaceholderType()) { 20430b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(*ArraySize); 20440b57cec5SDimitry Andric if (result.isInvalid()) return ExprError(); 20450b57cec5SDimitry Andric ArraySize = result.get(); 20460b57cec5SDimitry Andric } 20470b57cec5SDimitry Andric // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have 20480b57cec5SDimitry Andric // integral or enumeration type with a non-negative value." 20490b57cec5SDimitry Andric // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped 20500b57cec5SDimitry Andric // enumeration type, or a class type for which a single non-explicit 20510b57cec5SDimitry Andric // conversion function to integral or unscoped enumeration type exists. 20520b57cec5SDimitry Andric // C++1y [expr.new]p6: The expression [...] is implicitly converted to 20530b57cec5SDimitry Andric // std::size_t. 20540b57cec5SDimitry Andric llvm::Optional<uint64_t> KnownArraySize; 20550b57cec5SDimitry Andric if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { 20560b57cec5SDimitry Andric ExprResult ConvertedSize; 20570b57cec5SDimitry Andric if (getLangOpts().CPlusPlus14) { 20580b57cec5SDimitry Andric assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"); 20590b57cec5SDimitry Andric 20600b57cec5SDimitry Andric ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), 20610b57cec5SDimitry Andric AA_Converting); 20620b57cec5SDimitry Andric 20630b57cec5SDimitry Andric if (!ConvertedSize.isInvalid() && 20640b57cec5SDimitry Andric (*ArraySize)->getType()->getAs<RecordType>()) 20650b57cec5SDimitry Andric // Diagnose the compatibility of this conversion. 20660b57cec5SDimitry Andric Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) 20670b57cec5SDimitry Andric << (*ArraySize)->getType() << 0 << "'size_t'"; 20680b57cec5SDimitry Andric } else { 20690b57cec5SDimitry Andric class SizeConvertDiagnoser : public ICEConvertDiagnoser { 20700b57cec5SDimitry Andric protected: 20710b57cec5SDimitry Andric Expr *ArraySize; 20720b57cec5SDimitry Andric 20730b57cec5SDimitry Andric public: 20740b57cec5SDimitry Andric SizeConvertDiagnoser(Expr *ArraySize) 20750b57cec5SDimitry Andric : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), 20760b57cec5SDimitry Andric ArraySize(ArraySize) {} 20770b57cec5SDimitry Andric 20780b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 20790b57cec5SDimitry Andric QualType T) override { 20800b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_not_integral) 20810b57cec5SDimitry Andric << S.getLangOpts().CPlusPlus11 << T; 20820b57cec5SDimitry Andric } 20830b57cec5SDimitry Andric 20840b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseIncomplete( 20850b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T) override { 20860b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_incomplete_type) 20870b57cec5SDimitry Andric << T << ArraySize->getSourceRange(); 20880b57cec5SDimitry Andric } 20890b57cec5SDimitry Andric 20900b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseExplicitConv( 20910b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { 20920b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; 20930b57cec5SDimitry Andric } 20940b57cec5SDimitry Andric 20950b57cec5SDimitry Andric SemaDiagnosticBuilder noteExplicitConv( 20960b57cec5SDimitry Andric Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 20970b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 20980b57cec5SDimitry Andric << ConvTy->isEnumeralType() << ConvTy; 20990b57cec5SDimitry Andric } 21000b57cec5SDimitry Andric 21010b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseAmbiguous( 21020b57cec5SDimitry Andric Sema &S, SourceLocation Loc, QualType T) override { 21030b57cec5SDimitry Andric return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; 21040b57cec5SDimitry Andric } 21050b57cec5SDimitry Andric 21060b57cec5SDimitry Andric SemaDiagnosticBuilder noteAmbiguous( 21070b57cec5SDimitry Andric Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { 21080b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) 21090b57cec5SDimitry Andric << ConvTy->isEnumeralType() << ConvTy; 21100b57cec5SDimitry Andric } 21110b57cec5SDimitry Andric 21120b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 21130b57cec5SDimitry Andric QualType T, 21140b57cec5SDimitry Andric QualType ConvTy) override { 21150b57cec5SDimitry Andric return S.Diag(Loc, 21160b57cec5SDimitry Andric S.getLangOpts().CPlusPlus11 21170b57cec5SDimitry Andric ? diag::warn_cxx98_compat_array_size_conversion 21180b57cec5SDimitry Andric : diag::ext_array_size_conversion) 21190b57cec5SDimitry Andric << T << ConvTy->isEnumeralType() << ConvTy; 21200b57cec5SDimitry Andric } 21210b57cec5SDimitry Andric } SizeDiagnoser(*ArraySize); 21220b57cec5SDimitry Andric 21230b57cec5SDimitry Andric ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, 21240b57cec5SDimitry Andric SizeDiagnoser); 21250b57cec5SDimitry Andric } 21260b57cec5SDimitry Andric if (ConvertedSize.isInvalid()) 21270b57cec5SDimitry Andric return ExprError(); 21280b57cec5SDimitry Andric 21290b57cec5SDimitry Andric ArraySize = ConvertedSize.get(); 21300b57cec5SDimitry Andric QualType SizeType = (*ArraySize)->getType(); 21310b57cec5SDimitry Andric 21320b57cec5SDimitry Andric if (!SizeType->isIntegralOrUnscopedEnumerationType()) 21330b57cec5SDimitry Andric return ExprError(); 21340b57cec5SDimitry Andric 21350b57cec5SDimitry Andric // C++98 [expr.new]p7: 21360b57cec5SDimitry Andric // The expression in a direct-new-declarator shall have integral type 21370b57cec5SDimitry Andric // with a non-negative value. 21380b57cec5SDimitry Andric // 21390b57cec5SDimitry Andric // Let's see if this is a constant < 0. If so, we reject it out of hand, 21400b57cec5SDimitry Andric // per CWG1464. Otherwise, if it's not a constant, we must have an 21410b57cec5SDimitry Andric // unparenthesized array type. 2142349cc55cSDimitry Andric 21430b57cec5SDimitry Andric // We've already performed any required implicit conversion to integer or 21440b57cec5SDimitry Andric // unscoped enumeration type. 21450b57cec5SDimitry Andric // FIXME: Per CWG1464, we are required to check the value prior to 21460b57cec5SDimitry Andric // converting to size_t. This will never find a negative array size in 21470b57cec5SDimitry Andric // C++14 onwards, because Value is always unsigned here! 2148e8d8bef9SDimitry Andric if (Optional<llvm::APSInt> Value = 2149e8d8bef9SDimitry Andric (*ArraySize)->getIntegerConstantExpr(Context)) { 2150e8d8bef9SDimitry Andric if (Value->isSigned() && Value->isNegative()) { 21510b57cec5SDimitry Andric return ExprError(Diag((*ArraySize)->getBeginLoc(), 21520b57cec5SDimitry Andric diag::err_typecheck_negative_array_size) 21530b57cec5SDimitry Andric << (*ArraySize)->getSourceRange()); 21540b57cec5SDimitry Andric } 21550b57cec5SDimitry Andric 21560b57cec5SDimitry Andric if (!AllocType->isDependentType()) { 2157349cc55cSDimitry Andric unsigned ActiveSizeBits = 2158349cc55cSDimitry Andric ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value); 21590b57cec5SDimitry Andric if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) 21600b57cec5SDimitry Andric return ExprError( 21610b57cec5SDimitry Andric Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) 2162fe6060f1SDimitry Andric << toString(*Value, 10) << (*ArraySize)->getSourceRange()); 21630b57cec5SDimitry Andric } 21640b57cec5SDimitry Andric 2165e8d8bef9SDimitry Andric KnownArraySize = Value->getZExtValue(); 21660b57cec5SDimitry Andric } else if (TypeIdParens.isValid()) { 21670b57cec5SDimitry Andric // Can't have dynamic array size when the type-id is in parentheses. 21680b57cec5SDimitry Andric Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) 21690b57cec5SDimitry Andric << (*ArraySize)->getSourceRange() 21700b57cec5SDimitry Andric << FixItHint::CreateRemoval(TypeIdParens.getBegin()) 21710b57cec5SDimitry Andric << FixItHint::CreateRemoval(TypeIdParens.getEnd()); 21720b57cec5SDimitry Andric 21730b57cec5SDimitry Andric TypeIdParens = SourceRange(); 21740b57cec5SDimitry Andric } 21750b57cec5SDimitry Andric 21760b57cec5SDimitry Andric // Note that we do *not* convert the argument in any way. It can 21770b57cec5SDimitry Andric // be signed, larger than size_t, whatever. 21780b57cec5SDimitry Andric } 21790b57cec5SDimitry Andric 21800b57cec5SDimitry Andric FunctionDecl *OperatorNew = nullptr; 21810b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 21820b57cec5SDimitry Andric unsigned Alignment = 21830b57cec5SDimitry Andric AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); 21840b57cec5SDimitry Andric unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); 21850b57cec5SDimitry Andric bool PassAlignment = getLangOpts().AlignedAllocation && 21860b57cec5SDimitry Andric Alignment > NewAlignment; 21870b57cec5SDimitry Andric 21880b57cec5SDimitry Andric AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both; 21890b57cec5SDimitry Andric if (!AllocType->isDependentType() && 21900b57cec5SDimitry Andric !Expr::hasAnyTypeDependentArguments(PlacementArgs) && 21910b57cec5SDimitry Andric FindAllocationFunctions( 21920b57cec5SDimitry Andric StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope, 21930b57cec5SDimitry Andric AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs, 21940b57cec5SDimitry Andric OperatorNew, OperatorDelete)) 21950b57cec5SDimitry Andric return ExprError(); 21960b57cec5SDimitry Andric 21970b57cec5SDimitry Andric // If this is an array allocation, compute whether the usual array 21980b57cec5SDimitry Andric // deallocation function for the type has a size_t parameter. 21990b57cec5SDimitry Andric bool UsualArrayDeleteWantsSize = false; 22000b57cec5SDimitry Andric if (ArraySize && !AllocType->isDependentType()) 22010b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 22020b57cec5SDimitry Andric doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType); 22030b57cec5SDimitry Andric 22040b57cec5SDimitry Andric SmallVector<Expr *, 8> AllPlaceArgs; 22050b57cec5SDimitry Andric if (OperatorNew) { 22065ffd83dbSDimitry Andric auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 22070b57cec5SDimitry Andric VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction 22080b57cec5SDimitry Andric : VariadicDoesNotApply; 22090b57cec5SDimitry Andric 22100b57cec5SDimitry Andric // We've already converted the placement args, just fill in any default 22110b57cec5SDimitry Andric // arguments. Skip the first parameter because we don't have a corresponding 22120b57cec5SDimitry Andric // argument. Skip the second parameter too if we're passing in the 22130b57cec5SDimitry Andric // alignment; we've already filled it in. 22145ffd83dbSDimitry Andric unsigned NumImplicitArgs = PassAlignment ? 2 : 1; 22150b57cec5SDimitry Andric if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 22165ffd83dbSDimitry Andric NumImplicitArgs, PlacementArgs, AllPlaceArgs, 22175ffd83dbSDimitry Andric CallType)) 22180b57cec5SDimitry Andric return ExprError(); 22190b57cec5SDimitry Andric 22200b57cec5SDimitry Andric if (!AllPlaceArgs.empty()) 22210b57cec5SDimitry Andric PlacementArgs = AllPlaceArgs; 22220b57cec5SDimitry Andric 22235ffd83dbSDimitry Andric // We would like to perform some checking on the given `operator new` call, 22245ffd83dbSDimitry Andric // but the PlacementArgs does not contain the implicit arguments, 22255ffd83dbSDimitry Andric // namely allocation size and maybe allocation alignment, 22265ffd83dbSDimitry Andric // so we need to conjure them. 22270b57cec5SDimitry Andric 22285ffd83dbSDimitry Andric QualType SizeTy = Context.getSizeType(); 22295ffd83dbSDimitry Andric unsigned SizeTyWidth = Context.getTypeSize(SizeTy); 22305ffd83dbSDimitry Andric 22315ffd83dbSDimitry Andric llvm::APInt SingleEltSize( 22325ffd83dbSDimitry Andric SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); 22335ffd83dbSDimitry Andric 22345ffd83dbSDimitry Andric // How many bytes do we want to allocate here? 22355ffd83dbSDimitry Andric llvm::Optional<llvm::APInt> AllocationSize; 22365ffd83dbSDimitry Andric if (!ArraySize.hasValue() && !AllocType->isDependentType()) { 22375ffd83dbSDimitry Andric // For non-array operator new, we only want to allocate one element. 22385ffd83dbSDimitry Andric AllocationSize = SingleEltSize; 22395ffd83dbSDimitry Andric } else if (KnownArraySize.hasValue() && !AllocType->isDependentType()) { 22405ffd83dbSDimitry Andric // For array operator new, only deal with static array size case. 22415ffd83dbSDimitry Andric bool Overflow; 22425ffd83dbSDimitry Andric AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) 22435ffd83dbSDimitry Andric .umul_ov(SingleEltSize, Overflow); 22445ffd83dbSDimitry Andric (void)Overflow; 22455ffd83dbSDimitry Andric assert( 22465ffd83dbSDimitry Andric !Overflow && 22475ffd83dbSDimitry Andric "Expected that all the overflows would have been handled already."); 22485ffd83dbSDimitry Andric } 22495ffd83dbSDimitry Andric 22505ffd83dbSDimitry Andric IntegerLiteral AllocationSizeLiteral( 2251349cc55cSDimitry Andric Context, AllocationSize.getValueOr(llvm::APInt::getZero(SizeTyWidth)), 22525ffd83dbSDimitry Andric SizeTy, SourceLocation()); 22535ffd83dbSDimitry Andric // Otherwise, if we failed to constant-fold the allocation size, we'll 22545ffd83dbSDimitry Andric // just give up and pass-in something opaque, that isn't a null pointer. 2255fe6060f1SDimitry Andric OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue, 22565ffd83dbSDimitry Andric OK_Ordinary, /*SourceExpr=*/nullptr); 22575ffd83dbSDimitry Andric 22585ffd83dbSDimitry Andric // Let's synthesize the alignment argument in case we will need it. 22595ffd83dbSDimitry Andric // Since we *really* want to allocate these on stack, this is slightly ugly 22605ffd83dbSDimitry Andric // because there might not be a `std::align_val_t` type. 22615ffd83dbSDimitry Andric EnumDecl *StdAlignValT = getStdAlignValT(); 22625ffd83dbSDimitry Andric QualType AlignValT = 22635ffd83dbSDimitry Andric StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy; 22645ffd83dbSDimitry Andric IntegerLiteral AlignmentLiteral( 22655ffd83dbSDimitry Andric Context, 22665ffd83dbSDimitry Andric llvm::APInt(Context.getTypeSize(SizeTy), 22675ffd83dbSDimitry Andric Alignment / Context.getCharWidth()), 22685ffd83dbSDimitry Andric SizeTy, SourceLocation()); 22695ffd83dbSDimitry Andric ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, 22705ffd83dbSDimitry Andric CK_IntegralCast, &AlignmentLiteral, 2271fe6060f1SDimitry Andric VK_PRValue, FPOptionsOverride()); 22725ffd83dbSDimitry Andric 22735ffd83dbSDimitry Andric // Adjust placement args by prepending conjured size and alignment exprs. 22745ffd83dbSDimitry Andric llvm::SmallVector<Expr *, 8> CallArgs; 22755ffd83dbSDimitry Andric CallArgs.reserve(NumImplicitArgs + PlacementArgs.size()); 22765ffd83dbSDimitry Andric CallArgs.emplace_back(AllocationSize.hasValue() 22775ffd83dbSDimitry Andric ? static_cast<Expr *>(&AllocationSizeLiteral) 22785ffd83dbSDimitry Andric : &OpaqueAllocationSize); 22795ffd83dbSDimitry Andric if (PassAlignment) 22805ffd83dbSDimitry Andric CallArgs.emplace_back(&DesiredAlignment); 22815ffd83dbSDimitry Andric CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end()); 22825ffd83dbSDimitry Andric 22835ffd83dbSDimitry Andric DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); 22845ffd83dbSDimitry Andric 22855ffd83dbSDimitry Andric checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs, 22865ffd83dbSDimitry Andric /*IsMemberFunction=*/false, StartLoc, Range, CallType); 22870b57cec5SDimitry Andric 22880b57cec5SDimitry Andric // Warn if the type is over-aligned and is being allocated by (unaligned) 22890b57cec5SDimitry Andric // global operator new. 22900b57cec5SDimitry Andric if (PlacementArgs.empty() && !PassAlignment && 22910b57cec5SDimitry Andric (OperatorNew->isImplicit() || 22920b57cec5SDimitry Andric (OperatorNew->getBeginLoc().isValid() && 22930b57cec5SDimitry Andric getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { 22940b57cec5SDimitry Andric if (Alignment > NewAlignment) 22950b57cec5SDimitry Andric Diag(StartLoc, diag::warn_overaligned_type) 22960b57cec5SDimitry Andric << AllocType 22970b57cec5SDimitry Andric << unsigned(Alignment / Context.getCharWidth()) 22980b57cec5SDimitry Andric << unsigned(NewAlignment / Context.getCharWidth()); 22990b57cec5SDimitry Andric } 23000b57cec5SDimitry Andric } 23010b57cec5SDimitry Andric 23020b57cec5SDimitry Andric // Array 'new' can't have any initializers except empty parentheses. 23030b57cec5SDimitry Andric // Initializer lists are also allowed, in C++11. Rely on the parser for the 23040b57cec5SDimitry Andric // dialect distinction. 23050b57cec5SDimitry Andric if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) { 23060b57cec5SDimitry Andric SourceRange InitRange(Inits[0]->getBeginLoc(), 23070b57cec5SDimitry Andric Inits[NumInits - 1]->getEndLoc()); 23080b57cec5SDimitry Andric Diag(StartLoc, diag::err_new_array_init_args) << InitRange; 23090b57cec5SDimitry Andric return ExprError(); 23100b57cec5SDimitry Andric } 23110b57cec5SDimitry Andric 23120b57cec5SDimitry Andric // If we can perform the initialization, and we've not already done so, 23130b57cec5SDimitry Andric // do it now. 23140b57cec5SDimitry Andric if (!AllocType->isDependentType() && 23150b57cec5SDimitry Andric !Expr::hasAnyTypeDependentArguments( 23160b57cec5SDimitry Andric llvm::makeArrayRef(Inits, NumInits))) { 23170b57cec5SDimitry Andric // The type we initialize is the complete type, including the array bound. 23180b57cec5SDimitry Andric QualType InitType; 23190b57cec5SDimitry Andric if (KnownArraySize) 23200b57cec5SDimitry Andric InitType = Context.getConstantArrayType( 2321a7dea167SDimitry Andric AllocType, 2322a7dea167SDimitry Andric llvm::APInt(Context.getTypeSize(Context.getSizeType()), 23230b57cec5SDimitry Andric *KnownArraySize), 2324a7dea167SDimitry Andric *ArraySize, ArrayType::Normal, 0); 23250b57cec5SDimitry Andric else if (ArraySize) 23260b57cec5SDimitry Andric InitType = 23270b57cec5SDimitry Andric Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0); 23280b57cec5SDimitry Andric else 23290b57cec5SDimitry Andric InitType = AllocType; 23300b57cec5SDimitry Andric 23310b57cec5SDimitry Andric InitializedEntity Entity 23320b57cec5SDimitry Andric = InitializedEntity::InitializeNew(StartLoc, InitType); 23330b57cec5SDimitry Andric InitializationSequence InitSeq(*this, Entity, Kind, 23340b57cec5SDimitry Andric MultiExprArg(Inits, NumInits)); 23350b57cec5SDimitry Andric ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, 23360b57cec5SDimitry Andric MultiExprArg(Inits, NumInits)); 23370b57cec5SDimitry Andric if (FullInit.isInvalid()) 23380b57cec5SDimitry Andric return ExprError(); 23390b57cec5SDimitry Andric 23400b57cec5SDimitry Andric // FullInit is our initializer; strip off CXXBindTemporaryExprs, because 23410b57cec5SDimitry Andric // we don't want the initialized object to be destructed. 23420b57cec5SDimitry Andric // FIXME: We should not create these in the first place. 23430b57cec5SDimitry Andric if (CXXBindTemporaryExpr *Binder = 23440b57cec5SDimitry Andric dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) 23450b57cec5SDimitry Andric FullInit = Binder->getSubExpr(); 23460b57cec5SDimitry Andric 23470b57cec5SDimitry Andric Initializer = FullInit.get(); 23480b57cec5SDimitry Andric 23490b57cec5SDimitry Andric // FIXME: If we have a KnownArraySize, check that the array bound of the 23500b57cec5SDimitry Andric // initializer is no greater than that constant value. 23510b57cec5SDimitry Andric 23520b57cec5SDimitry Andric if (ArraySize && !*ArraySize) { 23530b57cec5SDimitry Andric auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); 23540b57cec5SDimitry Andric if (CAT) { 23550b57cec5SDimitry Andric // FIXME: Track that the array size was inferred rather than explicitly 23560b57cec5SDimitry Andric // specified. 23570b57cec5SDimitry Andric ArraySize = IntegerLiteral::Create( 23580b57cec5SDimitry Andric Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); 23590b57cec5SDimitry Andric } else { 23600b57cec5SDimitry Andric Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) 23610b57cec5SDimitry Andric << Initializer->getSourceRange(); 23620b57cec5SDimitry Andric } 23630b57cec5SDimitry Andric } 23640b57cec5SDimitry Andric } 23650b57cec5SDimitry Andric 23660b57cec5SDimitry Andric // Mark the new and delete operators as referenced. 23670b57cec5SDimitry Andric if (OperatorNew) { 23680b57cec5SDimitry Andric if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) 23690b57cec5SDimitry Andric return ExprError(); 23700b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorNew); 23710b57cec5SDimitry Andric } 23720b57cec5SDimitry Andric if (OperatorDelete) { 23730b57cec5SDimitry Andric if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) 23740b57cec5SDimitry Andric return ExprError(); 23750b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorDelete); 23760b57cec5SDimitry Andric } 23770b57cec5SDimitry Andric 23780b57cec5SDimitry Andric return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, 23790b57cec5SDimitry Andric PassAlignment, UsualArrayDeleteWantsSize, 23800b57cec5SDimitry Andric PlacementArgs, TypeIdParens, ArraySize, initStyle, 23810b57cec5SDimitry Andric Initializer, ResultType, AllocTypeInfo, Range, 23820b57cec5SDimitry Andric DirectInitRange); 23830b57cec5SDimitry Andric } 23840b57cec5SDimitry Andric 23850b57cec5SDimitry Andric /// Checks that a type is suitable as the allocated type 23860b57cec5SDimitry Andric /// in a new-expression. 23870b57cec5SDimitry Andric bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, 23880b57cec5SDimitry Andric SourceRange R) { 23890b57cec5SDimitry Andric // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an 23900b57cec5SDimitry Andric // abstract class type or array thereof. 23910b57cec5SDimitry Andric if (AllocType->isFunctionType()) 23920b57cec5SDimitry Andric return Diag(Loc, diag::err_bad_new_type) 23930b57cec5SDimitry Andric << AllocType << 0 << R; 23940b57cec5SDimitry Andric else if (AllocType->isReferenceType()) 23950b57cec5SDimitry Andric return Diag(Loc, diag::err_bad_new_type) 23960b57cec5SDimitry Andric << AllocType << 1 << R; 23970b57cec5SDimitry Andric else if (!AllocType->isDependentType() && 23985ffd83dbSDimitry Andric RequireCompleteSizedType( 23995ffd83dbSDimitry Andric Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) 24000b57cec5SDimitry Andric return true; 24010b57cec5SDimitry Andric else if (RequireNonAbstractType(Loc, AllocType, 24020b57cec5SDimitry Andric diag::err_allocation_of_abstract_type)) 24030b57cec5SDimitry Andric return true; 24040b57cec5SDimitry Andric else if (AllocType->isVariablyModifiedType()) 24050b57cec5SDimitry Andric return Diag(Loc, diag::err_variably_modified_new_type) 24060b57cec5SDimitry Andric << AllocType; 24070b57cec5SDimitry Andric else if (AllocType.getAddressSpace() != LangAS::Default && 24080b57cec5SDimitry Andric !getLangOpts().OpenCLCPlusPlus) 24090b57cec5SDimitry Andric return Diag(Loc, diag::err_address_space_qualified_new) 24100b57cec5SDimitry Andric << AllocType.getUnqualifiedType() 24110b57cec5SDimitry Andric << AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); 24120b57cec5SDimitry Andric else if (getLangOpts().ObjCAutoRefCount) { 24130b57cec5SDimitry Andric if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { 24140b57cec5SDimitry Andric QualType BaseAllocType = Context.getBaseElementType(AT); 24150b57cec5SDimitry Andric if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && 24160b57cec5SDimitry Andric BaseAllocType->isObjCLifetimeType()) 24170b57cec5SDimitry Andric return Diag(Loc, diag::err_arc_new_array_without_ownership) 24180b57cec5SDimitry Andric << BaseAllocType; 24190b57cec5SDimitry Andric } 24200b57cec5SDimitry Andric } 24210b57cec5SDimitry Andric 24220b57cec5SDimitry Andric return false; 24230b57cec5SDimitry Andric } 24240b57cec5SDimitry Andric 24250b57cec5SDimitry Andric static bool resolveAllocationOverload( 24260b57cec5SDimitry Andric Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, 24270b57cec5SDimitry Andric bool &PassAlignment, FunctionDecl *&Operator, 24280b57cec5SDimitry Andric OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { 24290b57cec5SDimitry Andric OverloadCandidateSet Candidates(R.getNameLoc(), 24300b57cec5SDimitry Andric OverloadCandidateSet::CSK_Normal); 24310b57cec5SDimitry Andric for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); 24320b57cec5SDimitry Andric Alloc != AllocEnd; ++Alloc) { 24330b57cec5SDimitry Andric // Even member operator new/delete are implicitly treated as 24340b57cec5SDimitry Andric // static, so don't use AddMemberCandidate. 24350b57cec5SDimitry Andric NamedDecl *D = (*Alloc)->getUnderlyingDecl(); 24360b57cec5SDimitry Andric 24370b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 24380b57cec5SDimitry Andric S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), 24390b57cec5SDimitry Andric /*ExplicitTemplateArgs=*/nullptr, Args, 24400b57cec5SDimitry Andric Candidates, 24410b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 24420b57cec5SDimitry Andric continue; 24430b57cec5SDimitry Andric } 24440b57cec5SDimitry Andric 24450b57cec5SDimitry Andric FunctionDecl *Fn = cast<FunctionDecl>(D); 24460b57cec5SDimitry Andric S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, 24470b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 24480b57cec5SDimitry Andric } 24490b57cec5SDimitry Andric 24500b57cec5SDimitry Andric // Do the resolution. 24510b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 24520b57cec5SDimitry Andric switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 24530b57cec5SDimitry Andric case OR_Success: { 24540b57cec5SDimitry Andric // Got one! 24550b57cec5SDimitry Andric FunctionDecl *FnDecl = Best->Function; 24560b57cec5SDimitry Andric if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), 24570b57cec5SDimitry Andric Best->FoundDecl) == Sema::AR_inaccessible) 24580b57cec5SDimitry Andric return true; 24590b57cec5SDimitry Andric 24600b57cec5SDimitry Andric Operator = FnDecl; 24610b57cec5SDimitry Andric return false; 24620b57cec5SDimitry Andric } 24630b57cec5SDimitry Andric 24640b57cec5SDimitry Andric case OR_No_Viable_Function: 24650b57cec5SDimitry Andric // C++17 [expr.new]p13: 24660b57cec5SDimitry Andric // If no matching function is found and the allocated object type has 24670b57cec5SDimitry Andric // new-extended alignment, the alignment argument is removed from the 24680b57cec5SDimitry Andric // argument list, and overload resolution is performed again. 24690b57cec5SDimitry Andric if (PassAlignment) { 24700b57cec5SDimitry Andric PassAlignment = false; 24710b57cec5SDimitry Andric AlignArg = Args[1]; 24720b57cec5SDimitry Andric Args.erase(Args.begin() + 1); 24730b57cec5SDimitry Andric return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 24740b57cec5SDimitry Andric Operator, &Candidates, AlignArg, 24750b57cec5SDimitry Andric Diagnose); 24760b57cec5SDimitry Andric } 24770b57cec5SDimitry Andric 24780b57cec5SDimitry Andric // MSVC will fall back on trying to find a matching global operator new 24790b57cec5SDimitry Andric // if operator new[] cannot be found. Also, MSVC will leak by not 24800b57cec5SDimitry Andric // generating a call to operator delete or operator delete[], but we 24810b57cec5SDimitry Andric // will not replicate that bug. 24820b57cec5SDimitry Andric // FIXME: Find out how this interacts with the std::align_val_t fallback 24830b57cec5SDimitry Andric // once MSVC implements it. 24840b57cec5SDimitry Andric if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && 24850b57cec5SDimitry Andric S.Context.getLangOpts().MSVCCompat) { 24860b57cec5SDimitry Andric R.clear(); 24870b57cec5SDimitry Andric R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); 24880b57cec5SDimitry Andric S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 24890b57cec5SDimitry Andric // FIXME: This will give bad diagnostics pointing at the wrong functions. 24900b57cec5SDimitry Andric return resolveAllocationOverload(S, R, Range, Args, PassAlignment, 24910b57cec5SDimitry Andric Operator, /*Candidates=*/nullptr, 24920b57cec5SDimitry Andric /*AlignArg=*/nullptr, Diagnose); 24930b57cec5SDimitry Andric } 24940b57cec5SDimitry Andric 24950b57cec5SDimitry Andric if (Diagnose) { 2496fe6060f1SDimitry Andric // If this is an allocation of the form 'new (p) X' for some object 2497fe6060f1SDimitry Andric // pointer p (or an expression that will decay to such a pointer), 2498fe6060f1SDimitry Andric // diagnose the missing inclusion of <new>. 2499fe6060f1SDimitry Andric if (!R.isClassLookup() && Args.size() == 2 && 2500fe6060f1SDimitry Andric (Args[1]->getType()->isObjectPointerType() || 2501fe6060f1SDimitry Andric Args[1]->getType()->isArrayType())) { 2502fe6060f1SDimitry Andric S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) 2503fe6060f1SDimitry Andric << R.getLookupName() << Range; 2504fe6060f1SDimitry Andric // Listing the candidates is unlikely to be useful; skip it. 2505fe6060f1SDimitry Andric return true; 2506fe6060f1SDimitry Andric } 25070b57cec5SDimitry Andric 2508fe6060f1SDimitry Andric // Finish checking all candidates before we note any. This checking can 2509fe6060f1SDimitry Andric // produce additional diagnostics so can't be interleaved with our 2510fe6060f1SDimitry Andric // emission of notes. 2511fe6060f1SDimitry Andric // 2512fe6060f1SDimitry Andric // For an aligned allocation, separately check the aligned and unaligned 2513fe6060f1SDimitry Andric // candidates with their respective argument lists. 2514fe6060f1SDimitry Andric SmallVector<OverloadCandidate*, 32> Cands; 2515fe6060f1SDimitry Andric SmallVector<OverloadCandidate*, 32> AlignedCands; 2516fe6060f1SDimitry Andric llvm::SmallVector<Expr*, 4> AlignedArgs; 25170b57cec5SDimitry Andric if (AlignedCandidates) { 25180b57cec5SDimitry Andric auto IsAligned = [](OverloadCandidate &C) { 25190b57cec5SDimitry Andric return C.Function->getNumParams() > 1 && 25200b57cec5SDimitry Andric C.Function->getParamDecl(1)->getType()->isAlignValT(); 25210b57cec5SDimitry Andric }; 25220b57cec5SDimitry Andric auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; 25230b57cec5SDimitry Andric 2524fe6060f1SDimitry Andric AlignedArgs.reserve(Args.size() + 1); 2525fe6060f1SDimitry Andric AlignedArgs.push_back(Args[0]); 2526fe6060f1SDimitry Andric AlignedArgs.push_back(AlignArg); 2527fe6060f1SDimitry Andric AlignedArgs.append(Args.begin() + 1, Args.end()); 2528fe6060f1SDimitry Andric AlignedCands = AlignedCandidates->CompleteCandidates( 2529fe6060f1SDimitry Andric S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); 2530fe6060f1SDimitry Andric 2531fe6060f1SDimitry Andric Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2532fe6060f1SDimitry Andric R.getNameLoc(), IsUnaligned); 25330b57cec5SDimitry Andric } else { 2534fe6060f1SDimitry Andric Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, 2535fe6060f1SDimitry Andric R.getNameLoc()); 25360b57cec5SDimitry Andric } 2537fe6060f1SDimitry Andric 2538fe6060f1SDimitry Andric S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) 2539fe6060f1SDimitry Andric << R.getLookupName() << Range; 2540fe6060f1SDimitry Andric if (AlignedCandidates) 2541fe6060f1SDimitry Andric AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "", 2542fe6060f1SDimitry Andric R.getNameLoc()); 2543fe6060f1SDimitry Andric Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc()); 25440b57cec5SDimitry Andric } 25450b57cec5SDimitry Andric return true; 25460b57cec5SDimitry Andric 25470b57cec5SDimitry Andric case OR_Ambiguous: 25480b57cec5SDimitry Andric if (Diagnose) { 25490b57cec5SDimitry Andric Candidates.NoteCandidates( 25500b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 25510b57cec5SDimitry Andric S.PDiag(diag::err_ovl_ambiguous_call) 25520b57cec5SDimitry Andric << R.getLookupName() << Range), 2553480093f4SDimitry Andric S, OCD_AmbiguousCandidates, Args); 25540b57cec5SDimitry Andric } 25550b57cec5SDimitry Andric return true; 25560b57cec5SDimitry Andric 25570b57cec5SDimitry Andric case OR_Deleted: { 25580b57cec5SDimitry Andric if (Diagnose) { 25590b57cec5SDimitry Andric Candidates.NoteCandidates( 25600b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 25610b57cec5SDimitry Andric S.PDiag(diag::err_ovl_deleted_call) 25620b57cec5SDimitry Andric << R.getLookupName() << Range), 25630b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 25640b57cec5SDimitry Andric } 25650b57cec5SDimitry Andric return true; 25660b57cec5SDimitry Andric } 25670b57cec5SDimitry Andric } 25680b57cec5SDimitry Andric llvm_unreachable("Unreachable, bad result from BestViableFunction"); 25690b57cec5SDimitry Andric } 25700b57cec5SDimitry Andric 25710b57cec5SDimitry Andric bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 25720b57cec5SDimitry Andric AllocationFunctionScope NewScope, 25730b57cec5SDimitry Andric AllocationFunctionScope DeleteScope, 25740b57cec5SDimitry Andric QualType AllocType, bool IsArray, 25750b57cec5SDimitry Andric bool &PassAlignment, MultiExprArg PlaceArgs, 25760b57cec5SDimitry Andric FunctionDecl *&OperatorNew, 25770b57cec5SDimitry Andric FunctionDecl *&OperatorDelete, 25780b57cec5SDimitry Andric bool Diagnose) { 25790b57cec5SDimitry Andric // --- Choosing an allocation function --- 25800b57cec5SDimitry Andric // C++ 5.3.4p8 - 14 & 18 25810b57cec5SDimitry Andric // 1) If looking in AFS_Global scope for allocation functions, only look in 25820b57cec5SDimitry Andric // the global scope. Else, if AFS_Class, only look in the scope of the 25830b57cec5SDimitry Andric // allocated class. If AFS_Both, look in both. 25840b57cec5SDimitry Andric // 2) If an array size is given, look for operator new[], else look for 25850b57cec5SDimitry Andric // operator new. 25860b57cec5SDimitry Andric // 3) The first argument is always size_t. Append the arguments from the 25870b57cec5SDimitry Andric // placement form. 25880b57cec5SDimitry Andric 25890b57cec5SDimitry Andric SmallVector<Expr*, 8> AllocArgs; 25900b57cec5SDimitry Andric AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); 25910b57cec5SDimitry Andric 25920b57cec5SDimitry Andric // We don't care about the actual value of these arguments. 25930b57cec5SDimitry Andric // FIXME: Should the Sema create the expression and embed it in the syntax 25940b57cec5SDimitry Andric // tree? Or should the consumer just recalculate the value? 25950b57cec5SDimitry Andric // FIXME: Using a dummy value will interact poorly with attribute enable_if. 2596349cc55cSDimitry Andric IntegerLiteral Size( 2597349cc55cSDimitry Andric Context, llvm::APInt::getZero(Context.getTargetInfo().getPointerWidth(0)), 2598349cc55cSDimitry Andric Context.getSizeType(), SourceLocation()); 25990b57cec5SDimitry Andric AllocArgs.push_back(&Size); 26000b57cec5SDimitry Andric 26010b57cec5SDimitry Andric QualType AlignValT = Context.VoidTy; 26020b57cec5SDimitry Andric if (PassAlignment) { 26030b57cec5SDimitry Andric DeclareGlobalNewDelete(); 26040b57cec5SDimitry Andric AlignValT = Context.getTypeDeclType(getStdAlignValT()); 26050b57cec5SDimitry Andric } 26060b57cec5SDimitry Andric CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); 26070b57cec5SDimitry Andric if (PassAlignment) 26080b57cec5SDimitry Andric AllocArgs.push_back(&Align); 26090b57cec5SDimitry Andric 26100b57cec5SDimitry Andric AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end()); 26110b57cec5SDimitry Andric 26120b57cec5SDimitry Andric // C++ [expr.new]p8: 26130b57cec5SDimitry Andric // If the allocated type is a non-array type, the allocation 26140b57cec5SDimitry Andric // function's name is operator new and the deallocation function's 26150b57cec5SDimitry Andric // name is operator delete. If the allocated type is an array 26160b57cec5SDimitry Andric // type, the allocation function's name is operator new[] and the 26170b57cec5SDimitry Andric // deallocation function's name is operator delete[]. 26180b57cec5SDimitry Andric DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( 26190b57cec5SDimitry Andric IsArray ? OO_Array_New : OO_New); 26200b57cec5SDimitry Andric 26210b57cec5SDimitry Andric QualType AllocElemType = Context.getBaseElementType(AllocType); 26220b57cec5SDimitry Andric 26230b57cec5SDimitry Andric // Find the allocation function. 26240b57cec5SDimitry Andric { 26250b57cec5SDimitry Andric LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); 26260b57cec5SDimitry Andric 26270b57cec5SDimitry Andric // C++1z [expr.new]p9: 26280b57cec5SDimitry Andric // If the new-expression begins with a unary :: operator, the allocation 26290b57cec5SDimitry Andric // function's name is looked up in the global scope. Otherwise, if the 26300b57cec5SDimitry Andric // allocated type is a class type T or array thereof, the allocation 26310b57cec5SDimitry Andric // function's name is looked up in the scope of T. 26320b57cec5SDimitry Andric if (AllocElemType->isRecordType() && NewScope != AFS_Global) 26330b57cec5SDimitry Andric LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); 26340b57cec5SDimitry Andric 26350b57cec5SDimitry Andric // We can see ambiguity here if the allocation function is found in 26360b57cec5SDimitry Andric // multiple base classes. 26370b57cec5SDimitry Andric if (R.isAmbiguous()) 26380b57cec5SDimitry Andric return true; 26390b57cec5SDimitry Andric 26400b57cec5SDimitry Andric // If this lookup fails to find the name, or if the allocated type is not 26410b57cec5SDimitry Andric // a class type, the allocation function's name is looked up in the 26420b57cec5SDimitry Andric // global scope. 26430b57cec5SDimitry Andric if (R.empty()) { 26440b57cec5SDimitry Andric if (NewScope == AFS_Class) 26450b57cec5SDimitry Andric return true; 26460b57cec5SDimitry Andric 26470b57cec5SDimitry Andric LookupQualifiedName(R, Context.getTranslationUnitDecl()); 26480b57cec5SDimitry Andric } 26490b57cec5SDimitry Andric 26500b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus && R.empty()) { 26510b57cec5SDimitry Andric if (PlaceArgs.empty()) { 26520b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; 26530b57cec5SDimitry Andric } else { 26540b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_placement_new); 26550b57cec5SDimitry Andric } 26560b57cec5SDimitry Andric return true; 26570b57cec5SDimitry Andric } 26580b57cec5SDimitry Andric 26590b57cec5SDimitry Andric assert(!R.empty() && "implicitly declared allocation functions not found"); 26600b57cec5SDimitry Andric assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 26610b57cec5SDimitry Andric 26620b57cec5SDimitry Andric // We do our own custom access checks below. 26630b57cec5SDimitry Andric R.suppressDiagnostics(); 26640b57cec5SDimitry Andric 26650b57cec5SDimitry Andric if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, 26660b57cec5SDimitry Andric OperatorNew, /*Candidates=*/nullptr, 26670b57cec5SDimitry Andric /*AlignArg=*/nullptr, Diagnose)) 26680b57cec5SDimitry Andric return true; 26690b57cec5SDimitry Andric } 26700b57cec5SDimitry Andric 26710b57cec5SDimitry Andric // We don't need an operator delete if we're running under -fno-exceptions. 26720b57cec5SDimitry Andric if (!getLangOpts().Exceptions) { 26730b57cec5SDimitry Andric OperatorDelete = nullptr; 26740b57cec5SDimitry Andric return false; 26750b57cec5SDimitry Andric } 26760b57cec5SDimitry Andric 26770b57cec5SDimitry Andric // Note, the name of OperatorNew might have been changed from array to 26780b57cec5SDimitry Andric // non-array by resolveAllocationOverload. 26790b57cec5SDimitry Andric DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 26800b57cec5SDimitry Andric OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New 26810b57cec5SDimitry Andric ? OO_Array_Delete 26820b57cec5SDimitry Andric : OO_Delete); 26830b57cec5SDimitry Andric 26840b57cec5SDimitry Andric // C++ [expr.new]p19: 26850b57cec5SDimitry Andric // 26860b57cec5SDimitry Andric // If the new-expression begins with a unary :: operator, the 26870b57cec5SDimitry Andric // deallocation function's name is looked up in the global 26880b57cec5SDimitry Andric // scope. Otherwise, if the allocated type is a class type T or an 26890b57cec5SDimitry Andric // array thereof, the deallocation function's name is looked up in 26900b57cec5SDimitry Andric // the scope of T. If this lookup fails to find the name, or if 26910b57cec5SDimitry Andric // the allocated type is not a class type or array thereof, the 26920b57cec5SDimitry Andric // deallocation function's name is looked up in the global scope. 26930b57cec5SDimitry Andric LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); 26940b57cec5SDimitry Andric if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) { 2695a7dea167SDimitry Andric auto *RD = 2696a7dea167SDimitry Andric cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl()); 26970b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, RD); 26980b57cec5SDimitry Andric } 26990b57cec5SDimitry Andric if (FoundDelete.isAmbiguous()) 27000b57cec5SDimitry Andric return true; // FIXME: clean up expressions? 27010b57cec5SDimitry Andric 2702e8d8bef9SDimitry Andric // Filter out any destroying operator deletes. We can't possibly call such a 2703e8d8bef9SDimitry Andric // function in this context, because we're handling the case where the object 2704e8d8bef9SDimitry Andric // was not successfully constructed. 2705e8d8bef9SDimitry Andric // FIXME: This is not covered by the language rules yet. 2706e8d8bef9SDimitry Andric { 2707e8d8bef9SDimitry Andric LookupResult::Filter Filter = FoundDelete.makeFilter(); 2708e8d8bef9SDimitry Andric while (Filter.hasNext()) { 2709e8d8bef9SDimitry Andric auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl()); 2710e8d8bef9SDimitry Andric if (FD && FD->isDestroyingOperatorDelete()) 2711e8d8bef9SDimitry Andric Filter.erase(); 2712e8d8bef9SDimitry Andric } 2713e8d8bef9SDimitry Andric Filter.done(); 2714e8d8bef9SDimitry Andric } 2715e8d8bef9SDimitry Andric 27160b57cec5SDimitry Andric bool FoundGlobalDelete = FoundDelete.empty(); 27170b57cec5SDimitry Andric if (FoundDelete.empty()) { 2718e8d8bef9SDimitry Andric FoundDelete.clear(LookupOrdinaryName); 2719e8d8bef9SDimitry Andric 27200b57cec5SDimitry Andric if (DeleteScope == AFS_Class) 27210b57cec5SDimitry Andric return true; 27220b57cec5SDimitry Andric 27230b57cec5SDimitry Andric DeclareGlobalNewDelete(); 27240b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 27250b57cec5SDimitry Andric } 27260b57cec5SDimitry Andric 27270b57cec5SDimitry Andric FoundDelete.suppressDiagnostics(); 27280b57cec5SDimitry Andric 27290b57cec5SDimitry Andric SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; 27300b57cec5SDimitry Andric 27310b57cec5SDimitry Andric // Whether we're looking for a placement operator delete is dictated 27320b57cec5SDimitry Andric // by whether we selected a placement operator new, not by whether 27330b57cec5SDimitry Andric // we had explicit placement arguments. This matters for things like 27340b57cec5SDimitry Andric // struct A { void *operator new(size_t, int = 0); ... }; 27350b57cec5SDimitry Andric // A *a = new A() 27360b57cec5SDimitry Andric // 27370b57cec5SDimitry Andric // We don't have any definition for what a "placement allocation function" 27380b57cec5SDimitry Andric // is, but we assume it's any allocation function whose 27390b57cec5SDimitry Andric // parameter-declaration-clause is anything other than (size_t). 27400b57cec5SDimitry Andric // 27410b57cec5SDimitry Andric // FIXME: Should (size_t, std::align_val_t) also be considered non-placement? 27420b57cec5SDimitry Andric // This affects whether an exception from the constructor of an overaligned 27430b57cec5SDimitry Andric // type uses the sized or non-sized form of aligned operator delete. 27440b57cec5SDimitry Andric bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || 27450b57cec5SDimitry Andric OperatorNew->isVariadic(); 27460b57cec5SDimitry Andric 27470b57cec5SDimitry Andric if (isPlacementNew) { 27480b57cec5SDimitry Andric // C++ [expr.new]p20: 27490b57cec5SDimitry Andric // A declaration of a placement deallocation function matches the 27500b57cec5SDimitry Andric // declaration of a placement allocation function if it has the 27510b57cec5SDimitry Andric // same number of parameters and, after parameter transformations 27520b57cec5SDimitry Andric // (8.3.5), all parameter types except the first are 27530b57cec5SDimitry Andric // identical. [...] 27540b57cec5SDimitry Andric // 27550b57cec5SDimitry Andric // To perform this comparison, we compute the function type that 27560b57cec5SDimitry Andric // the deallocation function should have, and use that type both 27570b57cec5SDimitry Andric // for template argument deduction and for comparison purposes. 27580b57cec5SDimitry Andric QualType ExpectedFunctionType; 27590b57cec5SDimitry Andric { 27605ffd83dbSDimitry Andric auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); 27610b57cec5SDimitry Andric 27620b57cec5SDimitry Andric SmallVector<QualType, 4> ArgTypes; 27630b57cec5SDimitry Andric ArgTypes.push_back(Context.VoidPtrTy); 27640b57cec5SDimitry Andric for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I) 27650b57cec5SDimitry Andric ArgTypes.push_back(Proto->getParamType(I)); 27660b57cec5SDimitry Andric 27670b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI; 27680b57cec5SDimitry Andric // FIXME: This is not part of the standard's rule. 27690b57cec5SDimitry Andric EPI.Variadic = Proto->isVariadic(); 27700b57cec5SDimitry Andric 27710b57cec5SDimitry Andric ExpectedFunctionType 27720b57cec5SDimitry Andric = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); 27730b57cec5SDimitry Andric } 27740b57cec5SDimitry Andric 27750b57cec5SDimitry Andric for (LookupResult::iterator D = FoundDelete.begin(), 27760b57cec5SDimitry Andric DEnd = FoundDelete.end(); 27770b57cec5SDimitry Andric D != DEnd; ++D) { 27780b57cec5SDimitry Andric FunctionDecl *Fn = nullptr; 27790b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTmpl = 27800b57cec5SDimitry Andric dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { 27810b57cec5SDimitry Andric // Perform template argument deduction to try to match the 27820b57cec5SDimitry Andric // expected function type. 27830b57cec5SDimitry Andric TemplateDeductionInfo Info(StartLoc); 27840b57cec5SDimitry Andric if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, 27850b57cec5SDimitry Andric Info)) 27860b57cec5SDimitry Andric continue; 27870b57cec5SDimitry Andric } else 27880b57cec5SDimitry Andric Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); 27890b57cec5SDimitry Andric 27900b57cec5SDimitry Andric if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), 27910b57cec5SDimitry Andric ExpectedFunctionType, 27920b57cec5SDimitry Andric /*AdjustExcpetionSpec*/true), 27930b57cec5SDimitry Andric ExpectedFunctionType)) 27940b57cec5SDimitry Andric Matches.push_back(std::make_pair(D.getPair(), Fn)); 27950b57cec5SDimitry Andric } 27960b57cec5SDimitry Andric 27970b57cec5SDimitry Andric if (getLangOpts().CUDA) 27980b57cec5SDimitry Andric EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches); 27990b57cec5SDimitry Andric } else { 28000b57cec5SDimitry Andric // C++1y [expr.new]p22: 28010b57cec5SDimitry Andric // For a non-placement allocation function, the normal deallocation 28020b57cec5SDimitry Andric // function lookup is used 28030b57cec5SDimitry Andric // 28040b57cec5SDimitry Andric // Per [expr.delete]p10, this lookup prefers a member operator delete 28050b57cec5SDimitry Andric // without a size_t argument, but prefers a non-member operator delete 28060b57cec5SDimitry Andric // with a size_t where possible (which it always is in this case). 28070b57cec5SDimitry Andric llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; 28080b57cec5SDimitry Andric UsualDeallocFnInfo Selected = resolveDeallocationOverload( 28090b57cec5SDimitry Andric *this, FoundDelete, /*WantSize*/ FoundGlobalDelete, 28100b57cec5SDimitry Andric /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType), 28110b57cec5SDimitry Andric &BestDeallocFns); 28120b57cec5SDimitry Andric if (Selected) 28130b57cec5SDimitry Andric Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); 28140b57cec5SDimitry Andric else { 28150b57cec5SDimitry Andric // If we failed to select an operator, all remaining functions are viable 28160b57cec5SDimitry Andric // but ambiguous. 28170b57cec5SDimitry Andric for (auto Fn : BestDeallocFns) 28180b57cec5SDimitry Andric Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); 28190b57cec5SDimitry Andric } 28200b57cec5SDimitry Andric } 28210b57cec5SDimitry Andric 28220b57cec5SDimitry Andric // C++ [expr.new]p20: 28230b57cec5SDimitry Andric // [...] If the lookup finds a single matching deallocation 28240b57cec5SDimitry Andric // function, that function will be called; otherwise, no 28250b57cec5SDimitry Andric // deallocation function will be called. 28260b57cec5SDimitry Andric if (Matches.size() == 1) { 28270b57cec5SDimitry Andric OperatorDelete = Matches[0].second; 28280b57cec5SDimitry Andric 28290b57cec5SDimitry Andric // C++1z [expr.new]p23: 28300b57cec5SDimitry Andric // If the lookup finds a usual deallocation function (3.7.4.2) 28310b57cec5SDimitry Andric // with a parameter of type std::size_t and that function, considered 28320b57cec5SDimitry Andric // as a placement deallocation function, would have been 28330b57cec5SDimitry Andric // selected as a match for the allocation function, the program 28340b57cec5SDimitry Andric // is ill-formed. 28350b57cec5SDimitry Andric if (getLangOpts().CPlusPlus11 && isPlacementNew && 28360b57cec5SDimitry Andric isNonPlacementDeallocationFunction(*this, OperatorDelete)) { 28370b57cec5SDimitry Andric UsualDeallocFnInfo Info(*this, 28380b57cec5SDimitry Andric DeclAccessPair::make(OperatorDelete, AS_public)); 28390b57cec5SDimitry Andric // Core issue, per mail to core reflector, 2016-10-09: 28400b57cec5SDimitry Andric // If this is a member operator delete, and there is a corresponding 28410b57cec5SDimitry Andric // non-sized member operator delete, this isn't /really/ a sized 28420b57cec5SDimitry Andric // deallocation function, it just happens to have a size_t parameter. 28430b57cec5SDimitry Andric bool IsSizedDelete = Info.HasSizeT; 28440b57cec5SDimitry Andric if (IsSizedDelete && !FoundGlobalDelete) { 28450b57cec5SDimitry Andric auto NonSizedDelete = 28460b57cec5SDimitry Andric resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false, 28470b57cec5SDimitry Andric /*WantAlign*/Info.HasAlignValT); 28480b57cec5SDimitry Andric if (NonSizedDelete && !NonSizedDelete.HasSizeT && 28490b57cec5SDimitry Andric NonSizedDelete.HasAlignValT == Info.HasAlignValT) 28500b57cec5SDimitry Andric IsSizedDelete = false; 28510b57cec5SDimitry Andric } 28520b57cec5SDimitry Andric 28530b57cec5SDimitry Andric if (IsSizedDelete) { 28540b57cec5SDimitry Andric SourceRange R = PlaceArgs.empty() 28550b57cec5SDimitry Andric ? SourceRange() 28560b57cec5SDimitry Andric : SourceRange(PlaceArgs.front()->getBeginLoc(), 28570b57cec5SDimitry Andric PlaceArgs.back()->getEndLoc()); 28580b57cec5SDimitry Andric Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; 28590b57cec5SDimitry Andric if (!OperatorDelete->isImplicit()) 28600b57cec5SDimitry Andric Diag(OperatorDelete->getLocation(), diag::note_previous_decl) 28610b57cec5SDimitry Andric << DeleteName; 28620b57cec5SDimitry Andric } 28630b57cec5SDimitry Andric } 28640b57cec5SDimitry Andric 28650b57cec5SDimitry Andric CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(), 28660b57cec5SDimitry Andric Matches[0].first); 28670b57cec5SDimitry Andric } else if (!Matches.empty()) { 28680b57cec5SDimitry Andric // We found multiple suitable operators. Per [expr.new]p20, that means we 28690b57cec5SDimitry Andric // call no 'operator delete' function, but we should at least warn the user. 28700b57cec5SDimitry Andric // FIXME: Suppress this warning if the construction cannot throw. 28710b57cec5SDimitry Andric Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) 28720b57cec5SDimitry Andric << DeleteName << AllocElemType; 28730b57cec5SDimitry Andric 28740b57cec5SDimitry Andric for (auto &Match : Matches) 28750b57cec5SDimitry Andric Diag(Match.second->getLocation(), 28760b57cec5SDimitry Andric diag::note_member_declared_here) << DeleteName; 28770b57cec5SDimitry Andric } 28780b57cec5SDimitry Andric 28790b57cec5SDimitry Andric return false; 28800b57cec5SDimitry Andric } 28810b57cec5SDimitry Andric 28820b57cec5SDimitry Andric /// DeclareGlobalNewDelete - Declare the global forms of operator new and 28830b57cec5SDimitry Andric /// delete. These are: 28840b57cec5SDimitry Andric /// @code 28850b57cec5SDimitry Andric /// // C++03: 28860b57cec5SDimitry Andric /// void* operator new(std::size_t) throw(std::bad_alloc); 28870b57cec5SDimitry Andric /// void* operator new[](std::size_t) throw(std::bad_alloc); 28880b57cec5SDimitry Andric /// void operator delete(void *) throw(); 28890b57cec5SDimitry Andric /// void operator delete[](void *) throw(); 28900b57cec5SDimitry Andric /// // C++11: 28910b57cec5SDimitry Andric /// void* operator new(std::size_t); 28920b57cec5SDimitry Andric /// void* operator new[](std::size_t); 28930b57cec5SDimitry Andric /// void operator delete(void *) noexcept; 28940b57cec5SDimitry Andric /// void operator delete[](void *) noexcept; 28950b57cec5SDimitry Andric /// // C++1y: 28960b57cec5SDimitry Andric /// void* operator new(std::size_t); 28970b57cec5SDimitry Andric /// void* operator new[](std::size_t); 28980b57cec5SDimitry Andric /// void operator delete(void *) noexcept; 28990b57cec5SDimitry Andric /// void operator delete[](void *) noexcept; 29000b57cec5SDimitry Andric /// void operator delete(void *, std::size_t) noexcept; 29010b57cec5SDimitry Andric /// void operator delete[](void *, std::size_t) noexcept; 29020b57cec5SDimitry Andric /// @endcode 29030b57cec5SDimitry Andric /// Note that the placement and nothrow forms of new are *not* implicitly 29040b57cec5SDimitry Andric /// declared. Their use requires including \<new\>. 29050b57cec5SDimitry Andric void Sema::DeclareGlobalNewDelete() { 29060b57cec5SDimitry Andric if (GlobalNewDeleteDeclared) 29070b57cec5SDimitry Andric return; 29080b57cec5SDimitry Andric 29090b57cec5SDimitry Andric // The implicitly declared new and delete operators 29100b57cec5SDimitry Andric // are not supported in OpenCL. 29110b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) 29120b57cec5SDimitry Andric return; 29130b57cec5SDimitry Andric 29140b57cec5SDimitry Andric // C++ [basic.std.dynamic]p2: 29150b57cec5SDimitry Andric // [...] The following allocation and deallocation functions (18.4) are 29160b57cec5SDimitry Andric // implicitly declared in global scope in each translation unit of a 29170b57cec5SDimitry Andric // program 29180b57cec5SDimitry Andric // 29190b57cec5SDimitry Andric // C++03: 29200b57cec5SDimitry Andric // void* operator new(std::size_t) throw(std::bad_alloc); 29210b57cec5SDimitry Andric // void* operator new[](std::size_t) throw(std::bad_alloc); 29220b57cec5SDimitry Andric // void operator delete(void*) throw(); 29230b57cec5SDimitry Andric // void operator delete[](void*) throw(); 29240b57cec5SDimitry Andric // C++11: 29250b57cec5SDimitry Andric // void* operator new(std::size_t); 29260b57cec5SDimitry Andric // void* operator new[](std::size_t); 29270b57cec5SDimitry Andric // void operator delete(void*) noexcept; 29280b57cec5SDimitry Andric // void operator delete[](void*) noexcept; 29290b57cec5SDimitry Andric // C++1y: 29300b57cec5SDimitry Andric // void* operator new(std::size_t); 29310b57cec5SDimitry Andric // void* operator new[](std::size_t); 29320b57cec5SDimitry Andric // void operator delete(void*) noexcept; 29330b57cec5SDimitry Andric // void operator delete[](void*) noexcept; 29340b57cec5SDimitry Andric // void operator delete(void*, std::size_t) noexcept; 29350b57cec5SDimitry Andric // void operator delete[](void*, std::size_t) noexcept; 29360b57cec5SDimitry Andric // 29370b57cec5SDimitry Andric // These implicit declarations introduce only the function names operator 29380b57cec5SDimitry Andric // new, operator new[], operator delete, operator delete[]. 29390b57cec5SDimitry Andric // 29400b57cec5SDimitry Andric // Here, we need to refer to std::bad_alloc, so we will implicitly declare 29410b57cec5SDimitry Andric // "std" or "bad_alloc" as necessary to form the exception specification. 29420b57cec5SDimitry Andric // However, we do not make these implicit declarations visible to name 29430b57cec5SDimitry Andric // lookup. 29440b57cec5SDimitry Andric if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { 29450b57cec5SDimitry Andric // The "std::bad_alloc" class has not yet been declared, so build it 29460b57cec5SDimitry Andric // implicitly. 29470b57cec5SDimitry Andric StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class, 29480b57cec5SDimitry Andric getOrCreateStdNamespace(), 29490b57cec5SDimitry Andric SourceLocation(), SourceLocation(), 29500b57cec5SDimitry Andric &PP.getIdentifierTable().get("bad_alloc"), 29510b57cec5SDimitry Andric nullptr); 29520b57cec5SDimitry Andric getStdBadAlloc()->setImplicit(true); 29530b57cec5SDimitry Andric } 29540b57cec5SDimitry Andric if (!StdAlignValT && getLangOpts().AlignedAllocation) { 29550b57cec5SDimitry Andric // The "std::align_val_t" enum class has not yet been declared, so build it 29560b57cec5SDimitry Andric // implicitly. 29570b57cec5SDimitry Andric auto *AlignValT = EnumDecl::Create( 29580b57cec5SDimitry Andric Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), 29590b57cec5SDimitry Andric &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); 29600b57cec5SDimitry Andric AlignValT->setIntegerType(Context.getSizeType()); 29610b57cec5SDimitry Andric AlignValT->setPromotionType(Context.getSizeType()); 29620b57cec5SDimitry Andric AlignValT->setImplicit(true); 29630b57cec5SDimitry Andric StdAlignValT = AlignValT; 29640b57cec5SDimitry Andric } 29650b57cec5SDimitry Andric 29660b57cec5SDimitry Andric GlobalNewDeleteDeclared = true; 29670b57cec5SDimitry Andric 29680b57cec5SDimitry Andric QualType VoidPtr = Context.getPointerType(Context.VoidTy); 29690b57cec5SDimitry Andric QualType SizeT = Context.getSizeType(); 29700b57cec5SDimitry Andric 29710b57cec5SDimitry Andric auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, 29720b57cec5SDimitry Andric QualType Return, QualType Param) { 29730b57cec5SDimitry Andric llvm::SmallVector<QualType, 3> Params; 29740b57cec5SDimitry Andric Params.push_back(Param); 29750b57cec5SDimitry Andric 29760b57cec5SDimitry Andric // Create up to four variants of the function (sized/aligned). 29770b57cec5SDimitry Andric bool HasSizedVariant = getLangOpts().SizedDeallocation && 29780b57cec5SDimitry Andric (Kind == OO_Delete || Kind == OO_Array_Delete); 29790b57cec5SDimitry Andric bool HasAlignedVariant = getLangOpts().AlignedAllocation; 29800b57cec5SDimitry Andric 29810b57cec5SDimitry Andric int NumSizeVariants = (HasSizedVariant ? 2 : 1); 29820b57cec5SDimitry Andric int NumAlignVariants = (HasAlignedVariant ? 2 : 1); 29830b57cec5SDimitry Andric for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { 29840b57cec5SDimitry Andric if (Sized) 29850b57cec5SDimitry Andric Params.push_back(SizeT); 29860b57cec5SDimitry Andric 29870b57cec5SDimitry Andric for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { 29880b57cec5SDimitry Andric if (Aligned) 29890b57cec5SDimitry Andric Params.push_back(Context.getTypeDeclType(getStdAlignValT())); 29900b57cec5SDimitry Andric 29910b57cec5SDimitry Andric DeclareGlobalAllocationFunction( 29920b57cec5SDimitry Andric Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); 29930b57cec5SDimitry Andric 29940b57cec5SDimitry Andric if (Aligned) 29950b57cec5SDimitry Andric Params.pop_back(); 29960b57cec5SDimitry Andric } 29970b57cec5SDimitry Andric } 29980b57cec5SDimitry Andric }; 29990b57cec5SDimitry Andric 30000b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); 30010b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); 30020b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); 30030b57cec5SDimitry Andric DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); 30040b57cec5SDimitry Andric } 30050b57cec5SDimitry Andric 30060b57cec5SDimitry Andric /// DeclareGlobalAllocationFunction - Declares a single implicit global 30070b57cec5SDimitry Andric /// allocation function if it doesn't already exist. 30080b57cec5SDimitry Andric void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, 30090b57cec5SDimitry Andric QualType Return, 30100b57cec5SDimitry Andric ArrayRef<QualType> Params) { 30110b57cec5SDimitry Andric DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); 30120b57cec5SDimitry Andric 30130b57cec5SDimitry Andric // Check if this function is already declared. 30140b57cec5SDimitry Andric DeclContext::lookup_result R = GlobalCtx->lookup(Name); 30150b57cec5SDimitry Andric for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); 30160b57cec5SDimitry Andric Alloc != AllocEnd; ++Alloc) { 30170b57cec5SDimitry Andric // Only look at non-template functions, as it is the predefined, 30180b57cec5SDimitry Andric // non-templated allocation function we are trying to declare here. 30190b57cec5SDimitry Andric if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { 30200b57cec5SDimitry Andric if (Func->getNumParams() == Params.size()) { 30210b57cec5SDimitry Andric llvm::SmallVector<QualType, 3> FuncParams; 30220b57cec5SDimitry Andric for (auto *P : Func->parameters()) 30230b57cec5SDimitry Andric FuncParams.push_back( 30240b57cec5SDimitry Andric Context.getCanonicalType(P->getType().getUnqualifiedType())); 30250b57cec5SDimitry Andric if (llvm::makeArrayRef(FuncParams) == Params) { 30260b57cec5SDimitry Andric // Make the function visible to name lookup, even if we found it in 30270b57cec5SDimitry Andric // an unimported module. It either is an implicitly-declared global 30280b57cec5SDimitry Andric // allocation function, or is suppressing that function. 30290b57cec5SDimitry Andric Func->setVisibleDespiteOwningModule(); 30300b57cec5SDimitry Andric return; 30310b57cec5SDimitry Andric } 30320b57cec5SDimitry Andric } 30330b57cec5SDimitry Andric } 30340b57cec5SDimitry Andric } 30350b57cec5SDimitry Andric 30360b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( 30370b57cec5SDimitry Andric /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true)); 30380b57cec5SDimitry Andric 30390b57cec5SDimitry Andric QualType BadAllocType; 30400b57cec5SDimitry Andric bool HasBadAllocExceptionSpec 30410b57cec5SDimitry Andric = (Name.getCXXOverloadedOperator() == OO_New || 30420b57cec5SDimitry Andric Name.getCXXOverloadedOperator() == OO_Array_New); 30430b57cec5SDimitry Andric if (HasBadAllocExceptionSpec) { 30440b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus11) { 30450b57cec5SDimitry Andric BadAllocType = Context.getTypeDeclType(getStdBadAlloc()); 30460b57cec5SDimitry Andric assert(StdBadAlloc && "Must have std::bad_alloc declared"); 30470b57cec5SDimitry Andric EPI.ExceptionSpec.Type = EST_Dynamic; 30480b57cec5SDimitry Andric EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType); 30490b57cec5SDimitry Andric } 3050349cc55cSDimitry Andric if (getLangOpts().NewInfallible) { 3051349cc55cSDimitry Andric EPI.ExceptionSpec.Type = EST_DynamicNone; 3052349cc55cSDimitry Andric } 30530b57cec5SDimitry Andric } else { 30540b57cec5SDimitry Andric EPI.ExceptionSpec = 30550b57cec5SDimitry Andric getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; 30560b57cec5SDimitry Andric } 30570b57cec5SDimitry Andric 30580b57cec5SDimitry Andric auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { 30590b57cec5SDimitry Andric QualType FnType = Context.getFunctionType(Return, Params, EPI); 30600b57cec5SDimitry Andric FunctionDecl *Alloc = FunctionDecl::Create( 3061349cc55cSDimitry Andric Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType, 3062349cc55cSDimitry Andric /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false, 3063349cc55cSDimitry Andric true); 30640b57cec5SDimitry Andric Alloc->setImplicit(); 30650b57cec5SDimitry Andric // Global allocation functions should always be visible. 30660b57cec5SDimitry Andric Alloc->setVisibleDespiteOwningModule(); 30670b57cec5SDimitry Andric 3068349cc55cSDimitry Andric if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible) 3069349cc55cSDimitry Andric Alloc->addAttr( 3070349cc55cSDimitry Andric ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation())); 3071349cc55cSDimitry Andric 30720b57cec5SDimitry Andric Alloc->addAttr(VisibilityAttr::CreateImplicit( 30730b57cec5SDimitry Andric Context, LangOpts.GlobalAllocationFunctionVisibilityHidden 30740b57cec5SDimitry Andric ? VisibilityAttr::Hidden 30750b57cec5SDimitry Andric : VisibilityAttr::Default)); 30760b57cec5SDimitry Andric 30770b57cec5SDimitry Andric llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; 30780b57cec5SDimitry Andric for (QualType T : Params) { 30790b57cec5SDimitry Andric ParamDecls.push_back(ParmVarDecl::Create( 30800b57cec5SDimitry Andric Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, 30810b57cec5SDimitry Andric /*TInfo=*/nullptr, SC_None, nullptr)); 30820b57cec5SDimitry Andric ParamDecls.back()->setImplicit(); 30830b57cec5SDimitry Andric } 30840b57cec5SDimitry Andric Alloc->setParams(ParamDecls); 30850b57cec5SDimitry Andric if (ExtraAttr) 30860b57cec5SDimitry Andric Alloc->addAttr(ExtraAttr); 30875ffd83dbSDimitry Andric AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc); 30880b57cec5SDimitry Andric Context.getTranslationUnitDecl()->addDecl(Alloc); 30890b57cec5SDimitry Andric IdResolver.tryAddTopLevelDecl(Alloc, Name); 30900b57cec5SDimitry Andric }; 30910b57cec5SDimitry Andric 30920b57cec5SDimitry Andric if (!LangOpts.CUDA) 30930b57cec5SDimitry Andric CreateAllocationFunctionDecl(nullptr); 30940b57cec5SDimitry Andric else { 30950b57cec5SDimitry Andric // Host and device get their own declaration so each can be 30960b57cec5SDimitry Andric // defined or re-declared independently. 30970b57cec5SDimitry Andric CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); 30980b57cec5SDimitry Andric CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); 30990b57cec5SDimitry Andric } 31000b57cec5SDimitry Andric } 31010b57cec5SDimitry Andric 31020b57cec5SDimitry Andric FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, 31030b57cec5SDimitry Andric bool CanProvideSize, 31040b57cec5SDimitry Andric bool Overaligned, 31050b57cec5SDimitry Andric DeclarationName Name) { 31060b57cec5SDimitry Andric DeclareGlobalNewDelete(); 31070b57cec5SDimitry Andric 31080b57cec5SDimitry Andric LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); 31090b57cec5SDimitry Andric LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl()); 31100b57cec5SDimitry Andric 31110b57cec5SDimitry Andric // FIXME: It's possible for this to result in ambiguity, through a 31120b57cec5SDimitry Andric // user-declared variadic operator delete or the enable_if attribute. We 31130b57cec5SDimitry Andric // should probably not consider those cases to be usual deallocation 31140b57cec5SDimitry Andric // functions. But for now we just make an arbitrary choice in that case. 31150b57cec5SDimitry Andric auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, 31160b57cec5SDimitry Andric Overaligned); 31170b57cec5SDimitry Andric assert(Result.FD && "operator delete missing from global scope?"); 31180b57cec5SDimitry Andric return Result.FD; 31190b57cec5SDimitry Andric } 31200b57cec5SDimitry Andric 31210b57cec5SDimitry Andric FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc, 31220b57cec5SDimitry Andric CXXRecordDecl *RD) { 31230b57cec5SDimitry Andric DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete); 31240b57cec5SDimitry Andric 31250b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 31260b57cec5SDimitry Andric if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete)) 31270b57cec5SDimitry Andric return nullptr; 31280b57cec5SDimitry Andric if (OperatorDelete) 31290b57cec5SDimitry Andric return OperatorDelete; 31300b57cec5SDimitry Andric 31310b57cec5SDimitry Andric // If there's no class-specific operator delete, look up the global 31320b57cec5SDimitry Andric // non-array delete. 31330b57cec5SDimitry Andric return FindUsualDeallocationFunction( 31340b57cec5SDimitry Andric Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), 31350b57cec5SDimitry Andric Name); 31360b57cec5SDimitry Andric } 31370b57cec5SDimitry Andric 31380b57cec5SDimitry Andric bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 31390b57cec5SDimitry Andric DeclarationName Name, 31400b57cec5SDimitry Andric FunctionDecl *&Operator, bool Diagnose) { 31410b57cec5SDimitry Andric LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); 31420b57cec5SDimitry Andric // Try to find operator delete/operator delete[] in class scope. 31430b57cec5SDimitry Andric LookupQualifiedName(Found, RD); 31440b57cec5SDimitry Andric 31450b57cec5SDimitry Andric if (Found.isAmbiguous()) 31460b57cec5SDimitry Andric return true; 31470b57cec5SDimitry Andric 31480b57cec5SDimitry Andric Found.suppressDiagnostics(); 31490b57cec5SDimitry Andric 31500b57cec5SDimitry Andric bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD)); 31510b57cec5SDimitry Andric 31520b57cec5SDimitry Andric // C++17 [expr.delete]p10: 31530b57cec5SDimitry Andric // If the deallocation functions have class scope, the one without a 31540b57cec5SDimitry Andric // parameter of type std::size_t is selected. 31550b57cec5SDimitry Andric llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; 31560b57cec5SDimitry Andric resolveDeallocationOverload(*this, Found, /*WantSize*/ false, 31570b57cec5SDimitry Andric /*WantAlign*/ Overaligned, &Matches); 31580b57cec5SDimitry Andric 31590b57cec5SDimitry Andric // If we could find an overload, use it. 31600b57cec5SDimitry Andric if (Matches.size() == 1) { 31610b57cec5SDimitry Andric Operator = cast<CXXMethodDecl>(Matches[0].FD); 31620b57cec5SDimitry Andric 31630b57cec5SDimitry Andric // FIXME: DiagnoseUseOfDecl? 31640b57cec5SDimitry Andric if (Operator->isDeleted()) { 31650b57cec5SDimitry Andric if (Diagnose) { 31660b57cec5SDimitry Andric Diag(StartLoc, diag::err_deleted_function_use); 31670b57cec5SDimitry Andric NoteDeletedFunction(Operator); 31680b57cec5SDimitry Andric } 31690b57cec5SDimitry Andric return true; 31700b57cec5SDimitry Andric } 31710b57cec5SDimitry Andric 31720b57cec5SDimitry Andric if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(), 31730b57cec5SDimitry Andric Matches[0].Found, Diagnose) == AR_inaccessible) 31740b57cec5SDimitry Andric return true; 31750b57cec5SDimitry Andric 31760b57cec5SDimitry Andric return false; 31770b57cec5SDimitry Andric } 31780b57cec5SDimitry Andric 31790b57cec5SDimitry Andric // We found multiple suitable operators; complain about the ambiguity. 31800b57cec5SDimitry Andric // FIXME: The standard doesn't say to do this; it appears that the intent 31810b57cec5SDimitry Andric // is that this should never happen. 31820b57cec5SDimitry Andric if (!Matches.empty()) { 31830b57cec5SDimitry Andric if (Diagnose) { 31840b57cec5SDimitry Andric Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) 31850b57cec5SDimitry Andric << Name << RD; 31860b57cec5SDimitry Andric for (auto &Match : Matches) 31870b57cec5SDimitry Andric Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; 31880b57cec5SDimitry Andric } 31890b57cec5SDimitry Andric return true; 31900b57cec5SDimitry Andric } 31910b57cec5SDimitry Andric 31920b57cec5SDimitry Andric // We did find operator delete/operator delete[] declarations, but 31930b57cec5SDimitry Andric // none of them were suitable. 31940b57cec5SDimitry Andric if (!Found.empty()) { 31950b57cec5SDimitry Andric if (Diagnose) { 31960b57cec5SDimitry Andric Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) 31970b57cec5SDimitry Andric << Name << RD; 31980b57cec5SDimitry Andric 31990b57cec5SDimitry Andric for (NamedDecl *D : Found) 32000b57cec5SDimitry Andric Diag(D->getUnderlyingDecl()->getLocation(), 32010b57cec5SDimitry Andric diag::note_member_declared_here) << Name; 32020b57cec5SDimitry Andric } 32030b57cec5SDimitry Andric return true; 32040b57cec5SDimitry Andric } 32050b57cec5SDimitry Andric 32060b57cec5SDimitry Andric Operator = nullptr; 32070b57cec5SDimitry Andric return false; 32080b57cec5SDimitry Andric } 32090b57cec5SDimitry Andric 32100b57cec5SDimitry Andric namespace { 32110b57cec5SDimitry Andric /// Checks whether delete-expression, and new-expression used for 32120b57cec5SDimitry Andric /// initializing deletee have the same array form. 32130b57cec5SDimitry Andric class MismatchingNewDeleteDetector { 32140b57cec5SDimitry Andric public: 32150b57cec5SDimitry Andric enum MismatchResult { 32160b57cec5SDimitry Andric /// Indicates that there is no mismatch or a mismatch cannot be proven. 32170b57cec5SDimitry Andric NoMismatch, 32180b57cec5SDimitry Andric /// Indicates that variable is initialized with mismatching form of \a new. 32190b57cec5SDimitry Andric VarInitMismatches, 32200b57cec5SDimitry Andric /// Indicates that member is initialized with mismatching form of \a new. 32210b57cec5SDimitry Andric MemberInitMismatches, 32220b57cec5SDimitry Andric /// Indicates that 1 or more constructors' definitions could not been 32230b57cec5SDimitry Andric /// analyzed, and they will be checked again at the end of translation unit. 32240b57cec5SDimitry Andric AnalyzeLater 32250b57cec5SDimitry Andric }; 32260b57cec5SDimitry Andric 32270b57cec5SDimitry Andric /// \param EndOfTU True, if this is the final analysis at the end of 32280b57cec5SDimitry Andric /// translation unit. False, if this is the initial analysis at the point 32290b57cec5SDimitry Andric /// delete-expression was encountered. 32300b57cec5SDimitry Andric explicit MismatchingNewDeleteDetector(bool EndOfTU) 32310b57cec5SDimitry Andric : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), 32320b57cec5SDimitry Andric HasUndefinedConstructors(false) {} 32330b57cec5SDimitry Andric 32340b57cec5SDimitry Andric /// Checks whether pointee of a delete-expression is initialized with 32350b57cec5SDimitry Andric /// matching form of new-expression. 32360b57cec5SDimitry Andric /// 32370b57cec5SDimitry Andric /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the 32380b57cec5SDimitry Andric /// point where delete-expression is encountered, then a warning will be 32390b57cec5SDimitry Andric /// issued immediately. If return value is \c AnalyzeLater at the point where 32400b57cec5SDimitry Andric /// delete-expression is seen, then member will be analyzed at the end of 32410b57cec5SDimitry Andric /// translation unit. \c AnalyzeLater is returned iff at least one constructor 32420b57cec5SDimitry Andric /// couldn't be analyzed. If at least one constructor initializes the member 32430b57cec5SDimitry Andric /// with matching type of new, the return value is \c NoMismatch. 32440b57cec5SDimitry Andric MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); 32450b57cec5SDimitry Andric /// Analyzes a class member. 32460b57cec5SDimitry Andric /// \param Field Class member to analyze. 32470b57cec5SDimitry Andric /// \param DeleteWasArrayForm Array form-ness of the delete-expression used 32480b57cec5SDimitry Andric /// for deleting the \p Field. 32490b57cec5SDimitry Andric MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); 32500b57cec5SDimitry Andric FieldDecl *Field; 32510b57cec5SDimitry Andric /// List of mismatching new-expressions used for initialization of the pointee 32520b57cec5SDimitry Andric llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; 32530b57cec5SDimitry Andric /// Indicates whether delete-expression was in array form. 32540b57cec5SDimitry Andric bool IsArrayForm; 32550b57cec5SDimitry Andric 32560b57cec5SDimitry Andric private: 32570b57cec5SDimitry Andric const bool EndOfTU; 32580b57cec5SDimitry Andric /// Indicates that there is at least one constructor without body. 32590b57cec5SDimitry Andric bool HasUndefinedConstructors; 32600b57cec5SDimitry Andric /// Returns \c CXXNewExpr from given initialization expression. 32610b57cec5SDimitry Andric /// \param E Expression used for initializing pointee in delete-expression. 32620b57cec5SDimitry Andric /// E can be a single-element \c InitListExpr consisting of new-expression. 32630b57cec5SDimitry Andric const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); 32640b57cec5SDimitry Andric /// Returns whether member is initialized with mismatching form of 32650b57cec5SDimitry Andric /// \c new either by the member initializer or in-class initialization. 32660b57cec5SDimitry Andric /// 32670b57cec5SDimitry Andric /// If bodies of all constructors are not visible at the end of translation 32680b57cec5SDimitry Andric /// unit or at least one constructor initializes member with the matching 32690b57cec5SDimitry Andric /// form of \c new, mismatch cannot be proven, and this function will return 32700b57cec5SDimitry Andric /// \c NoMismatch. 32710b57cec5SDimitry Andric MismatchResult analyzeMemberExpr(const MemberExpr *ME); 32720b57cec5SDimitry Andric /// Returns whether variable is initialized with mismatching form of 32730b57cec5SDimitry Andric /// \c new. 32740b57cec5SDimitry Andric /// 32750b57cec5SDimitry Andric /// If variable is initialized with matching form of \c new or variable is not 32760b57cec5SDimitry Andric /// initialized with a \c new expression, this function will return true. 32770b57cec5SDimitry Andric /// If variable is initialized with mismatching form of \c new, returns false. 32780b57cec5SDimitry Andric /// \param D Variable to analyze. 32790b57cec5SDimitry Andric bool hasMatchingVarInit(const DeclRefExpr *D); 32800b57cec5SDimitry Andric /// Checks whether the constructor initializes pointee with mismatching 32810b57cec5SDimitry Andric /// form of \c new. 32820b57cec5SDimitry Andric /// 32830b57cec5SDimitry Andric /// Returns true, if member is initialized with matching form of \c new in 32840b57cec5SDimitry Andric /// member initializer list. Returns false, if member is initialized with the 32850b57cec5SDimitry Andric /// matching form of \c new in this constructor's initializer or given 32860b57cec5SDimitry Andric /// constructor isn't defined at the point where delete-expression is seen, or 32870b57cec5SDimitry Andric /// member isn't initialized by the constructor. 32880b57cec5SDimitry Andric bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); 32890b57cec5SDimitry Andric /// Checks whether member is initialized with matching form of 32900b57cec5SDimitry Andric /// \c new in member initializer list. 32910b57cec5SDimitry Andric bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); 32920b57cec5SDimitry Andric /// Checks whether member is initialized with mismatching form of \c new by 32930b57cec5SDimitry Andric /// in-class initializer. 32940b57cec5SDimitry Andric MismatchResult analyzeInClassInitializer(); 32950b57cec5SDimitry Andric }; 32960b57cec5SDimitry Andric } 32970b57cec5SDimitry Andric 32980b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 32990b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { 33000b57cec5SDimitry Andric NewExprs.clear(); 33010b57cec5SDimitry Andric assert(DE && "Expected delete-expression"); 33020b57cec5SDimitry Andric IsArrayForm = DE->isArrayForm(); 33030b57cec5SDimitry Andric const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); 33040b57cec5SDimitry Andric if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { 33050b57cec5SDimitry Andric return analyzeMemberExpr(ME); 33060b57cec5SDimitry Andric } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { 33070b57cec5SDimitry Andric if (!hasMatchingVarInit(D)) 33080b57cec5SDimitry Andric return VarInitMismatches; 33090b57cec5SDimitry Andric } 33100b57cec5SDimitry Andric return NoMismatch; 33110b57cec5SDimitry Andric } 33120b57cec5SDimitry Andric 33130b57cec5SDimitry Andric const CXXNewExpr * 33140b57cec5SDimitry Andric MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { 33150b57cec5SDimitry Andric assert(E != nullptr && "Expected a valid initializer expression"); 33160b57cec5SDimitry Andric E = E->IgnoreParenImpCasts(); 33170b57cec5SDimitry Andric if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { 33180b57cec5SDimitry Andric if (ILE->getNumInits() == 1) 33190b57cec5SDimitry Andric E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); 33200b57cec5SDimitry Andric } 33210b57cec5SDimitry Andric 33220b57cec5SDimitry Andric return dyn_cast_or_null<const CXXNewExpr>(E); 33230b57cec5SDimitry Andric } 33240b57cec5SDimitry Andric 33250b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( 33260b57cec5SDimitry Andric const CXXCtorInitializer *CI) { 33270b57cec5SDimitry Andric const CXXNewExpr *NE = nullptr; 33280b57cec5SDimitry Andric if (Field == CI->getMember() && 33290b57cec5SDimitry Andric (NE = getNewExprFromInitListOrExpr(CI->getInit()))) { 33300b57cec5SDimitry Andric if (NE->isArray() == IsArrayForm) 33310b57cec5SDimitry Andric return true; 33320b57cec5SDimitry Andric else 33330b57cec5SDimitry Andric NewExprs.push_back(NE); 33340b57cec5SDimitry Andric } 33350b57cec5SDimitry Andric return false; 33360b57cec5SDimitry Andric } 33370b57cec5SDimitry Andric 33380b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( 33390b57cec5SDimitry Andric const CXXConstructorDecl *CD) { 33400b57cec5SDimitry Andric if (CD->isImplicit()) 33410b57cec5SDimitry Andric return false; 33420b57cec5SDimitry Andric const FunctionDecl *Definition = CD; 33430b57cec5SDimitry Andric if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { 33440b57cec5SDimitry Andric HasUndefinedConstructors = true; 33450b57cec5SDimitry Andric return EndOfTU; 33460b57cec5SDimitry Andric } 33470b57cec5SDimitry Andric for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { 33480b57cec5SDimitry Andric if (hasMatchingNewInCtorInit(CI)) 33490b57cec5SDimitry Andric return true; 33500b57cec5SDimitry Andric } 33510b57cec5SDimitry Andric return false; 33520b57cec5SDimitry Andric } 33530b57cec5SDimitry Andric 33540b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 33550b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeInClassInitializer() { 33560b57cec5SDimitry Andric assert(Field != nullptr && "This should be called only for members"); 33570b57cec5SDimitry Andric const Expr *InitExpr = Field->getInClassInitializer(); 33580b57cec5SDimitry Andric if (!InitExpr) 33590b57cec5SDimitry Andric return EndOfTU ? NoMismatch : AnalyzeLater; 33600b57cec5SDimitry Andric if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { 33610b57cec5SDimitry Andric if (NE->isArray() != IsArrayForm) { 33620b57cec5SDimitry Andric NewExprs.push_back(NE); 33630b57cec5SDimitry Andric return MemberInitMismatches; 33640b57cec5SDimitry Andric } 33650b57cec5SDimitry Andric } 33660b57cec5SDimitry Andric return NoMismatch; 33670b57cec5SDimitry Andric } 33680b57cec5SDimitry Andric 33690b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 33700b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, 33710b57cec5SDimitry Andric bool DeleteWasArrayForm) { 33720b57cec5SDimitry Andric assert(Field != nullptr && "Analysis requires a valid class member."); 33730b57cec5SDimitry Andric this->Field = Field; 33740b57cec5SDimitry Andric IsArrayForm = DeleteWasArrayForm; 33750b57cec5SDimitry Andric const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); 33760b57cec5SDimitry Andric for (const auto *CD : RD->ctors()) { 33770b57cec5SDimitry Andric if (hasMatchingNewInCtor(CD)) 33780b57cec5SDimitry Andric return NoMismatch; 33790b57cec5SDimitry Andric } 33800b57cec5SDimitry Andric if (HasUndefinedConstructors) 33810b57cec5SDimitry Andric return EndOfTU ? NoMismatch : AnalyzeLater; 33820b57cec5SDimitry Andric if (!NewExprs.empty()) 33830b57cec5SDimitry Andric return MemberInitMismatches; 33840b57cec5SDimitry Andric return Field->hasInClassInitializer() ? analyzeInClassInitializer() 33850b57cec5SDimitry Andric : NoMismatch; 33860b57cec5SDimitry Andric } 33870b57cec5SDimitry Andric 33880b57cec5SDimitry Andric MismatchingNewDeleteDetector::MismatchResult 33890b57cec5SDimitry Andric MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { 33900b57cec5SDimitry Andric assert(ME != nullptr && "Expected a member expression"); 33910b57cec5SDimitry Andric if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) 33920b57cec5SDimitry Andric return analyzeField(F, IsArrayForm); 33930b57cec5SDimitry Andric return NoMismatch; 33940b57cec5SDimitry Andric } 33950b57cec5SDimitry Andric 33960b57cec5SDimitry Andric bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { 33970b57cec5SDimitry Andric const CXXNewExpr *NE = nullptr; 33980b57cec5SDimitry Andric if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { 33990b57cec5SDimitry Andric if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && 34000b57cec5SDimitry Andric NE->isArray() != IsArrayForm) { 34010b57cec5SDimitry Andric NewExprs.push_back(NE); 34020b57cec5SDimitry Andric } 34030b57cec5SDimitry Andric } 34040b57cec5SDimitry Andric return NewExprs.empty(); 34050b57cec5SDimitry Andric } 34060b57cec5SDimitry Andric 34070b57cec5SDimitry Andric static void 34080b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, 34090b57cec5SDimitry Andric const MismatchingNewDeleteDetector &Detector) { 34100b57cec5SDimitry Andric SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); 34110b57cec5SDimitry Andric FixItHint H; 34120b57cec5SDimitry Andric if (!Detector.IsArrayForm) 34130b57cec5SDimitry Andric H = FixItHint::CreateInsertion(EndOfDelete, "[]"); 34140b57cec5SDimitry Andric else { 34150b57cec5SDimitry Andric SourceLocation RSquare = Lexer::findLocationAfterToken( 34160b57cec5SDimitry Andric DeleteLoc, tok::l_square, SemaRef.getSourceManager(), 34170b57cec5SDimitry Andric SemaRef.getLangOpts(), true); 34180b57cec5SDimitry Andric if (RSquare.isValid()) 34190b57cec5SDimitry Andric H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); 34200b57cec5SDimitry Andric } 34210b57cec5SDimitry Andric SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) 34220b57cec5SDimitry Andric << Detector.IsArrayForm << H; 34230b57cec5SDimitry Andric 34240b57cec5SDimitry Andric for (const auto *NE : Detector.NewExprs) 34250b57cec5SDimitry Andric SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) 34260b57cec5SDimitry Andric << Detector.IsArrayForm; 34270b57cec5SDimitry Andric } 34280b57cec5SDimitry Andric 34290b57cec5SDimitry Andric void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { 34300b57cec5SDimitry Andric if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) 34310b57cec5SDimitry Andric return; 34320b57cec5SDimitry Andric MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); 34330b57cec5SDimitry Andric switch (Detector.analyzeDeleteExpr(DE)) { 34340b57cec5SDimitry Andric case MismatchingNewDeleteDetector::VarInitMismatches: 34350b57cec5SDimitry Andric case MismatchingNewDeleteDetector::MemberInitMismatches: { 34360b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); 34370b57cec5SDimitry Andric break; 34380b57cec5SDimitry Andric } 34390b57cec5SDimitry Andric case MismatchingNewDeleteDetector::AnalyzeLater: { 34400b57cec5SDimitry Andric DeleteExprs[Detector.Field].push_back( 34410b57cec5SDimitry Andric std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); 34420b57cec5SDimitry Andric break; 34430b57cec5SDimitry Andric } 34440b57cec5SDimitry Andric case MismatchingNewDeleteDetector::NoMismatch: 34450b57cec5SDimitry Andric break; 34460b57cec5SDimitry Andric } 34470b57cec5SDimitry Andric } 34480b57cec5SDimitry Andric 34490b57cec5SDimitry Andric void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, 34500b57cec5SDimitry Andric bool DeleteWasArrayForm) { 34510b57cec5SDimitry Andric MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); 34520b57cec5SDimitry Andric switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { 34530b57cec5SDimitry Andric case MismatchingNewDeleteDetector::VarInitMismatches: 34540b57cec5SDimitry Andric llvm_unreachable("This analysis should have been done for class members."); 34550b57cec5SDimitry Andric case MismatchingNewDeleteDetector::AnalyzeLater: 34560b57cec5SDimitry Andric llvm_unreachable("Analysis cannot be postponed any point beyond end of " 34570b57cec5SDimitry Andric "translation unit."); 34580b57cec5SDimitry Andric case MismatchingNewDeleteDetector::MemberInitMismatches: 34590b57cec5SDimitry Andric DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); 34600b57cec5SDimitry Andric break; 34610b57cec5SDimitry Andric case MismatchingNewDeleteDetector::NoMismatch: 34620b57cec5SDimitry Andric break; 34630b57cec5SDimitry Andric } 34640b57cec5SDimitry Andric } 34650b57cec5SDimitry Andric 34660b57cec5SDimitry Andric /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in: 34670b57cec5SDimitry Andric /// @code ::delete ptr; @endcode 34680b57cec5SDimitry Andric /// or 34690b57cec5SDimitry Andric /// @code delete [] ptr; @endcode 34700b57cec5SDimitry Andric ExprResult 34710b57cec5SDimitry Andric Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, 34720b57cec5SDimitry Andric bool ArrayForm, Expr *ExE) { 34730b57cec5SDimitry Andric // C++ [expr.delete]p1: 34740b57cec5SDimitry Andric // The operand shall have a pointer type, or a class type having a single 34750b57cec5SDimitry Andric // non-explicit conversion function to a pointer type. The result has type 34760b57cec5SDimitry Andric // void. 34770b57cec5SDimitry Andric // 34780b57cec5SDimitry Andric // DR599 amends "pointer type" to "pointer to object type" in both cases. 34790b57cec5SDimitry Andric 34800b57cec5SDimitry Andric ExprResult Ex = ExE; 34810b57cec5SDimitry Andric FunctionDecl *OperatorDelete = nullptr; 34820b57cec5SDimitry Andric bool ArrayFormAsWritten = ArrayForm; 34830b57cec5SDimitry Andric bool UsualArrayDeleteWantsSize = false; 34840b57cec5SDimitry Andric 34850b57cec5SDimitry Andric if (!Ex.get()->isTypeDependent()) { 34860b57cec5SDimitry Andric // Perform lvalue-to-rvalue cast, if needed. 34870b57cec5SDimitry Andric Ex = DefaultLvalueConversion(Ex.get()); 34880b57cec5SDimitry Andric if (Ex.isInvalid()) 34890b57cec5SDimitry Andric return ExprError(); 34900b57cec5SDimitry Andric 34910b57cec5SDimitry Andric QualType Type = Ex.get()->getType(); 34920b57cec5SDimitry Andric 34930b57cec5SDimitry Andric class DeleteConverter : public ContextualImplicitConverter { 34940b57cec5SDimitry Andric public: 34950b57cec5SDimitry Andric DeleteConverter() : ContextualImplicitConverter(false, true) {} 34960b57cec5SDimitry Andric 34970b57cec5SDimitry Andric bool match(QualType ConvType) override { 34980b57cec5SDimitry Andric // FIXME: If we have an operator T* and an operator void*, we must pick 34990b57cec5SDimitry Andric // the operator T*. 35000b57cec5SDimitry Andric if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 35010b57cec5SDimitry Andric if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) 35020b57cec5SDimitry Andric return true; 35030b57cec5SDimitry Andric return false; 35040b57cec5SDimitry Andric } 35050b57cec5SDimitry Andric 35060b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, 35070b57cec5SDimitry Andric QualType T) override { 35080b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_operand) << T; 35090b57cec5SDimitry Andric } 35100b57cec5SDimitry Andric 35110b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 35120b57cec5SDimitry Andric QualType T) override { 35130b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; 35140b57cec5SDimitry Andric } 35150b57cec5SDimitry Andric 35160b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 35170b57cec5SDimitry Andric QualType T, 35180b57cec5SDimitry Andric QualType ConvTy) override { 35190b57cec5SDimitry Andric return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; 35200b57cec5SDimitry Andric } 35210b57cec5SDimitry Andric 35220b57cec5SDimitry Andric SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 35230b57cec5SDimitry Andric QualType ConvTy) override { 35240b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 35250b57cec5SDimitry Andric << ConvTy; 35260b57cec5SDimitry Andric } 35270b57cec5SDimitry Andric 35280b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 35290b57cec5SDimitry Andric QualType T) override { 35300b57cec5SDimitry Andric return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; 35310b57cec5SDimitry Andric } 35320b57cec5SDimitry Andric 35330b57cec5SDimitry Andric SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 35340b57cec5SDimitry Andric QualType ConvTy) override { 35350b57cec5SDimitry Andric return S.Diag(Conv->getLocation(), diag::note_delete_conversion) 35360b57cec5SDimitry Andric << ConvTy; 35370b57cec5SDimitry Andric } 35380b57cec5SDimitry Andric 35390b57cec5SDimitry Andric SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 35400b57cec5SDimitry Andric QualType T, 35410b57cec5SDimitry Andric QualType ConvTy) override { 35420b57cec5SDimitry Andric llvm_unreachable("conversion functions are permitted"); 35430b57cec5SDimitry Andric } 35440b57cec5SDimitry Andric } Converter; 35450b57cec5SDimitry Andric 35460b57cec5SDimitry Andric Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); 35470b57cec5SDimitry Andric if (Ex.isInvalid()) 35480b57cec5SDimitry Andric return ExprError(); 35490b57cec5SDimitry Andric Type = Ex.get()->getType(); 35500b57cec5SDimitry Andric if (!Converter.match(Type)) 35510b57cec5SDimitry Andric // FIXME: PerformContextualImplicitConversion should return ExprError 35520b57cec5SDimitry Andric // itself in this case. 35530b57cec5SDimitry Andric return ExprError(); 35540b57cec5SDimitry Andric 3555a7dea167SDimitry Andric QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); 35560b57cec5SDimitry Andric QualType PointeeElem = Context.getBaseElementType(Pointee); 35570b57cec5SDimitry Andric 35580b57cec5SDimitry Andric if (Pointee.getAddressSpace() != LangAS::Default && 35590b57cec5SDimitry Andric !getLangOpts().OpenCLCPlusPlus) 35600b57cec5SDimitry Andric return Diag(Ex.get()->getBeginLoc(), 35610b57cec5SDimitry Andric diag::err_address_space_qualified_delete) 35620b57cec5SDimitry Andric << Pointee.getUnqualifiedType() 35630b57cec5SDimitry Andric << Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); 35640b57cec5SDimitry Andric 35650b57cec5SDimitry Andric CXXRecordDecl *PointeeRD = nullptr; 35660b57cec5SDimitry Andric if (Pointee->isVoidType() && !isSFINAEContext()) { 35670b57cec5SDimitry Andric // The C++ standard bans deleting a pointer to a non-object type, which 35680b57cec5SDimitry Andric // effectively bans deletion of "void*". However, most compilers support 35690b57cec5SDimitry Andric // this, so we treat it as a warning unless we're in a SFINAE context. 35700b57cec5SDimitry Andric Diag(StartLoc, diag::ext_delete_void_ptr_operand) 35710b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange(); 35725ffd83dbSDimitry Andric } else if (Pointee->isFunctionType() || Pointee->isVoidType() || 35735ffd83dbSDimitry Andric Pointee->isSizelessType()) { 35740b57cec5SDimitry Andric return ExprError(Diag(StartLoc, diag::err_delete_operand) 35750b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange()); 35760b57cec5SDimitry Andric } else if (!Pointee->isDependentType()) { 35770b57cec5SDimitry Andric // FIXME: This can result in errors if the definition was imported from a 35780b57cec5SDimitry Andric // module but is hidden. 35790b57cec5SDimitry Andric if (!RequireCompleteType(StartLoc, Pointee, 35800b57cec5SDimitry Andric diag::warn_delete_incomplete, Ex.get())) { 35810b57cec5SDimitry Andric if (const RecordType *RT = PointeeElem->getAs<RecordType>()) 35820b57cec5SDimitry Andric PointeeRD = cast<CXXRecordDecl>(RT->getDecl()); 35830b57cec5SDimitry Andric } 35840b57cec5SDimitry Andric } 35850b57cec5SDimitry Andric 35860b57cec5SDimitry Andric if (Pointee->isArrayType() && !ArrayForm) { 35870b57cec5SDimitry Andric Diag(StartLoc, diag::warn_delete_array_type) 35880b57cec5SDimitry Andric << Type << Ex.get()->getSourceRange() 35890b57cec5SDimitry Andric << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); 35900b57cec5SDimitry Andric ArrayForm = true; 35910b57cec5SDimitry Andric } 35920b57cec5SDimitry Andric 35930b57cec5SDimitry Andric DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( 35940b57cec5SDimitry Andric ArrayForm ? OO_Array_Delete : OO_Delete); 35950b57cec5SDimitry Andric 35960b57cec5SDimitry Andric if (PointeeRD) { 35970b57cec5SDimitry Andric if (!UseGlobal && 35980b57cec5SDimitry Andric FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, 35990b57cec5SDimitry Andric OperatorDelete)) 36000b57cec5SDimitry Andric return ExprError(); 36010b57cec5SDimitry Andric 36020b57cec5SDimitry Andric // If we're allocating an array of records, check whether the 36030b57cec5SDimitry Andric // usual operator delete[] has a size_t parameter. 36040b57cec5SDimitry Andric if (ArrayForm) { 36050b57cec5SDimitry Andric // If the user specifically asked to use the global allocator, 36060b57cec5SDimitry Andric // we'll need to do the lookup into the class. 36070b57cec5SDimitry Andric if (UseGlobal) 36080b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 36090b57cec5SDimitry Andric doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); 36100b57cec5SDimitry Andric 36110b57cec5SDimitry Andric // Otherwise, the usual operator delete[] should be the 36120b57cec5SDimitry Andric // function we just found. 36130b57cec5SDimitry Andric else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete)) 36140b57cec5SDimitry Andric UsualArrayDeleteWantsSize = 36150b57cec5SDimitry Andric UsualDeallocFnInfo(*this, 36160b57cec5SDimitry Andric DeclAccessPair::make(OperatorDelete, AS_public)) 36170b57cec5SDimitry Andric .HasSizeT; 36180b57cec5SDimitry Andric } 36190b57cec5SDimitry Andric 36200b57cec5SDimitry Andric if (!PointeeRD->hasIrrelevantDestructor()) 36210b57cec5SDimitry Andric if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 36220b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, 36230b57cec5SDimitry Andric const_cast<CXXDestructorDecl*>(Dtor)); 36240b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Dtor, StartLoc)) 36250b57cec5SDimitry Andric return ExprError(); 36260b57cec5SDimitry Andric } 36270b57cec5SDimitry Andric 36280b57cec5SDimitry Andric CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, 36290b57cec5SDimitry Andric /*IsDelete=*/true, /*CallCanBeVirtual=*/true, 36300b57cec5SDimitry Andric /*WarnOnNonAbstractTypes=*/!ArrayForm, 36310b57cec5SDimitry Andric SourceLocation()); 36320b57cec5SDimitry Andric } 36330b57cec5SDimitry Andric 36340b57cec5SDimitry Andric if (!OperatorDelete) { 36350b57cec5SDimitry Andric if (getLangOpts().OpenCLCPlusPlus) { 36360b57cec5SDimitry Andric Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; 36370b57cec5SDimitry Andric return ExprError(); 36380b57cec5SDimitry Andric } 36390b57cec5SDimitry Andric 36400b57cec5SDimitry Andric bool IsComplete = isCompleteType(StartLoc, Pointee); 36410b57cec5SDimitry Andric bool CanProvideSize = 36420b57cec5SDimitry Andric IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || 36430b57cec5SDimitry Andric Pointee.isDestructedType()); 36440b57cec5SDimitry Andric bool Overaligned = hasNewExtendedAlignment(*this, Pointee); 36450b57cec5SDimitry Andric 36460b57cec5SDimitry Andric // Look for a global declaration. 36470b57cec5SDimitry Andric OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, 36480b57cec5SDimitry Andric Overaligned, DeleteName); 36490b57cec5SDimitry Andric } 36500b57cec5SDimitry Andric 36510b57cec5SDimitry Andric MarkFunctionReferenced(StartLoc, OperatorDelete); 36520b57cec5SDimitry Andric 36530b57cec5SDimitry Andric // Check access and ambiguity of destructor if we're going to call it. 36540b57cec5SDimitry Andric // Note that this is required even for a virtual delete. 36550b57cec5SDimitry Andric bool IsVirtualDelete = false; 36560b57cec5SDimitry Andric if (PointeeRD) { 36570b57cec5SDimitry Andric if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { 36580b57cec5SDimitry Andric CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, 36590b57cec5SDimitry Andric PDiag(diag::err_access_dtor) << PointeeElem); 36600b57cec5SDimitry Andric IsVirtualDelete = Dtor->isVirtual(); 36610b57cec5SDimitry Andric } 36620b57cec5SDimitry Andric } 36630b57cec5SDimitry Andric 36640b57cec5SDimitry Andric DiagnoseUseOfDecl(OperatorDelete, StartLoc); 36650b57cec5SDimitry Andric 36660b57cec5SDimitry Andric // Convert the operand to the type of the first parameter of operator 36670b57cec5SDimitry Andric // delete. This is only necessary if we selected a destroying operator 36680b57cec5SDimitry Andric // delete that we are going to call (non-virtually); converting to void* 36690b57cec5SDimitry Andric // is trivial and left to AST consumers to handle. 36700b57cec5SDimitry Andric QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); 36710b57cec5SDimitry Andric if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { 36720b57cec5SDimitry Andric Qualifiers Qs = Pointee.getQualifiers(); 36730b57cec5SDimitry Andric if (Qs.hasCVRQualifiers()) { 36740b57cec5SDimitry Andric // Qualifiers are irrelevant to this conversion; we're only looking 36750b57cec5SDimitry Andric // for access and ambiguity. 36760b57cec5SDimitry Andric Qs.removeCVRQualifiers(); 36770b57cec5SDimitry Andric QualType Unqual = Context.getPointerType( 36780b57cec5SDimitry Andric Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); 36790b57cec5SDimitry Andric Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); 36800b57cec5SDimitry Andric } 36810b57cec5SDimitry Andric Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing); 36820b57cec5SDimitry Andric if (Ex.isInvalid()) 36830b57cec5SDimitry Andric return ExprError(); 36840b57cec5SDimitry Andric } 36850b57cec5SDimitry Andric } 36860b57cec5SDimitry Andric 36870b57cec5SDimitry Andric CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( 36880b57cec5SDimitry Andric Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, 36890b57cec5SDimitry Andric UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); 36900b57cec5SDimitry Andric AnalyzeDeleteExprMismatch(Result); 36910b57cec5SDimitry Andric return Result; 36920b57cec5SDimitry Andric } 36930b57cec5SDimitry Andric 36940b57cec5SDimitry Andric static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, 36950b57cec5SDimitry Andric bool IsDelete, 36960b57cec5SDimitry Andric FunctionDecl *&Operator) { 36970b57cec5SDimitry Andric 36980b57cec5SDimitry Andric DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( 36990b57cec5SDimitry Andric IsDelete ? OO_Delete : OO_New); 37000b57cec5SDimitry Andric 37010b57cec5SDimitry Andric LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); 37020b57cec5SDimitry Andric S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); 37030b57cec5SDimitry Andric assert(!R.empty() && "implicitly declared allocation functions not found"); 37040b57cec5SDimitry Andric assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); 37050b57cec5SDimitry Andric 37060b57cec5SDimitry Andric // We do our own custom access checks below. 37070b57cec5SDimitry Andric R.suppressDiagnostics(); 37080b57cec5SDimitry Andric 37090b57cec5SDimitry Andric SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end()); 37100b57cec5SDimitry Andric OverloadCandidateSet Candidates(R.getNameLoc(), 37110b57cec5SDimitry Andric OverloadCandidateSet::CSK_Normal); 37120b57cec5SDimitry Andric for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); 37130b57cec5SDimitry Andric FnOvl != FnOvlEnd; ++FnOvl) { 37140b57cec5SDimitry Andric // Even member operator new/delete are implicitly treated as 37150b57cec5SDimitry Andric // static, so don't use AddMemberCandidate. 37160b57cec5SDimitry Andric NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); 37170b57cec5SDimitry Andric 37180b57cec5SDimitry Andric if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { 37190b57cec5SDimitry Andric S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), 37200b57cec5SDimitry Andric /*ExplicitTemplateArgs=*/nullptr, Args, 37210b57cec5SDimitry Andric Candidates, 37220b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 37230b57cec5SDimitry Andric continue; 37240b57cec5SDimitry Andric } 37250b57cec5SDimitry Andric 37260b57cec5SDimitry Andric FunctionDecl *Fn = cast<FunctionDecl>(D); 37270b57cec5SDimitry Andric S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, 37280b57cec5SDimitry Andric /*SuppressUserConversions=*/false); 37290b57cec5SDimitry Andric } 37300b57cec5SDimitry Andric 37310b57cec5SDimitry Andric SourceRange Range = TheCall->getSourceRange(); 37320b57cec5SDimitry Andric 37330b57cec5SDimitry Andric // Do the resolution. 37340b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 37350b57cec5SDimitry Andric switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { 37360b57cec5SDimitry Andric case OR_Success: { 37370b57cec5SDimitry Andric // Got one! 37380b57cec5SDimitry Andric FunctionDecl *FnDecl = Best->Function; 37390b57cec5SDimitry Andric assert(R.getNamingClass() == nullptr && 37400b57cec5SDimitry Andric "class members should not be considered"); 37410b57cec5SDimitry Andric 37420b57cec5SDimitry Andric if (!FnDecl->isReplaceableGlobalAllocationFunction()) { 37430b57cec5SDimitry Andric S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) 37440b57cec5SDimitry Andric << (IsDelete ? 1 : 0) << Range; 37450b57cec5SDimitry Andric S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) 37460b57cec5SDimitry Andric << R.getLookupName() << FnDecl->getSourceRange(); 37470b57cec5SDimitry Andric return true; 37480b57cec5SDimitry Andric } 37490b57cec5SDimitry Andric 37500b57cec5SDimitry Andric Operator = FnDecl; 37510b57cec5SDimitry Andric return false; 37520b57cec5SDimitry Andric } 37530b57cec5SDimitry Andric 37540b57cec5SDimitry Andric case OR_No_Viable_Function: 37550b57cec5SDimitry Andric Candidates.NoteCandidates( 37560b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 37570b57cec5SDimitry Andric S.PDiag(diag::err_ovl_no_viable_function_in_call) 37580b57cec5SDimitry Andric << R.getLookupName() << Range), 37590b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 37600b57cec5SDimitry Andric return true; 37610b57cec5SDimitry Andric 37620b57cec5SDimitry Andric case OR_Ambiguous: 37630b57cec5SDimitry Andric Candidates.NoteCandidates( 37640b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), 37650b57cec5SDimitry Andric S.PDiag(diag::err_ovl_ambiguous_call) 37660b57cec5SDimitry Andric << R.getLookupName() << Range), 3767480093f4SDimitry Andric S, OCD_AmbiguousCandidates, Args); 37680b57cec5SDimitry Andric return true; 37690b57cec5SDimitry Andric 37700b57cec5SDimitry Andric case OR_Deleted: { 37710b57cec5SDimitry Andric Candidates.NoteCandidates( 37720b57cec5SDimitry Andric PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call) 37730b57cec5SDimitry Andric << R.getLookupName() << Range), 37740b57cec5SDimitry Andric S, OCD_AllCandidates, Args); 37750b57cec5SDimitry Andric return true; 37760b57cec5SDimitry Andric } 37770b57cec5SDimitry Andric } 37780b57cec5SDimitry Andric llvm_unreachable("Unreachable, bad result from BestViableFunction"); 37790b57cec5SDimitry Andric } 37800b57cec5SDimitry Andric 37810b57cec5SDimitry Andric ExprResult 37820b57cec5SDimitry Andric Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, 37830b57cec5SDimitry Andric bool IsDelete) { 37840b57cec5SDimitry Andric CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 37850b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) { 37860b57cec5SDimitry Andric Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) 37870b57cec5SDimitry Andric << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") 37880b57cec5SDimitry Andric << "C++"; 37890b57cec5SDimitry Andric return ExprError(); 37900b57cec5SDimitry Andric } 37910b57cec5SDimitry Andric // CodeGen assumes it can find the global new and delete to call, 37920b57cec5SDimitry Andric // so ensure that they are declared. 37930b57cec5SDimitry Andric DeclareGlobalNewDelete(); 37940b57cec5SDimitry Andric 37950b57cec5SDimitry Andric FunctionDecl *OperatorNewOrDelete = nullptr; 37960b57cec5SDimitry Andric if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, 37970b57cec5SDimitry Andric OperatorNewOrDelete)) 37980b57cec5SDimitry Andric return ExprError(); 37990b57cec5SDimitry Andric assert(OperatorNewOrDelete && "should be found"); 38000b57cec5SDimitry Andric 38010b57cec5SDimitry Andric DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); 38020b57cec5SDimitry Andric MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); 38030b57cec5SDimitry Andric 38040b57cec5SDimitry Andric TheCall->setType(OperatorNewOrDelete->getReturnType()); 38050b57cec5SDimitry Andric for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { 38060b57cec5SDimitry Andric QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); 38070b57cec5SDimitry Andric InitializedEntity Entity = 38080b57cec5SDimitry Andric InitializedEntity::InitializeParameter(Context, ParamTy, false); 38090b57cec5SDimitry Andric ExprResult Arg = PerformCopyInitialization( 38100b57cec5SDimitry Andric Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); 38110b57cec5SDimitry Andric if (Arg.isInvalid()) 38120b57cec5SDimitry Andric return ExprError(); 38130b57cec5SDimitry Andric TheCall->setArg(i, Arg.get()); 38140b57cec5SDimitry Andric } 38150b57cec5SDimitry Andric auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); 38160b57cec5SDimitry Andric assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && 38170b57cec5SDimitry Andric "Callee expected to be implicit cast to a builtin function pointer"); 38180b57cec5SDimitry Andric Callee->setType(OperatorNewOrDelete->getType()); 38190b57cec5SDimitry Andric 38200b57cec5SDimitry Andric return TheCallResult; 38210b57cec5SDimitry Andric } 38220b57cec5SDimitry Andric 38230b57cec5SDimitry Andric void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, 38240b57cec5SDimitry Andric bool IsDelete, bool CallCanBeVirtual, 38250b57cec5SDimitry Andric bool WarnOnNonAbstractTypes, 38260b57cec5SDimitry Andric SourceLocation DtorLoc) { 38270b57cec5SDimitry Andric if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) 38280b57cec5SDimitry Andric return; 38290b57cec5SDimitry Andric 38300b57cec5SDimitry Andric // C++ [expr.delete]p3: 38310b57cec5SDimitry Andric // In the first alternative (delete object), if the static type of the 38320b57cec5SDimitry Andric // object to be deleted is different from its dynamic type, the static 38330b57cec5SDimitry Andric // type shall be a base class of the dynamic type of the object to be 38340b57cec5SDimitry Andric // deleted and the static type shall have a virtual destructor or the 38350b57cec5SDimitry Andric // behavior is undefined. 38360b57cec5SDimitry Andric // 38370b57cec5SDimitry Andric const CXXRecordDecl *PointeeRD = dtor->getParent(); 38380b57cec5SDimitry Andric // Note: a final class cannot be derived from, no issue there 38390b57cec5SDimitry Andric if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) 38400b57cec5SDimitry Andric return; 38410b57cec5SDimitry Andric 38420b57cec5SDimitry Andric // If the superclass is in a system header, there's nothing that can be done. 38430b57cec5SDimitry Andric // The `delete` (where we emit the warning) can be in a system header, 38440b57cec5SDimitry Andric // what matters for this warning is where the deleted type is defined. 38450b57cec5SDimitry Andric if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) 38460b57cec5SDimitry Andric return; 38470b57cec5SDimitry Andric 38480b57cec5SDimitry Andric QualType ClassType = dtor->getThisType()->getPointeeType(); 38490b57cec5SDimitry Andric if (PointeeRD->isAbstract()) { 38500b57cec5SDimitry Andric // If the class is abstract, we warn by default, because we're 38510b57cec5SDimitry Andric // sure the code has undefined behavior. 38520b57cec5SDimitry Andric Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) 38530b57cec5SDimitry Andric << ClassType; 38540b57cec5SDimitry Andric } else if (WarnOnNonAbstractTypes) { 38550b57cec5SDimitry Andric // Otherwise, if this is not an array delete, it's a bit suspect, 38560b57cec5SDimitry Andric // but not necessarily wrong. 38570b57cec5SDimitry Andric Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) 38580b57cec5SDimitry Andric << ClassType; 38590b57cec5SDimitry Andric } 38600b57cec5SDimitry Andric if (!IsDelete) { 38610b57cec5SDimitry Andric std::string TypeStr; 38620b57cec5SDimitry Andric ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); 38630b57cec5SDimitry Andric Diag(DtorLoc, diag::note_delete_non_virtual) 38640b57cec5SDimitry Andric << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); 38650b57cec5SDimitry Andric } 38660b57cec5SDimitry Andric } 38670b57cec5SDimitry Andric 38680b57cec5SDimitry Andric Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, 38690b57cec5SDimitry Andric SourceLocation StmtLoc, 38700b57cec5SDimitry Andric ConditionKind CK) { 38710b57cec5SDimitry Andric ExprResult E = 38720b57cec5SDimitry Andric CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); 38730b57cec5SDimitry Andric if (E.isInvalid()) 38740b57cec5SDimitry Andric return ConditionError(); 38750b57cec5SDimitry Andric return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc), 38760b57cec5SDimitry Andric CK == ConditionKind::ConstexprIf); 38770b57cec5SDimitry Andric } 38780b57cec5SDimitry Andric 38790b57cec5SDimitry Andric /// Check the use of the given variable as a C++ condition in an if, 38800b57cec5SDimitry Andric /// while, do-while, or switch statement. 38810b57cec5SDimitry Andric ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, 38820b57cec5SDimitry Andric SourceLocation StmtLoc, 38830b57cec5SDimitry Andric ConditionKind CK) { 38840b57cec5SDimitry Andric if (ConditionVar->isInvalidDecl()) 38850b57cec5SDimitry Andric return ExprError(); 38860b57cec5SDimitry Andric 38870b57cec5SDimitry Andric QualType T = ConditionVar->getType(); 38880b57cec5SDimitry Andric 38890b57cec5SDimitry Andric // C++ [stmt.select]p2: 38900b57cec5SDimitry Andric // The declarator shall not specify a function or an array. 38910b57cec5SDimitry Andric if (T->isFunctionType()) 38920b57cec5SDimitry Andric return ExprError(Diag(ConditionVar->getLocation(), 38930b57cec5SDimitry Andric diag::err_invalid_use_of_function_type) 38940b57cec5SDimitry Andric << ConditionVar->getSourceRange()); 38950b57cec5SDimitry Andric else if (T->isArrayType()) 38960b57cec5SDimitry Andric return ExprError(Diag(ConditionVar->getLocation(), 38970b57cec5SDimitry Andric diag::err_invalid_use_of_array_type) 38980b57cec5SDimitry Andric << ConditionVar->getSourceRange()); 38990b57cec5SDimitry Andric 39000b57cec5SDimitry Andric ExprResult Condition = BuildDeclRefExpr( 39010b57cec5SDimitry Andric ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, 39020b57cec5SDimitry Andric ConditionVar->getLocation()); 39030b57cec5SDimitry Andric 39040b57cec5SDimitry Andric switch (CK) { 39050b57cec5SDimitry Andric case ConditionKind::Boolean: 39060b57cec5SDimitry Andric return CheckBooleanCondition(StmtLoc, Condition.get()); 39070b57cec5SDimitry Andric 39080b57cec5SDimitry Andric case ConditionKind::ConstexprIf: 39090b57cec5SDimitry Andric return CheckBooleanCondition(StmtLoc, Condition.get(), true); 39100b57cec5SDimitry Andric 39110b57cec5SDimitry Andric case ConditionKind::Switch: 39120b57cec5SDimitry Andric return CheckSwitchCondition(StmtLoc, Condition.get()); 39130b57cec5SDimitry Andric } 39140b57cec5SDimitry Andric 39150b57cec5SDimitry Andric llvm_unreachable("unexpected condition kind"); 39160b57cec5SDimitry Andric } 39170b57cec5SDimitry Andric 39180b57cec5SDimitry Andric /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid. 39190b57cec5SDimitry Andric ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { 3920fe6060f1SDimitry Andric // C++11 6.4p4: 39210b57cec5SDimitry Andric // The value of a condition that is an initialized declaration in a statement 39220b57cec5SDimitry Andric // other than a switch statement is the value of the declared variable 39230b57cec5SDimitry Andric // implicitly converted to type bool. If that conversion is ill-formed, the 39240b57cec5SDimitry Andric // program is ill-formed. 39250b57cec5SDimitry Andric // The value of a condition that is an expression is the value of the 39260b57cec5SDimitry Andric // expression, implicitly converted to bool. 39270b57cec5SDimitry Andric // 3928fe6060f1SDimitry Andric // C++2b 8.5.2p2 3929fe6060f1SDimitry Andric // If the if statement is of the form if constexpr, the value of the condition 3930fe6060f1SDimitry Andric // is contextually converted to bool and the converted expression shall be 3931fe6060f1SDimitry Andric // a constant expression. 3932fe6060f1SDimitry Andric // 3933fe6060f1SDimitry Andric 3934fe6060f1SDimitry Andric ExprResult E = PerformContextuallyConvertToBool(CondExpr); 3935fe6060f1SDimitry Andric if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent()) 3936fe6060f1SDimitry Andric return E; 3937fe6060f1SDimitry Andric 39380b57cec5SDimitry Andric // FIXME: Return this value to the caller so they don't need to recompute it. 3939fe6060f1SDimitry Andric llvm::APSInt Cond; 3940fe6060f1SDimitry Andric E = VerifyIntegerConstantExpression( 3941fe6060f1SDimitry Andric E.get(), &Cond, 3942fe6060f1SDimitry Andric diag::err_constexpr_if_condition_expression_is_not_constant); 3943fe6060f1SDimitry Andric return E; 39440b57cec5SDimitry Andric } 39450b57cec5SDimitry Andric 39460b57cec5SDimitry Andric /// Helper function to determine whether this is the (deprecated) C++ 39470b57cec5SDimitry Andric /// conversion from a string literal to a pointer to non-const char or 39480b57cec5SDimitry Andric /// non-const wchar_t (for narrow and wide string literals, 39490b57cec5SDimitry Andric /// respectively). 39500b57cec5SDimitry Andric bool 39510b57cec5SDimitry Andric Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { 39520b57cec5SDimitry Andric // Look inside the implicit cast, if it exists. 39530b57cec5SDimitry Andric if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) 39540b57cec5SDimitry Andric From = Cast->getSubExpr(); 39550b57cec5SDimitry Andric 39560b57cec5SDimitry Andric // A string literal (2.13.4) that is not a wide string literal can 39570b57cec5SDimitry Andric // be converted to an rvalue of type "pointer to char"; a wide 39580b57cec5SDimitry Andric // string literal can be converted to an rvalue of type "pointer 39590b57cec5SDimitry Andric // to wchar_t" (C++ 4.2p2). 39600b57cec5SDimitry Andric if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) 39610b57cec5SDimitry Andric if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) 39620b57cec5SDimitry Andric if (const BuiltinType *ToPointeeType 39630b57cec5SDimitry Andric = ToPtrType->getPointeeType()->getAs<BuiltinType>()) { 39640b57cec5SDimitry Andric // This conversion is considered only when there is an 39650b57cec5SDimitry Andric // explicit appropriate pointer target type (C++ 4.2p2). 39660b57cec5SDimitry Andric if (!ToPtrType->getPointeeType().hasQualifiers()) { 39670b57cec5SDimitry Andric switch (StrLit->getKind()) { 39680b57cec5SDimitry Andric case StringLiteral::UTF8: 39690b57cec5SDimitry Andric case StringLiteral::UTF16: 39700b57cec5SDimitry Andric case StringLiteral::UTF32: 39710b57cec5SDimitry Andric // We don't allow UTF literals to be implicitly converted 39720b57cec5SDimitry Andric break; 39730b57cec5SDimitry Andric case StringLiteral::Ascii: 39740b57cec5SDimitry Andric return (ToPointeeType->getKind() == BuiltinType::Char_U || 39750b57cec5SDimitry Andric ToPointeeType->getKind() == BuiltinType::Char_S); 39760b57cec5SDimitry Andric case StringLiteral::Wide: 39770b57cec5SDimitry Andric return Context.typesAreCompatible(Context.getWideCharType(), 39780b57cec5SDimitry Andric QualType(ToPointeeType, 0)); 39790b57cec5SDimitry Andric } 39800b57cec5SDimitry Andric } 39810b57cec5SDimitry Andric } 39820b57cec5SDimitry Andric 39830b57cec5SDimitry Andric return false; 39840b57cec5SDimitry Andric } 39850b57cec5SDimitry Andric 39860b57cec5SDimitry Andric static ExprResult BuildCXXCastArgument(Sema &S, 39870b57cec5SDimitry Andric SourceLocation CastLoc, 39880b57cec5SDimitry Andric QualType Ty, 39890b57cec5SDimitry Andric CastKind Kind, 39900b57cec5SDimitry Andric CXXMethodDecl *Method, 39910b57cec5SDimitry Andric DeclAccessPair FoundDecl, 39920b57cec5SDimitry Andric bool HadMultipleCandidates, 39930b57cec5SDimitry Andric Expr *From) { 39940b57cec5SDimitry Andric switch (Kind) { 39950b57cec5SDimitry Andric default: llvm_unreachable("Unhandled cast kind!"); 39960b57cec5SDimitry Andric case CK_ConstructorConversion: { 39970b57cec5SDimitry Andric CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); 39980b57cec5SDimitry Andric SmallVector<Expr*, 8> ConstructorArgs; 39990b57cec5SDimitry Andric 40000b57cec5SDimitry Andric if (S.RequireNonAbstractType(CastLoc, Ty, 40010b57cec5SDimitry Andric diag::err_allocation_of_abstract_type)) 40020b57cec5SDimitry Andric return ExprError(); 40030b57cec5SDimitry Andric 4004fe6060f1SDimitry Andric if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc, 4005fe6060f1SDimitry Andric ConstructorArgs)) 40060b57cec5SDimitry Andric return ExprError(); 40070b57cec5SDimitry Andric 40080b57cec5SDimitry Andric S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, 40090b57cec5SDimitry Andric InitializedEntity::InitializeTemporary(Ty)); 40100b57cec5SDimitry Andric if (S.DiagnoseUseOfDecl(Method, CastLoc)) 40110b57cec5SDimitry Andric return ExprError(); 40120b57cec5SDimitry Andric 40130b57cec5SDimitry Andric ExprResult Result = S.BuildCXXConstructExpr( 40140b57cec5SDimitry Andric CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), 40150b57cec5SDimitry Andric ConstructorArgs, HadMultipleCandidates, 40160b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 40170b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 40180b57cec5SDimitry Andric if (Result.isInvalid()) 40190b57cec5SDimitry Andric return ExprError(); 40200b57cec5SDimitry Andric 40210b57cec5SDimitry Andric return S.MaybeBindToTemporary(Result.getAs<Expr>()); 40220b57cec5SDimitry Andric } 40230b57cec5SDimitry Andric 40240b57cec5SDimitry Andric case CK_UserDefinedConversion: { 40250b57cec5SDimitry Andric assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); 40260b57cec5SDimitry Andric 40270b57cec5SDimitry Andric S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); 40280b57cec5SDimitry Andric if (S.DiagnoseUseOfDecl(Method, CastLoc)) 40290b57cec5SDimitry Andric return ExprError(); 40300b57cec5SDimitry Andric 40310b57cec5SDimitry Andric // Create an implicit call expr that calls it. 40320b57cec5SDimitry Andric CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); 40330b57cec5SDimitry Andric ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, 40340b57cec5SDimitry Andric HadMultipleCandidates); 40350b57cec5SDimitry Andric if (Result.isInvalid()) 40360b57cec5SDimitry Andric return ExprError(); 40370b57cec5SDimitry Andric // Record usage of conversion in an implicit cast. 40380b57cec5SDimitry Andric Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), 40390b57cec5SDimitry Andric CK_UserDefinedConversion, Result.get(), 4040e8d8bef9SDimitry Andric nullptr, Result.get()->getValueKind(), 4041e8d8bef9SDimitry Andric S.CurFPFeatureOverrides()); 40420b57cec5SDimitry Andric 40430b57cec5SDimitry Andric return S.MaybeBindToTemporary(Result.get()); 40440b57cec5SDimitry Andric } 40450b57cec5SDimitry Andric } 40460b57cec5SDimitry Andric } 40470b57cec5SDimitry Andric 40480b57cec5SDimitry Andric /// PerformImplicitConversion - Perform an implicit conversion of the 40490b57cec5SDimitry Andric /// expression From to the type ToType using the pre-computed implicit 40500b57cec5SDimitry Andric /// conversion sequence ICS. Returns the converted 40510b57cec5SDimitry Andric /// expression. Action is the kind of conversion we're performing, 40520b57cec5SDimitry Andric /// used in the error message. 40530b57cec5SDimitry Andric ExprResult 40540b57cec5SDimitry Andric Sema::PerformImplicitConversion(Expr *From, QualType ToType, 40550b57cec5SDimitry Andric const ImplicitConversionSequence &ICS, 40560b57cec5SDimitry Andric AssignmentAction Action, 40570b57cec5SDimitry Andric CheckedConversionKind CCK) { 40580b57cec5SDimitry Andric // C++ [over.match.oper]p7: [...] operands of class type are converted [...] 40590b57cec5SDimitry Andric if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType()) 40600b57cec5SDimitry Andric return From; 40610b57cec5SDimitry Andric 40620b57cec5SDimitry Andric switch (ICS.getKind()) { 40630b57cec5SDimitry Andric case ImplicitConversionSequence::StandardConversion: { 40640b57cec5SDimitry Andric ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, 40650b57cec5SDimitry Andric Action, CCK); 40660b57cec5SDimitry Andric if (Res.isInvalid()) 40670b57cec5SDimitry Andric return ExprError(); 40680b57cec5SDimitry Andric From = Res.get(); 40690b57cec5SDimitry Andric break; 40700b57cec5SDimitry Andric } 40710b57cec5SDimitry Andric 40720b57cec5SDimitry Andric case ImplicitConversionSequence::UserDefinedConversion: { 40730b57cec5SDimitry Andric 40740b57cec5SDimitry Andric FunctionDecl *FD = ICS.UserDefined.ConversionFunction; 40750b57cec5SDimitry Andric CastKind CastKind; 40760b57cec5SDimitry Andric QualType BeforeToType; 40770b57cec5SDimitry Andric assert(FD && "no conversion function for user-defined conversion seq"); 40780b57cec5SDimitry Andric if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { 40790b57cec5SDimitry Andric CastKind = CK_UserDefinedConversion; 40800b57cec5SDimitry Andric 40810b57cec5SDimitry Andric // If the user-defined conversion is specified by a conversion function, 40820b57cec5SDimitry Andric // the initial standard conversion sequence converts the source type to 40830b57cec5SDimitry Andric // the implicit object parameter of the conversion function. 40840b57cec5SDimitry Andric BeforeToType = Context.getTagDeclType(Conv->getParent()); 40850b57cec5SDimitry Andric } else { 40860b57cec5SDimitry Andric const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); 40870b57cec5SDimitry Andric CastKind = CK_ConstructorConversion; 40880b57cec5SDimitry Andric // Do no conversion if dealing with ... for the first conversion. 40890b57cec5SDimitry Andric if (!ICS.UserDefined.EllipsisConversion) { 40900b57cec5SDimitry Andric // If the user-defined conversion is specified by a constructor, the 40910b57cec5SDimitry Andric // initial standard conversion sequence converts the source type to 40920b57cec5SDimitry Andric // the type required by the argument of the constructor 40930b57cec5SDimitry Andric BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); 40940b57cec5SDimitry Andric } 40950b57cec5SDimitry Andric } 40960b57cec5SDimitry Andric // Watch out for ellipsis conversion. 40970b57cec5SDimitry Andric if (!ICS.UserDefined.EllipsisConversion) { 40980b57cec5SDimitry Andric ExprResult Res = 40990b57cec5SDimitry Andric PerformImplicitConversion(From, BeforeToType, 41000b57cec5SDimitry Andric ICS.UserDefined.Before, AA_Converting, 41010b57cec5SDimitry Andric CCK); 41020b57cec5SDimitry Andric if (Res.isInvalid()) 41030b57cec5SDimitry Andric return ExprError(); 41040b57cec5SDimitry Andric From = Res.get(); 41050b57cec5SDimitry Andric } 41060b57cec5SDimitry Andric 41070b57cec5SDimitry Andric ExprResult CastArg = BuildCXXCastArgument( 41080b57cec5SDimitry Andric *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, 41090b57cec5SDimitry Andric cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, 41100b57cec5SDimitry Andric ICS.UserDefined.HadMultipleCandidates, From); 41110b57cec5SDimitry Andric 41120b57cec5SDimitry Andric if (CastArg.isInvalid()) 41130b57cec5SDimitry Andric return ExprError(); 41140b57cec5SDimitry Andric 41150b57cec5SDimitry Andric From = CastArg.get(); 41160b57cec5SDimitry Andric 41170b57cec5SDimitry Andric // C++ [over.match.oper]p7: 41180b57cec5SDimitry Andric // [...] the second standard conversion sequence of a user-defined 41190b57cec5SDimitry Andric // conversion sequence is not applied. 41200b57cec5SDimitry Andric if (CCK == CCK_ForBuiltinOverloadedOp) 41210b57cec5SDimitry Andric return From; 41220b57cec5SDimitry Andric 41230b57cec5SDimitry Andric return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, 41240b57cec5SDimitry Andric AA_Converting, CCK); 41250b57cec5SDimitry Andric } 41260b57cec5SDimitry Andric 41270b57cec5SDimitry Andric case ImplicitConversionSequence::AmbiguousConversion: 41280b57cec5SDimitry Andric ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), 41290b57cec5SDimitry Andric PDiag(diag::err_typecheck_ambiguous_condition) 41300b57cec5SDimitry Andric << From->getSourceRange()); 41310b57cec5SDimitry Andric return ExprError(); 41320b57cec5SDimitry Andric 41330b57cec5SDimitry Andric case ImplicitConversionSequence::EllipsisConversion: 41340b57cec5SDimitry Andric llvm_unreachable("Cannot perform an ellipsis conversion"); 41350b57cec5SDimitry Andric 41360b57cec5SDimitry Andric case ImplicitConversionSequence::BadConversion: 41375ffd83dbSDimitry Andric Sema::AssignConvertType ConvTy = 41385ffd83dbSDimitry Andric CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType()); 41395ffd83dbSDimitry Andric bool Diagnosed = DiagnoseAssignmentResult( 41405ffd83dbSDimitry Andric ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(), 41415ffd83dbSDimitry Andric ToType, From->getType(), From, Action); 41420b57cec5SDimitry Andric assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed; 41430b57cec5SDimitry Andric return ExprError(); 41440b57cec5SDimitry Andric } 41450b57cec5SDimitry Andric 41460b57cec5SDimitry Andric // Everything went well. 41470b57cec5SDimitry Andric return From; 41480b57cec5SDimitry Andric } 41490b57cec5SDimitry Andric 41500b57cec5SDimitry Andric /// PerformImplicitConversion - Perform an implicit conversion of the 41510b57cec5SDimitry Andric /// expression From to the type ToType by following the standard 41520b57cec5SDimitry Andric /// conversion sequence SCS. Returns the converted 41530b57cec5SDimitry Andric /// expression. Flavor is the context in which we're performing this 41540b57cec5SDimitry Andric /// conversion, for use in error messages. 41550b57cec5SDimitry Andric ExprResult 41560b57cec5SDimitry Andric Sema::PerformImplicitConversion(Expr *From, QualType ToType, 41570b57cec5SDimitry Andric const StandardConversionSequence& SCS, 41580b57cec5SDimitry Andric AssignmentAction Action, 41590b57cec5SDimitry Andric CheckedConversionKind CCK) { 41600b57cec5SDimitry Andric bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast); 41610b57cec5SDimitry Andric 41620b57cec5SDimitry Andric // Overall FIXME: we are recomputing too many types here and doing far too 41630b57cec5SDimitry Andric // much extra work. What this means is that we need to keep track of more 41640b57cec5SDimitry Andric // information that is computed when we try the implicit conversion initially, 41650b57cec5SDimitry Andric // so that we don't need to recompute anything here. 41660b57cec5SDimitry Andric QualType FromType = From->getType(); 41670b57cec5SDimitry Andric 41680b57cec5SDimitry Andric if (SCS.CopyConstructor) { 41690b57cec5SDimitry Andric // FIXME: When can ToType be a reference type? 41700b57cec5SDimitry Andric assert(!ToType->isReferenceType()); 41710b57cec5SDimitry Andric if (SCS.Second == ICK_Derived_To_Base) { 41720b57cec5SDimitry Andric SmallVector<Expr*, 8> ConstructorArgs; 4173fe6060f1SDimitry Andric if (CompleteConstructorCall( 4174fe6060f1SDimitry Andric cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From, 4175fe6060f1SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs)) 41760b57cec5SDimitry Andric return ExprError(); 41770b57cec5SDimitry Andric return BuildCXXConstructExpr( 41780b57cec5SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 41790b57cec5SDimitry Andric SCS.FoundCopyConstructor, SCS.CopyConstructor, 41800b57cec5SDimitry Andric ConstructorArgs, /*HadMultipleCandidates*/ false, 41810b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 41820b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 41830b57cec5SDimitry Andric } 41840b57cec5SDimitry Andric return BuildCXXConstructExpr( 41850b57cec5SDimitry Andric /*FIXME:ConstructLoc*/ SourceLocation(), ToType, 41860b57cec5SDimitry Andric SCS.FoundCopyConstructor, SCS.CopyConstructor, 41870b57cec5SDimitry Andric From, /*HadMultipleCandidates*/ false, 41880b57cec5SDimitry Andric /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, 41890b57cec5SDimitry Andric CXXConstructExpr::CK_Complete, SourceRange()); 41900b57cec5SDimitry Andric } 41910b57cec5SDimitry Andric 41920b57cec5SDimitry Andric // Resolve overloaded function references. 41930b57cec5SDimitry Andric if (Context.hasSameType(FromType, Context.OverloadTy)) { 41940b57cec5SDimitry Andric DeclAccessPair Found; 41950b57cec5SDimitry Andric FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, 41960b57cec5SDimitry Andric true, Found); 41970b57cec5SDimitry Andric if (!Fn) 41980b57cec5SDimitry Andric return ExprError(); 41990b57cec5SDimitry Andric 42000b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) 42010b57cec5SDimitry Andric return ExprError(); 42020b57cec5SDimitry Andric 42030b57cec5SDimitry Andric From = FixOverloadedFunctionReference(From, Found, Fn); 42040b57cec5SDimitry Andric FromType = From->getType(); 42050b57cec5SDimitry Andric } 42060b57cec5SDimitry Andric 42070b57cec5SDimitry Andric // If we're converting to an atomic type, first convert to the corresponding 42080b57cec5SDimitry Andric // non-atomic type. 42090b57cec5SDimitry Andric QualType ToAtomicType; 42100b57cec5SDimitry Andric if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { 42110b57cec5SDimitry Andric ToAtomicType = ToType; 42120b57cec5SDimitry Andric ToType = ToAtomic->getValueType(); 42130b57cec5SDimitry Andric } 42140b57cec5SDimitry Andric 42150b57cec5SDimitry Andric QualType InitialFromType = FromType; 42160b57cec5SDimitry Andric // Perform the first implicit conversion. 42170b57cec5SDimitry Andric switch (SCS.First) { 42180b57cec5SDimitry Andric case ICK_Identity: 42190b57cec5SDimitry Andric if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { 42200b57cec5SDimitry Andric FromType = FromAtomic->getValueType().getUnqualifiedType(); 42210b57cec5SDimitry Andric From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, 4222fe6060f1SDimitry Andric From, /*BasePath=*/nullptr, VK_PRValue, 4223e8d8bef9SDimitry Andric FPOptionsOverride()); 42240b57cec5SDimitry Andric } 42250b57cec5SDimitry Andric break; 42260b57cec5SDimitry Andric 42270b57cec5SDimitry Andric case ICK_Lvalue_To_Rvalue: { 42280b57cec5SDimitry Andric assert(From->getObjectKind() != OK_ObjCProperty); 42290b57cec5SDimitry Andric ExprResult FromRes = DefaultLvalueConversion(From); 4230fe6060f1SDimitry Andric if (FromRes.isInvalid()) 4231fe6060f1SDimitry Andric return ExprError(); 4232fe6060f1SDimitry Andric 42330b57cec5SDimitry Andric From = FromRes.get(); 42340b57cec5SDimitry Andric FromType = From->getType(); 42350b57cec5SDimitry Andric break; 42360b57cec5SDimitry Andric } 42370b57cec5SDimitry Andric 42380b57cec5SDimitry Andric case ICK_Array_To_Pointer: 42390b57cec5SDimitry Andric FromType = Context.getArrayDecayedType(FromType); 4240fe6060f1SDimitry Andric From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue, 4241fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4242fe6060f1SDimitry Andric .get(); 42430b57cec5SDimitry Andric break; 42440b57cec5SDimitry Andric 42450b57cec5SDimitry Andric case ICK_Function_To_Pointer: 42460b57cec5SDimitry Andric FromType = Context.getPointerType(FromType); 42470b57cec5SDimitry Andric From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, 4248fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4249fe6060f1SDimitry Andric .get(); 42500b57cec5SDimitry Andric break; 42510b57cec5SDimitry Andric 42520b57cec5SDimitry Andric default: 42530b57cec5SDimitry Andric llvm_unreachable("Improper first standard conversion"); 42540b57cec5SDimitry Andric } 42550b57cec5SDimitry Andric 42560b57cec5SDimitry Andric // Perform the second implicit conversion 42570b57cec5SDimitry Andric switch (SCS.Second) { 42580b57cec5SDimitry Andric case ICK_Identity: 42590b57cec5SDimitry Andric // C++ [except.spec]p5: 42600b57cec5SDimitry Andric // [For] assignment to and initialization of pointers to functions, 42610b57cec5SDimitry Andric // pointers to member functions, and references to functions: the 42620b57cec5SDimitry Andric // target entity shall allow at least the exceptions allowed by the 42630b57cec5SDimitry Andric // source value in the assignment or initialization. 42640b57cec5SDimitry Andric switch (Action) { 42650b57cec5SDimitry Andric case AA_Assigning: 42660b57cec5SDimitry Andric case AA_Initializing: 42670b57cec5SDimitry Andric // Note, function argument passing and returning are initialization. 42680b57cec5SDimitry Andric case AA_Passing: 42690b57cec5SDimitry Andric case AA_Returning: 42700b57cec5SDimitry Andric case AA_Sending: 42710b57cec5SDimitry Andric case AA_Passing_CFAudited: 42720b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 42730b57cec5SDimitry Andric return ExprError(); 42740b57cec5SDimitry Andric break; 42750b57cec5SDimitry Andric 42760b57cec5SDimitry Andric case AA_Casting: 42770b57cec5SDimitry Andric case AA_Converting: 42780b57cec5SDimitry Andric // Casts and implicit conversions are not initialization, so are not 42790b57cec5SDimitry Andric // checked for exception specification mismatches. 42800b57cec5SDimitry Andric break; 42810b57cec5SDimitry Andric } 42820b57cec5SDimitry Andric // Nothing else to do. 42830b57cec5SDimitry Andric break; 42840b57cec5SDimitry Andric 42850b57cec5SDimitry Andric case ICK_Integral_Promotion: 42860b57cec5SDimitry Andric case ICK_Integral_Conversion: 42870b57cec5SDimitry Andric if (ToType->isBooleanType()) { 42880b57cec5SDimitry Andric assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && 42890b57cec5SDimitry Andric SCS.Second == ICK_Integral_Promotion && 42900b57cec5SDimitry Andric "only enums with fixed underlying type can promote to bool"); 4291fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue, 4292fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4293fe6060f1SDimitry Andric .get(); 42940b57cec5SDimitry Andric } else { 4295fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue, 4296fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4297fe6060f1SDimitry Andric .get(); 42980b57cec5SDimitry Andric } 42990b57cec5SDimitry Andric break; 43000b57cec5SDimitry Andric 43010b57cec5SDimitry Andric case ICK_Floating_Promotion: 43020b57cec5SDimitry Andric case ICK_Floating_Conversion: 4303fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue, 4304fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4305fe6060f1SDimitry Andric .get(); 43060b57cec5SDimitry Andric break; 43070b57cec5SDimitry Andric 43080b57cec5SDimitry Andric case ICK_Complex_Promotion: 43090b57cec5SDimitry Andric case ICK_Complex_Conversion: { 4310a7dea167SDimitry Andric QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); 4311a7dea167SDimitry Andric QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); 43120b57cec5SDimitry Andric CastKind CK; 43130b57cec5SDimitry Andric if (FromEl->isRealFloatingType()) { 43140b57cec5SDimitry Andric if (ToEl->isRealFloatingType()) 43150b57cec5SDimitry Andric CK = CK_FloatingComplexCast; 43160b57cec5SDimitry Andric else 43170b57cec5SDimitry Andric CK = CK_FloatingComplexToIntegralComplex; 43180b57cec5SDimitry Andric } else if (ToEl->isRealFloatingType()) { 43190b57cec5SDimitry Andric CK = CK_IntegralComplexToFloatingComplex; 43200b57cec5SDimitry Andric } else { 43210b57cec5SDimitry Andric CK = CK_IntegralComplexCast; 43220b57cec5SDimitry Andric } 4323fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr, 4324fe6060f1SDimitry Andric CCK) 4325fe6060f1SDimitry Andric .get(); 43260b57cec5SDimitry Andric break; 43270b57cec5SDimitry Andric } 43280b57cec5SDimitry Andric 43290b57cec5SDimitry Andric case ICK_Floating_Integral: 43300b57cec5SDimitry Andric if (ToType->isRealFloatingType()) 4331fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue, 4332fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4333fe6060f1SDimitry Andric .get(); 43340b57cec5SDimitry Andric else 4335fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue, 4336fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4337fe6060f1SDimitry Andric .get(); 43380b57cec5SDimitry Andric break; 43390b57cec5SDimitry Andric 43400b57cec5SDimitry Andric case ICK_Compatible_Conversion: 4341f13e6193SDimitry Andric From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), 4342f13e6193SDimitry Andric /*BasePath=*/nullptr, CCK).get(); 43430b57cec5SDimitry Andric break; 43440b57cec5SDimitry Andric 43450b57cec5SDimitry Andric case ICK_Writeback_Conversion: 43460b57cec5SDimitry Andric case ICK_Pointer_Conversion: { 43470b57cec5SDimitry Andric if (SCS.IncompatibleObjC && Action != AA_Casting) { 43480b57cec5SDimitry Andric // Diagnose incompatible Objective-C conversions 43490b57cec5SDimitry Andric if (Action == AA_Initializing || Action == AA_Assigning) 43500b57cec5SDimitry Andric Diag(From->getBeginLoc(), 43510b57cec5SDimitry Andric diag::ext_typecheck_convert_incompatible_pointer) 43520b57cec5SDimitry Andric << ToType << From->getType() << Action << From->getSourceRange() 43530b57cec5SDimitry Andric << 0; 43540b57cec5SDimitry Andric else 43550b57cec5SDimitry Andric Diag(From->getBeginLoc(), 43560b57cec5SDimitry Andric diag::ext_typecheck_convert_incompatible_pointer) 43570b57cec5SDimitry Andric << From->getType() << ToType << Action << From->getSourceRange() 43580b57cec5SDimitry Andric << 0; 43590b57cec5SDimitry Andric 43600b57cec5SDimitry Andric if (From->getType()->isObjCObjectPointerType() && 43610b57cec5SDimitry Andric ToType->isObjCObjectPointerType()) 43620b57cec5SDimitry Andric EmitRelatedResultTypeNote(From); 43630b57cec5SDimitry Andric } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 43640b57cec5SDimitry Andric !CheckObjCARCUnavailableWeakConversion(ToType, 43650b57cec5SDimitry Andric From->getType())) { 43660b57cec5SDimitry Andric if (Action == AA_Initializing) 43670b57cec5SDimitry Andric Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); 43680b57cec5SDimitry Andric else 43690b57cec5SDimitry Andric Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) 43700b57cec5SDimitry Andric << (Action == AA_Casting) << From->getType() << ToType 43710b57cec5SDimitry Andric << From->getSourceRange(); 43720b57cec5SDimitry Andric } 43730b57cec5SDimitry Andric 4374480093f4SDimitry Andric // Defer address space conversion to the third conversion. 4375480093f4SDimitry Andric QualType FromPteeType = From->getType()->getPointeeType(); 4376480093f4SDimitry Andric QualType ToPteeType = ToType->getPointeeType(); 4377480093f4SDimitry Andric QualType NewToType = ToType; 4378480093f4SDimitry Andric if (!FromPteeType.isNull() && !ToPteeType.isNull() && 4379480093f4SDimitry Andric FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { 4380480093f4SDimitry Andric NewToType = Context.removeAddrSpaceQualType(ToPteeType); 4381480093f4SDimitry Andric NewToType = Context.getAddrSpaceQualType(NewToType, 4382480093f4SDimitry Andric FromPteeType.getAddressSpace()); 4383480093f4SDimitry Andric if (ToType->isObjCObjectPointerType()) 4384480093f4SDimitry Andric NewToType = Context.getObjCObjectPointerType(NewToType); 4385480093f4SDimitry Andric else if (ToType->isBlockPointerType()) 4386480093f4SDimitry Andric NewToType = Context.getBlockPointerType(NewToType); 4387480093f4SDimitry Andric else 4388480093f4SDimitry Andric NewToType = Context.getPointerType(NewToType); 4389480093f4SDimitry Andric } 4390480093f4SDimitry Andric 43910b57cec5SDimitry Andric CastKind Kind; 43920b57cec5SDimitry Andric CXXCastPath BasePath; 4393480093f4SDimitry Andric if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) 43940b57cec5SDimitry Andric return ExprError(); 43950b57cec5SDimitry Andric 43960b57cec5SDimitry Andric // Make sure we extend blocks if necessary. 43970b57cec5SDimitry Andric // FIXME: doing this here is really ugly. 43980b57cec5SDimitry Andric if (Kind == CK_BlockPointerToObjCPointerCast) { 43990b57cec5SDimitry Andric ExprResult E = From; 44000b57cec5SDimitry Andric (void) PrepareCastToObjCObjectPointer(E); 44010b57cec5SDimitry Andric From = E.get(); 44020b57cec5SDimitry Andric } 44030b57cec5SDimitry Andric if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) 4404480093f4SDimitry Andric CheckObjCConversion(SourceRange(), NewToType, From, CCK); 4405fe6060f1SDimitry Andric From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK) 44060b57cec5SDimitry Andric .get(); 44070b57cec5SDimitry Andric break; 44080b57cec5SDimitry Andric } 44090b57cec5SDimitry Andric 44100b57cec5SDimitry Andric case ICK_Pointer_Member: { 44110b57cec5SDimitry Andric CastKind Kind; 44120b57cec5SDimitry Andric CXXCastPath BasePath; 44130b57cec5SDimitry Andric if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle)) 44140b57cec5SDimitry Andric return ExprError(); 44150b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 44160b57cec5SDimitry Andric return ExprError(); 44170b57cec5SDimitry Andric 44180b57cec5SDimitry Andric // We may not have been able to figure out what this member pointer resolved 44190b57cec5SDimitry Andric // to up until this exact point. Attempt to lock-in it's inheritance model. 44200b57cec5SDimitry Andric if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 44210b57cec5SDimitry Andric (void)isCompleteType(From->getExprLoc(), From->getType()); 44220b57cec5SDimitry Andric (void)isCompleteType(From->getExprLoc(), ToType); 44230b57cec5SDimitry Andric } 44240b57cec5SDimitry Andric 4425fe6060f1SDimitry Andric From = 4426fe6060f1SDimitry Andric ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get(); 44270b57cec5SDimitry Andric break; 44280b57cec5SDimitry Andric } 44290b57cec5SDimitry Andric 44300b57cec5SDimitry Andric case ICK_Boolean_Conversion: 44310b57cec5SDimitry Andric // Perform half-to-boolean conversion via float. 44320b57cec5SDimitry Andric if (From->getType()->isHalfType()) { 44330b57cec5SDimitry Andric From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); 44340b57cec5SDimitry Andric FromType = Context.FloatTy; 44350b57cec5SDimitry Andric } 44360b57cec5SDimitry Andric 44370b57cec5SDimitry Andric From = ImpCastExprToType(From, Context.BoolTy, 4438fe6060f1SDimitry Andric ScalarTypeToBooleanCastKind(FromType), VK_PRValue, 4439fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4440fe6060f1SDimitry Andric .get(); 44410b57cec5SDimitry Andric break; 44420b57cec5SDimitry Andric 44430b57cec5SDimitry Andric case ICK_Derived_To_Base: { 44440b57cec5SDimitry Andric CXXCastPath BasePath; 44450b57cec5SDimitry Andric if (CheckDerivedToBaseConversion( 44460b57cec5SDimitry Andric From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), 44470b57cec5SDimitry Andric From->getSourceRange(), &BasePath, CStyle)) 44480b57cec5SDimitry Andric return ExprError(); 44490b57cec5SDimitry Andric 44500b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getNonReferenceType(), 44510b57cec5SDimitry Andric CK_DerivedToBase, From->getValueKind(), 44520b57cec5SDimitry Andric &BasePath, CCK).get(); 44530b57cec5SDimitry Andric break; 44540b57cec5SDimitry Andric } 44550b57cec5SDimitry Andric 44560b57cec5SDimitry Andric case ICK_Vector_Conversion: 4457fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, 4458fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4459fe6060f1SDimitry Andric .get(); 44600b57cec5SDimitry Andric break; 44610b57cec5SDimitry Andric 4462e8d8bef9SDimitry Andric case ICK_SVE_Vector_Conversion: 4463fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, 4464e8d8bef9SDimitry Andric /*BasePath=*/nullptr, CCK) 4465e8d8bef9SDimitry Andric .get(); 4466e8d8bef9SDimitry Andric break; 4467e8d8bef9SDimitry Andric 44680b57cec5SDimitry Andric case ICK_Vector_Splat: { 44690b57cec5SDimitry Andric // Vector splat from any arithmetic type to a vector. 44700b57cec5SDimitry Andric Expr *Elem = prepareVectorSplat(ToType, From).get(); 4471fe6060f1SDimitry Andric From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue, 4472fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4473fe6060f1SDimitry Andric .get(); 44740b57cec5SDimitry Andric break; 44750b57cec5SDimitry Andric } 44760b57cec5SDimitry Andric 44770b57cec5SDimitry Andric case ICK_Complex_Real: 44780b57cec5SDimitry Andric // Case 1. x -> _Complex y 44790b57cec5SDimitry Andric if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { 44800b57cec5SDimitry Andric QualType ElType = ToComplex->getElementType(); 44810b57cec5SDimitry Andric bool isFloatingComplex = ElType->isRealFloatingType(); 44820b57cec5SDimitry Andric 44830b57cec5SDimitry Andric // x -> y 44840b57cec5SDimitry Andric if (Context.hasSameUnqualifiedType(ElType, From->getType())) { 44850b57cec5SDimitry Andric // do nothing 44860b57cec5SDimitry Andric } else if (From->getType()->isRealFloatingType()) { 44870b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 44880b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); 44890b57cec5SDimitry Andric } else { 44900b57cec5SDimitry Andric assert(From->getType()->isIntegerType()); 44910b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 44920b57cec5SDimitry Andric isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); 44930b57cec5SDimitry Andric } 44940b57cec5SDimitry Andric // y -> _Complex y 44950b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 44960b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingRealToComplex 44970b57cec5SDimitry Andric : CK_IntegralRealToComplex).get(); 44980b57cec5SDimitry Andric 44990b57cec5SDimitry Andric // Case 2. _Complex x -> y 45000b57cec5SDimitry Andric } else { 45015ffd83dbSDimitry Andric auto *FromComplex = From->getType()->castAs<ComplexType>(); 45020b57cec5SDimitry Andric QualType ElType = FromComplex->getElementType(); 45030b57cec5SDimitry Andric bool isFloatingComplex = ElType->isRealFloatingType(); 45040b57cec5SDimitry Andric 45050b57cec5SDimitry Andric // _Complex x -> x 45060b57cec5SDimitry Andric From = ImpCastExprToType(From, ElType, 45070b57cec5SDimitry Andric isFloatingComplex ? CK_FloatingComplexToReal 45080b57cec5SDimitry Andric : CK_IntegralComplexToReal, 4509fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4510fe6060f1SDimitry Andric .get(); 45110b57cec5SDimitry Andric 45120b57cec5SDimitry Andric // x -> y 45130b57cec5SDimitry Andric if (Context.hasSameUnqualifiedType(ElType, ToType)) { 45140b57cec5SDimitry Andric // do nothing 45150b57cec5SDimitry Andric } else if (ToType->isRealFloatingType()) { 45160b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 4517fe6060f1SDimitry Andric isFloatingComplex ? CK_FloatingCast 4518fe6060f1SDimitry Andric : CK_IntegralToFloating, 4519fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4520fe6060f1SDimitry Andric .get(); 45210b57cec5SDimitry Andric } else { 45220b57cec5SDimitry Andric assert(ToType->isIntegerType()); 45230b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 4524fe6060f1SDimitry Andric isFloatingComplex ? CK_FloatingToIntegral 4525fe6060f1SDimitry Andric : CK_IntegralCast, 4526fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4527fe6060f1SDimitry Andric .get(); 45280b57cec5SDimitry Andric } 45290b57cec5SDimitry Andric } 45300b57cec5SDimitry Andric break; 45310b57cec5SDimitry Andric 45320b57cec5SDimitry Andric case ICK_Block_Pointer_Conversion: { 45330b57cec5SDimitry Andric LangAS AddrSpaceL = 45340b57cec5SDimitry Andric ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 45350b57cec5SDimitry Andric LangAS AddrSpaceR = 45360b57cec5SDimitry Andric FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); 45370b57cec5SDimitry Andric assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && 45380b57cec5SDimitry Andric "Invalid cast"); 45390b57cec5SDimitry Andric CastKind Kind = 45400b57cec5SDimitry Andric AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; 45410b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, 4542fe6060f1SDimitry Andric VK_PRValue, /*BasePath=*/nullptr, CCK) 4543fe6060f1SDimitry Andric .get(); 45440b57cec5SDimitry Andric break; 45450b57cec5SDimitry Andric } 45460b57cec5SDimitry Andric 45470b57cec5SDimitry Andric case ICK_TransparentUnionConversion: { 45480b57cec5SDimitry Andric ExprResult FromRes = From; 45490b57cec5SDimitry Andric Sema::AssignConvertType ConvTy = 45500b57cec5SDimitry Andric CheckTransparentUnionArgumentConstraints(ToType, FromRes); 45510b57cec5SDimitry Andric if (FromRes.isInvalid()) 45520b57cec5SDimitry Andric return ExprError(); 45530b57cec5SDimitry Andric From = FromRes.get(); 45540b57cec5SDimitry Andric assert ((ConvTy == Sema::Compatible) && 45550b57cec5SDimitry Andric "Improper transparent union conversion"); 45560b57cec5SDimitry Andric (void)ConvTy; 45570b57cec5SDimitry Andric break; 45580b57cec5SDimitry Andric } 45590b57cec5SDimitry Andric 45600b57cec5SDimitry Andric case ICK_Zero_Event_Conversion: 45610b57cec5SDimitry Andric case ICK_Zero_Queue_Conversion: 45620b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType, 45630b57cec5SDimitry Andric CK_ZeroToOCLOpaqueType, 45640b57cec5SDimitry Andric From->getValueKind()).get(); 45650b57cec5SDimitry Andric break; 45660b57cec5SDimitry Andric 45670b57cec5SDimitry Andric case ICK_Lvalue_To_Rvalue: 45680b57cec5SDimitry Andric case ICK_Array_To_Pointer: 45690b57cec5SDimitry Andric case ICK_Function_To_Pointer: 45700b57cec5SDimitry Andric case ICK_Function_Conversion: 45710b57cec5SDimitry Andric case ICK_Qualification: 45720b57cec5SDimitry Andric case ICK_Num_Conversion_Kinds: 45730b57cec5SDimitry Andric case ICK_C_Only_Conversion: 45740b57cec5SDimitry Andric case ICK_Incompatible_Pointer_Conversion: 45750b57cec5SDimitry Andric llvm_unreachable("Improper second standard conversion"); 45760b57cec5SDimitry Andric } 45770b57cec5SDimitry Andric 45780b57cec5SDimitry Andric switch (SCS.Third) { 45790b57cec5SDimitry Andric case ICK_Identity: 45800b57cec5SDimitry Andric // Nothing to do. 45810b57cec5SDimitry Andric break; 45820b57cec5SDimitry Andric 45830b57cec5SDimitry Andric case ICK_Function_Conversion: 45840b57cec5SDimitry Andric // If both sides are functions (or pointers/references to them), there could 45850b57cec5SDimitry Andric // be incompatible exception declarations. 45860b57cec5SDimitry Andric if (CheckExceptionSpecCompatibility(From, ToType)) 45870b57cec5SDimitry Andric return ExprError(); 45880b57cec5SDimitry Andric 4589fe6060f1SDimitry Andric From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue, 4590fe6060f1SDimitry Andric /*BasePath=*/nullptr, CCK) 4591fe6060f1SDimitry Andric .get(); 45920b57cec5SDimitry Andric break; 45930b57cec5SDimitry Andric 45940b57cec5SDimitry Andric case ICK_Qualification: { 4595f13e6193SDimitry Andric ExprValueKind VK = From->getValueKind(); 45960b57cec5SDimitry Andric CastKind CK = CK_NoOp; 45970b57cec5SDimitry Andric 45980b57cec5SDimitry Andric if (ToType->isReferenceType() && 45990b57cec5SDimitry Andric ToType->getPointeeType().getAddressSpace() != 46000b57cec5SDimitry Andric From->getType().getAddressSpace()) 46010b57cec5SDimitry Andric CK = CK_AddressSpaceConversion; 46020b57cec5SDimitry Andric 46030b57cec5SDimitry Andric if (ToType->isPointerType() && 46040b57cec5SDimitry Andric ToType->getPointeeType().getAddressSpace() != 46050b57cec5SDimitry Andric From->getType()->getPointeeType().getAddressSpace()) 46060b57cec5SDimitry Andric CK = CK_AddressSpaceConversion; 46070b57cec5SDimitry Andric 46080b57cec5SDimitry Andric From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, 46090b57cec5SDimitry Andric /*BasePath=*/nullptr, CCK) 46100b57cec5SDimitry Andric .get(); 46110b57cec5SDimitry Andric 46120b57cec5SDimitry Andric if (SCS.DeprecatedStringLiteralToCharPtr && 46130b57cec5SDimitry Andric !getLangOpts().WritableStrings) { 46140b57cec5SDimitry Andric Diag(From->getBeginLoc(), 46150b57cec5SDimitry Andric getLangOpts().CPlusPlus11 46160b57cec5SDimitry Andric ? diag::ext_deprecated_string_literal_conversion 46170b57cec5SDimitry Andric : diag::warn_deprecated_string_literal_conversion) 46180b57cec5SDimitry Andric << ToType.getNonReferenceType(); 46190b57cec5SDimitry Andric } 46200b57cec5SDimitry Andric 46210b57cec5SDimitry Andric break; 46220b57cec5SDimitry Andric } 46230b57cec5SDimitry Andric 46240b57cec5SDimitry Andric default: 46250b57cec5SDimitry Andric llvm_unreachable("Improper third standard conversion"); 46260b57cec5SDimitry Andric } 46270b57cec5SDimitry Andric 46280b57cec5SDimitry Andric // If this conversion sequence involved a scalar -> atomic conversion, perform 46290b57cec5SDimitry Andric // that conversion now. 46300b57cec5SDimitry Andric if (!ToAtomicType.isNull()) { 46310b57cec5SDimitry Andric assert(Context.hasSameType( 46320b57cec5SDimitry Andric ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); 46330b57cec5SDimitry Andric From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, 4634fe6060f1SDimitry Andric VK_PRValue, nullptr, CCK) 4635fe6060f1SDimitry Andric .get(); 46360b57cec5SDimitry Andric } 46370b57cec5SDimitry Andric 46385ffd83dbSDimitry Andric // Materialize a temporary if we're implicitly converting to a reference 46395ffd83dbSDimitry Andric // type. This is not required by the C++ rules but is necessary to maintain 46405ffd83dbSDimitry Andric // AST invariants. 4641fe6060f1SDimitry Andric if (ToType->isReferenceType() && From->isPRValue()) { 46425ffd83dbSDimitry Andric ExprResult Res = TemporaryMaterializationConversion(From); 46435ffd83dbSDimitry Andric if (Res.isInvalid()) 46445ffd83dbSDimitry Andric return ExprError(); 46455ffd83dbSDimitry Andric From = Res.get(); 46465ffd83dbSDimitry Andric } 46475ffd83dbSDimitry Andric 46480b57cec5SDimitry Andric // If this conversion sequence succeeded and involved implicitly converting a 46490b57cec5SDimitry Andric // _Nullable type to a _Nonnull one, complain. 46500b57cec5SDimitry Andric if (!isCast(CCK)) 46510b57cec5SDimitry Andric diagnoseNullableToNonnullConversion(ToType, InitialFromType, 46520b57cec5SDimitry Andric From->getBeginLoc()); 46530b57cec5SDimitry Andric 46540b57cec5SDimitry Andric return From; 46550b57cec5SDimitry Andric } 46560b57cec5SDimitry Andric 46570b57cec5SDimitry Andric /// Check the completeness of a type in a unary type trait. 46580b57cec5SDimitry Andric /// 46590b57cec5SDimitry Andric /// If the particular type trait requires a complete type, tries to complete 46600b57cec5SDimitry Andric /// it. If completing the type fails, a diagnostic is emitted and false 46610b57cec5SDimitry Andric /// returned. If completing the type succeeds or no completion was required, 46620b57cec5SDimitry Andric /// returns true. 46630b57cec5SDimitry Andric static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, 46640b57cec5SDimitry Andric SourceLocation Loc, 46650b57cec5SDimitry Andric QualType ArgTy) { 46660b57cec5SDimitry Andric // C++0x [meta.unary.prop]p3: 46670b57cec5SDimitry Andric // For all of the class templates X declared in this Clause, instantiating 46680b57cec5SDimitry Andric // that template with a template argument that is a class template 46690b57cec5SDimitry Andric // specialization may result in the implicit instantiation of the template 46700b57cec5SDimitry Andric // argument if and only if the semantics of X require that the argument 46710b57cec5SDimitry Andric // must be a complete type. 46720b57cec5SDimitry Andric // We apply this rule to all the type trait expressions used to implement 46730b57cec5SDimitry Andric // these class templates. We also try to follow any GCC documented behavior 46740b57cec5SDimitry Andric // in these expressions to ensure portability of standard libraries. 46750b57cec5SDimitry Andric switch (UTT) { 46760b57cec5SDimitry Andric default: llvm_unreachable("not a UTT"); 46770b57cec5SDimitry Andric // is_complete_type somewhat obviously cannot require a complete type. 46780b57cec5SDimitry Andric case UTT_IsCompleteType: 46790b57cec5SDimitry Andric // Fall-through 46800b57cec5SDimitry Andric 46810b57cec5SDimitry Andric // These traits are modeled on the type predicates in C++0x 46820b57cec5SDimitry Andric // [meta.unary.cat] and [meta.unary.comp]. They are not specified as 46830b57cec5SDimitry Andric // requiring a complete type, as whether or not they return true cannot be 46840b57cec5SDimitry Andric // impacted by the completeness of the type. 46850b57cec5SDimitry Andric case UTT_IsVoid: 46860b57cec5SDimitry Andric case UTT_IsIntegral: 46870b57cec5SDimitry Andric case UTT_IsFloatingPoint: 46880b57cec5SDimitry Andric case UTT_IsArray: 46890b57cec5SDimitry Andric case UTT_IsPointer: 46900b57cec5SDimitry Andric case UTT_IsLvalueReference: 46910b57cec5SDimitry Andric case UTT_IsRvalueReference: 46920b57cec5SDimitry Andric case UTT_IsMemberFunctionPointer: 46930b57cec5SDimitry Andric case UTT_IsMemberObjectPointer: 46940b57cec5SDimitry Andric case UTT_IsEnum: 46950b57cec5SDimitry Andric case UTT_IsUnion: 46960b57cec5SDimitry Andric case UTT_IsClass: 46970b57cec5SDimitry Andric case UTT_IsFunction: 46980b57cec5SDimitry Andric case UTT_IsReference: 46990b57cec5SDimitry Andric case UTT_IsArithmetic: 47000b57cec5SDimitry Andric case UTT_IsFundamental: 47010b57cec5SDimitry Andric case UTT_IsObject: 47020b57cec5SDimitry Andric case UTT_IsScalar: 47030b57cec5SDimitry Andric case UTT_IsCompound: 47040b57cec5SDimitry Andric case UTT_IsMemberPointer: 47050b57cec5SDimitry Andric // Fall-through 47060b57cec5SDimitry Andric 47070b57cec5SDimitry Andric // These traits are modeled on type predicates in C++0x [meta.unary.prop] 47080b57cec5SDimitry Andric // which requires some of its traits to have the complete type. However, 47090b57cec5SDimitry Andric // the completeness of the type cannot impact these traits' semantics, and 47100b57cec5SDimitry Andric // so they don't require it. This matches the comments on these traits in 47110b57cec5SDimitry Andric // Table 49. 47120b57cec5SDimitry Andric case UTT_IsConst: 47130b57cec5SDimitry Andric case UTT_IsVolatile: 47140b57cec5SDimitry Andric case UTT_IsSigned: 47150b57cec5SDimitry Andric case UTT_IsUnsigned: 47160b57cec5SDimitry Andric 47170b57cec5SDimitry Andric // This type trait always returns false, checking the type is moot. 47180b57cec5SDimitry Andric case UTT_IsInterfaceClass: 47190b57cec5SDimitry Andric return true; 47200b57cec5SDimitry Andric 47210b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 47220b57cec5SDimitry Andric // If T is a non-union class type, T shall be a complete type. 47230b57cec5SDimitry Andric case UTT_IsEmpty: 47240b57cec5SDimitry Andric case UTT_IsPolymorphic: 47250b57cec5SDimitry Andric case UTT_IsAbstract: 47260b57cec5SDimitry Andric if (const auto *RD = ArgTy->getAsCXXRecordDecl()) 47270b57cec5SDimitry Andric if (!RD->isUnion()) 47280b57cec5SDimitry Andric return !S.RequireCompleteType( 47290b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 47300b57cec5SDimitry Andric return true; 47310b57cec5SDimitry Andric 47320b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 47330b57cec5SDimitry Andric // If T is a class type, T shall be a complete type. 47340b57cec5SDimitry Andric case UTT_IsFinal: 47350b57cec5SDimitry Andric case UTT_IsSealed: 47360b57cec5SDimitry Andric if (ArgTy->getAsCXXRecordDecl()) 47370b57cec5SDimitry Andric return !S.RequireCompleteType( 47380b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 47390b57cec5SDimitry Andric return true; 47400b57cec5SDimitry Andric 47410b57cec5SDimitry Andric // C++1z [meta.unary.prop]: 47420b57cec5SDimitry Andric // remove_all_extents_t<T> shall be a complete type or cv void. 47430b57cec5SDimitry Andric case UTT_IsAggregate: 47440b57cec5SDimitry Andric case UTT_IsTrivial: 47450b57cec5SDimitry Andric case UTT_IsTriviallyCopyable: 47460b57cec5SDimitry Andric case UTT_IsStandardLayout: 47470b57cec5SDimitry Andric case UTT_IsPOD: 47480b57cec5SDimitry Andric case UTT_IsLiteral: 47490b57cec5SDimitry Andric // Per the GCC type traits documentation, T shall be a complete type, cv void, 47500b57cec5SDimitry Andric // or an array of unknown bound. But GCC actually imposes the same constraints 47510b57cec5SDimitry Andric // as above. 47520b57cec5SDimitry Andric case UTT_HasNothrowAssign: 47530b57cec5SDimitry Andric case UTT_HasNothrowMoveAssign: 47540b57cec5SDimitry Andric case UTT_HasNothrowConstructor: 47550b57cec5SDimitry Andric case UTT_HasNothrowCopy: 47560b57cec5SDimitry Andric case UTT_HasTrivialAssign: 47570b57cec5SDimitry Andric case UTT_HasTrivialMoveAssign: 47580b57cec5SDimitry Andric case UTT_HasTrivialDefaultConstructor: 47590b57cec5SDimitry Andric case UTT_HasTrivialMoveConstructor: 47600b57cec5SDimitry Andric case UTT_HasTrivialCopy: 47610b57cec5SDimitry Andric case UTT_HasTrivialDestructor: 47620b57cec5SDimitry Andric case UTT_HasVirtualDestructor: 47630b57cec5SDimitry Andric ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0); 47640b57cec5SDimitry Andric LLVM_FALLTHROUGH; 47650b57cec5SDimitry Andric 47660b57cec5SDimitry Andric // C++1z [meta.unary.prop]: 47670b57cec5SDimitry Andric // T shall be a complete type, cv void, or an array of unknown bound. 47680b57cec5SDimitry Andric case UTT_IsDestructible: 47690b57cec5SDimitry Andric case UTT_IsNothrowDestructible: 47700b57cec5SDimitry Andric case UTT_IsTriviallyDestructible: 47710b57cec5SDimitry Andric case UTT_HasUniqueObjectRepresentations: 47720b57cec5SDimitry Andric if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType()) 47730b57cec5SDimitry Andric return true; 47740b57cec5SDimitry Andric 47750b57cec5SDimitry Andric return !S.RequireCompleteType( 47760b57cec5SDimitry Andric Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr); 47770b57cec5SDimitry Andric } 47780b57cec5SDimitry Andric } 47790b57cec5SDimitry Andric 47800b57cec5SDimitry Andric static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op, 47810b57cec5SDimitry Andric Sema &Self, SourceLocation KeyLoc, ASTContext &C, 47820b57cec5SDimitry Andric bool (CXXRecordDecl::*HasTrivial)() const, 47830b57cec5SDimitry Andric bool (CXXRecordDecl::*HasNonTrivial)() const, 47840b57cec5SDimitry Andric bool (CXXMethodDecl::*IsDesiredOp)() const) 47850b57cec5SDimitry Andric { 47860b57cec5SDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 47870b57cec5SDimitry Andric if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)()) 47880b57cec5SDimitry Andric return true; 47890b57cec5SDimitry Andric 47900b57cec5SDimitry Andric DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op); 47910b57cec5SDimitry Andric DeclarationNameInfo NameInfo(Name, KeyLoc); 47920b57cec5SDimitry Andric LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName); 47930b57cec5SDimitry Andric if (Self.LookupQualifiedName(Res, RD)) { 47940b57cec5SDimitry Andric bool FoundOperator = false; 47950b57cec5SDimitry Andric Res.suppressDiagnostics(); 47960b57cec5SDimitry Andric for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end(); 47970b57cec5SDimitry Andric Op != OpEnd; ++Op) { 47980b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(*Op)) 47990b57cec5SDimitry Andric continue; 48000b57cec5SDimitry Andric 48010b57cec5SDimitry Andric CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op); 48020b57cec5SDimitry Andric if((Operator->*IsDesiredOp)()) { 48030b57cec5SDimitry Andric FoundOperator = true; 48045ffd83dbSDimitry Andric auto *CPT = Operator->getType()->castAs<FunctionProtoType>(); 48050b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 48060b57cec5SDimitry Andric if (!CPT || !CPT->isNothrow()) 48070b57cec5SDimitry Andric return false; 48080b57cec5SDimitry Andric } 48090b57cec5SDimitry Andric } 48100b57cec5SDimitry Andric return FoundOperator; 48110b57cec5SDimitry Andric } 48120b57cec5SDimitry Andric return false; 48130b57cec5SDimitry Andric } 48140b57cec5SDimitry Andric 48150b57cec5SDimitry Andric static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, 48160b57cec5SDimitry Andric SourceLocation KeyLoc, QualType T) { 48170b57cec5SDimitry Andric assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 48180b57cec5SDimitry Andric 48190b57cec5SDimitry Andric ASTContext &C = Self.Context; 48200b57cec5SDimitry Andric switch(UTT) { 48210b57cec5SDimitry Andric default: llvm_unreachable("not a UTT"); 48220b57cec5SDimitry Andric // Type trait expressions corresponding to the primary type category 48230b57cec5SDimitry Andric // predicates in C++0x [meta.unary.cat]. 48240b57cec5SDimitry Andric case UTT_IsVoid: 48250b57cec5SDimitry Andric return T->isVoidType(); 48260b57cec5SDimitry Andric case UTT_IsIntegral: 48270b57cec5SDimitry Andric return T->isIntegralType(C); 48280b57cec5SDimitry Andric case UTT_IsFloatingPoint: 48290b57cec5SDimitry Andric return T->isFloatingType(); 48300b57cec5SDimitry Andric case UTT_IsArray: 48310b57cec5SDimitry Andric return T->isArrayType(); 48320b57cec5SDimitry Andric case UTT_IsPointer: 48335ffd83dbSDimitry Andric return T->isAnyPointerType(); 48340b57cec5SDimitry Andric case UTT_IsLvalueReference: 48350b57cec5SDimitry Andric return T->isLValueReferenceType(); 48360b57cec5SDimitry Andric case UTT_IsRvalueReference: 48370b57cec5SDimitry Andric return T->isRValueReferenceType(); 48380b57cec5SDimitry Andric case UTT_IsMemberFunctionPointer: 48390b57cec5SDimitry Andric return T->isMemberFunctionPointerType(); 48400b57cec5SDimitry Andric case UTT_IsMemberObjectPointer: 48410b57cec5SDimitry Andric return T->isMemberDataPointerType(); 48420b57cec5SDimitry Andric case UTT_IsEnum: 48430b57cec5SDimitry Andric return T->isEnumeralType(); 48440b57cec5SDimitry Andric case UTT_IsUnion: 48450b57cec5SDimitry Andric return T->isUnionType(); 48460b57cec5SDimitry Andric case UTT_IsClass: 48470b57cec5SDimitry Andric return T->isClassType() || T->isStructureType() || T->isInterfaceType(); 48480b57cec5SDimitry Andric case UTT_IsFunction: 48490b57cec5SDimitry Andric return T->isFunctionType(); 48500b57cec5SDimitry Andric 48510b57cec5SDimitry Andric // Type trait expressions which correspond to the convenient composition 48520b57cec5SDimitry Andric // predicates in C++0x [meta.unary.comp]. 48530b57cec5SDimitry Andric case UTT_IsReference: 48540b57cec5SDimitry Andric return T->isReferenceType(); 48550b57cec5SDimitry Andric case UTT_IsArithmetic: 48560b57cec5SDimitry Andric return T->isArithmeticType() && !T->isEnumeralType(); 48570b57cec5SDimitry Andric case UTT_IsFundamental: 48580b57cec5SDimitry Andric return T->isFundamentalType(); 48590b57cec5SDimitry Andric case UTT_IsObject: 48600b57cec5SDimitry Andric return T->isObjectType(); 48610b57cec5SDimitry Andric case UTT_IsScalar: 48620b57cec5SDimitry Andric // Note: semantic analysis depends on Objective-C lifetime types to be 48630b57cec5SDimitry Andric // considered scalar types. However, such types do not actually behave 48640b57cec5SDimitry Andric // like scalar types at run time (since they may require retain/release 48650b57cec5SDimitry Andric // operations), so we report them as non-scalar. 48660b57cec5SDimitry Andric if (T->isObjCLifetimeType()) { 48670b57cec5SDimitry Andric switch (T.getObjCLifetime()) { 48680b57cec5SDimitry Andric case Qualifiers::OCL_None: 48690b57cec5SDimitry Andric case Qualifiers::OCL_ExplicitNone: 48700b57cec5SDimitry Andric return true; 48710b57cec5SDimitry Andric 48720b57cec5SDimitry Andric case Qualifiers::OCL_Strong: 48730b57cec5SDimitry Andric case Qualifiers::OCL_Weak: 48740b57cec5SDimitry Andric case Qualifiers::OCL_Autoreleasing: 48750b57cec5SDimitry Andric return false; 48760b57cec5SDimitry Andric } 48770b57cec5SDimitry Andric } 48780b57cec5SDimitry Andric 48790b57cec5SDimitry Andric return T->isScalarType(); 48800b57cec5SDimitry Andric case UTT_IsCompound: 48810b57cec5SDimitry Andric return T->isCompoundType(); 48820b57cec5SDimitry Andric case UTT_IsMemberPointer: 48830b57cec5SDimitry Andric return T->isMemberPointerType(); 48840b57cec5SDimitry Andric 48850b57cec5SDimitry Andric // Type trait expressions which correspond to the type property predicates 48860b57cec5SDimitry Andric // in C++0x [meta.unary.prop]. 48870b57cec5SDimitry Andric case UTT_IsConst: 48880b57cec5SDimitry Andric return T.isConstQualified(); 48890b57cec5SDimitry Andric case UTT_IsVolatile: 48900b57cec5SDimitry Andric return T.isVolatileQualified(); 48910b57cec5SDimitry Andric case UTT_IsTrivial: 48920b57cec5SDimitry Andric return T.isTrivialType(C); 48930b57cec5SDimitry Andric case UTT_IsTriviallyCopyable: 48940b57cec5SDimitry Andric return T.isTriviallyCopyableType(C); 48950b57cec5SDimitry Andric case UTT_IsStandardLayout: 48960b57cec5SDimitry Andric return T->isStandardLayoutType(); 48970b57cec5SDimitry Andric case UTT_IsPOD: 48980b57cec5SDimitry Andric return T.isPODType(C); 48990b57cec5SDimitry Andric case UTT_IsLiteral: 49000b57cec5SDimitry Andric return T->isLiteralType(C); 49010b57cec5SDimitry Andric case UTT_IsEmpty: 49020b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49030b57cec5SDimitry Andric return !RD->isUnion() && RD->isEmpty(); 49040b57cec5SDimitry Andric return false; 49050b57cec5SDimitry Andric case UTT_IsPolymorphic: 49060b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49070b57cec5SDimitry Andric return !RD->isUnion() && RD->isPolymorphic(); 49080b57cec5SDimitry Andric return false; 49090b57cec5SDimitry Andric case UTT_IsAbstract: 49100b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49110b57cec5SDimitry Andric return !RD->isUnion() && RD->isAbstract(); 49120b57cec5SDimitry Andric return false; 49130b57cec5SDimitry Andric case UTT_IsAggregate: 49140b57cec5SDimitry Andric // Report vector extensions and complex types as aggregates because they 49150b57cec5SDimitry Andric // support aggregate initialization. GCC mirrors this behavior for vectors 49160b57cec5SDimitry Andric // but not _Complex. 49170b57cec5SDimitry Andric return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || 49180b57cec5SDimitry Andric T->isAnyComplexType(); 49190b57cec5SDimitry Andric // __is_interface_class only returns true when CL is invoked in /CLR mode and 49200b57cec5SDimitry Andric // even then only when it is used with the 'interface struct ...' syntax 49210b57cec5SDimitry Andric // Clang doesn't support /CLR which makes this type trait moot. 49220b57cec5SDimitry Andric case UTT_IsInterfaceClass: 49230b57cec5SDimitry Andric return false; 49240b57cec5SDimitry Andric case UTT_IsFinal: 49250b57cec5SDimitry Andric case UTT_IsSealed: 49260b57cec5SDimitry Andric if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49270b57cec5SDimitry Andric return RD->hasAttr<FinalAttr>(); 49280b57cec5SDimitry Andric return false; 49290b57cec5SDimitry Andric case UTT_IsSigned: 4930a7dea167SDimitry Andric // Enum types should always return false. 4931a7dea167SDimitry Andric // Floating points should always return true. 4932fe6060f1SDimitry Andric return T->isFloatingType() || 4933fe6060f1SDimitry Andric (T->isSignedIntegerType() && !T->isEnumeralType()); 49340b57cec5SDimitry Andric case UTT_IsUnsigned: 4935fe6060f1SDimitry Andric // Enum types should always return false. 4936fe6060f1SDimitry Andric return T->isUnsignedIntegerType() && !T->isEnumeralType(); 49370b57cec5SDimitry Andric 49380b57cec5SDimitry Andric // Type trait expressions which query classes regarding their construction, 49390b57cec5SDimitry Andric // destruction, and copying. Rather than being based directly on the 49400b57cec5SDimitry Andric // related type predicates in the standard, they are specified by both 49410b57cec5SDimitry Andric // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those 49420b57cec5SDimitry Andric // specifications. 49430b57cec5SDimitry Andric // 49440b57cec5SDimitry Andric // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html 49450b57cec5SDimitry Andric // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 49460b57cec5SDimitry Andric // 49470b57cec5SDimitry Andric // Note that these builtins do not behave as documented in g++: if a class 49480b57cec5SDimitry Andric // has both a trivial and a non-trivial special member of a particular kind, 49490b57cec5SDimitry Andric // they return false! For now, we emulate this behavior. 49500b57cec5SDimitry Andric // FIXME: This appears to be a g++ bug: more complex cases reveal that it 49510b57cec5SDimitry Andric // does not correctly compute triviality in the presence of multiple special 49520b57cec5SDimitry Andric // members of the same kind. Revisit this once the g++ bug is fixed. 49530b57cec5SDimitry Andric case UTT_HasTrivialDefaultConstructor: 49540b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 49550b57cec5SDimitry Andric // If __is_pod (type) is true then the trait is true, else if type is 49560b57cec5SDimitry Andric // a cv class or union type (or array thereof) with a trivial default 49570b57cec5SDimitry Andric // constructor ([class.ctor]) then the trait is true, else it is false. 49580b57cec5SDimitry Andric if (T.isPODType(C)) 49590b57cec5SDimitry Andric return true; 49600b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 49610b57cec5SDimitry Andric return RD->hasTrivialDefaultConstructor() && 49620b57cec5SDimitry Andric !RD->hasNonTrivialDefaultConstructor(); 49630b57cec5SDimitry Andric return false; 49640b57cec5SDimitry Andric case UTT_HasTrivialMoveConstructor: 49650b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 49660b57cec5SDimitry Andric // standard library headers. Specifically this is used as the logic 49670b57cec5SDimitry Andric // behind std::is_trivially_move_constructible (20.9.4.3). 49680b57cec5SDimitry Andric if (T.isPODType(C)) 49690b57cec5SDimitry Andric return true; 49700b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 49710b57cec5SDimitry Andric return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor(); 49720b57cec5SDimitry Andric return false; 49730b57cec5SDimitry Andric case UTT_HasTrivialCopy: 49740b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 49750b57cec5SDimitry Andric // If __is_pod (type) is true or type is a reference type then 49760b57cec5SDimitry Andric // the trait is true, else if type is a cv class or union type 49770b57cec5SDimitry Andric // with a trivial copy constructor ([class.copy]) then the trait 49780b57cec5SDimitry Andric // is true, else it is false. 49790b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType()) 49800b57cec5SDimitry Andric return true; 49810b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 49820b57cec5SDimitry Andric return RD->hasTrivialCopyConstructor() && 49830b57cec5SDimitry Andric !RD->hasNonTrivialCopyConstructor(); 49840b57cec5SDimitry Andric return false; 49850b57cec5SDimitry Andric case UTT_HasTrivialMoveAssign: 49860b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 49870b57cec5SDimitry Andric // standard library headers. Specifically it is used as the logic 49880b57cec5SDimitry Andric // behind std::is_trivially_move_assignable (20.9.4.3) 49890b57cec5SDimitry Andric if (T.isPODType(C)) 49900b57cec5SDimitry Andric return true; 49910b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 49920b57cec5SDimitry Andric return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment(); 49930b57cec5SDimitry Andric return false; 49940b57cec5SDimitry Andric case UTT_HasTrivialAssign: 49950b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 49960b57cec5SDimitry Andric // If type is const qualified or is a reference type then the 49970b57cec5SDimitry Andric // trait is false. Otherwise if __is_pod (type) is true then the 49980b57cec5SDimitry Andric // trait is true, else if type is a cv class or union type with 49990b57cec5SDimitry Andric // a trivial copy assignment ([class.copy]) then the trait is 50000b57cec5SDimitry Andric // true, else it is false. 50010b57cec5SDimitry Andric // Note: the const and reference restrictions are interesting, 50020b57cec5SDimitry Andric // given that const and reference members don't prevent a class 50030b57cec5SDimitry Andric // from having a trivial copy assignment operator (but do cause 50040b57cec5SDimitry Andric // errors if the copy assignment operator is actually used, q.v. 50050b57cec5SDimitry Andric // [class.copy]p12). 50060b57cec5SDimitry Andric 50070b57cec5SDimitry Andric if (T.isConstQualified()) 50080b57cec5SDimitry Andric return false; 50090b57cec5SDimitry Andric if (T.isPODType(C)) 50100b57cec5SDimitry Andric return true; 50110b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 50120b57cec5SDimitry Andric return RD->hasTrivialCopyAssignment() && 50130b57cec5SDimitry Andric !RD->hasNonTrivialCopyAssignment(); 50140b57cec5SDimitry Andric return false; 50150b57cec5SDimitry Andric case UTT_IsDestructible: 50160b57cec5SDimitry Andric case UTT_IsTriviallyDestructible: 50170b57cec5SDimitry Andric case UTT_IsNothrowDestructible: 50180b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 50190b57cec5SDimitry Andric // For reference types, is_destructible<T>::value is true. 50200b57cec5SDimitry Andric if (T->isReferenceType()) 50210b57cec5SDimitry Andric return true; 50220b57cec5SDimitry Andric 50230b57cec5SDimitry Andric // Objective-C++ ARC: autorelease types don't require destruction. 50240b57cec5SDimitry Andric if (T->isObjCLifetimeType() && 50250b57cec5SDimitry Andric T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 50260b57cec5SDimitry Andric return true; 50270b57cec5SDimitry Andric 50280b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 50290b57cec5SDimitry Andric // For incomplete types and function types, is_destructible<T>::value is 50300b57cec5SDimitry Andric // false. 50310b57cec5SDimitry Andric if (T->isIncompleteType() || T->isFunctionType()) 50320b57cec5SDimitry Andric return false; 50330b57cec5SDimitry Andric 50340b57cec5SDimitry Andric // A type that requires destruction (via a non-trivial destructor or ARC 50350b57cec5SDimitry Andric // lifetime semantics) is not trivially-destructible. 50360b57cec5SDimitry Andric if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) 50370b57cec5SDimitry Andric return false; 50380b57cec5SDimitry Andric 50390b57cec5SDimitry Andric // C++14 [meta.unary.prop]: 50400b57cec5SDimitry Andric // For object types and given U equal to remove_all_extents_t<T>, if the 50410b57cec5SDimitry Andric // expression std::declval<U&>().~U() is well-formed when treated as an 50420b57cec5SDimitry Andric // unevaluated operand (Clause 5), then is_destructible<T>::value is true 50430b57cec5SDimitry Andric if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 50440b57cec5SDimitry Andric CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); 50450b57cec5SDimitry Andric if (!Destructor) 50460b57cec5SDimitry Andric return false; 50470b57cec5SDimitry Andric // C++14 [dcl.fct.def.delete]p2: 50480b57cec5SDimitry Andric // A program that refers to a deleted function implicitly or 50490b57cec5SDimitry Andric // explicitly, other than to declare it, is ill-formed. 50500b57cec5SDimitry Andric if (Destructor->isDeleted()) 50510b57cec5SDimitry Andric return false; 50520b57cec5SDimitry Andric if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public) 50530b57cec5SDimitry Andric return false; 50540b57cec5SDimitry Andric if (UTT == UTT_IsNothrowDestructible) { 50555ffd83dbSDimitry Andric auto *CPT = Destructor->getType()->castAs<FunctionProtoType>(); 50560b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 50570b57cec5SDimitry Andric if (!CPT || !CPT->isNothrow()) 50580b57cec5SDimitry Andric return false; 50590b57cec5SDimitry Andric } 50600b57cec5SDimitry Andric } 50610b57cec5SDimitry Andric return true; 50620b57cec5SDimitry Andric 50630b57cec5SDimitry Andric case UTT_HasTrivialDestructor: 50640b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 50650b57cec5SDimitry Andric // If __is_pod (type) is true or type is a reference type 50660b57cec5SDimitry Andric // then the trait is true, else if type is a cv class or union 50670b57cec5SDimitry Andric // type (or array thereof) with a trivial destructor 50680b57cec5SDimitry Andric // ([class.dtor]) then the trait is true, else it is 50690b57cec5SDimitry Andric // false. 50700b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType()) 50710b57cec5SDimitry Andric return true; 50720b57cec5SDimitry Andric 50730b57cec5SDimitry Andric // Objective-C++ ARC: autorelease types don't require destruction. 50740b57cec5SDimitry Andric if (T->isObjCLifetimeType() && 50750b57cec5SDimitry Andric T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) 50760b57cec5SDimitry Andric return true; 50770b57cec5SDimitry Andric 50780b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) 50790b57cec5SDimitry Andric return RD->hasTrivialDestructor(); 50800b57cec5SDimitry Andric return false; 50810b57cec5SDimitry Andric // TODO: Propagate nothrowness for implicitly declared special members. 50820b57cec5SDimitry Andric case UTT_HasNothrowAssign: 50830b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 50840b57cec5SDimitry Andric // If type is const qualified or is a reference type then the 50850b57cec5SDimitry Andric // trait is false. Otherwise if __has_trivial_assign (type) 50860b57cec5SDimitry Andric // is true then the trait is true, else if type is a cv class 50870b57cec5SDimitry Andric // or union type with copy assignment operators that are known 50880b57cec5SDimitry Andric // not to throw an exception then the trait is true, else it is 50890b57cec5SDimitry Andric // false. 50900b57cec5SDimitry Andric if (C.getBaseElementType(T).isConstQualified()) 50910b57cec5SDimitry Andric return false; 50920b57cec5SDimitry Andric if (T->isReferenceType()) 50930b57cec5SDimitry Andric return false; 50940b57cec5SDimitry Andric if (T.isPODType(C) || T->isObjCLifetimeType()) 50950b57cec5SDimitry Andric return true; 50960b57cec5SDimitry Andric 50970b57cec5SDimitry Andric if (const RecordType *RT = T->getAs<RecordType>()) 50980b57cec5SDimitry Andric return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 50990b57cec5SDimitry Andric &CXXRecordDecl::hasTrivialCopyAssignment, 51000b57cec5SDimitry Andric &CXXRecordDecl::hasNonTrivialCopyAssignment, 51010b57cec5SDimitry Andric &CXXMethodDecl::isCopyAssignmentOperator); 51020b57cec5SDimitry Andric return false; 51030b57cec5SDimitry Andric case UTT_HasNothrowMoveAssign: 51040b57cec5SDimitry Andric // This trait is implemented by MSVC 2012 and needed to parse the 51050b57cec5SDimitry Andric // standard library headers. Specifically this is used as the logic 51060b57cec5SDimitry Andric // behind std::is_nothrow_move_assignable (20.9.4.3). 51070b57cec5SDimitry Andric if (T.isPODType(C)) 51080b57cec5SDimitry Andric return true; 51090b57cec5SDimitry Andric 51100b57cec5SDimitry Andric if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) 51110b57cec5SDimitry Andric return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C, 51120b57cec5SDimitry Andric &CXXRecordDecl::hasTrivialMoveAssignment, 51130b57cec5SDimitry Andric &CXXRecordDecl::hasNonTrivialMoveAssignment, 51140b57cec5SDimitry Andric &CXXMethodDecl::isMoveAssignmentOperator); 51150b57cec5SDimitry Andric return false; 51160b57cec5SDimitry Andric case UTT_HasNothrowCopy: 51170b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 51180b57cec5SDimitry Andric // If __has_trivial_copy (type) is true then the trait is true, else 51190b57cec5SDimitry Andric // if type is a cv class or union type with copy constructors that are 51200b57cec5SDimitry Andric // known not to throw an exception then the trait is true, else it is 51210b57cec5SDimitry Andric // false. 51220b57cec5SDimitry Andric if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType()) 51230b57cec5SDimitry Andric return true; 51240b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 51250b57cec5SDimitry Andric if (RD->hasTrivialCopyConstructor() && 51260b57cec5SDimitry Andric !RD->hasNonTrivialCopyConstructor()) 51270b57cec5SDimitry Andric return true; 51280b57cec5SDimitry Andric 51290b57cec5SDimitry Andric bool FoundConstructor = false; 51300b57cec5SDimitry Andric unsigned FoundTQs; 51310b57cec5SDimitry Andric for (const auto *ND : Self.LookupConstructors(RD)) { 51320b57cec5SDimitry Andric // A template constructor is never a copy constructor. 51330b57cec5SDimitry Andric // FIXME: However, it may actually be selected at the actual overload 51340b57cec5SDimitry Andric // resolution point. 51350b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 51360b57cec5SDimitry Andric continue; 51370b57cec5SDimitry Andric // UsingDecl itself is not a constructor 51380b57cec5SDimitry Andric if (isa<UsingDecl>(ND)) 51390b57cec5SDimitry Andric continue; 51400b57cec5SDimitry Andric auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 51410b57cec5SDimitry Andric if (Constructor->isCopyConstructor(FoundTQs)) { 51420b57cec5SDimitry Andric FoundConstructor = true; 51435ffd83dbSDimitry Andric auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 51440b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 51450b57cec5SDimitry Andric if (!CPT) 51460b57cec5SDimitry Andric return false; 51470b57cec5SDimitry Andric // TODO: check whether evaluating default arguments can throw. 51480b57cec5SDimitry Andric // For now, we'll be conservative and assume that they can throw. 51490b57cec5SDimitry Andric if (!CPT->isNothrow() || CPT->getNumParams() > 1) 51500b57cec5SDimitry Andric return false; 51510b57cec5SDimitry Andric } 51520b57cec5SDimitry Andric } 51530b57cec5SDimitry Andric 51540b57cec5SDimitry Andric return FoundConstructor; 51550b57cec5SDimitry Andric } 51560b57cec5SDimitry Andric return false; 51570b57cec5SDimitry Andric case UTT_HasNothrowConstructor: 51580b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html 51590b57cec5SDimitry Andric // If __has_trivial_constructor (type) is true then the trait is 51600b57cec5SDimitry Andric // true, else if type is a cv class or union type (or array 51610b57cec5SDimitry Andric // thereof) with a default constructor that is known not to 51620b57cec5SDimitry Andric // throw an exception then the trait is true, else it is false. 51630b57cec5SDimitry Andric if (T.isPODType(C) || T->isObjCLifetimeType()) 51640b57cec5SDimitry Andric return true; 51650b57cec5SDimitry Andric if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { 51660b57cec5SDimitry Andric if (RD->hasTrivialDefaultConstructor() && 51670b57cec5SDimitry Andric !RD->hasNonTrivialDefaultConstructor()) 51680b57cec5SDimitry Andric return true; 51690b57cec5SDimitry Andric 51700b57cec5SDimitry Andric bool FoundConstructor = false; 51710b57cec5SDimitry Andric for (const auto *ND : Self.LookupConstructors(RD)) { 51720b57cec5SDimitry Andric // FIXME: In C++0x, a constructor template can be a default constructor. 51730b57cec5SDimitry Andric if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) 51740b57cec5SDimitry Andric continue; 51750b57cec5SDimitry Andric // UsingDecl itself is not a constructor 51760b57cec5SDimitry Andric if (isa<UsingDecl>(ND)) 51770b57cec5SDimitry Andric continue; 51780b57cec5SDimitry Andric auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl()); 51790b57cec5SDimitry Andric if (Constructor->isDefaultConstructor()) { 51800b57cec5SDimitry Andric FoundConstructor = true; 51815ffd83dbSDimitry Andric auto *CPT = Constructor->getType()->castAs<FunctionProtoType>(); 51820b57cec5SDimitry Andric CPT = Self.ResolveExceptionSpec(KeyLoc, CPT); 51830b57cec5SDimitry Andric if (!CPT) 51840b57cec5SDimitry Andric return false; 51850b57cec5SDimitry Andric // FIXME: check whether evaluating default arguments can throw. 51860b57cec5SDimitry Andric // For now, we'll be conservative and assume that they can throw. 51870b57cec5SDimitry Andric if (!CPT->isNothrow() || CPT->getNumParams() > 0) 51880b57cec5SDimitry Andric return false; 51890b57cec5SDimitry Andric } 51900b57cec5SDimitry Andric } 51910b57cec5SDimitry Andric return FoundConstructor; 51920b57cec5SDimitry Andric } 51930b57cec5SDimitry Andric return false; 51940b57cec5SDimitry Andric case UTT_HasVirtualDestructor: 51950b57cec5SDimitry Andric // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html: 51960b57cec5SDimitry Andric // If type is a class type with a virtual destructor ([class.dtor]) 51970b57cec5SDimitry Andric // then the trait is true, else it is false. 51980b57cec5SDimitry Andric if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 51990b57cec5SDimitry Andric if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) 52000b57cec5SDimitry Andric return Destructor->isVirtual(); 52010b57cec5SDimitry Andric return false; 52020b57cec5SDimitry Andric 52030b57cec5SDimitry Andric // These type trait expressions are modeled on the specifications for the 52040b57cec5SDimitry Andric // Embarcadero C++0x type trait functions: 52050b57cec5SDimitry Andric // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index 52060b57cec5SDimitry Andric case UTT_IsCompleteType: 52070b57cec5SDimitry Andric // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_): 52080b57cec5SDimitry Andric // Returns True if and only if T is a complete type at the point of the 52090b57cec5SDimitry Andric // function call. 52100b57cec5SDimitry Andric return !T->isIncompleteType(); 52110b57cec5SDimitry Andric case UTT_HasUniqueObjectRepresentations: 52120b57cec5SDimitry Andric return C.hasUniqueObjectRepresentations(T); 52130b57cec5SDimitry Andric } 52140b57cec5SDimitry Andric } 52150b57cec5SDimitry Andric 52160b57cec5SDimitry Andric static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 52170b57cec5SDimitry Andric QualType RhsT, SourceLocation KeyLoc); 52180b57cec5SDimitry Andric 52190b57cec5SDimitry Andric static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc, 52200b57cec5SDimitry Andric ArrayRef<TypeSourceInfo *> Args, 52210b57cec5SDimitry Andric SourceLocation RParenLoc) { 52220b57cec5SDimitry Andric if (Kind <= UTT_Last) 52230b57cec5SDimitry Andric return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType()); 52240b57cec5SDimitry Andric 52250b57cec5SDimitry Andric // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible 52260b57cec5SDimitry Andric // traits to avoid duplication. 52270b57cec5SDimitry Andric if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary) 52280b57cec5SDimitry Andric return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(), 52290b57cec5SDimitry Andric Args[1]->getType(), RParenLoc); 52300b57cec5SDimitry Andric 52310b57cec5SDimitry Andric switch (Kind) { 52320b57cec5SDimitry Andric case clang::BTT_ReferenceBindsToTemporary: 52330b57cec5SDimitry Andric case clang::TT_IsConstructible: 52340b57cec5SDimitry Andric case clang::TT_IsNothrowConstructible: 52350b57cec5SDimitry Andric case clang::TT_IsTriviallyConstructible: { 52360b57cec5SDimitry Andric // C++11 [meta.unary.prop]: 52370b57cec5SDimitry Andric // is_trivially_constructible is defined as: 52380b57cec5SDimitry Andric // 52390b57cec5SDimitry Andric // is_constructible<T, Args...>::value is true and the variable 52400b57cec5SDimitry Andric // definition for is_constructible, as defined below, is known to call 52410b57cec5SDimitry Andric // no operation that is not trivial. 52420b57cec5SDimitry Andric // 52430b57cec5SDimitry Andric // The predicate condition for a template specialization 52440b57cec5SDimitry Andric // is_constructible<T, Args...> shall be satisfied if and only if the 52450b57cec5SDimitry Andric // following variable definition would be well-formed for some invented 52460b57cec5SDimitry Andric // variable t: 52470b57cec5SDimitry Andric // 52480b57cec5SDimitry Andric // T t(create<Args>()...); 52490b57cec5SDimitry Andric assert(!Args.empty()); 52500b57cec5SDimitry Andric 52510b57cec5SDimitry Andric // Precondition: T and all types in the parameter pack Args shall be 52520b57cec5SDimitry Andric // complete types, (possibly cv-qualified) void, or arrays of 52530b57cec5SDimitry Andric // unknown bound. 52540b57cec5SDimitry Andric for (const auto *TSI : Args) { 52550b57cec5SDimitry Andric QualType ArgTy = TSI->getType(); 52560b57cec5SDimitry Andric if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType()) 52570b57cec5SDimitry Andric continue; 52580b57cec5SDimitry Andric 52590b57cec5SDimitry Andric if (S.RequireCompleteType(KWLoc, ArgTy, 52600b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 52610b57cec5SDimitry Andric return false; 52620b57cec5SDimitry Andric } 52630b57cec5SDimitry Andric 52640b57cec5SDimitry Andric // Make sure the first argument is not incomplete nor a function type. 52650b57cec5SDimitry Andric QualType T = Args[0]->getType(); 52660b57cec5SDimitry Andric if (T->isIncompleteType() || T->isFunctionType()) 52670b57cec5SDimitry Andric return false; 52680b57cec5SDimitry Andric 52690b57cec5SDimitry Andric // Make sure the first argument is not an abstract type. 52700b57cec5SDimitry Andric CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 52710b57cec5SDimitry Andric if (RD && RD->isAbstract()) 52720b57cec5SDimitry Andric return false; 52730b57cec5SDimitry Andric 52745ffd83dbSDimitry Andric llvm::BumpPtrAllocator OpaqueExprAllocator; 52750b57cec5SDimitry Andric SmallVector<Expr *, 2> ArgExprs; 52760b57cec5SDimitry Andric ArgExprs.reserve(Args.size() - 1); 52770b57cec5SDimitry Andric for (unsigned I = 1, N = Args.size(); I != N; ++I) { 52780b57cec5SDimitry Andric QualType ArgTy = Args[I]->getType(); 52790b57cec5SDimitry Andric if (ArgTy->isObjectType() || ArgTy->isFunctionType()) 52800b57cec5SDimitry Andric ArgTy = S.Context.getRValueReferenceType(ArgTy); 52815ffd83dbSDimitry Andric ArgExprs.push_back( 52825ffd83dbSDimitry Andric new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>()) 52830b57cec5SDimitry Andric OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(), 52840b57cec5SDimitry Andric ArgTy.getNonLValueExprType(S.Context), 52850b57cec5SDimitry Andric Expr::getValueKindForType(ArgTy))); 52860b57cec5SDimitry Andric } 52870b57cec5SDimitry Andric 52880b57cec5SDimitry Andric // Perform the initialization in an unevaluated context within a SFINAE 52890b57cec5SDimitry Andric // trap at translation unit scope. 52900b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 52910b57cec5SDimitry Andric S, Sema::ExpressionEvaluationContext::Unevaluated); 52920b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true); 52930b57cec5SDimitry Andric Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl()); 5294349cc55cSDimitry Andric InitializedEntity To( 5295349cc55cSDimitry Andric InitializedEntity::InitializeTemporary(S.Context, Args[0])); 52960b57cec5SDimitry Andric InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc, 52970b57cec5SDimitry Andric RParenLoc)); 52980b57cec5SDimitry Andric InitializationSequence Init(S, To, InitKind, ArgExprs); 52990b57cec5SDimitry Andric if (Init.Failed()) 53000b57cec5SDimitry Andric return false; 53010b57cec5SDimitry Andric 53020b57cec5SDimitry Andric ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs); 53030b57cec5SDimitry Andric if (Result.isInvalid() || SFINAE.hasErrorOccurred()) 53040b57cec5SDimitry Andric return false; 53050b57cec5SDimitry Andric 53060b57cec5SDimitry Andric if (Kind == clang::TT_IsConstructible) 53070b57cec5SDimitry Andric return true; 53080b57cec5SDimitry Andric 53090b57cec5SDimitry Andric if (Kind == clang::BTT_ReferenceBindsToTemporary) { 53100b57cec5SDimitry Andric if (!T->isReferenceType()) 53110b57cec5SDimitry Andric return false; 53120b57cec5SDimitry Andric 53130b57cec5SDimitry Andric return !Init.isDirectReferenceBinding(); 53140b57cec5SDimitry Andric } 53150b57cec5SDimitry Andric 53160b57cec5SDimitry Andric if (Kind == clang::TT_IsNothrowConstructible) 53170b57cec5SDimitry Andric return S.canThrow(Result.get()) == CT_Cannot; 53180b57cec5SDimitry Andric 53190b57cec5SDimitry Andric if (Kind == clang::TT_IsTriviallyConstructible) { 53200b57cec5SDimitry Andric // Under Objective-C ARC and Weak, if the destination has non-trivial 53210b57cec5SDimitry Andric // Objective-C lifetime, this is a non-trivial construction. 53220b57cec5SDimitry Andric if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) 53230b57cec5SDimitry Andric return false; 53240b57cec5SDimitry Andric 53250b57cec5SDimitry Andric // The initialization succeeded; now make sure there are no non-trivial 53260b57cec5SDimitry Andric // calls. 53270b57cec5SDimitry Andric return !Result.get()->hasNonTrivialCall(S.Context); 53280b57cec5SDimitry Andric } 53290b57cec5SDimitry Andric 53300b57cec5SDimitry Andric llvm_unreachable("unhandled type trait"); 53310b57cec5SDimitry Andric return false; 53320b57cec5SDimitry Andric } 53330b57cec5SDimitry Andric default: llvm_unreachable("not a TT"); 53340b57cec5SDimitry Andric } 53350b57cec5SDimitry Andric 53360b57cec5SDimitry Andric return false; 53370b57cec5SDimitry Andric } 53380b57cec5SDimitry Andric 53390b57cec5SDimitry Andric ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 53400b57cec5SDimitry Andric ArrayRef<TypeSourceInfo *> Args, 53410b57cec5SDimitry Andric SourceLocation RParenLoc) { 53420b57cec5SDimitry Andric QualType ResultType = Context.getLogicalOperationType(); 53430b57cec5SDimitry Andric 53440b57cec5SDimitry Andric if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness( 53450b57cec5SDimitry Andric *this, Kind, KWLoc, Args[0]->getType())) 53460b57cec5SDimitry Andric return ExprError(); 53470b57cec5SDimitry Andric 53480b57cec5SDimitry Andric bool Dependent = false; 53490b57cec5SDimitry Andric for (unsigned I = 0, N = Args.size(); I != N; ++I) { 53500b57cec5SDimitry Andric if (Args[I]->getType()->isDependentType()) { 53510b57cec5SDimitry Andric Dependent = true; 53520b57cec5SDimitry Andric break; 53530b57cec5SDimitry Andric } 53540b57cec5SDimitry Andric } 53550b57cec5SDimitry Andric 53560b57cec5SDimitry Andric bool Result = false; 53570b57cec5SDimitry Andric if (!Dependent) 53580b57cec5SDimitry Andric Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc); 53590b57cec5SDimitry Andric 53600b57cec5SDimitry Andric return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args, 53610b57cec5SDimitry Andric RParenLoc, Result); 53620b57cec5SDimitry Andric } 53630b57cec5SDimitry Andric 53640b57cec5SDimitry Andric ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 53650b57cec5SDimitry Andric ArrayRef<ParsedType> Args, 53660b57cec5SDimitry Andric SourceLocation RParenLoc) { 53670b57cec5SDimitry Andric SmallVector<TypeSourceInfo *, 4> ConvertedArgs; 53680b57cec5SDimitry Andric ConvertedArgs.reserve(Args.size()); 53690b57cec5SDimitry Andric 53700b57cec5SDimitry Andric for (unsigned I = 0, N = Args.size(); I != N; ++I) { 53710b57cec5SDimitry Andric TypeSourceInfo *TInfo; 53720b57cec5SDimitry Andric QualType T = GetTypeFromParser(Args[I], &TInfo); 53730b57cec5SDimitry Andric if (!TInfo) 53740b57cec5SDimitry Andric TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc); 53750b57cec5SDimitry Andric 53760b57cec5SDimitry Andric ConvertedArgs.push_back(TInfo); 53770b57cec5SDimitry Andric } 53780b57cec5SDimitry Andric 53790b57cec5SDimitry Andric return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc); 53800b57cec5SDimitry Andric } 53810b57cec5SDimitry Andric 53820b57cec5SDimitry Andric static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, 53830b57cec5SDimitry Andric QualType RhsT, SourceLocation KeyLoc) { 53840b57cec5SDimitry Andric assert(!LhsT->isDependentType() && !RhsT->isDependentType() && 53850b57cec5SDimitry Andric "Cannot evaluate traits of dependent types"); 53860b57cec5SDimitry Andric 53870b57cec5SDimitry Andric switch(BTT) { 53880b57cec5SDimitry Andric case BTT_IsBaseOf: { 53890b57cec5SDimitry Andric // C++0x [meta.rel]p2 53900b57cec5SDimitry Andric // Base is a base class of Derived without regard to cv-qualifiers or 53910b57cec5SDimitry Andric // Base and Derived are not unions and name the same class type without 53920b57cec5SDimitry Andric // regard to cv-qualifiers. 53930b57cec5SDimitry Andric 53940b57cec5SDimitry Andric const RecordType *lhsRecord = LhsT->getAs<RecordType>(); 53950b57cec5SDimitry Andric const RecordType *rhsRecord = RhsT->getAs<RecordType>(); 53960b57cec5SDimitry Andric if (!rhsRecord || !lhsRecord) { 53970b57cec5SDimitry Andric const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>(); 53980b57cec5SDimitry Andric const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>(); 53990b57cec5SDimitry Andric if (!LHSObjTy || !RHSObjTy) 54000b57cec5SDimitry Andric return false; 54010b57cec5SDimitry Andric 54020b57cec5SDimitry Andric ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface(); 54030b57cec5SDimitry Andric ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface(); 54040b57cec5SDimitry Andric if (!BaseInterface || !DerivedInterface) 54050b57cec5SDimitry Andric return false; 54060b57cec5SDimitry Andric 54070b57cec5SDimitry Andric if (Self.RequireCompleteType( 54080b57cec5SDimitry Andric KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr)) 54090b57cec5SDimitry Andric return false; 54100b57cec5SDimitry Andric 54110b57cec5SDimitry Andric return BaseInterface->isSuperClassOf(DerivedInterface); 54120b57cec5SDimitry Andric } 54130b57cec5SDimitry Andric 54140b57cec5SDimitry Andric assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT) 54150b57cec5SDimitry Andric == (lhsRecord == rhsRecord)); 54160b57cec5SDimitry Andric 54170b57cec5SDimitry Andric // Unions are never base classes, and never have base classes. 54180b57cec5SDimitry Andric // It doesn't matter if they are complete or not. See PR#41843 54190b57cec5SDimitry Andric if (lhsRecord && lhsRecord->getDecl()->isUnion()) 54200b57cec5SDimitry Andric return false; 54210b57cec5SDimitry Andric if (rhsRecord && rhsRecord->getDecl()->isUnion()) 54220b57cec5SDimitry Andric return false; 54230b57cec5SDimitry Andric 54240b57cec5SDimitry Andric if (lhsRecord == rhsRecord) 54250b57cec5SDimitry Andric return true; 54260b57cec5SDimitry Andric 54270b57cec5SDimitry Andric // C++0x [meta.rel]p2: 54280b57cec5SDimitry Andric // If Base and Derived are class types and are different types 54290b57cec5SDimitry Andric // (ignoring possible cv-qualifiers) then Derived shall be a 54300b57cec5SDimitry Andric // complete type. 54310b57cec5SDimitry Andric if (Self.RequireCompleteType(KeyLoc, RhsT, 54320b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 54330b57cec5SDimitry Andric return false; 54340b57cec5SDimitry Andric 54350b57cec5SDimitry Andric return cast<CXXRecordDecl>(rhsRecord->getDecl()) 54360b57cec5SDimitry Andric ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl())); 54370b57cec5SDimitry Andric } 54380b57cec5SDimitry Andric case BTT_IsSame: 54390b57cec5SDimitry Andric return Self.Context.hasSameType(LhsT, RhsT); 54400b57cec5SDimitry Andric case BTT_TypeCompatible: { 54410b57cec5SDimitry Andric // GCC ignores cv-qualifiers on arrays for this builtin. 54420b57cec5SDimitry Andric Qualifiers LhsQuals, RhsQuals; 54430b57cec5SDimitry Andric QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals); 54440b57cec5SDimitry Andric QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals); 54450b57cec5SDimitry Andric return Self.Context.typesAreCompatible(Lhs, Rhs); 54460b57cec5SDimitry Andric } 54470b57cec5SDimitry Andric case BTT_IsConvertible: 54480b57cec5SDimitry Andric case BTT_IsConvertibleTo: { 54490b57cec5SDimitry Andric // C++0x [meta.rel]p4: 54500b57cec5SDimitry Andric // Given the following function prototype: 54510b57cec5SDimitry Andric // 54520b57cec5SDimitry Andric // template <class T> 54530b57cec5SDimitry Andric // typename add_rvalue_reference<T>::type create(); 54540b57cec5SDimitry Andric // 54550b57cec5SDimitry Andric // the predicate condition for a template specialization 54560b57cec5SDimitry Andric // is_convertible<From, To> shall be satisfied if and only if 54570b57cec5SDimitry Andric // the return expression in the following code would be 54580b57cec5SDimitry Andric // well-formed, including any implicit conversions to the return 54590b57cec5SDimitry Andric // type of the function: 54600b57cec5SDimitry Andric // 54610b57cec5SDimitry Andric // To test() { 54620b57cec5SDimitry Andric // return create<From>(); 54630b57cec5SDimitry Andric // } 54640b57cec5SDimitry Andric // 54650b57cec5SDimitry Andric // Access checking is performed as if in a context unrelated to To and 54660b57cec5SDimitry Andric // From. Only the validity of the immediate context of the expression 54670b57cec5SDimitry Andric // of the return-statement (including conversions to the return type) 54680b57cec5SDimitry Andric // is considered. 54690b57cec5SDimitry Andric // 54700b57cec5SDimitry Andric // We model the initialization as a copy-initialization of a temporary 54710b57cec5SDimitry Andric // of the appropriate type, which for this expression is identical to the 54720b57cec5SDimitry Andric // return statement (since NRVO doesn't apply). 54730b57cec5SDimitry Andric 54740b57cec5SDimitry Andric // Functions aren't allowed to return function or array types. 54750b57cec5SDimitry Andric if (RhsT->isFunctionType() || RhsT->isArrayType()) 54760b57cec5SDimitry Andric return false; 54770b57cec5SDimitry Andric 54780b57cec5SDimitry Andric // A return statement in a void function must have void type. 54790b57cec5SDimitry Andric if (RhsT->isVoidType()) 54800b57cec5SDimitry Andric return LhsT->isVoidType(); 54810b57cec5SDimitry Andric 54820b57cec5SDimitry Andric // A function definition requires a complete, non-abstract return type. 54830b57cec5SDimitry Andric if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) 54840b57cec5SDimitry Andric return false; 54850b57cec5SDimitry Andric 54860b57cec5SDimitry Andric // Compute the result of add_rvalue_reference. 54870b57cec5SDimitry Andric if (LhsT->isObjectType() || LhsT->isFunctionType()) 54880b57cec5SDimitry Andric LhsT = Self.Context.getRValueReferenceType(LhsT); 54890b57cec5SDimitry Andric 54900b57cec5SDimitry Andric // Build a fake source and destination for initialization. 54910b57cec5SDimitry Andric InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT)); 54920b57cec5SDimitry Andric OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 54930b57cec5SDimitry Andric Expr::getValueKindForType(LhsT)); 54940b57cec5SDimitry Andric Expr *FromPtr = &From; 54950b57cec5SDimitry Andric InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc, 54960b57cec5SDimitry Andric SourceLocation())); 54970b57cec5SDimitry Andric 54980b57cec5SDimitry Andric // Perform the initialization in an unevaluated context within a SFINAE 54990b57cec5SDimitry Andric // trap at translation unit scope. 55000b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 55010b57cec5SDimitry Andric Self, Sema::ExpressionEvaluationContext::Unevaluated); 55020b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 55030b57cec5SDimitry Andric Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 55040b57cec5SDimitry Andric InitializationSequence Init(Self, To, Kind, FromPtr); 55050b57cec5SDimitry Andric if (Init.Failed()) 55060b57cec5SDimitry Andric return false; 55070b57cec5SDimitry Andric 55080b57cec5SDimitry Andric ExprResult Result = Init.Perform(Self, To, Kind, FromPtr); 55090b57cec5SDimitry Andric return !Result.isInvalid() && !SFINAE.hasErrorOccurred(); 55100b57cec5SDimitry Andric } 55110b57cec5SDimitry Andric 55120b57cec5SDimitry Andric case BTT_IsAssignable: 55130b57cec5SDimitry Andric case BTT_IsNothrowAssignable: 55140b57cec5SDimitry Andric case BTT_IsTriviallyAssignable: { 55150b57cec5SDimitry Andric // C++11 [meta.unary.prop]p3: 55160b57cec5SDimitry Andric // is_trivially_assignable is defined as: 55170b57cec5SDimitry Andric // is_assignable<T, U>::value is true and the assignment, as defined by 55180b57cec5SDimitry Andric // is_assignable, is known to call no operation that is not trivial 55190b57cec5SDimitry Andric // 55200b57cec5SDimitry Andric // is_assignable is defined as: 55210b57cec5SDimitry Andric // The expression declval<T>() = declval<U>() is well-formed when 55220b57cec5SDimitry Andric // treated as an unevaluated operand (Clause 5). 55230b57cec5SDimitry Andric // 55240b57cec5SDimitry Andric // For both, T and U shall be complete types, (possibly cv-qualified) 55250b57cec5SDimitry Andric // void, or arrays of unknown bound. 55260b57cec5SDimitry Andric if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() && 55270b57cec5SDimitry Andric Self.RequireCompleteType(KeyLoc, LhsT, 55280b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 55290b57cec5SDimitry Andric return false; 55300b57cec5SDimitry Andric if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() && 55310b57cec5SDimitry Andric Self.RequireCompleteType(KeyLoc, RhsT, 55320b57cec5SDimitry Andric diag::err_incomplete_type_used_in_type_trait_expr)) 55330b57cec5SDimitry Andric return false; 55340b57cec5SDimitry Andric 55350b57cec5SDimitry Andric // cv void is never assignable. 55360b57cec5SDimitry Andric if (LhsT->isVoidType() || RhsT->isVoidType()) 55370b57cec5SDimitry Andric return false; 55380b57cec5SDimitry Andric 55390b57cec5SDimitry Andric // Build expressions that emulate the effect of declval<T>() and 55400b57cec5SDimitry Andric // declval<U>(). 55410b57cec5SDimitry Andric if (LhsT->isObjectType() || LhsT->isFunctionType()) 55420b57cec5SDimitry Andric LhsT = Self.Context.getRValueReferenceType(LhsT); 55430b57cec5SDimitry Andric if (RhsT->isObjectType() || RhsT->isFunctionType()) 55440b57cec5SDimitry Andric RhsT = Self.Context.getRValueReferenceType(RhsT); 55450b57cec5SDimitry Andric OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context), 55460b57cec5SDimitry Andric Expr::getValueKindForType(LhsT)); 55470b57cec5SDimitry Andric OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context), 55480b57cec5SDimitry Andric Expr::getValueKindForType(RhsT)); 55490b57cec5SDimitry Andric 55500b57cec5SDimitry Andric // Attempt the assignment in an unevaluated context within a SFINAE 55510b57cec5SDimitry Andric // trap at translation unit scope. 55520b57cec5SDimitry Andric EnterExpressionEvaluationContext Unevaluated( 55530b57cec5SDimitry Andric Self, Sema::ExpressionEvaluationContext::Unevaluated); 55540b57cec5SDimitry Andric Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true); 55550b57cec5SDimitry Andric Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); 55560b57cec5SDimitry Andric ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs, 55570b57cec5SDimitry Andric &Rhs); 5558a7dea167SDimitry Andric if (Result.isInvalid()) 5559a7dea167SDimitry Andric return false; 5560a7dea167SDimitry Andric 5561a7dea167SDimitry Andric // Treat the assignment as unused for the purpose of -Wdeprecated-volatile. 5562a7dea167SDimitry Andric Self.CheckUnusedVolatileAssignment(Result.get()); 5563a7dea167SDimitry Andric 5564a7dea167SDimitry Andric if (SFINAE.hasErrorOccurred()) 55650b57cec5SDimitry Andric return false; 55660b57cec5SDimitry Andric 55670b57cec5SDimitry Andric if (BTT == BTT_IsAssignable) 55680b57cec5SDimitry Andric return true; 55690b57cec5SDimitry Andric 55700b57cec5SDimitry Andric if (BTT == BTT_IsNothrowAssignable) 55710b57cec5SDimitry Andric return Self.canThrow(Result.get()) == CT_Cannot; 55720b57cec5SDimitry Andric 55730b57cec5SDimitry Andric if (BTT == BTT_IsTriviallyAssignable) { 55740b57cec5SDimitry Andric // Under Objective-C ARC and Weak, if the destination has non-trivial 55750b57cec5SDimitry Andric // Objective-C lifetime, this is a non-trivial assignment. 55760b57cec5SDimitry Andric if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) 55770b57cec5SDimitry Andric return false; 55780b57cec5SDimitry Andric 55790b57cec5SDimitry Andric return !Result.get()->hasNonTrivialCall(Self.Context); 55800b57cec5SDimitry Andric } 55810b57cec5SDimitry Andric 55820b57cec5SDimitry Andric llvm_unreachable("unhandled type trait"); 55830b57cec5SDimitry Andric return false; 55840b57cec5SDimitry Andric } 55850b57cec5SDimitry Andric default: llvm_unreachable("not a BTT"); 55860b57cec5SDimitry Andric } 55870b57cec5SDimitry Andric llvm_unreachable("Unknown type trait or not implemented"); 55880b57cec5SDimitry Andric } 55890b57cec5SDimitry Andric 55900b57cec5SDimitry Andric ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT, 55910b57cec5SDimitry Andric SourceLocation KWLoc, 55920b57cec5SDimitry Andric ParsedType Ty, 55930b57cec5SDimitry Andric Expr* DimExpr, 55940b57cec5SDimitry Andric SourceLocation RParen) { 55950b57cec5SDimitry Andric TypeSourceInfo *TSInfo; 55960b57cec5SDimitry Andric QualType T = GetTypeFromParser(Ty, &TSInfo); 55970b57cec5SDimitry Andric if (!TSInfo) 55980b57cec5SDimitry Andric TSInfo = Context.getTrivialTypeSourceInfo(T); 55990b57cec5SDimitry Andric 56000b57cec5SDimitry Andric return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen); 56010b57cec5SDimitry Andric } 56020b57cec5SDimitry Andric 56030b57cec5SDimitry Andric static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT, 56040b57cec5SDimitry Andric QualType T, Expr *DimExpr, 56050b57cec5SDimitry Andric SourceLocation KeyLoc) { 56060b57cec5SDimitry Andric assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); 56070b57cec5SDimitry Andric 56080b57cec5SDimitry Andric switch(ATT) { 56090b57cec5SDimitry Andric case ATT_ArrayRank: 56100b57cec5SDimitry Andric if (T->isArrayType()) { 56110b57cec5SDimitry Andric unsigned Dim = 0; 56120b57cec5SDimitry Andric while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 56130b57cec5SDimitry Andric ++Dim; 56140b57cec5SDimitry Andric T = AT->getElementType(); 56150b57cec5SDimitry Andric } 56160b57cec5SDimitry Andric return Dim; 56170b57cec5SDimitry Andric } 56180b57cec5SDimitry Andric return 0; 56190b57cec5SDimitry Andric 56200b57cec5SDimitry Andric case ATT_ArrayExtent: { 56210b57cec5SDimitry Andric llvm::APSInt Value; 56220b57cec5SDimitry Andric uint64_t Dim; 5623e8d8bef9SDimitry Andric if (Self.VerifyIntegerConstantExpression( 5624e8d8bef9SDimitry Andric DimExpr, &Value, diag::err_dimension_expr_not_constant_integer) 5625e8d8bef9SDimitry Andric .isInvalid()) 56260b57cec5SDimitry Andric return 0; 56270b57cec5SDimitry Andric if (Value.isSigned() && Value.isNegative()) { 56280b57cec5SDimitry Andric Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer) 56290b57cec5SDimitry Andric << DimExpr->getSourceRange(); 56300b57cec5SDimitry Andric return 0; 56310b57cec5SDimitry Andric } 56320b57cec5SDimitry Andric Dim = Value.getLimitedValue(); 56330b57cec5SDimitry Andric 56340b57cec5SDimitry Andric if (T->isArrayType()) { 56350b57cec5SDimitry Andric unsigned D = 0; 56360b57cec5SDimitry Andric bool Matched = false; 56370b57cec5SDimitry Andric while (const ArrayType *AT = Self.Context.getAsArrayType(T)) { 56380b57cec5SDimitry Andric if (Dim == D) { 56390b57cec5SDimitry Andric Matched = true; 56400b57cec5SDimitry Andric break; 56410b57cec5SDimitry Andric } 56420b57cec5SDimitry Andric ++D; 56430b57cec5SDimitry Andric T = AT->getElementType(); 56440b57cec5SDimitry Andric } 56450b57cec5SDimitry Andric 56460b57cec5SDimitry Andric if (Matched && T->isArrayType()) { 56470b57cec5SDimitry Andric if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T)) 56480b57cec5SDimitry Andric return CAT->getSize().getLimitedValue(); 56490b57cec5SDimitry Andric } 56500b57cec5SDimitry Andric } 56510b57cec5SDimitry Andric return 0; 56520b57cec5SDimitry Andric } 56530b57cec5SDimitry Andric } 56540b57cec5SDimitry Andric llvm_unreachable("Unknown type trait or not implemented"); 56550b57cec5SDimitry Andric } 56560b57cec5SDimitry Andric 56570b57cec5SDimitry Andric ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, 56580b57cec5SDimitry Andric SourceLocation KWLoc, 56590b57cec5SDimitry Andric TypeSourceInfo *TSInfo, 56600b57cec5SDimitry Andric Expr* DimExpr, 56610b57cec5SDimitry Andric SourceLocation RParen) { 56620b57cec5SDimitry Andric QualType T = TSInfo->getType(); 56630b57cec5SDimitry Andric 56640b57cec5SDimitry Andric // FIXME: This should likely be tracked as an APInt to remove any host 56650b57cec5SDimitry Andric // assumptions about the width of size_t on the target. 56660b57cec5SDimitry Andric uint64_t Value = 0; 56670b57cec5SDimitry Andric if (!T->isDependentType()) 56680b57cec5SDimitry Andric Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); 56690b57cec5SDimitry Andric 56700b57cec5SDimitry Andric // While the specification for these traits from the Embarcadero C++ 56710b57cec5SDimitry Andric // compiler's documentation says the return type is 'unsigned int', Clang 56720b57cec5SDimitry Andric // returns 'size_t'. On Windows, the primary platform for the Embarcadero 56730b57cec5SDimitry Andric // compiler, there is no difference. On several other platforms this is an 56740b57cec5SDimitry Andric // important distinction. 56750b57cec5SDimitry Andric return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, 56760b57cec5SDimitry Andric RParen, Context.getSizeType()); 56770b57cec5SDimitry Andric } 56780b57cec5SDimitry Andric 56790b57cec5SDimitry Andric ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, 56800b57cec5SDimitry Andric SourceLocation KWLoc, 56810b57cec5SDimitry Andric Expr *Queried, 56820b57cec5SDimitry Andric SourceLocation RParen) { 56830b57cec5SDimitry Andric // If error parsing the expression, ignore. 56840b57cec5SDimitry Andric if (!Queried) 56850b57cec5SDimitry Andric return ExprError(); 56860b57cec5SDimitry Andric 56870b57cec5SDimitry Andric ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); 56880b57cec5SDimitry Andric 56890b57cec5SDimitry Andric return Result; 56900b57cec5SDimitry Andric } 56910b57cec5SDimitry Andric 56920b57cec5SDimitry Andric static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) { 56930b57cec5SDimitry Andric switch (ET) { 56940b57cec5SDimitry Andric case ET_IsLValueExpr: return E->isLValue(); 5695fe6060f1SDimitry Andric case ET_IsRValueExpr: 5696fe6060f1SDimitry Andric return E->isPRValue(); 56970b57cec5SDimitry Andric } 56980b57cec5SDimitry Andric llvm_unreachable("Expression trait not covered by switch"); 56990b57cec5SDimitry Andric } 57000b57cec5SDimitry Andric 57010b57cec5SDimitry Andric ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, 57020b57cec5SDimitry Andric SourceLocation KWLoc, 57030b57cec5SDimitry Andric Expr *Queried, 57040b57cec5SDimitry Andric SourceLocation RParen) { 57050b57cec5SDimitry Andric if (Queried->isTypeDependent()) { 57060b57cec5SDimitry Andric // Delay type-checking for type-dependent expressions. 57070b57cec5SDimitry Andric } else if (Queried->getType()->isPlaceholderType()) { 57080b57cec5SDimitry Andric ExprResult PE = CheckPlaceholderExpr(Queried); 57090b57cec5SDimitry Andric if (PE.isInvalid()) return ExprError(); 57100b57cec5SDimitry Andric return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen); 57110b57cec5SDimitry Andric } 57120b57cec5SDimitry Andric 57130b57cec5SDimitry Andric bool Value = EvaluateExpressionTrait(ET, Queried); 57140b57cec5SDimitry Andric 57150b57cec5SDimitry Andric return new (Context) 57160b57cec5SDimitry Andric ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy); 57170b57cec5SDimitry Andric } 57180b57cec5SDimitry Andric 57190b57cec5SDimitry Andric QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, 57200b57cec5SDimitry Andric ExprValueKind &VK, 57210b57cec5SDimitry Andric SourceLocation Loc, 57220b57cec5SDimitry Andric bool isIndirect) { 57230b57cec5SDimitry Andric assert(!LHS.get()->getType()->isPlaceholderType() && 57240b57cec5SDimitry Andric !RHS.get()->getType()->isPlaceholderType() && 57250b57cec5SDimitry Andric "placeholders should have been weeded out by now"); 57260b57cec5SDimitry Andric 57270b57cec5SDimitry Andric // The LHS undergoes lvalue conversions if this is ->*, and undergoes the 57280b57cec5SDimitry Andric // temporary materialization conversion otherwise. 57290b57cec5SDimitry Andric if (isIndirect) 57300b57cec5SDimitry Andric LHS = DefaultLvalueConversion(LHS.get()); 5731fe6060f1SDimitry Andric else if (LHS.get()->isPRValue()) 57320b57cec5SDimitry Andric LHS = TemporaryMaterializationConversion(LHS.get()); 57330b57cec5SDimitry Andric if (LHS.isInvalid()) 57340b57cec5SDimitry Andric return QualType(); 57350b57cec5SDimitry Andric 57360b57cec5SDimitry Andric // The RHS always undergoes lvalue conversions. 57370b57cec5SDimitry Andric RHS = DefaultLvalueConversion(RHS.get()); 57380b57cec5SDimitry Andric if (RHS.isInvalid()) return QualType(); 57390b57cec5SDimitry Andric 57400b57cec5SDimitry Andric const char *OpSpelling = isIndirect ? "->*" : ".*"; 57410b57cec5SDimitry Andric // C++ 5.5p2 57420b57cec5SDimitry Andric // The binary operator .* [p3: ->*] binds its second operand, which shall 57430b57cec5SDimitry Andric // be of type "pointer to member of T" (where T is a completely-defined 57440b57cec5SDimitry Andric // class type) [...] 57450b57cec5SDimitry Andric QualType RHSType = RHS.get()->getType(); 57460b57cec5SDimitry Andric const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); 57470b57cec5SDimitry Andric if (!MemPtr) { 57480b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_rhs) 57490b57cec5SDimitry Andric << OpSpelling << RHSType << RHS.get()->getSourceRange(); 57500b57cec5SDimitry Andric return QualType(); 57510b57cec5SDimitry Andric } 57520b57cec5SDimitry Andric 57530b57cec5SDimitry Andric QualType Class(MemPtr->getClass(), 0); 57540b57cec5SDimitry Andric 57550b57cec5SDimitry Andric // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the 57560b57cec5SDimitry Andric // member pointer points must be completely-defined. However, there is no 57570b57cec5SDimitry Andric // reason for this semantic distinction, and the rule is not enforced by 57580b57cec5SDimitry Andric // other compilers. Therefore, we do not check this property, as it is 57590b57cec5SDimitry Andric // likely to be considered a defect. 57600b57cec5SDimitry Andric 57610b57cec5SDimitry Andric // C++ 5.5p2 57620b57cec5SDimitry Andric // [...] to its first operand, which shall be of class T or of a class of 57630b57cec5SDimitry Andric // which T is an unambiguous and accessible base class. [p3: a pointer to 57640b57cec5SDimitry Andric // such a class] 57650b57cec5SDimitry Andric QualType LHSType = LHS.get()->getType(); 57660b57cec5SDimitry Andric if (isIndirect) { 57670b57cec5SDimitry Andric if (const PointerType *Ptr = LHSType->getAs<PointerType>()) 57680b57cec5SDimitry Andric LHSType = Ptr->getPointeeType(); 57690b57cec5SDimitry Andric else { 57700b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_lhs) 57710b57cec5SDimitry Andric << OpSpelling << 1 << LHSType 57720b57cec5SDimitry Andric << FixItHint::CreateReplacement(SourceRange(Loc), ".*"); 57730b57cec5SDimitry Andric return QualType(); 57740b57cec5SDimitry Andric } 57750b57cec5SDimitry Andric } 57760b57cec5SDimitry Andric 57770b57cec5SDimitry Andric if (!Context.hasSameUnqualifiedType(Class, LHSType)) { 57780b57cec5SDimitry Andric // If we want to check the hierarchy, we need a complete type. 57790b57cec5SDimitry Andric if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, 57800b57cec5SDimitry Andric OpSpelling, (int)isIndirect)) { 57810b57cec5SDimitry Andric return QualType(); 57820b57cec5SDimitry Andric } 57830b57cec5SDimitry Andric 57840b57cec5SDimitry Andric if (!IsDerivedFrom(Loc, LHSType, Class)) { 57850b57cec5SDimitry Andric Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling 57860b57cec5SDimitry Andric << (int)isIndirect << LHS.get()->getType(); 57870b57cec5SDimitry Andric return QualType(); 57880b57cec5SDimitry Andric } 57890b57cec5SDimitry Andric 57900b57cec5SDimitry Andric CXXCastPath BasePath; 57910b57cec5SDimitry Andric if (CheckDerivedToBaseConversion( 57920b57cec5SDimitry Andric LHSType, Class, Loc, 57930b57cec5SDimitry Andric SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), 57940b57cec5SDimitry Andric &BasePath)) 57950b57cec5SDimitry Andric return QualType(); 57960b57cec5SDimitry Andric 57970b57cec5SDimitry Andric // Cast LHS to type of use. 57980b57cec5SDimitry Andric QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers()); 57990b57cec5SDimitry Andric if (isIndirect) 58000b57cec5SDimitry Andric UseType = Context.getPointerType(UseType); 5801fe6060f1SDimitry Andric ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind(); 58020b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, 58030b57cec5SDimitry Andric &BasePath); 58040b57cec5SDimitry Andric } 58050b57cec5SDimitry Andric 58060b57cec5SDimitry Andric if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { 58070b57cec5SDimitry Andric // Diagnose use of pointer-to-member type which when used as 58080b57cec5SDimitry Andric // the functional cast in a pointer-to-member expression. 58090b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; 58100b57cec5SDimitry Andric return QualType(); 58110b57cec5SDimitry Andric } 58120b57cec5SDimitry Andric 58130b57cec5SDimitry Andric // C++ 5.5p2 58140b57cec5SDimitry Andric // The result is an object or a function of the type specified by the 58150b57cec5SDimitry Andric // second operand. 58160b57cec5SDimitry Andric // The cv qualifiers are the union of those in the pointer and the left side, 58170b57cec5SDimitry Andric // in accordance with 5.5p5 and 5.2.5. 58180b57cec5SDimitry Andric QualType Result = MemPtr->getPointeeType(); 58190b57cec5SDimitry Andric Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); 58200b57cec5SDimitry Andric 58210b57cec5SDimitry Andric // C++0x [expr.mptr.oper]p6: 58220b57cec5SDimitry Andric // In a .* expression whose object expression is an rvalue, the program is 58230b57cec5SDimitry Andric // ill-formed if the second operand is a pointer to member function with 58240b57cec5SDimitry Andric // ref-qualifier &. In a ->* expression or in a .* expression whose object 58250b57cec5SDimitry Andric // expression is an lvalue, the program is ill-formed if the second operand 58260b57cec5SDimitry Andric // is a pointer to member function with ref-qualifier &&. 58270b57cec5SDimitry Andric if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { 58280b57cec5SDimitry Andric switch (Proto->getRefQualifier()) { 58290b57cec5SDimitry Andric case RQ_None: 58300b57cec5SDimitry Andric // Do nothing 58310b57cec5SDimitry Andric break; 58320b57cec5SDimitry Andric 58330b57cec5SDimitry Andric case RQ_LValue: 58340b57cec5SDimitry Andric if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { 58350b57cec5SDimitry Andric // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq 58360b57cec5SDimitry Andric // is (exactly) 'const'. 58370b57cec5SDimitry Andric if (Proto->isConst() && !Proto->isVolatile()) 58385ffd83dbSDimitry Andric Diag(Loc, getLangOpts().CPlusPlus20 58390b57cec5SDimitry Andric ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue 58400b57cec5SDimitry Andric : diag::ext_pointer_to_const_ref_member_on_rvalue); 58410b57cec5SDimitry Andric else 58420b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 58430b57cec5SDimitry Andric << RHSType << 1 << LHS.get()->getSourceRange(); 58440b57cec5SDimitry Andric } 58450b57cec5SDimitry Andric break; 58460b57cec5SDimitry Andric 58470b57cec5SDimitry Andric case RQ_RValue: 58480b57cec5SDimitry Andric if (isIndirect || !LHS.get()->Classify(Context).isRValue()) 58490b57cec5SDimitry Andric Diag(Loc, diag::err_pointer_to_member_oper_value_classify) 58500b57cec5SDimitry Andric << RHSType << 0 << LHS.get()->getSourceRange(); 58510b57cec5SDimitry Andric break; 58520b57cec5SDimitry Andric } 58530b57cec5SDimitry Andric } 58540b57cec5SDimitry Andric 58550b57cec5SDimitry Andric // C++ [expr.mptr.oper]p6: 58560b57cec5SDimitry Andric // The result of a .* expression whose second operand is a pointer 58570b57cec5SDimitry Andric // to a data member is of the same value category as its 58580b57cec5SDimitry Andric // first operand. The result of a .* expression whose second 58590b57cec5SDimitry Andric // operand is a pointer to a member function is a prvalue. The 58600b57cec5SDimitry Andric // result of an ->* expression is an lvalue if its second operand 58610b57cec5SDimitry Andric // is a pointer to data member and a prvalue otherwise. 58620b57cec5SDimitry Andric if (Result->isFunctionType()) { 5863fe6060f1SDimitry Andric VK = VK_PRValue; 58640b57cec5SDimitry Andric return Context.BoundMemberTy; 58650b57cec5SDimitry Andric } else if (isIndirect) { 58660b57cec5SDimitry Andric VK = VK_LValue; 58670b57cec5SDimitry Andric } else { 58680b57cec5SDimitry Andric VK = LHS.get()->getValueKind(); 58690b57cec5SDimitry Andric } 58700b57cec5SDimitry Andric 58710b57cec5SDimitry Andric return Result; 58720b57cec5SDimitry Andric } 58730b57cec5SDimitry Andric 58740b57cec5SDimitry Andric /// Try to convert a type to another according to C++11 5.16p3. 58750b57cec5SDimitry Andric /// 58760b57cec5SDimitry Andric /// This is part of the parameter validation for the ? operator. If either 58770b57cec5SDimitry Andric /// value operand is a class type, the two operands are attempted to be 58780b57cec5SDimitry Andric /// converted to each other. This function does the conversion in one direction. 58790b57cec5SDimitry Andric /// It returns true if the program is ill-formed and has already been diagnosed 58800b57cec5SDimitry Andric /// as such. 58810b57cec5SDimitry Andric static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, 58820b57cec5SDimitry Andric SourceLocation QuestionLoc, 58830b57cec5SDimitry Andric bool &HaveConversion, 58840b57cec5SDimitry Andric QualType &ToType) { 58850b57cec5SDimitry Andric HaveConversion = false; 58860b57cec5SDimitry Andric ToType = To->getType(); 58870b57cec5SDimitry Andric 58880b57cec5SDimitry Andric InitializationKind Kind = 58890b57cec5SDimitry Andric InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); 58900b57cec5SDimitry Andric // C++11 5.16p3 58910b57cec5SDimitry Andric // The process for determining whether an operand expression E1 of type T1 58920b57cec5SDimitry Andric // can be converted to match an operand expression E2 of type T2 is defined 58930b57cec5SDimitry Andric // as follows: 58940b57cec5SDimitry Andric // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be 58950b57cec5SDimitry Andric // implicitly converted to type "lvalue reference to T2", subject to the 58960b57cec5SDimitry Andric // constraint that in the conversion the reference must bind directly to 58970b57cec5SDimitry Andric // an lvalue. 58980b57cec5SDimitry Andric // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be 58990b57cec5SDimitry Andric // implicitly converted to the type "rvalue reference to R2", subject to 59000b57cec5SDimitry Andric // the constraint that the reference must bind directly. 5901349cc55cSDimitry Andric if (To->isGLValue()) { 5902349cc55cSDimitry Andric QualType T = Self.Context.getReferenceQualifiedType(To); 59030b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 59040b57cec5SDimitry Andric 59050b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 59060b57cec5SDimitry Andric if (InitSeq.isDirectReferenceBinding()) { 59070b57cec5SDimitry Andric ToType = T; 59080b57cec5SDimitry Andric HaveConversion = true; 59090b57cec5SDimitry Andric return false; 59100b57cec5SDimitry Andric } 59110b57cec5SDimitry Andric 59120b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 59130b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 59140b57cec5SDimitry Andric } 59150b57cec5SDimitry Andric 59160b57cec5SDimitry Andric // -- If E2 is an rvalue, or if the conversion above cannot be done: 59170b57cec5SDimitry Andric // -- if E1 and E2 have class type, and the underlying class types are 59180b57cec5SDimitry Andric // the same or one is a base class of the other: 59190b57cec5SDimitry Andric QualType FTy = From->getType(); 59200b57cec5SDimitry Andric QualType TTy = To->getType(); 59210b57cec5SDimitry Andric const RecordType *FRec = FTy->getAs<RecordType>(); 59220b57cec5SDimitry Andric const RecordType *TRec = TTy->getAs<RecordType>(); 59230b57cec5SDimitry Andric bool FDerivedFromT = FRec && TRec && FRec != TRec && 59240b57cec5SDimitry Andric Self.IsDerivedFrom(QuestionLoc, FTy, TTy); 59250b57cec5SDimitry Andric if (FRec && TRec && (FRec == TRec || FDerivedFromT || 59260b57cec5SDimitry Andric Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { 59270b57cec5SDimitry Andric // E1 can be converted to match E2 if the class of T2 is the 59280b57cec5SDimitry Andric // same type as, or a base class of, the class of T1, and 59290b57cec5SDimitry Andric // [cv2 > cv1]. 59300b57cec5SDimitry Andric if (FRec == TRec || FDerivedFromT) { 59310b57cec5SDimitry Andric if (TTy.isAtLeastAsQualifiedAs(FTy)) { 59320b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 59330b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 59340b57cec5SDimitry Andric if (InitSeq) { 59350b57cec5SDimitry Andric HaveConversion = true; 59360b57cec5SDimitry Andric return false; 59370b57cec5SDimitry Andric } 59380b57cec5SDimitry Andric 59390b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 59400b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 59410b57cec5SDimitry Andric } 59420b57cec5SDimitry Andric } 59430b57cec5SDimitry Andric 59440b57cec5SDimitry Andric return false; 59450b57cec5SDimitry Andric } 59460b57cec5SDimitry Andric 59470b57cec5SDimitry Andric // -- Otherwise: E1 can be converted to match E2 if E1 can be 59480b57cec5SDimitry Andric // implicitly converted to the type that expression E2 would have 59490b57cec5SDimitry Andric // if E2 were converted to an rvalue (or the type it has, if E2 is 59500b57cec5SDimitry Andric // an rvalue). 59510b57cec5SDimitry Andric // 59520b57cec5SDimitry Andric // This actually refers very narrowly to the lvalue-to-rvalue conversion, not 59530b57cec5SDimitry Andric // to the array-to-pointer or function-to-pointer conversions. 59540b57cec5SDimitry Andric TTy = TTy.getNonLValueExprType(Self.Context); 59550b57cec5SDimitry Andric 59560b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); 59570b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, From); 59580b57cec5SDimitry Andric HaveConversion = !InitSeq.Failed(); 59590b57cec5SDimitry Andric ToType = TTy; 59600b57cec5SDimitry Andric if (InitSeq.isAmbiguous()) 59610b57cec5SDimitry Andric return InitSeq.Diagnose(Self, Entity, Kind, From); 59620b57cec5SDimitry Andric 59630b57cec5SDimitry Andric return false; 59640b57cec5SDimitry Andric } 59650b57cec5SDimitry Andric 59660b57cec5SDimitry Andric /// Try to find a common type for two according to C++0x 5.16p5. 59670b57cec5SDimitry Andric /// 59680b57cec5SDimitry Andric /// This is part of the parameter validation for the ? operator. If either 59690b57cec5SDimitry Andric /// value operand is a class type, overload resolution is used to find a 59700b57cec5SDimitry Andric /// conversion to a common type. 59710b57cec5SDimitry Andric static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, 59720b57cec5SDimitry Andric SourceLocation QuestionLoc) { 59730b57cec5SDimitry Andric Expr *Args[2] = { LHS.get(), RHS.get() }; 59740b57cec5SDimitry Andric OverloadCandidateSet CandidateSet(QuestionLoc, 59750b57cec5SDimitry Andric OverloadCandidateSet::CSK_Operator); 59760b57cec5SDimitry Andric Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 59770b57cec5SDimitry Andric CandidateSet); 59780b57cec5SDimitry Andric 59790b57cec5SDimitry Andric OverloadCandidateSet::iterator Best; 59800b57cec5SDimitry Andric switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { 59810b57cec5SDimitry Andric case OR_Success: { 59820b57cec5SDimitry Andric // We found a match. Perform the conversions on the arguments and move on. 59830b57cec5SDimitry Andric ExprResult LHSRes = Self.PerformImplicitConversion( 59840b57cec5SDimitry Andric LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], 59850b57cec5SDimitry Andric Sema::AA_Converting); 59860b57cec5SDimitry Andric if (LHSRes.isInvalid()) 59870b57cec5SDimitry Andric break; 59880b57cec5SDimitry Andric LHS = LHSRes; 59890b57cec5SDimitry Andric 59900b57cec5SDimitry Andric ExprResult RHSRes = Self.PerformImplicitConversion( 59910b57cec5SDimitry Andric RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], 59920b57cec5SDimitry Andric Sema::AA_Converting); 59930b57cec5SDimitry Andric if (RHSRes.isInvalid()) 59940b57cec5SDimitry Andric break; 59950b57cec5SDimitry Andric RHS = RHSRes; 59960b57cec5SDimitry Andric if (Best->Function) 59970b57cec5SDimitry Andric Self.MarkFunctionReferenced(QuestionLoc, Best->Function); 59980b57cec5SDimitry Andric return false; 59990b57cec5SDimitry Andric } 60000b57cec5SDimitry Andric 60010b57cec5SDimitry Andric case OR_No_Viable_Function: 60020b57cec5SDimitry Andric 60030b57cec5SDimitry Andric // Emit a better diagnostic if one of the expressions is a null pointer 60040b57cec5SDimitry Andric // constant and the other is a pointer type. In this case, the user most 60050b57cec5SDimitry Andric // likely forgot to take the address of the other expression. 60060b57cec5SDimitry Andric if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 60070b57cec5SDimitry Andric return true; 60080b57cec5SDimitry Andric 60090b57cec5SDimitry Andric Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 60100b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 60110b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 60120b57cec5SDimitry Andric return true; 60130b57cec5SDimitry Andric 60140b57cec5SDimitry Andric case OR_Ambiguous: 60150b57cec5SDimitry Andric Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) 60160b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 60170b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 60180b57cec5SDimitry Andric // FIXME: Print the possible common types by printing the return types of 60190b57cec5SDimitry Andric // the viable candidates. 60200b57cec5SDimitry Andric break; 60210b57cec5SDimitry Andric 60220b57cec5SDimitry Andric case OR_Deleted: 60230b57cec5SDimitry Andric llvm_unreachable("Conditional operator has only built-in overloads"); 60240b57cec5SDimitry Andric } 60250b57cec5SDimitry Andric return true; 60260b57cec5SDimitry Andric } 60270b57cec5SDimitry Andric 60280b57cec5SDimitry Andric /// Perform an "extended" implicit conversion as returned by 60290b57cec5SDimitry Andric /// TryClassUnification. 60300b57cec5SDimitry Andric static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { 60310b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); 60320b57cec5SDimitry Andric InitializationKind Kind = 60330b57cec5SDimitry Andric InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); 60340b57cec5SDimitry Andric Expr *Arg = E.get(); 60350b57cec5SDimitry Andric InitializationSequence InitSeq(Self, Entity, Kind, Arg); 60360b57cec5SDimitry Andric ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); 60370b57cec5SDimitry Andric if (Result.isInvalid()) 60380b57cec5SDimitry Andric return true; 60390b57cec5SDimitry Andric 60400b57cec5SDimitry Andric E = Result; 60410b57cec5SDimitry Andric return false; 60420b57cec5SDimitry Andric } 60430b57cec5SDimitry Andric 6044480093f4SDimitry Andric // Check the condition operand of ?: to see if it is valid for the GCC 6045480093f4SDimitry Andric // extension. 6046480093f4SDimitry Andric static bool isValidVectorForConditionalCondition(ASTContext &Ctx, 6047480093f4SDimitry Andric QualType CondTy) { 6048fe6060f1SDimitry Andric if (!CondTy->isVectorType() && !CondTy->isExtVectorType()) 6049480093f4SDimitry Andric return false; 6050480093f4SDimitry Andric const QualType EltTy = 6051480093f4SDimitry Andric cast<VectorType>(CondTy.getCanonicalType())->getElementType(); 6052480093f4SDimitry Andric assert(!EltTy->isBooleanType() && !EltTy->isEnumeralType() && 6053480093f4SDimitry Andric "Vectors cant be boolean or enum types"); 6054480093f4SDimitry Andric return EltTy->isIntegralType(Ctx); 6055480093f4SDimitry Andric } 6056480093f4SDimitry Andric 6057fe6060f1SDimitry Andric QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, 6058480093f4SDimitry Andric ExprResult &RHS, 6059480093f4SDimitry Andric SourceLocation QuestionLoc) { 6060480093f4SDimitry Andric LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 6061480093f4SDimitry Andric RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 6062480093f4SDimitry Andric 6063480093f4SDimitry Andric QualType CondType = Cond.get()->getType(); 60645ffd83dbSDimitry Andric const auto *CondVT = CondType->castAs<VectorType>(); 6065480093f4SDimitry Andric QualType CondElementTy = CondVT->getElementType(); 6066480093f4SDimitry Andric unsigned CondElementCount = CondVT->getNumElements(); 6067480093f4SDimitry Andric QualType LHSType = LHS.get()->getType(); 6068480093f4SDimitry Andric const auto *LHSVT = LHSType->getAs<VectorType>(); 6069480093f4SDimitry Andric QualType RHSType = RHS.get()->getType(); 6070480093f4SDimitry Andric const auto *RHSVT = RHSType->getAs<VectorType>(); 6071480093f4SDimitry Andric 6072480093f4SDimitry Andric QualType ResultType; 6073480093f4SDimitry Andric 6074480093f4SDimitry Andric 6075480093f4SDimitry Andric if (LHSVT && RHSVT) { 6076fe6060f1SDimitry Andric if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) { 6077fe6060f1SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch) 6078fe6060f1SDimitry Andric << /*isExtVector*/ isa<ExtVectorType>(CondVT); 6079fe6060f1SDimitry Andric return {}; 6080fe6060f1SDimitry Andric } 6081fe6060f1SDimitry Andric 6082480093f4SDimitry Andric // If both are vector types, they must be the same type. 6083480093f4SDimitry Andric if (!Context.hasSameType(LHSType, RHSType)) { 6084fe6060f1SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_mismatched) 6085480093f4SDimitry Andric << LHSType << RHSType; 6086480093f4SDimitry Andric return {}; 6087480093f4SDimitry Andric } 6088480093f4SDimitry Andric ResultType = LHSType; 6089480093f4SDimitry Andric } else if (LHSVT || RHSVT) { 6090480093f4SDimitry Andric ResultType = CheckVectorOperands( 6091480093f4SDimitry Andric LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true, 6092480093f4SDimitry Andric /*AllowBoolConversions*/ false); 6093480093f4SDimitry Andric if (ResultType.isNull()) 6094480093f4SDimitry Andric return {}; 6095480093f4SDimitry Andric } else { 6096480093f4SDimitry Andric // Both are scalar. 6097480093f4SDimitry Andric QualType ResultElementTy; 6098480093f4SDimitry Andric LHSType = LHSType.getCanonicalType().getUnqualifiedType(); 6099480093f4SDimitry Andric RHSType = RHSType.getCanonicalType().getUnqualifiedType(); 6100480093f4SDimitry Andric 6101480093f4SDimitry Andric if (Context.hasSameType(LHSType, RHSType)) 6102480093f4SDimitry Andric ResultElementTy = LHSType; 6103480093f4SDimitry Andric else 6104480093f4SDimitry Andric ResultElementTy = 6105480093f4SDimitry Andric UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 6106480093f4SDimitry Andric 6107480093f4SDimitry Andric if (ResultElementTy->isEnumeralType()) { 6108480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_operand_type) 6109fe6060f1SDimitry Andric << ResultElementTy; 6110480093f4SDimitry Andric return {}; 6111480093f4SDimitry Andric } 6112fe6060f1SDimitry Andric if (CondType->isExtVectorType()) 6113fe6060f1SDimitry Andric ResultType = 6114fe6060f1SDimitry Andric Context.getExtVectorType(ResultElementTy, CondVT->getNumElements()); 6115fe6060f1SDimitry Andric else 6116480093f4SDimitry Andric ResultType = Context.getVectorType( 6117fe6060f1SDimitry Andric ResultElementTy, CondVT->getNumElements(), VectorType::GenericVector); 6118480093f4SDimitry Andric 6119480093f4SDimitry Andric LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); 6120480093f4SDimitry Andric RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); 6121480093f4SDimitry Andric } 6122480093f4SDimitry Andric 6123480093f4SDimitry Andric assert(!ResultType.isNull() && ResultType->isVectorType() && 6124fe6060f1SDimitry Andric (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && 6125480093f4SDimitry Andric "Result should have been a vector type"); 61265ffd83dbSDimitry Andric auto *ResultVectorTy = ResultType->castAs<VectorType>(); 61275ffd83dbSDimitry Andric QualType ResultElementTy = ResultVectorTy->getElementType(); 61285ffd83dbSDimitry Andric unsigned ResultElementCount = ResultVectorTy->getNumElements(); 6129480093f4SDimitry Andric 6130480093f4SDimitry Andric if (ResultElementCount != CondElementCount) { 6131480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType 6132480093f4SDimitry Andric << ResultType; 6133480093f4SDimitry Andric return {}; 6134480093f4SDimitry Andric } 6135480093f4SDimitry Andric 6136480093f4SDimitry Andric if (Context.getTypeSize(ResultElementTy) != 6137480093f4SDimitry Andric Context.getTypeSize(CondElementTy)) { 6138480093f4SDimitry Andric Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType 6139480093f4SDimitry Andric << ResultType; 6140480093f4SDimitry Andric return {}; 6141480093f4SDimitry Andric } 6142480093f4SDimitry Andric 6143480093f4SDimitry Andric return ResultType; 6144480093f4SDimitry Andric } 6145480093f4SDimitry Andric 61460b57cec5SDimitry Andric /// Check the operands of ?: under C++ semantics. 61470b57cec5SDimitry Andric /// 61480b57cec5SDimitry Andric /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y 61490b57cec5SDimitry Andric /// extension. In this case, LHS == Cond. (But they're not aliases.) 6150480093f4SDimitry Andric /// 6151fe6060f1SDimitry Andric /// This function also implements GCC's vector extension and the 6152fe6060f1SDimitry Andric /// OpenCL/ext_vector_type extension for conditionals. The vector extensions 6153fe6060f1SDimitry Andric /// permit the use of a?b:c where the type of a is that of a integer vector with 6154fe6060f1SDimitry Andric /// the same number of elements and size as the vectors of b and c. If one of 6155fe6060f1SDimitry Andric /// either b or c is a scalar it is implicitly converted to match the type of 6156fe6060f1SDimitry Andric /// the vector. Otherwise the expression is ill-formed. If both b and c are 6157fe6060f1SDimitry Andric /// scalars, then b and c are checked and converted to the type of a if 6158fe6060f1SDimitry Andric /// possible. 6159fe6060f1SDimitry Andric /// 6160fe6060f1SDimitry Andric /// The expressions are evaluated differently for GCC's and OpenCL's extensions. 6161fe6060f1SDimitry Andric /// For the GCC extension, the ?: operator is evaluated as 6162480093f4SDimitry Andric /// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]). 6163fe6060f1SDimitry Andric /// For the OpenCL extensions, the ?: operator is evaluated as 6164fe6060f1SDimitry Andric /// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. , 6165fe6060f1SDimitry Andric /// most-significant-bit-set(a[n]) ? b[n] : c[n]). 61660b57cec5SDimitry Andric QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, 61670b57cec5SDimitry Andric ExprResult &RHS, ExprValueKind &VK, 61680b57cec5SDimitry Andric ExprObjectKind &OK, 61690b57cec5SDimitry Andric SourceLocation QuestionLoc) { 6170480093f4SDimitry Andric // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface 6171480093f4SDimitry Andric // pointers. 61720b57cec5SDimitry Andric 61730b57cec5SDimitry Andric // Assume r-value. 6174fe6060f1SDimitry Andric VK = VK_PRValue; 61750b57cec5SDimitry Andric OK = OK_Ordinary; 6176480093f4SDimitry Andric bool IsVectorConditional = 6177480093f4SDimitry Andric isValidVectorForConditionalCondition(Context, Cond.get()->getType()); 6178480093f4SDimitry Andric 6179480093f4SDimitry Andric // C++11 [expr.cond]p1 6180480093f4SDimitry Andric // The first expression is contextually converted to bool. 6181480093f4SDimitry Andric if (!Cond.get()->isTypeDependent()) { 6182480093f4SDimitry Andric ExprResult CondRes = IsVectorConditional 6183480093f4SDimitry Andric ? DefaultFunctionArrayLvalueConversion(Cond.get()) 6184480093f4SDimitry Andric : CheckCXXBooleanCondition(Cond.get()); 6185480093f4SDimitry Andric if (CondRes.isInvalid()) 6186480093f4SDimitry Andric return QualType(); 6187480093f4SDimitry Andric Cond = CondRes; 6188480093f4SDimitry Andric } else { 6189480093f4SDimitry Andric // To implement C++, the first expression typically doesn't alter the result 6190480093f4SDimitry Andric // type of the conditional, however the GCC compatible vector extension 6191480093f4SDimitry Andric // changes the result type to be that of the conditional. Since we cannot 6192480093f4SDimitry Andric // know if this is a vector extension here, delay the conversion of the 6193480093f4SDimitry Andric // LHS/RHS below until later. 6194480093f4SDimitry Andric return Context.DependentTy; 6195480093f4SDimitry Andric } 6196480093f4SDimitry Andric 61970b57cec5SDimitry Andric 61980b57cec5SDimitry Andric // Either of the arguments dependent? 61990b57cec5SDimitry Andric if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) 62000b57cec5SDimitry Andric return Context.DependentTy; 62010b57cec5SDimitry Andric 62020b57cec5SDimitry Andric // C++11 [expr.cond]p2 62030b57cec5SDimitry Andric // If either the second or the third operand has type (cv) void, ... 62040b57cec5SDimitry Andric QualType LTy = LHS.get()->getType(); 62050b57cec5SDimitry Andric QualType RTy = RHS.get()->getType(); 62060b57cec5SDimitry Andric bool LVoid = LTy->isVoidType(); 62070b57cec5SDimitry Andric bool RVoid = RTy->isVoidType(); 62080b57cec5SDimitry Andric if (LVoid || RVoid) { 62090b57cec5SDimitry Andric // ... one of the following shall hold: 62100b57cec5SDimitry Andric // -- The second or the third operand (but not both) is a (possibly 62110b57cec5SDimitry Andric // parenthesized) throw-expression; the result is of the type 62120b57cec5SDimitry Andric // and value category of the other. 62130b57cec5SDimitry Andric bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); 62140b57cec5SDimitry Andric bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); 6215480093f4SDimitry Andric 6216480093f4SDimitry Andric // Void expressions aren't legal in the vector-conditional expressions. 6217480093f4SDimitry Andric if (IsVectorConditional) { 6218480093f4SDimitry Andric SourceRange DiagLoc = 6219480093f4SDimitry Andric LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); 6220480093f4SDimitry Andric bool IsThrow = LVoid ? LThrow : RThrow; 6221480093f4SDimitry Andric Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) 6222480093f4SDimitry Andric << DiagLoc << IsThrow; 6223480093f4SDimitry Andric return QualType(); 6224480093f4SDimitry Andric } 6225480093f4SDimitry Andric 62260b57cec5SDimitry Andric if (LThrow != RThrow) { 62270b57cec5SDimitry Andric Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); 62280b57cec5SDimitry Andric VK = NonThrow->getValueKind(); 62290b57cec5SDimitry Andric // DR (no number yet): the result is a bit-field if the 62300b57cec5SDimitry Andric // non-throw-expression operand is a bit-field. 62310b57cec5SDimitry Andric OK = NonThrow->getObjectKind(); 62320b57cec5SDimitry Andric return NonThrow->getType(); 62330b57cec5SDimitry Andric } 62340b57cec5SDimitry Andric 62350b57cec5SDimitry Andric // -- Both the second and third operands have type void; the result is of 62360b57cec5SDimitry Andric // type void and is a prvalue. 62370b57cec5SDimitry Andric if (LVoid && RVoid) 62380b57cec5SDimitry Andric return Context.VoidTy; 62390b57cec5SDimitry Andric 62400b57cec5SDimitry Andric // Neither holds, error. 62410b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_conditional_void_nonvoid) 62420b57cec5SDimitry Andric << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) 62430b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 62440b57cec5SDimitry Andric return QualType(); 62450b57cec5SDimitry Andric } 62460b57cec5SDimitry Andric 62470b57cec5SDimitry Andric // Neither is void. 6248480093f4SDimitry Andric if (IsVectorConditional) 6249fe6060f1SDimitry Andric return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); 62500b57cec5SDimitry Andric 62510b57cec5SDimitry Andric // C++11 [expr.cond]p3 62520b57cec5SDimitry Andric // Otherwise, if the second and third operand have different types, and 62530b57cec5SDimitry Andric // either has (cv) class type [...] an attempt is made to convert each of 62540b57cec5SDimitry Andric // those operands to the type of the other. 62550b57cec5SDimitry Andric if (!Context.hasSameType(LTy, RTy) && 62560b57cec5SDimitry Andric (LTy->isRecordType() || RTy->isRecordType())) { 62570b57cec5SDimitry Andric // These return true if a single direction is already ambiguous. 62580b57cec5SDimitry Andric QualType L2RType, R2LType; 62590b57cec5SDimitry Andric bool HaveL2R, HaveR2L; 62600b57cec5SDimitry Andric if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) 62610b57cec5SDimitry Andric return QualType(); 62620b57cec5SDimitry Andric if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) 62630b57cec5SDimitry Andric return QualType(); 62640b57cec5SDimitry Andric 62650b57cec5SDimitry Andric // If both can be converted, [...] the program is ill-formed. 62660b57cec5SDimitry Andric if (HaveL2R && HaveR2L) { 62670b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_conditional_ambiguous) 62680b57cec5SDimitry Andric << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 62690b57cec5SDimitry Andric return QualType(); 62700b57cec5SDimitry Andric } 62710b57cec5SDimitry Andric 62720b57cec5SDimitry Andric // If exactly one conversion is possible, that conversion is applied to 62730b57cec5SDimitry Andric // the chosen operand and the converted operands are used in place of the 62740b57cec5SDimitry Andric // original operands for the remainder of this section. 62750b57cec5SDimitry Andric if (HaveL2R) { 62760b57cec5SDimitry Andric if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) 62770b57cec5SDimitry Andric return QualType(); 62780b57cec5SDimitry Andric LTy = LHS.get()->getType(); 62790b57cec5SDimitry Andric } else if (HaveR2L) { 62800b57cec5SDimitry Andric if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) 62810b57cec5SDimitry Andric return QualType(); 62820b57cec5SDimitry Andric RTy = RHS.get()->getType(); 62830b57cec5SDimitry Andric } 62840b57cec5SDimitry Andric } 62850b57cec5SDimitry Andric 62860b57cec5SDimitry Andric // C++11 [expr.cond]p3 62870b57cec5SDimitry Andric // if both are glvalues of the same value category and the same type except 62880b57cec5SDimitry Andric // for cv-qualification, an attempt is made to convert each of those 62890b57cec5SDimitry Andric // operands to the type of the other. 62900b57cec5SDimitry Andric // FIXME: 62910b57cec5SDimitry Andric // Resolving a defect in P0012R1: we extend this to cover all cases where 62920b57cec5SDimitry Andric // one of the operands is reference-compatible with the other, in order 6293480093f4SDimitry Andric // to support conditionals between functions differing in noexcept. This 6294480093f4SDimitry Andric // will similarly cover difference in array bounds after P0388R4. 6295480093f4SDimitry Andric // FIXME: If LTy and RTy have a composite pointer type, should we convert to 6296480093f4SDimitry Andric // that instead? 62970b57cec5SDimitry Andric ExprValueKind LVK = LHS.get()->getValueKind(); 62980b57cec5SDimitry Andric ExprValueKind RVK = RHS.get()->getValueKind(); 6299fe6060f1SDimitry Andric if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) { 63000b57cec5SDimitry Andric // DerivedToBase was already handled by the class-specific case above. 63010b57cec5SDimitry Andric // FIXME: Should we allow ObjC conversions here? 6302480093f4SDimitry Andric const ReferenceConversions AllowedConversions = 6303480093f4SDimitry Andric ReferenceConversions::Qualification | 6304480093f4SDimitry Andric ReferenceConversions::NestedQualification | 6305480093f4SDimitry Andric ReferenceConversions::Function; 6306480093f4SDimitry Andric 6307480093f4SDimitry Andric ReferenceConversions RefConv; 6308480093f4SDimitry Andric if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) == 6309480093f4SDimitry Andric Ref_Compatible && 6310480093f4SDimitry Andric !(RefConv & ~AllowedConversions) && 63110b57cec5SDimitry Andric // [...] subject to the constraint that the reference must bind 63120b57cec5SDimitry Andric // directly [...] 6313a7dea167SDimitry Andric !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { 63140b57cec5SDimitry Andric RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); 63150b57cec5SDimitry Andric RTy = RHS.get()->getType(); 6316480093f4SDimitry Andric } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) == 6317480093f4SDimitry Andric Ref_Compatible && 6318480093f4SDimitry Andric !(RefConv & ~AllowedConversions) && 63190b57cec5SDimitry Andric !LHS.get()->refersToBitField() && 63200b57cec5SDimitry Andric !LHS.get()->refersToVectorElement()) { 63210b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); 63220b57cec5SDimitry Andric LTy = LHS.get()->getType(); 63230b57cec5SDimitry Andric } 63240b57cec5SDimitry Andric } 63250b57cec5SDimitry Andric 63260b57cec5SDimitry Andric // C++11 [expr.cond]p4 63270b57cec5SDimitry Andric // If the second and third operands are glvalues of the same value 63280b57cec5SDimitry Andric // category and have the same type, the result is of that type and 63290b57cec5SDimitry Andric // value category and it is a bit-field if the second or the third 63300b57cec5SDimitry Andric // operand is a bit-field, or if both are bit-fields. 63310b57cec5SDimitry Andric // We only extend this to bitfields, not to the crazy other kinds of 63320b57cec5SDimitry Andric // l-values. 63330b57cec5SDimitry Andric bool Same = Context.hasSameType(LTy, RTy); 6334fe6060f1SDimitry Andric if (Same && LVK == RVK && LVK != VK_PRValue && 63350b57cec5SDimitry Andric LHS.get()->isOrdinaryOrBitFieldObject() && 63360b57cec5SDimitry Andric RHS.get()->isOrdinaryOrBitFieldObject()) { 63370b57cec5SDimitry Andric VK = LHS.get()->getValueKind(); 63380b57cec5SDimitry Andric if (LHS.get()->getObjectKind() == OK_BitField || 63390b57cec5SDimitry Andric RHS.get()->getObjectKind() == OK_BitField) 63400b57cec5SDimitry Andric OK = OK_BitField; 63410b57cec5SDimitry Andric 63420b57cec5SDimitry Andric // If we have function pointer types, unify them anyway to unify their 63430b57cec5SDimitry Andric // exception specifications, if any. 63440b57cec5SDimitry Andric if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 63450b57cec5SDimitry Andric Qualifiers Qs = LTy.getQualifiers(); 63460b57cec5SDimitry Andric LTy = FindCompositePointerType(QuestionLoc, LHS, RHS, 63470b57cec5SDimitry Andric /*ConvertArgs*/false); 63480b57cec5SDimitry Andric LTy = Context.getQualifiedType(LTy, Qs); 63490b57cec5SDimitry Andric 63500b57cec5SDimitry Andric assert(!LTy.isNull() && "failed to find composite pointer type for " 63510b57cec5SDimitry Andric "canonically equivalent function ptr types"); 63520b57cec5SDimitry Andric assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type"); 63530b57cec5SDimitry Andric } 63540b57cec5SDimitry Andric 63550b57cec5SDimitry Andric return LTy; 63560b57cec5SDimitry Andric } 63570b57cec5SDimitry Andric 63580b57cec5SDimitry Andric // C++11 [expr.cond]p5 63590b57cec5SDimitry Andric // Otherwise, the result is a prvalue. If the second and third operands 63600b57cec5SDimitry Andric // do not have the same type, and either has (cv) class type, ... 63610b57cec5SDimitry Andric if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { 63620b57cec5SDimitry Andric // ... overload resolution is used to determine the conversions (if any) 63630b57cec5SDimitry Andric // to be applied to the operands. If the overload resolution fails, the 63640b57cec5SDimitry Andric // program is ill-formed. 63650b57cec5SDimitry Andric if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) 63660b57cec5SDimitry Andric return QualType(); 63670b57cec5SDimitry Andric } 63680b57cec5SDimitry Andric 63690b57cec5SDimitry Andric // C++11 [expr.cond]p6 63700b57cec5SDimitry Andric // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard 63710b57cec5SDimitry Andric // conversions are performed on the second and third operands. 63720b57cec5SDimitry Andric LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); 63730b57cec5SDimitry Andric RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); 63740b57cec5SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 63750b57cec5SDimitry Andric return QualType(); 63760b57cec5SDimitry Andric LTy = LHS.get()->getType(); 63770b57cec5SDimitry Andric RTy = RHS.get()->getType(); 63780b57cec5SDimitry Andric 63790b57cec5SDimitry Andric // After those conversions, one of the following shall hold: 63800b57cec5SDimitry Andric // -- The second and third operands have the same type; the result 63810b57cec5SDimitry Andric // is of that type. If the operands have class type, the result 63820b57cec5SDimitry Andric // is a prvalue temporary of the result type, which is 63830b57cec5SDimitry Andric // copy-initialized from either the second operand or the third 63840b57cec5SDimitry Andric // operand depending on the value of the first operand. 63850b57cec5SDimitry Andric if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) { 63860b57cec5SDimitry Andric if (LTy->isRecordType()) { 63870b57cec5SDimitry Andric // The operands have class type. Make a temporary copy. 63880b57cec5SDimitry Andric InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy); 63890b57cec5SDimitry Andric 63900b57cec5SDimitry Andric ExprResult LHSCopy = PerformCopyInitialization(Entity, 63910b57cec5SDimitry Andric SourceLocation(), 63920b57cec5SDimitry Andric LHS); 63930b57cec5SDimitry Andric if (LHSCopy.isInvalid()) 63940b57cec5SDimitry Andric return QualType(); 63950b57cec5SDimitry Andric 63960b57cec5SDimitry Andric ExprResult RHSCopy = PerformCopyInitialization(Entity, 63970b57cec5SDimitry Andric SourceLocation(), 63980b57cec5SDimitry Andric RHS); 63990b57cec5SDimitry Andric if (RHSCopy.isInvalid()) 64000b57cec5SDimitry Andric return QualType(); 64010b57cec5SDimitry Andric 64020b57cec5SDimitry Andric LHS = LHSCopy; 64030b57cec5SDimitry Andric RHS = RHSCopy; 64040b57cec5SDimitry Andric } 64050b57cec5SDimitry Andric 64060b57cec5SDimitry Andric // If we have function pointer types, unify them anyway to unify their 64070b57cec5SDimitry Andric // exception specifications, if any. 64080b57cec5SDimitry Andric if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) { 64090b57cec5SDimitry Andric LTy = FindCompositePointerType(QuestionLoc, LHS, RHS); 64100b57cec5SDimitry Andric assert(!LTy.isNull() && "failed to find composite pointer type for " 64110b57cec5SDimitry Andric "canonically equivalent function ptr types"); 64120b57cec5SDimitry Andric } 64130b57cec5SDimitry Andric 64140b57cec5SDimitry Andric return LTy; 64150b57cec5SDimitry Andric } 64160b57cec5SDimitry Andric 64170b57cec5SDimitry Andric // Extension: conditional operator involving vector types. 64180b57cec5SDimitry Andric if (LTy->isVectorType() || RTy->isVectorType()) 64190b57cec5SDimitry Andric return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false, 64200b57cec5SDimitry Andric /*AllowBothBool*/true, 64210b57cec5SDimitry Andric /*AllowBoolConversions*/false); 64220b57cec5SDimitry Andric 64230b57cec5SDimitry Andric // -- The second and third operands have arithmetic or enumeration type; 64240b57cec5SDimitry Andric // the usual arithmetic conversions are performed to bring them to a 64250b57cec5SDimitry Andric // common type, and the result is of that type. 64260b57cec5SDimitry Andric if (LTy->isArithmeticType() && RTy->isArithmeticType()) { 6427480093f4SDimitry Andric QualType ResTy = 6428480093f4SDimitry Andric UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional); 64290b57cec5SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 64300b57cec5SDimitry Andric return QualType(); 64310b57cec5SDimitry Andric if (ResTy.isNull()) { 64320b57cec5SDimitry Andric Diag(QuestionLoc, 64330b57cec5SDimitry Andric diag::err_typecheck_cond_incompatible_operands) << LTy << RTy 64340b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 64350b57cec5SDimitry Andric return QualType(); 64360b57cec5SDimitry Andric } 64370b57cec5SDimitry Andric 64380b57cec5SDimitry Andric LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); 64390b57cec5SDimitry Andric RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); 64400b57cec5SDimitry Andric 64410b57cec5SDimitry Andric return ResTy; 64420b57cec5SDimitry Andric } 64430b57cec5SDimitry Andric 64440b57cec5SDimitry Andric // -- The second and third operands have pointer type, or one has pointer 64450b57cec5SDimitry Andric // type and the other is a null pointer constant, or both are null 64460b57cec5SDimitry Andric // pointer constants, at least one of which is non-integral; pointer 64470b57cec5SDimitry Andric // conversions and qualification conversions are performed to bring them 64480b57cec5SDimitry Andric // to their composite pointer type. The result is of the composite 64490b57cec5SDimitry Andric // pointer type. 64500b57cec5SDimitry Andric // -- The second and third operands have pointer to member type, or one has 64510b57cec5SDimitry Andric // pointer to member type and the other is a null pointer constant; 64520b57cec5SDimitry Andric // pointer to member conversions and qualification conversions are 64530b57cec5SDimitry Andric // performed to bring them to a common type, whose cv-qualification 64540b57cec5SDimitry Andric // shall match the cv-qualification of either the second or the third 64550b57cec5SDimitry Andric // operand. The result is of the common type. 64560b57cec5SDimitry Andric QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); 64570b57cec5SDimitry Andric if (!Composite.isNull()) 64580b57cec5SDimitry Andric return Composite; 64590b57cec5SDimitry Andric 64600b57cec5SDimitry Andric // Similarly, attempt to find composite type of two objective-c pointers. 64610b57cec5SDimitry Andric Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); 6462e8d8bef9SDimitry Andric if (LHS.isInvalid() || RHS.isInvalid()) 6463e8d8bef9SDimitry Andric return QualType(); 64640b57cec5SDimitry Andric if (!Composite.isNull()) 64650b57cec5SDimitry Andric return Composite; 64660b57cec5SDimitry Andric 64670b57cec5SDimitry Andric // Check if we are using a null with a non-pointer type. 64680b57cec5SDimitry Andric if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) 64690b57cec5SDimitry Andric return QualType(); 64700b57cec5SDimitry Andric 64710b57cec5SDimitry Andric Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) 64720b57cec5SDimitry Andric << LHS.get()->getType() << RHS.get()->getType() 64730b57cec5SDimitry Andric << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); 64740b57cec5SDimitry Andric return QualType(); 64750b57cec5SDimitry Andric } 64760b57cec5SDimitry Andric 64770b57cec5SDimitry Andric static FunctionProtoType::ExceptionSpecInfo 64780b57cec5SDimitry Andric mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1, 64790b57cec5SDimitry Andric FunctionProtoType::ExceptionSpecInfo ESI2, 64800b57cec5SDimitry Andric SmallVectorImpl<QualType> &ExceptionTypeStorage) { 64810b57cec5SDimitry Andric ExceptionSpecificationType EST1 = ESI1.Type; 64820b57cec5SDimitry Andric ExceptionSpecificationType EST2 = ESI2.Type; 64830b57cec5SDimitry Andric 64840b57cec5SDimitry Andric // If either of them can throw anything, that is the result. 64850b57cec5SDimitry Andric if (EST1 == EST_None) return ESI1; 64860b57cec5SDimitry Andric if (EST2 == EST_None) return ESI2; 64870b57cec5SDimitry Andric if (EST1 == EST_MSAny) return ESI1; 64880b57cec5SDimitry Andric if (EST2 == EST_MSAny) return ESI2; 64890b57cec5SDimitry Andric if (EST1 == EST_NoexceptFalse) return ESI1; 64900b57cec5SDimitry Andric if (EST2 == EST_NoexceptFalse) return ESI2; 64910b57cec5SDimitry Andric 64920b57cec5SDimitry Andric // If either of them is non-throwing, the result is the other. 64930b57cec5SDimitry Andric if (EST1 == EST_NoThrow) return ESI2; 64940b57cec5SDimitry Andric if (EST2 == EST_NoThrow) return ESI1; 64950b57cec5SDimitry Andric if (EST1 == EST_DynamicNone) return ESI2; 64960b57cec5SDimitry Andric if (EST2 == EST_DynamicNone) return ESI1; 64970b57cec5SDimitry Andric if (EST1 == EST_BasicNoexcept) return ESI2; 64980b57cec5SDimitry Andric if (EST2 == EST_BasicNoexcept) return ESI1; 64990b57cec5SDimitry Andric if (EST1 == EST_NoexceptTrue) return ESI2; 65000b57cec5SDimitry Andric if (EST2 == EST_NoexceptTrue) return ESI1; 65010b57cec5SDimitry Andric 65020b57cec5SDimitry Andric // If we're left with value-dependent computed noexcept expressions, we're 65030b57cec5SDimitry Andric // stuck. Before C++17, we can just drop the exception specification entirely, 65040b57cec5SDimitry Andric // since it's not actually part of the canonical type. And this should never 65050b57cec5SDimitry Andric // happen in C++17, because it would mean we were computing the composite 65060b57cec5SDimitry Andric // pointer type of dependent types, which should never happen. 65070b57cec5SDimitry Andric if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) { 65080b57cec5SDimitry Andric assert(!S.getLangOpts().CPlusPlus17 && 65090b57cec5SDimitry Andric "computing composite pointer type of dependent types"); 65100b57cec5SDimitry Andric return FunctionProtoType::ExceptionSpecInfo(); 65110b57cec5SDimitry Andric } 65120b57cec5SDimitry Andric 65130b57cec5SDimitry Andric // Switch over the possibilities so that people adding new values know to 65140b57cec5SDimitry Andric // update this function. 65150b57cec5SDimitry Andric switch (EST1) { 65160b57cec5SDimitry Andric case EST_None: 65170b57cec5SDimitry Andric case EST_DynamicNone: 65180b57cec5SDimitry Andric case EST_MSAny: 65190b57cec5SDimitry Andric case EST_BasicNoexcept: 65200b57cec5SDimitry Andric case EST_DependentNoexcept: 65210b57cec5SDimitry Andric case EST_NoexceptFalse: 65220b57cec5SDimitry Andric case EST_NoexceptTrue: 65230b57cec5SDimitry Andric case EST_NoThrow: 65240b57cec5SDimitry Andric llvm_unreachable("handled above"); 65250b57cec5SDimitry Andric 65260b57cec5SDimitry Andric case EST_Dynamic: { 65270b57cec5SDimitry Andric // This is the fun case: both exception specifications are dynamic. Form 65280b57cec5SDimitry Andric // the union of the two lists. 65290b57cec5SDimitry Andric assert(EST2 == EST_Dynamic && "other cases should already be handled"); 65300b57cec5SDimitry Andric llvm::SmallPtrSet<QualType, 8> Found; 65310b57cec5SDimitry Andric for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions}) 65320b57cec5SDimitry Andric for (QualType E : Exceptions) 65330b57cec5SDimitry Andric if (Found.insert(S.Context.getCanonicalType(E)).second) 65340b57cec5SDimitry Andric ExceptionTypeStorage.push_back(E); 65350b57cec5SDimitry Andric 65360b57cec5SDimitry Andric FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic); 65370b57cec5SDimitry Andric Result.Exceptions = ExceptionTypeStorage; 65380b57cec5SDimitry Andric return Result; 65390b57cec5SDimitry Andric } 65400b57cec5SDimitry Andric 65410b57cec5SDimitry Andric case EST_Unevaluated: 65420b57cec5SDimitry Andric case EST_Uninstantiated: 65430b57cec5SDimitry Andric case EST_Unparsed: 65440b57cec5SDimitry Andric llvm_unreachable("shouldn't see unresolved exception specifications here"); 65450b57cec5SDimitry Andric } 65460b57cec5SDimitry Andric 65470b57cec5SDimitry Andric llvm_unreachable("invalid ExceptionSpecificationType"); 65480b57cec5SDimitry Andric } 65490b57cec5SDimitry Andric 65500b57cec5SDimitry Andric /// Find a merged pointer type and convert the two expressions to it. 65510b57cec5SDimitry Andric /// 6552480093f4SDimitry Andric /// This finds the composite pointer type for \p E1 and \p E2 according to 6553480093f4SDimitry Andric /// C++2a [expr.type]p3. It converts both expressions to this type and returns 6554480093f4SDimitry Andric /// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs 6555480093f4SDimitry Andric /// is \c true). 65560b57cec5SDimitry Andric /// 65570b57cec5SDimitry Andric /// \param Loc The location of the operator requiring these two expressions to 65580b57cec5SDimitry Andric /// be converted to the composite pointer type. 65590b57cec5SDimitry Andric /// 65600b57cec5SDimitry Andric /// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type. 65610b57cec5SDimitry Andric QualType Sema::FindCompositePointerType(SourceLocation Loc, 65620b57cec5SDimitry Andric Expr *&E1, Expr *&E2, 65630b57cec5SDimitry Andric bool ConvertArgs) { 65640b57cec5SDimitry Andric assert(getLangOpts().CPlusPlus && "This function assumes C++"); 65650b57cec5SDimitry Andric 65660b57cec5SDimitry Andric // C++1z [expr]p14: 65670b57cec5SDimitry Andric // The composite pointer type of two operands p1 and p2 having types T1 65680b57cec5SDimitry Andric // and T2 65690b57cec5SDimitry Andric QualType T1 = E1->getType(), T2 = E2->getType(); 65700b57cec5SDimitry Andric 65710b57cec5SDimitry Andric // where at least one is a pointer or pointer to member type or 65720b57cec5SDimitry Andric // std::nullptr_t is: 65730b57cec5SDimitry Andric bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || 65740b57cec5SDimitry Andric T1->isNullPtrType(); 65750b57cec5SDimitry Andric bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || 65760b57cec5SDimitry Andric T2->isNullPtrType(); 65770b57cec5SDimitry Andric if (!T1IsPointerLike && !T2IsPointerLike) 65780b57cec5SDimitry Andric return QualType(); 65790b57cec5SDimitry Andric 65800b57cec5SDimitry Andric // - if both p1 and p2 are null pointer constants, std::nullptr_t; 65810b57cec5SDimitry Andric // This can't actually happen, following the standard, but we also use this 65820b57cec5SDimitry Andric // to implement the end of [expr.conv], which hits this case. 65830b57cec5SDimitry Andric // 65840b57cec5SDimitry Andric // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; 65850b57cec5SDimitry Andric if (T1IsPointerLike && 65860b57cec5SDimitry Andric E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 65870b57cec5SDimitry Andric if (ConvertArgs) 65880b57cec5SDimitry Andric E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() 65890b57cec5SDimitry Andric ? CK_NullToMemberPointer 65900b57cec5SDimitry Andric : CK_NullToPointer).get(); 65910b57cec5SDimitry Andric return T1; 65920b57cec5SDimitry Andric } 65930b57cec5SDimitry Andric if (T2IsPointerLike && 65940b57cec5SDimitry Andric E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { 65950b57cec5SDimitry Andric if (ConvertArgs) 65960b57cec5SDimitry Andric E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() 65970b57cec5SDimitry Andric ? CK_NullToMemberPointer 65980b57cec5SDimitry Andric : CK_NullToPointer).get(); 65990b57cec5SDimitry Andric return T2; 66000b57cec5SDimitry Andric } 66010b57cec5SDimitry Andric 66020b57cec5SDimitry Andric // Now both have to be pointers or member pointers. 66030b57cec5SDimitry Andric if (!T1IsPointerLike || !T2IsPointerLike) 66040b57cec5SDimitry Andric return QualType(); 66050b57cec5SDimitry Andric assert(!T1->isNullPtrType() && !T2->isNullPtrType() && 66060b57cec5SDimitry Andric "nullptr_t should be a null pointer constant"); 66070b57cec5SDimitry Andric 6608480093f4SDimitry Andric struct Step { 6609480093f4SDimitry Andric enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; 6610480093f4SDimitry Andric // Qualifiers to apply under the step kind. 6611480093f4SDimitry Andric Qualifiers Quals; 6612480093f4SDimitry Andric /// The class for a pointer-to-member; a constant array type with a bound 6613480093f4SDimitry Andric /// (if any) for an array. 6614480093f4SDimitry Andric const Type *ClassOrBound; 6615480093f4SDimitry Andric 6616480093f4SDimitry Andric Step(Kind K, const Type *ClassOrBound = nullptr) 661704eeddc0SDimitry Andric : K(K), ClassOrBound(ClassOrBound) {} 6618480093f4SDimitry Andric QualType rebuild(ASTContext &Ctx, QualType T) const { 6619480093f4SDimitry Andric T = Ctx.getQualifiedType(T, Quals); 6620480093f4SDimitry Andric switch (K) { 6621480093f4SDimitry Andric case Pointer: 6622480093f4SDimitry Andric return Ctx.getPointerType(T); 6623480093f4SDimitry Andric case MemberPointer: 6624480093f4SDimitry Andric return Ctx.getMemberPointerType(T, ClassOrBound); 6625480093f4SDimitry Andric case ObjCPointer: 6626480093f4SDimitry Andric return Ctx.getObjCObjectPointerType(T); 6627480093f4SDimitry Andric case Array: 6628480093f4SDimitry Andric if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound)) 6629480093f4SDimitry Andric return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr, 6630480093f4SDimitry Andric ArrayType::Normal, 0); 6631480093f4SDimitry Andric else 6632480093f4SDimitry Andric return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0); 6633480093f4SDimitry Andric } 6634480093f4SDimitry Andric llvm_unreachable("unknown step kind"); 6635480093f4SDimitry Andric } 6636480093f4SDimitry Andric }; 6637480093f4SDimitry Andric 6638480093f4SDimitry Andric SmallVector<Step, 8> Steps; 6639480093f4SDimitry Andric 66400b57cec5SDimitry Andric // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 66410b57cec5SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 66420b57cec5SDimitry Andric // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, 66430b57cec5SDimitry Andric // respectively; 66440b57cec5SDimitry Andric // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer 6645480093f4SDimitry Andric // to member of C2 of type cv2 U2" for some non-function type U, where 6646480093f4SDimitry Andric // C1 is reference-related to C2 or C2 is reference-related to C1, the 6647480093f4SDimitry Andric // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, 6648480093f4SDimitry Andric // respectively; 66490b57cec5SDimitry Andric // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and 66500b57cec5SDimitry Andric // T2; 66510b57cec5SDimitry Andric // 6652480093f4SDimitry Andric // Dismantle T1 and T2 to simultaneously determine whether they are similar 6653480093f4SDimitry Andric // and to prepare to form the cv-combined type if so. 66540b57cec5SDimitry Andric QualType Composite1 = T1; 66550b57cec5SDimitry Andric QualType Composite2 = T2; 66560b57cec5SDimitry Andric unsigned NeedConstBefore = 0; 66570b57cec5SDimitry Andric while (true) { 6658480093f4SDimitry Andric assert(!Composite1.isNull() && !Composite2.isNull()); 6659480093f4SDimitry Andric 6660480093f4SDimitry Andric Qualifiers Q1, Q2; 6661480093f4SDimitry Andric Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1); 6662480093f4SDimitry Andric Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2); 6663480093f4SDimitry Andric 6664480093f4SDimitry Andric // Top-level qualifiers are ignored. Merge at all lower levels. 6665480093f4SDimitry Andric if (!Steps.empty()) { 6666480093f4SDimitry Andric // Find the qualifier union: (approximately) the unique minimal set of 6667480093f4SDimitry Andric // qualifiers that is compatible with both types. 6668480093f4SDimitry Andric Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() | 6669480093f4SDimitry Andric Q2.getCVRUQualifiers()); 6670480093f4SDimitry Andric 6671480093f4SDimitry Andric // Under one level of pointer or pointer-to-member, we can change to an 6672480093f4SDimitry Andric // unambiguous compatible address space. 6673480093f4SDimitry Andric if (Q1.getAddressSpace() == Q2.getAddressSpace()) { 6674480093f4SDimitry Andric Quals.setAddressSpace(Q1.getAddressSpace()); 6675480093f4SDimitry Andric } else if (Steps.size() == 1) { 6676480093f4SDimitry Andric bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2); 6677480093f4SDimitry Andric bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1); 6678349cc55cSDimitry Andric if (MaybeQ1 == MaybeQ2) { 6679349cc55cSDimitry Andric // Exception for ptr size address spaces. Should be able to choose 6680349cc55cSDimitry Andric // either address space during comparison. 6681349cc55cSDimitry Andric if (isPtrSizeAddressSpace(Q1.getAddressSpace()) || 6682349cc55cSDimitry Andric isPtrSizeAddressSpace(Q2.getAddressSpace())) 6683349cc55cSDimitry Andric MaybeQ1 = true; 6684349cc55cSDimitry Andric else 6685480093f4SDimitry Andric return QualType(); // No unique best address space. 6686349cc55cSDimitry Andric } 6687480093f4SDimitry Andric Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() 6688480093f4SDimitry Andric : Q2.getAddressSpace()); 6689480093f4SDimitry Andric } else { 6690480093f4SDimitry Andric return QualType(); 6691480093f4SDimitry Andric } 6692480093f4SDimitry Andric 6693480093f4SDimitry Andric // FIXME: In C, we merge __strong and none to __strong at the top level. 6694480093f4SDimitry Andric if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) 6695480093f4SDimitry Andric Quals.setObjCGCAttr(Q1.getObjCGCAttr()); 6696e8d8bef9SDimitry Andric else if (T1->isVoidPointerType() || T2->isVoidPointerType()) 6697e8d8bef9SDimitry Andric assert(Steps.size() == 1); 6698480093f4SDimitry Andric else 6699480093f4SDimitry Andric return QualType(); 6700480093f4SDimitry Andric 6701480093f4SDimitry Andric // Mismatched lifetime qualifiers never compatibly include each other. 6702480093f4SDimitry Andric if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) 6703480093f4SDimitry Andric Quals.setObjCLifetime(Q1.getObjCLifetime()); 6704e8d8bef9SDimitry Andric else if (T1->isVoidPointerType() || T2->isVoidPointerType()) 6705e8d8bef9SDimitry Andric assert(Steps.size() == 1); 6706480093f4SDimitry Andric else 6707480093f4SDimitry Andric return QualType(); 6708480093f4SDimitry Andric 6709480093f4SDimitry Andric Steps.back().Quals = Quals; 6710480093f4SDimitry Andric if (Q1 != Quals || Q2 != Quals) 6711480093f4SDimitry Andric NeedConstBefore = Steps.size() - 1; 6712480093f4SDimitry Andric } 6713480093f4SDimitry Andric 6714480093f4SDimitry Andric // FIXME: Can we unify the following with UnwrapSimilarTypes? 6715349cc55cSDimitry Andric 6716349cc55cSDimitry Andric const ArrayType *Arr1, *Arr2; 6717349cc55cSDimitry Andric if ((Arr1 = Context.getAsArrayType(Composite1)) && 6718349cc55cSDimitry Andric (Arr2 = Context.getAsArrayType(Composite2))) { 6719349cc55cSDimitry Andric auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1); 6720349cc55cSDimitry Andric auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2); 6721349cc55cSDimitry Andric if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) { 6722349cc55cSDimitry Andric Composite1 = Arr1->getElementType(); 6723349cc55cSDimitry Andric Composite2 = Arr2->getElementType(); 6724349cc55cSDimitry Andric Steps.emplace_back(Step::Array, CAT1); 6725349cc55cSDimitry Andric continue; 6726349cc55cSDimitry Andric } 6727349cc55cSDimitry Andric bool IAT1 = isa<IncompleteArrayType>(Arr1); 6728349cc55cSDimitry Andric bool IAT2 = isa<IncompleteArrayType>(Arr2); 6729349cc55cSDimitry Andric if ((IAT1 && IAT2) || 6730349cc55cSDimitry Andric (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) && 6731349cc55cSDimitry Andric ((bool)CAT1 != (bool)CAT2) && 6732349cc55cSDimitry Andric (Steps.empty() || Steps.back().K != Step::Array))) { 6733349cc55cSDimitry Andric // In C++20 onwards, we can unify an array of N T with an array of 6734349cc55cSDimitry Andric // a different or unknown bound. But we can't form an array whose 6735349cc55cSDimitry Andric // element type is an array of unknown bound by doing so. 6736349cc55cSDimitry Andric Composite1 = Arr1->getElementType(); 6737349cc55cSDimitry Andric Composite2 = Arr2->getElementType(); 6738349cc55cSDimitry Andric Steps.emplace_back(Step::Array); 6739349cc55cSDimitry Andric if (CAT1 || CAT2) 6740349cc55cSDimitry Andric NeedConstBefore = Steps.size(); 6741349cc55cSDimitry Andric continue; 6742349cc55cSDimitry Andric } 6743349cc55cSDimitry Andric } 6744349cc55cSDimitry Andric 67450b57cec5SDimitry Andric const PointerType *Ptr1, *Ptr2; 67460b57cec5SDimitry Andric if ((Ptr1 = Composite1->getAs<PointerType>()) && 67470b57cec5SDimitry Andric (Ptr2 = Composite2->getAs<PointerType>())) { 67480b57cec5SDimitry Andric Composite1 = Ptr1->getPointeeType(); 67490b57cec5SDimitry Andric Composite2 = Ptr2->getPointeeType(); 6750480093f4SDimitry Andric Steps.emplace_back(Step::Pointer); 6751480093f4SDimitry Andric continue; 6752480093f4SDimitry Andric } 67530b57cec5SDimitry Andric 6754480093f4SDimitry Andric const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; 6755480093f4SDimitry Andric if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && 6756480093f4SDimitry Andric (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { 6757480093f4SDimitry Andric Composite1 = ObjPtr1->getPointeeType(); 6758480093f4SDimitry Andric Composite2 = ObjPtr2->getPointeeType(); 6759480093f4SDimitry Andric Steps.emplace_back(Step::ObjCPointer); 67600b57cec5SDimitry Andric continue; 67610b57cec5SDimitry Andric } 67620b57cec5SDimitry Andric 67630b57cec5SDimitry Andric const MemberPointerType *MemPtr1, *MemPtr2; 67640b57cec5SDimitry Andric if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && 67650b57cec5SDimitry Andric (MemPtr2 = Composite2->getAs<MemberPointerType>())) { 67660b57cec5SDimitry Andric Composite1 = MemPtr1->getPointeeType(); 67670b57cec5SDimitry Andric Composite2 = MemPtr2->getPointeeType(); 67680b57cec5SDimitry Andric 6769480093f4SDimitry Andric // At the top level, we can perform a base-to-derived pointer-to-member 6770480093f4SDimitry Andric // conversion: 6771480093f4SDimitry Andric // 6772480093f4SDimitry Andric // - [...] where C1 is reference-related to C2 or C2 is 6773480093f4SDimitry Andric // reference-related to C1 6774480093f4SDimitry Andric // 6775480093f4SDimitry Andric // (Note that the only kinds of reference-relatedness in scope here are 6776480093f4SDimitry Andric // "same type or derived from".) At any other level, the class must 6777480093f4SDimitry Andric // exactly match. 6778480093f4SDimitry Andric const Type *Class = nullptr; 6779480093f4SDimitry Andric QualType Cls1(MemPtr1->getClass(), 0); 6780480093f4SDimitry Andric QualType Cls2(MemPtr2->getClass(), 0); 6781480093f4SDimitry Andric if (Context.hasSameType(Cls1, Cls2)) 6782480093f4SDimitry Andric Class = MemPtr1->getClass(); 6783480093f4SDimitry Andric else if (Steps.empty()) 6784480093f4SDimitry Andric Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() : 6785480093f4SDimitry Andric IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr; 6786480093f4SDimitry Andric if (!Class) 6787480093f4SDimitry Andric return QualType(); 67880b57cec5SDimitry Andric 6789480093f4SDimitry Andric Steps.emplace_back(Step::MemberPointer, Class); 67900b57cec5SDimitry Andric continue; 67910b57cec5SDimitry Andric } 67920b57cec5SDimitry Andric 6793480093f4SDimitry Andric // Special case: at the top level, we can decompose an Objective-C pointer 6794480093f4SDimitry Andric // and a 'cv void *'. Unify the qualifiers. 6795480093f4SDimitry Andric if (Steps.empty() && ((Composite1->isVoidPointerType() && 6796480093f4SDimitry Andric Composite2->isObjCObjectPointerType()) || 6797480093f4SDimitry Andric (Composite1->isObjCObjectPointerType() && 6798480093f4SDimitry Andric Composite2->isVoidPointerType()))) { 6799480093f4SDimitry Andric Composite1 = Composite1->getPointeeType(); 6800480093f4SDimitry Andric Composite2 = Composite2->getPointeeType(); 6801480093f4SDimitry Andric Steps.emplace_back(Step::Pointer); 6802480093f4SDimitry Andric continue; 6803480093f4SDimitry Andric } 6804480093f4SDimitry Andric 68050b57cec5SDimitry Andric // FIXME: block pointer types? 68060b57cec5SDimitry Andric 68070b57cec5SDimitry Andric // Cannot unwrap any more types. 68080b57cec5SDimitry Andric break; 68090b57cec5SDimitry Andric } 68100b57cec5SDimitry Andric 6811480093f4SDimitry Andric // - if T1 or T2 is "pointer to noexcept function" and the other type is 6812480093f4SDimitry Andric // "pointer to function", where the function types are otherwise the same, 6813480093f4SDimitry Andric // "pointer to function"; 6814480093f4SDimitry Andric // - if T1 or T2 is "pointer to member of C1 of type function", the other 6815480093f4SDimitry Andric // type is "pointer to member of C2 of type noexcept function", and C1 6816480093f4SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1, where 6817480093f4SDimitry Andric // the function types are otherwise the same, "pointer to member of C2 of 6818480093f4SDimitry Andric // type function" or "pointer to member of C1 of type function", 6819480093f4SDimitry Andric // respectively; 6820480093f4SDimitry Andric // 6821480093f4SDimitry Andric // We also support 'noreturn' here, so as a Clang extension we generalize the 6822480093f4SDimitry Andric // above to: 6823480093f4SDimitry Andric // 6824480093f4SDimitry Andric // - [Clang] If T1 and T2 are both of type "pointer to function" or 6825480093f4SDimitry Andric // "pointer to member function" and the pointee types can be unified 6826480093f4SDimitry Andric // by a function pointer conversion, that conversion is applied 6827480093f4SDimitry Andric // before checking the following rules. 6828480093f4SDimitry Andric // 6829480093f4SDimitry Andric // We've already unwrapped down to the function types, and we want to merge 6830480093f4SDimitry Andric // rather than just convert, so do this ourselves rather than calling 68310b57cec5SDimitry Andric // IsFunctionConversion. 68320b57cec5SDimitry Andric // 68330b57cec5SDimitry Andric // FIXME: In order to match the standard wording as closely as possible, we 68340b57cec5SDimitry Andric // currently only do this under a single level of pointers. Ideally, we would 68350b57cec5SDimitry Andric // allow this in general, and set NeedConstBefore to the relevant depth on 6836480093f4SDimitry Andric // the side(s) where we changed anything. If we permit that, we should also 6837480093f4SDimitry Andric // consider this conversion when determining type similarity and model it as 6838480093f4SDimitry Andric // a qualification conversion. 6839480093f4SDimitry Andric if (Steps.size() == 1) { 68400b57cec5SDimitry Andric if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { 68410b57cec5SDimitry Andric if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { 68420b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); 68430b57cec5SDimitry Andric FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); 68440b57cec5SDimitry Andric 68450b57cec5SDimitry Andric // The result is noreturn if both operands are. 68460b57cec5SDimitry Andric bool Noreturn = 68470b57cec5SDimitry Andric EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); 68480b57cec5SDimitry Andric EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); 68490b57cec5SDimitry Andric EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); 68500b57cec5SDimitry Andric 68510b57cec5SDimitry Andric // The result is nothrow if both operands are. 68520b57cec5SDimitry Andric SmallVector<QualType, 8> ExceptionTypeStorage; 68530b57cec5SDimitry Andric EPI1.ExceptionSpec = EPI2.ExceptionSpec = 68540b57cec5SDimitry Andric mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec, 68550b57cec5SDimitry Andric ExceptionTypeStorage); 68560b57cec5SDimitry Andric 68570b57cec5SDimitry Andric Composite1 = Context.getFunctionType(FPT1->getReturnType(), 68580b57cec5SDimitry Andric FPT1->getParamTypes(), EPI1); 68590b57cec5SDimitry Andric Composite2 = Context.getFunctionType(FPT2->getReturnType(), 68600b57cec5SDimitry Andric FPT2->getParamTypes(), EPI2); 68610b57cec5SDimitry Andric } 68620b57cec5SDimitry Andric } 68630b57cec5SDimitry Andric } 68640b57cec5SDimitry Andric 6865480093f4SDimitry Andric // There are some more conversions we can perform under exactly one pointer. 6866480093f4SDimitry Andric if (Steps.size() == 1 && Steps.front().K == Step::Pointer && 6867480093f4SDimitry Andric !Context.hasSameType(Composite1, Composite2)) { 6868480093f4SDimitry Andric // - if T1 or T2 is "pointer to cv1 void" and the other type is 6869480093f4SDimitry Andric // "pointer to cv2 T", where T is an object type or void, 6870480093f4SDimitry Andric // "pointer to cv12 void", where cv12 is the union of cv1 and cv2; 6871480093f4SDimitry Andric if (Composite1->isVoidType() && Composite2->isObjectType()) 6872480093f4SDimitry Andric Composite2 = Composite1; 6873480093f4SDimitry Andric else if (Composite2->isVoidType() && Composite1->isObjectType()) 6874480093f4SDimitry Andric Composite1 = Composite2; 6875480093f4SDimitry Andric // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 6876480093f4SDimitry Andric // is reference-related to C2 or C2 is reference-related to C1 (8.6.3), 6877480093f4SDimitry Andric // the cv-combined type of T1 and T2 or the cv-combined type of T2 and 6878480093f4SDimitry Andric // T1, respectively; 6879480093f4SDimitry Andric // 6880480093f4SDimitry Andric // The "similar type" handling covers all of this except for the "T1 is a 6881480093f4SDimitry Andric // base class of T2" case in the definition of reference-related. 6882480093f4SDimitry Andric else if (IsDerivedFrom(Loc, Composite1, Composite2)) 6883480093f4SDimitry Andric Composite1 = Composite2; 6884480093f4SDimitry Andric else if (IsDerivedFrom(Loc, Composite2, Composite1)) 6885480093f4SDimitry Andric Composite2 = Composite1; 6886480093f4SDimitry Andric } 6887480093f4SDimitry Andric 6888480093f4SDimitry Andric // At this point, either the inner types are the same or we have failed to 6889480093f4SDimitry Andric // find a composite pointer type. 6890480093f4SDimitry Andric if (!Context.hasSameType(Composite1, Composite2)) 6891480093f4SDimitry Andric return QualType(); 6892480093f4SDimitry Andric 6893480093f4SDimitry Andric // Per C++ [conv.qual]p3, add 'const' to every level before the last 6894480093f4SDimitry Andric // differing qualifier. 68950b57cec5SDimitry Andric for (unsigned I = 0; I != NeedConstBefore; ++I) 6896480093f4SDimitry Andric Steps[I].Quals.addConst(); 68970b57cec5SDimitry Andric 6898480093f4SDimitry Andric // Rebuild the composite type. 6899480093f4SDimitry Andric QualType Composite = Composite1; 6900480093f4SDimitry Andric for (auto &S : llvm::reverse(Steps)) 6901480093f4SDimitry Andric Composite = S.rebuild(Context, Composite); 69020b57cec5SDimitry Andric 6903480093f4SDimitry Andric if (ConvertArgs) { 6904480093f4SDimitry Andric // Convert the expressions to the composite pointer type. 6905480093f4SDimitry Andric InitializedEntity Entity = 6906480093f4SDimitry Andric InitializedEntity::InitializeTemporary(Composite); 6907480093f4SDimitry Andric InitializationKind Kind = 6908480093f4SDimitry Andric InitializationKind::CreateCopy(Loc, SourceLocation()); 69090b57cec5SDimitry Andric 6910480093f4SDimitry Andric InitializationSequence E1ToC(*this, Entity, Kind, E1); 6911480093f4SDimitry Andric if (!E1ToC) 6912480093f4SDimitry Andric return QualType(); 69130b57cec5SDimitry Andric 6914480093f4SDimitry Andric InitializationSequence E2ToC(*this, Entity, Kind, E2); 6915480093f4SDimitry Andric if (!E2ToC) 6916480093f4SDimitry Andric return QualType(); 6917480093f4SDimitry Andric 6918480093f4SDimitry Andric // FIXME: Let the caller know if these fail to avoid duplicate diagnostics. 6919480093f4SDimitry Andric ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1); 69200b57cec5SDimitry Andric if (E1Result.isInvalid()) 6921480093f4SDimitry Andric return QualType(); 6922480093f4SDimitry Andric E1 = E1Result.get(); 69230b57cec5SDimitry Andric 6924480093f4SDimitry Andric ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2); 69250b57cec5SDimitry Andric if (E2Result.isInvalid()) 69260b57cec5SDimitry Andric return QualType(); 6927480093f4SDimitry Andric E2 = E2Result.get(); 69280b57cec5SDimitry Andric } 69290b57cec5SDimitry Andric 6930480093f4SDimitry Andric return Composite; 69310b57cec5SDimitry Andric } 69320b57cec5SDimitry Andric 69330b57cec5SDimitry Andric ExprResult Sema::MaybeBindToTemporary(Expr *E) { 69340b57cec5SDimitry Andric if (!E) 69350b57cec5SDimitry Andric return ExprError(); 69360b57cec5SDimitry Andric 69370b57cec5SDimitry Andric assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); 69380b57cec5SDimitry Andric 69390b57cec5SDimitry Andric // If the result is a glvalue, we shouldn't bind it. 6940fe6060f1SDimitry Andric if (E->isGLValue()) 69410b57cec5SDimitry Andric return E; 69420b57cec5SDimitry Andric 69430b57cec5SDimitry Andric // In ARC, calls that return a retainable type can return retained, 69440b57cec5SDimitry Andric // in which case we have to insert a consuming cast. 69450b57cec5SDimitry Andric if (getLangOpts().ObjCAutoRefCount && 69460b57cec5SDimitry Andric E->getType()->isObjCRetainableType()) { 69470b57cec5SDimitry Andric 69480b57cec5SDimitry Andric bool ReturnsRetained; 69490b57cec5SDimitry Andric 69500b57cec5SDimitry Andric // For actual calls, we compute this by examining the type of the 69510b57cec5SDimitry Andric // called value. 69520b57cec5SDimitry Andric if (CallExpr *Call = dyn_cast<CallExpr>(E)) { 69530b57cec5SDimitry Andric Expr *Callee = Call->getCallee()->IgnoreParens(); 69540b57cec5SDimitry Andric QualType T = Callee->getType(); 69550b57cec5SDimitry Andric 69560b57cec5SDimitry Andric if (T == Context.BoundMemberTy) { 69570b57cec5SDimitry Andric // Handle pointer-to-members. 69580b57cec5SDimitry Andric if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) 69590b57cec5SDimitry Andric T = BinOp->getRHS()->getType(); 69600b57cec5SDimitry Andric else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) 69610b57cec5SDimitry Andric T = Mem->getMemberDecl()->getType(); 69620b57cec5SDimitry Andric } 69630b57cec5SDimitry Andric 69640b57cec5SDimitry Andric if (const PointerType *Ptr = T->getAs<PointerType>()) 69650b57cec5SDimitry Andric T = Ptr->getPointeeType(); 69660b57cec5SDimitry Andric else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) 69670b57cec5SDimitry Andric T = Ptr->getPointeeType(); 69680b57cec5SDimitry Andric else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) 69690b57cec5SDimitry Andric T = MemPtr->getPointeeType(); 69700b57cec5SDimitry Andric 69715ffd83dbSDimitry Andric auto *FTy = T->castAs<FunctionType>(); 69720b57cec5SDimitry Andric ReturnsRetained = FTy->getExtInfo().getProducesResult(); 69730b57cec5SDimitry Andric 69740b57cec5SDimitry Andric // ActOnStmtExpr arranges things so that StmtExprs of retainable 69750b57cec5SDimitry Andric // type always produce a +1 object. 69760b57cec5SDimitry Andric } else if (isa<StmtExpr>(E)) { 69770b57cec5SDimitry Andric ReturnsRetained = true; 69780b57cec5SDimitry Andric 69790b57cec5SDimitry Andric // We hit this case with the lambda conversion-to-block optimization; 69800b57cec5SDimitry Andric // we don't want any extra casts here. 69810b57cec5SDimitry Andric } else if (isa<CastExpr>(E) && 69820b57cec5SDimitry Andric isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { 69830b57cec5SDimitry Andric return E; 69840b57cec5SDimitry Andric 69850b57cec5SDimitry Andric // For message sends and property references, we try to find an 69860b57cec5SDimitry Andric // actual method. FIXME: we should infer retention by selector in 69870b57cec5SDimitry Andric // cases where we don't have an actual method. 69880b57cec5SDimitry Andric } else { 69890b57cec5SDimitry Andric ObjCMethodDecl *D = nullptr; 69900b57cec5SDimitry Andric if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { 69910b57cec5SDimitry Andric D = Send->getMethodDecl(); 69920b57cec5SDimitry Andric } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { 69930b57cec5SDimitry Andric D = BoxedExpr->getBoxingMethod(); 69940b57cec5SDimitry Andric } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { 69950b57cec5SDimitry Andric // Don't do reclaims if we're using the zero-element array 69960b57cec5SDimitry Andric // constant. 69970b57cec5SDimitry Andric if (ArrayLit->getNumElements() == 0 && 69980b57cec5SDimitry Andric Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 69990b57cec5SDimitry Andric return E; 70000b57cec5SDimitry Andric 70010b57cec5SDimitry Andric D = ArrayLit->getArrayWithObjectsMethod(); 70020b57cec5SDimitry Andric } else if (ObjCDictionaryLiteral *DictLit 70030b57cec5SDimitry Andric = dyn_cast<ObjCDictionaryLiteral>(E)) { 70040b57cec5SDimitry Andric // Don't do reclaims if we're using the zero-element dictionary 70050b57cec5SDimitry Andric // constant. 70060b57cec5SDimitry Andric if (DictLit->getNumElements() == 0 && 70070b57cec5SDimitry Andric Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) 70080b57cec5SDimitry Andric return E; 70090b57cec5SDimitry Andric 70100b57cec5SDimitry Andric D = DictLit->getDictWithObjectsMethod(); 70110b57cec5SDimitry Andric } 70120b57cec5SDimitry Andric 70130b57cec5SDimitry Andric ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); 70140b57cec5SDimitry Andric 70150b57cec5SDimitry Andric // Don't do reclaims on performSelector calls; despite their 70160b57cec5SDimitry Andric // return type, the invoked method doesn't necessarily actually 70170b57cec5SDimitry Andric // return an object. 70180b57cec5SDimitry Andric if (!ReturnsRetained && 70190b57cec5SDimitry Andric D && D->getMethodFamily() == OMF_performSelector) 70200b57cec5SDimitry Andric return E; 70210b57cec5SDimitry Andric } 70220b57cec5SDimitry Andric 70230b57cec5SDimitry Andric // Don't reclaim an object of Class type. 70240b57cec5SDimitry Andric if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) 70250b57cec5SDimitry Andric return E; 70260b57cec5SDimitry Andric 70270b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 70280b57cec5SDimitry Andric 70290b57cec5SDimitry Andric CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject 70300b57cec5SDimitry Andric : CK_ARCReclaimReturnedObject); 70310b57cec5SDimitry Andric return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, 7032fe6060f1SDimitry Andric VK_PRValue, FPOptionsOverride()); 70330b57cec5SDimitry Andric } 70340b57cec5SDimitry Andric 70355ffd83dbSDimitry Andric if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 70365ffd83dbSDimitry Andric Cleanup.setExprNeedsCleanups(true); 70375ffd83dbSDimitry Andric 70380b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus) 70390b57cec5SDimitry Andric return E; 70400b57cec5SDimitry Andric 70410b57cec5SDimitry Andric // Search for the base element type (cf. ASTContext::getBaseElementType) with 70420b57cec5SDimitry Andric // a fast path for the common case that the type is directly a RecordType. 70430b57cec5SDimitry Andric const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); 70440b57cec5SDimitry Andric const RecordType *RT = nullptr; 70450b57cec5SDimitry Andric while (!RT) { 70460b57cec5SDimitry Andric switch (T->getTypeClass()) { 70470b57cec5SDimitry Andric case Type::Record: 70480b57cec5SDimitry Andric RT = cast<RecordType>(T); 70490b57cec5SDimitry Andric break; 70500b57cec5SDimitry Andric case Type::ConstantArray: 70510b57cec5SDimitry Andric case Type::IncompleteArray: 70520b57cec5SDimitry Andric case Type::VariableArray: 70530b57cec5SDimitry Andric case Type::DependentSizedArray: 70540b57cec5SDimitry Andric T = cast<ArrayType>(T)->getElementType().getTypePtr(); 70550b57cec5SDimitry Andric break; 70560b57cec5SDimitry Andric default: 70570b57cec5SDimitry Andric return E; 70580b57cec5SDimitry Andric } 70590b57cec5SDimitry Andric } 70600b57cec5SDimitry Andric 70610b57cec5SDimitry Andric // That should be enough to guarantee that this type is complete, if we're 70620b57cec5SDimitry Andric // not processing a decltype expression. 70630b57cec5SDimitry Andric CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 70640b57cec5SDimitry Andric if (RD->isInvalidDecl() || RD->isDependentContext()) 70650b57cec5SDimitry Andric return E; 70660b57cec5SDimitry Andric 70670b57cec5SDimitry Andric bool IsDecltype = ExprEvalContexts.back().ExprContext == 70680b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Decltype; 70690b57cec5SDimitry Andric CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); 70700b57cec5SDimitry Andric 70710b57cec5SDimitry Andric if (Destructor) { 70720b57cec5SDimitry Andric MarkFunctionReferenced(E->getExprLoc(), Destructor); 70730b57cec5SDimitry Andric CheckDestructorAccess(E->getExprLoc(), Destructor, 70740b57cec5SDimitry Andric PDiag(diag::err_access_dtor_temp) 70750b57cec5SDimitry Andric << E->getType()); 70760b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) 70770b57cec5SDimitry Andric return ExprError(); 70780b57cec5SDimitry Andric 70790b57cec5SDimitry Andric // If destructor is trivial, we can avoid the extra copy. 70800b57cec5SDimitry Andric if (Destructor->isTrivial()) 70810b57cec5SDimitry Andric return E; 70820b57cec5SDimitry Andric 70830b57cec5SDimitry Andric // We need a cleanup, but we don't need to remember the temporary. 70840b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 70850b57cec5SDimitry Andric } 70860b57cec5SDimitry Andric 70870b57cec5SDimitry Andric CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); 70880b57cec5SDimitry Andric CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); 70890b57cec5SDimitry Andric 70900b57cec5SDimitry Andric if (IsDecltype) 70910b57cec5SDimitry Andric ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); 70920b57cec5SDimitry Andric 70930b57cec5SDimitry Andric return Bind; 70940b57cec5SDimitry Andric } 70950b57cec5SDimitry Andric 70960b57cec5SDimitry Andric ExprResult 70970b57cec5SDimitry Andric Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { 70980b57cec5SDimitry Andric if (SubExpr.isInvalid()) 70990b57cec5SDimitry Andric return ExprError(); 71000b57cec5SDimitry Andric 71010b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(SubExpr.get()); 71020b57cec5SDimitry Andric } 71030b57cec5SDimitry Andric 71040b57cec5SDimitry Andric Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { 71050b57cec5SDimitry Andric assert(SubExpr && "subexpression can't be null!"); 71060b57cec5SDimitry Andric 71070b57cec5SDimitry Andric CleanupVarDeclMarking(); 71080b57cec5SDimitry Andric 71090b57cec5SDimitry Andric unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; 71100b57cec5SDimitry Andric assert(ExprCleanupObjects.size() >= FirstCleanup); 71110b57cec5SDimitry Andric assert(Cleanup.exprNeedsCleanups() || 71120b57cec5SDimitry Andric ExprCleanupObjects.size() == FirstCleanup); 71130b57cec5SDimitry Andric if (!Cleanup.exprNeedsCleanups()) 71140b57cec5SDimitry Andric return SubExpr; 71150b57cec5SDimitry Andric 71160b57cec5SDimitry Andric auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup, 71170b57cec5SDimitry Andric ExprCleanupObjects.size() - FirstCleanup); 71180b57cec5SDimitry Andric 71190b57cec5SDimitry Andric auto *E = ExprWithCleanups::Create( 71200b57cec5SDimitry Andric Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); 71210b57cec5SDimitry Andric DiscardCleanupsInEvaluationContext(); 71220b57cec5SDimitry Andric 71230b57cec5SDimitry Andric return E; 71240b57cec5SDimitry Andric } 71250b57cec5SDimitry Andric 71260b57cec5SDimitry Andric Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { 71270b57cec5SDimitry Andric assert(SubStmt && "sub-statement can't be null!"); 71280b57cec5SDimitry Andric 71290b57cec5SDimitry Andric CleanupVarDeclMarking(); 71300b57cec5SDimitry Andric 71310b57cec5SDimitry Andric if (!Cleanup.exprNeedsCleanups()) 71320b57cec5SDimitry Andric return SubStmt; 71330b57cec5SDimitry Andric 71340b57cec5SDimitry Andric // FIXME: In order to attach the temporaries, wrap the statement into 71350b57cec5SDimitry Andric // a StmtExpr; currently this is only used for asm statements. 71360b57cec5SDimitry Andric // This is hacky, either create a new CXXStmtWithTemporaries statement or 71370b57cec5SDimitry Andric // a new AsmStmtWithTemporaries. 71380b57cec5SDimitry Andric CompoundStmt *CompStmt = CompoundStmt::Create( 71390b57cec5SDimitry Andric Context, SubStmt, SourceLocation(), SourceLocation()); 71408c27c554SDimitry Andric Expr *E = new (Context) 71418c27c554SDimitry Andric StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), 7142cd675bb6SDimitry Andric /*FIXME TemplateDepth=*/0); 71430b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(E); 71440b57cec5SDimitry Andric } 71450b57cec5SDimitry Andric 71460b57cec5SDimitry Andric /// Process the expression contained within a decltype. For such expressions, 71470b57cec5SDimitry Andric /// certain semantic checks on temporaries are delayed until this point, and 71480b57cec5SDimitry Andric /// are omitted for the 'topmost' call in the decltype expression. If the 71490b57cec5SDimitry Andric /// topmost call bound a temporary, strip that temporary off the expression. 71500b57cec5SDimitry Andric ExprResult Sema::ActOnDecltypeExpression(Expr *E) { 71510b57cec5SDimitry Andric assert(ExprEvalContexts.back().ExprContext == 71520b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Decltype && 71530b57cec5SDimitry Andric "not in a decltype expression"); 71540b57cec5SDimitry Andric 71550b57cec5SDimitry Andric ExprResult Result = CheckPlaceholderExpr(E); 71560b57cec5SDimitry Andric if (Result.isInvalid()) 71570b57cec5SDimitry Andric return ExprError(); 71580b57cec5SDimitry Andric E = Result.get(); 71590b57cec5SDimitry Andric 71600b57cec5SDimitry Andric // C++11 [expr.call]p11: 71610b57cec5SDimitry Andric // If a function call is a prvalue of object type, 71620b57cec5SDimitry Andric // -- if the function call is either 71630b57cec5SDimitry Andric // -- the operand of a decltype-specifier, or 71640b57cec5SDimitry Andric // -- the right operand of a comma operator that is the operand of a 71650b57cec5SDimitry Andric // decltype-specifier, 71660b57cec5SDimitry Andric // a temporary object is not introduced for the prvalue. 71670b57cec5SDimitry Andric 71680b57cec5SDimitry Andric // Recursively rebuild ParenExprs and comma expressions to strip out the 71690b57cec5SDimitry Andric // outermost CXXBindTemporaryExpr, if any. 71700b57cec5SDimitry Andric if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 71710b57cec5SDimitry Andric ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); 71720b57cec5SDimitry Andric if (SubExpr.isInvalid()) 71730b57cec5SDimitry Andric return ExprError(); 71740b57cec5SDimitry Andric if (SubExpr.get() == PE->getSubExpr()) 71750b57cec5SDimitry Andric return E; 71760b57cec5SDimitry Andric return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); 71770b57cec5SDimitry Andric } 71780b57cec5SDimitry Andric if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 71790b57cec5SDimitry Andric if (BO->getOpcode() == BO_Comma) { 71800b57cec5SDimitry Andric ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); 71810b57cec5SDimitry Andric if (RHS.isInvalid()) 71820b57cec5SDimitry Andric return ExprError(); 71830b57cec5SDimitry Andric if (RHS.get() == BO->getRHS()) 71840b57cec5SDimitry Andric return E; 71855ffd83dbSDimitry Andric return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma, 71865ffd83dbSDimitry Andric BO->getType(), BO->getValueKind(), 71875ffd83dbSDimitry Andric BO->getObjectKind(), BO->getOperatorLoc(), 71885ffd83dbSDimitry Andric BO->getFPFeatures(getLangOpts())); 71890b57cec5SDimitry Andric } 71900b57cec5SDimitry Andric } 71910b57cec5SDimitry Andric 71920b57cec5SDimitry Andric CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); 71930b57cec5SDimitry Andric CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) 71940b57cec5SDimitry Andric : nullptr; 71950b57cec5SDimitry Andric if (TopCall) 71960b57cec5SDimitry Andric E = TopCall; 71970b57cec5SDimitry Andric else 71980b57cec5SDimitry Andric TopBind = nullptr; 71990b57cec5SDimitry Andric 72000b57cec5SDimitry Andric // Disable the special decltype handling now. 72010b57cec5SDimitry Andric ExprEvalContexts.back().ExprContext = 72020b57cec5SDimitry Andric ExpressionEvaluationContextRecord::EK_Other; 72030b57cec5SDimitry Andric 7204a7dea167SDimitry Andric Result = CheckUnevaluatedOperand(E); 7205a7dea167SDimitry Andric if (Result.isInvalid()) 7206a7dea167SDimitry Andric return ExprError(); 7207a7dea167SDimitry Andric E = Result.get(); 7208a7dea167SDimitry Andric 72090b57cec5SDimitry Andric // In MS mode, don't perform any extra checking of call return types within a 72100b57cec5SDimitry Andric // decltype expression. 72110b57cec5SDimitry Andric if (getLangOpts().MSVCCompat) 72120b57cec5SDimitry Andric return E; 72130b57cec5SDimitry Andric 72140b57cec5SDimitry Andric // Perform the semantic checks we delayed until this point. 72150b57cec5SDimitry Andric for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); 72160b57cec5SDimitry Andric I != N; ++I) { 72170b57cec5SDimitry Andric CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; 72180b57cec5SDimitry Andric if (Call == TopCall) 72190b57cec5SDimitry Andric continue; 72200b57cec5SDimitry Andric 72210b57cec5SDimitry Andric if (CheckCallReturnType(Call->getCallReturnType(Context), 72220b57cec5SDimitry Andric Call->getBeginLoc(), Call, Call->getDirectCallee())) 72230b57cec5SDimitry Andric return ExprError(); 72240b57cec5SDimitry Andric } 72250b57cec5SDimitry Andric 72260b57cec5SDimitry Andric // Now all relevant types are complete, check the destructors are accessible 72270b57cec5SDimitry Andric // and non-deleted, and annotate them on the temporaries. 72280b57cec5SDimitry Andric for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); 72290b57cec5SDimitry Andric I != N; ++I) { 72300b57cec5SDimitry Andric CXXBindTemporaryExpr *Bind = 72310b57cec5SDimitry Andric ExprEvalContexts.back().DelayedDecltypeBinds[I]; 72320b57cec5SDimitry Andric if (Bind == TopBind) 72330b57cec5SDimitry Andric continue; 72340b57cec5SDimitry Andric 72350b57cec5SDimitry Andric CXXTemporary *Temp = Bind->getTemporary(); 72360b57cec5SDimitry Andric 72370b57cec5SDimitry Andric CXXRecordDecl *RD = 72380b57cec5SDimitry Andric Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 72390b57cec5SDimitry Andric CXXDestructorDecl *Destructor = LookupDestructor(RD); 72400b57cec5SDimitry Andric Temp->setDestructor(Destructor); 72410b57cec5SDimitry Andric 72420b57cec5SDimitry Andric MarkFunctionReferenced(Bind->getExprLoc(), Destructor); 72430b57cec5SDimitry Andric CheckDestructorAccess(Bind->getExprLoc(), Destructor, 72440b57cec5SDimitry Andric PDiag(diag::err_access_dtor_temp) 72450b57cec5SDimitry Andric << Bind->getType()); 72460b57cec5SDimitry Andric if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) 72470b57cec5SDimitry Andric return ExprError(); 72480b57cec5SDimitry Andric 72490b57cec5SDimitry Andric // We need a cleanup, but we don't need to remember the temporary. 72500b57cec5SDimitry Andric Cleanup.setExprNeedsCleanups(true); 72510b57cec5SDimitry Andric } 72520b57cec5SDimitry Andric 72530b57cec5SDimitry Andric // Possibly strip off the top CXXBindTemporaryExpr. 72540b57cec5SDimitry Andric return E; 72550b57cec5SDimitry Andric } 72560b57cec5SDimitry Andric 72570b57cec5SDimitry Andric /// Note a set of 'operator->' functions that were used for a member access. 72580b57cec5SDimitry Andric static void noteOperatorArrows(Sema &S, 72590b57cec5SDimitry Andric ArrayRef<FunctionDecl *> OperatorArrows) { 72600b57cec5SDimitry Andric unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; 72610b57cec5SDimitry Andric // FIXME: Make this configurable? 72620b57cec5SDimitry Andric unsigned Limit = 9; 72630b57cec5SDimitry Andric if (OperatorArrows.size() > Limit) { 72640b57cec5SDimitry Andric // Produce Limit-1 normal notes and one 'skipping' note. 72650b57cec5SDimitry Andric SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; 72660b57cec5SDimitry Andric SkipCount = OperatorArrows.size() - (Limit - 1); 72670b57cec5SDimitry Andric } 72680b57cec5SDimitry Andric 72690b57cec5SDimitry Andric for (unsigned I = 0; I < OperatorArrows.size(); /**/) { 72700b57cec5SDimitry Andric if (I == SkipStart) { 72710b57cec5SDimitry Andric S.Diag(OperatorArrows[I]->getLocation(), 72720b57cec5SDimitry Andric diag::note_operator_arrows_suppressed) 72730b57cec5SDimitry Andric << SkipCount; 72740b57cec5SDimitry Andric I += SkipCount; 72750b57cec5SDimitry Andric } else { 72760b57cec5SDimitry Andric S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) 72770b57cec5SDimitry Andric << OperatorArrows[I]->getCallResultType(); 72780b57cec5SDimitry Andric ++I; 72790b57cec5SDimitry Andric } 72800b57cec5SDimitry Andric } 72810b57cec5SDimitry Andric } 72820b57cec5SDimitry Andric 72830b57cec5SDimitry Andric ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, 72840b57cec5SDimitry Andric SourceLocation OpLoc, 72850b57cec5SDimitry Andric tok::TokenKind OpKind, 72860b57cec5SDimitry Andric ParsedType &ObjectType, 72870b57cec5SDimitry Andric bool &MayBePseudoDestructor) { 72880b57cec5SDimitry Andric // Since this might be a postfix expression, get rid of ParenListExprs. 72890b57cec5SDimitry Andric ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 72900b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 72910b57cec5SDimitry Andric Base = Result.get(); 72920b57cec5SDimitry Andric 72930b57cec5SDimitry Andric Result = CheckPlaceholderExpr(Base); 72940b57cec5SDimitry Andric if (Result.isInvalid()) return ExprError(); 72950b57cec5SDimitry Andric Base = Result.get(); 72960b57cec5SDimitry Andric 72970b57cec5SDimitry Andric QualType BaseType = Base->getType(); 72980b57cec5SDimitry Andric MayBePseudoDestructor = false; 72990b57cec5SDimitry Andric if (BaseType->isDependentType()) { 73000b57cec5SDimitry Andric // If we have a pointer to a dependent type and are using the -> operator, 73010b57cec5SDimitry Andric // the object type is the type that the pointer points to. We might still 73020b57cec5SDimitry Andric // have enough information about that type to do something useful. 73030b57cec5SDimitry Andric if (OpKind == tok::arrow) 73040b57cec5SDimitry Andric if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 73050b57cec5SDimitry Andric BaseType = Ptr->getPointeeType(); 73060b57cec5SDimitry Andric 73070b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 73080b57cec5SDimitry Andric MayBePseudoDestructor = true; 73090b57cec5SDimitry Andric return Base; 73100b57cec5SDimitry Andric } 73110b57cec5SDimitry Andric 73120b57cec5SDimitry Andric // C++ [over.match.oper]p8: 73130b57cec5SDimitry Andric // [...] When operator->returns, the operator-> is applied to the value 73140b57cec5SDimitry Andric // returned, with the original second operand. 73150b57cec5SDimitry Andric if (OpKind == tok::arrow) { 73160b57cec5SDimitry Andric QualType StartingType = BaseType; 73170b57cec5SDimitry Andric bool NoArrowOperatorFound = false; 73180b57cec5SDimitry Andric bool FirstIteration = true; 73190b57cec5SDimitry Andric FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); 73200b57cec5SDimitry Andric // The set of types we've considered so far. 73210b57cec5SDimitry Andric llvm::SmallPtrSet<CanQualType,8> CTypes; 73220b57cec5SDimitry Andric SmallVector<FunctionDecl*, 8> OperatorArrows; 73230b57cec5SDimitry Andric CTypes.insert(Context.getCanonicalType(BaseType)); 73240b57cec5SDimitry Andric 73250b57cec5SDimitry Andric while (BaseType->isRecordType()) { 73260b57cec5SDimitry Andric if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { 73270b57cec5SDimitry Andric Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) 73280b57cec5SDimitry Andric << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); 73290b57cec5SDimitry Andric noteOperatorArrows(*this, OperatorArrows); 73300b57cec5SDimitry Andric Diag(OpLoc, diag::note_operator_arrow_depth) 73310b57cec5SDimitry Andric << getLangOpts().ArrowDepth; 73320b57cec5SDimitry Andric return ExprError(); 73330b57cec5SDimitry Andric } 73340b57cec5SDimitry Andric 73350b57cec5SDimitry Andric Result = BuildOverloadedArrowExpr( 73360b57cec5SDimitry Andric S, Base, OpLoc, 73370b57cec5SDimitry Andric // When in a template specialization and on the first loop iteration, 73380b57cec5SDimitry Andric // potentially give the default diagnostic (with the fixit in a 73390b57cec5SDimitry Andric // separate note) instead of having the error reported back to here 73400b57cec5SDimitry Andric // and giving a diagnostic with a fixit attached to the error itself. 73410b57cec5SDimitry Andric (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) 73420b57cec5SDimitry Andric ? nullptr 73430b57cec5SDimitry Andric : &NoArrowOperatorFound); 73440b57cec5SDimitry Andric if (Result.isInvalid()) { 73450b57cec5SDimitry Andric if (NoArrowOperatorFound) { 73460b57cec5SDimitry Andric if (FirstIteration) { 73470b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 73480b57cec5SDimitry Andric << BaseType << 1 << Base->getSourceRange() 73490b57cec5SDimitry Andric << FixItHint::CreateReplacement(OpLoc, "."); 73500b57cec5SDimitry Andric OpKind = tok::period; 73510b57cec5SDimitry Andric break; 73520b57cec5SDimitry Andric } 73530b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 73540b57cec5SDimitry Andric << BaseType << Base->getSourceRange(); 73550b57cec5SDimitry Andric CallExpr *CE = dyn_cast<CallExpr>(Base); 73560b57cec5SDimitry Andric if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { 73570b57cec5SDimitry Andric Diag(CD->getBeginLoc(), 73580b57cec5SDimitry Andric diag::note_member_reference_arrow_from_operator_arrow); 73590b57cec5SDimitry Andric } 73600b57cec5SDimitry Andric } 73610b57cec5SDimitry Andric return ExprError(); 73620b57cec5SDimitry Andric } 73630b57cec5SDimitry Andric Base = Result.get(); 73640b57cec5SDimitry Andric if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) 73650b57cec5SDimitry Andric OperatorArrows.push_back(OpCall->getDirectCallee()); 73660b57cec5SDimitry Andric BaseType = Base->getType(); 73670b57cec5SDimitry Andric CanQualType CBaseType = Context.getCanonicalType(BaseType); 73680b57cec5SDimitry Andric if (!CTypes.insert(CBaseType).second) { 73690b57cec5SDimitry Andric Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; 73700b57cec5SDimitry Andric noteOperatorArrows(*this, OperatorArrows); 73710b57cec5SDimitry Andric return ExprError(); 73720b57cec5SDimitry Andric } 73730b57cec5SDimitry Andric FirstIteration = false; 73740b57cec5SDimitry Andric } 73750b57cec5SDimitry Andric 73760b57cec5SDimitry Andric if (OpKind == tok::arrow) { 73770b57cec5SDimitry Andric if (BaseType->isPointerType()) 73780b57cec5SDimitry Andric BaseType = BaseType->getPointeeType(); 73790b57cec5SDimitry Andric else if (auto *AT = Context.getAsArrayType(BaseType)) 73800b57cec5SDimitry Andric BaseType = AT->getElementType(); 73810b57cec5SDimitry Andric } 73820b57cec5SDimitry Andric } 73830b57cec5SDimitry Andric 73840b57cec5SDimitry Andric // Objective-C properties allow "." access on Objective-C pointer types, 73850b57cec5SDimitry Andric // so adjust the base type to the object type itself. 73860b57cec5SDimitry Andric if (BaseType->isObjCObjectPointerType()) 73870b57cec5SDimitry Andric BaseType = BaseType->getPointeeType(); 73880b57cec5SDimitry Andric 73890b57cec5SDimitry Andric // C++ [basic.lookup.classref]p2: 73900b57cec5SDimitry Andric // [...] If the type of the object expression is of pointer to scalar 73910b57cec5SDimitry Andric // type, the unqualified-id is looked up in the context of the complete 73920b57cec5SDimitry Andric // postfix-expression. 73930b57cec5SDimitry Andric // 73940b57cec5SDimitry Andric // This also indicates that we could be parsing a pseudo-destructor-name. 73950b57cec5SDimitry Andric // Note that Objective-C class and object types can be pseudo-destructor 73960b57cec5SDimitry Andric // expressions or normal member (ivar or property) access expressions, and 73970b57cec5SDimitry Andric // it's legal for the type to be incomplete if this is a pseudo-destructor 73980b57cec5SDimitry Andric // call. We'll do more incomplete-type checks later in the lookup process, 73990b57cec5SDimitry Andric // so just skip this check for ObjC types. 74000b57cec5SDimitry Andric if (!BaseType->isRecordType()) { 74010b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 74020b57cec5SDimitry Andric MayBePseudoDestructor = true; 74030b57cec5SDimitry Andric return Base; 74040b57cec5SDimitry Andric } 74050b57cec5SDimitry Andric 74060b57cec5SDimitry Andric // The object type must be complete (or dependent), or 74070b57cec5SDimitry Andric // C++11 [expr.prim.general]p3: 74080b57cec5SDimitry Andric // Unlike the object expression in other contexts, *this is not required to 74090b57cec5SDimitry Andric // be of complete type for purposes of class member access (5.2.5) outside 74100b57cec5SDimitry Andric // the member function body. 74110b57cec5SDimitry Andric if (!BaseType->isDependentType() && 74120b57cec5SDimitry Andric !isThisOutsideMemberFunctionBody(BaseType) && 741304eeddc0SDimitry Andric RequireCompleteType(OpLoc, BaseType, 741404eeddc0SDimitry Andric diag::err_incomplete_member_access)) { 741504eeddc0SDimitry Andric return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base}); 741604eeddc0SDimitry Andric } 74170b57cec5SDimitry Andric 74180b57cec5SDimitry Andric // C++ [basic.lookup.classref]p2: 74190b57cec5SDimitry Andric // If the id-expression in a class member access (5.2.5) is an 74200b57cec5SDimitry Andric // unqualified-id, and the type of the object expression is of a class 74210b57cec5SDimitry Andric // type C (or of pointer to a class type C), the unqualified-id is looked 74220b57cec5SDimitry Andric // up in the scope of class C. [...] 74230b57cec5SDimitry Andric ObjectType = ParsedType::make(BaseType); 74240b57cec5SDimitry Andric return Base; 74250b57cec5SDimitry Andric } 74260b57cec5SDimitry Andric 74270b57cec5SDimitry Andric static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, 74280b57cec5SDimitry Andric tok::TokenKind &OpKind, SourceLocation OpLoc) { 74290b57cec5SDimitry Andric if (Base->hasPlaceholderType()) { 74300b57cec5SDimitry Andric ExprResult result = S.CheckPlaceholderExpr(Base); 74310b57cec5SDimitry Andric if (result.isInvalid()) return true; 74320b57cec5SDimitry Andric Base = result.get(); 74330b57cec5SDimitry Andric } 74340b57cec5SDimitry Andric ObjectType = Base->getType(); 74350b57cec5SDimitry Andric 74360b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 74370b57cec5SDimitry Andric // The left-hand side of the dot operator shall be of scalar type. The 74380b57cec5SDimitry Andric // left-hand side of the arrow operator shall be of pointer to scalar type. 74390b57cec5SDimitry Andric // This scalar type is the object type. 74400b57cec5SDimitry Andric // Note that this is rather different from the normal handling for the 74410b57cec5SDimitry Andric // arrow operator. 74420b57cec5SDimitry Andric if (OpKind == tok::arrow) { 7443e8d8bef9SDimitry Andric // The operator requires a prvalue, so perform lvalue conversions. 7444e8d8bef9SDimitry Andric // Only do this if we might plausibly end with a pointer, as otherwise 7445e8d8bef9SDimitry Andric // this was likely to be intended to be a '.'. 7446e8d8bef9SDimitry Andric if (ObjectType->isPointerType() || ObjectType->isArrayType() || 7447e8d8bef9SDimitry Andric ObjectType->isFunctionType()) { 7448e8d8bef9SDimitry Andric ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base); 7449e8d8bef9SDimitry Andric if (BaseResult.isInvalid()) 7450e8d8bef9SDimitry Andric return true; 7451e8d8bef9SDimitry Andric Base = BaseResult.get(); 7452e8d8bef9SDimitry Andric ObjectType = Base->getType(); 7453e8d8bef9SDimitry Andric } 7454e8d8bef9SDimitry Andric 74550b57cec5SDimitry Andric if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { 74560b57cec5SDimitry Andric ObjectType = Ptr->getPointeeType(); 74570b57cec5SDimitry Andric } else if (!Base->isTypeDependent()) { 74580b57cec5SDimitry Andric // The user wrote "p->" when they probably meant "p."; fix it. 74590b57cec5SDimitry Andric S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 74600b57cec5SDimitry Andric << ObjectType << true 74610b57cec5SDimitry Andric << FixItHint::CreateReplacement(OpLoc, "."); 74620b57cec5SDimitry Andric if (S.isSFINAEContext()) 74630b57cec5SDimitry Andric return true; 74640b57cec5SDimitry Andric 74650b57cec5SDimitry Andric OpKind = tok::period; 74660b57cec5SDimitry Andric } 74670b57cec5SDimitry Andric } 74680b57cec5SDimitry Andric 74690b57cec5SDimitry Andric return false; 74700b57cec5SDimitry Andric } 74710b57cec5SDimitry Andric 74720b57cec5SDimitry Andric /// Check if it's ok to try and recover dot pseudo destructor calls on 74730b57cec5SDimitry Andric /// pointer objects. 74740b57cec5SDimitry Andric static bool 74750b57cec5SDimitry Andric canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, 74760b57cec5SDimitry Andric QualType DestructedType) { 74770b57cec5SDimitry Andric // If this is a record type, check if its destructor is callable. 74780b57cec5SDimitry Andric if (auto *RD = DestructedType->getAsCXXRecordDecl()) { 74790b57cec5SDimitry Andric if (RD->hasDefinition()) 74800b57cec5SDimitry Andric if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) 74810b57cec5SDimitry Andric return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); 74820b57cec5SDimitry Andric return false; 74830b57cec5SDimitry Andric } 74840b57cec5SDimitry Andric 74850b57cec5SDimitry Andric // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. 74860b57cec5SDimitry Andric return DestructedType->isDependentType() || DestructedType->isScalarType() || 74870b57cec5SDimitry Andric DestructedType->isVectorType(); 74880b57cec5SDimitry Andric } 74890b57cec5SDimitry Andric 74900b57cec5SDimitry Andric ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, 74910b57cec5SDimitry Andric SourceLocation OpLoc, 74920b57cec5SDimitry Andric tok::TokenKind OpKind, 74930b57cec5SDimitry Andric const CXXScopeSpec &SS, 74940b57cec5SDimitry Andric TypeSourceInfo *ScopeTypeInfo, 74950b57cec5SDimitry Andric SourceLocation CCLoc, 74960b57cec5SDimitry Andric SourceLocation TildeLoc, 74970b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed) { 74980b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); 74990b57cec5SDimitry Andric 75000b57cec5SDimitry Andric QualType ObjectType; 75010b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 75020b57cec5SDimitry Andric return ExprError(); 75030b57cec5SDimitry Andric 75040b57cec5SDimitry Andric if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && 75050b57cec5SDimitry Andric !ObjectType->isVectorType()) { 75060b57cec5SDimitry Andric if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) 75070b57cec5SDimitry Andric Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); 75080b57cec5SDimitry Andric else { 75090b57cec5SDimitry Andric Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) 75100b57cec5SDimitry Andric << ObjectType << Base->getSourceRange(); 75110b57cec5SDimitry Andric return ExprError(); 75120b57cec5SDimitry Andric } 75130b57cec5SDimitry Andric } 75140b57cec5SDimitry Andric 75150b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 75160b57cec5SDimitry Andric // [...] The cv-unqualified versions of the object type and of the type 75170b57cec5SDimitry Andric // designated by the pseudo-destructor-name shall be the same type. 75180b57cec5SDimitry Andric if (DestructedTypeInfo) { 75190b57cec5SDimitry Andric QualType DestructedType = DestructedTypeInfo->getType(); 75200b57cec5SDimitry Andric SourceLocation DestructedTypeStart 75210b57cec5SDimitry Andric = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(); 75220b57cec5SDimitry Andric if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { 75230b57cec5SDimitry Andric if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { 75240b57cec5SDimitry Andric // Detect dot pseudo destructor calls on pointer objects, e.g.: 75250b57cec5SDimitry Andric // Foo *foo; 75260b57cec5SDimitry Andric // foo.~Foo(); 75270b57cec5SDimitry Andric if (OpKind == tok::period && ObjectType->isPointerType() && 75280b57cec5SDimitry Andric Context.hasSameUnqualifiedType(DestructedType, 75290b57cec5SDimitry Andric ObjectType->getPointeeType())) { 75300b57cec5SDimitry Andric auto Diagnostic = 75310b57cec5SDimitry Andric Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 75320b57cec5SDimitry Andric << ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); 75330b57cec5SDimitry Andric 75340b57cec5SDimitry Andric // Issue a fixit only when the destructor is valid. 75350b57cec5SDimitry Andric if (canRecoverDotPseudoDestructorCallsOnPointerObjects( 75360b57cec5SDimitry Andric *this, DestructedType)) 75370b57cec5SDimitry Andric Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); 75380b57cec5SDimitry Andric 75390b57cec5SDimitry Andric // Recover by setting the object type to the destructed type and the 75400b57cec5SDimitry Andric // operator to '->'. 75410b57cec5SDimitry Andric ObjectType = DestructedType; 75420b57cec5SDimitry Andric OpKind = tok::arrow; 75430b57cec5SDimitry Andric } else { 75440b57cec5SDimitry Andric Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) 75450b57cec5SDimitry Andric << ObjectType << DestructedType << Base->getSourceRange() 75460b57cec5SDimitry Andric << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 75470b57cec5SDimitry Andric 75480b57cec5SDimitry Andric // Recover by setting the destructed type to the object type. 75490b57cec5SDimitry Andric DestructedType = ObjectType; 75500b57cec5SDimitry Andric DestructedTypeInfo = 75510b57cec5SDimitry Andric Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); 75520b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 75530b57cec5SDimitry Andric } 75540b57cec5SDimitry Andric } else if (DestructedType.getObjCLifetime() != 75550b57cec5SDimitry Andric ObjectType.getObjCLifetime()) { 75560b57cec5SDimitry Andric 75570b57cec5SDimitry Andric if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { 75580b57cec5SDimitry Andric // Okay: just pretend that the user provided the correctly-qualified 75590b57cec5SDimitry Andric // type. 75600b57cec5SDimitry Andric } else { 75610b57cec5SDimitry Andric Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) 75620b57cec5SDimitry Andric << ObjectType << DestructedType << Base->getSourceRange() 75630b57cec5SDimitry Andric << DestructedTypeInfo->getTypeLoc().getLocalSourceRange(); 75640b57cec5SDimitry Andric } 75650b57cec5SDimitry Andric 75660b57cec5SDimitry Andric // Recover by setting the destructed type to the object type. 75670b57cec5SDimitry Andric DestructedType = ObjectType; 75680b57cec5SDimitry Andric DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, 75690b57cec5SDimitry Andric DestructedTypeStart); 75700b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 75710b57cec5SDimitry Andric } 75720b57cec5SDimitry Andric } 75730b57cec5SDimitry Andric } 75740b57cec5SDimitry Andric 75750b57cec5SDimitry Andric // C++ [expr.pseudo]p2: 75760b57cec5SDimitry Andric // [...] Furthermore, the two type-names in a pseudo-destructor-name of the 75770b57cec5SDimitry Andric // form 75780b57cec5SDimitry Andric // 75790b57cec5SDimitry Andric // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name 75800b57cec5SDimitry Andric // 75810b57cec5SDimitry Andric // shall designate the same scalar type. 75820b57cec5SDimitry Andric if (ScopeTypeInfo) { 75830b57cec5SDimitry Andric QualType ScopeType = ScopeTypeInfo->getType(); 75840b57cec5SDimitry Andric if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && 75850b57cec5SDimitry Andric !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { 75860b57cec5SDimitry Andric 75870b57cec5SDimitry Andric Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(), 75880b57cec5SDimitry Andric diag::err_pseudo_dtor_type_mismatch) 75890b57cec5SDimitry Andric << ObjectType << ScopeType << Base->getSourceRange() 75900b57cec5SDimitry Andric << ScopeTypeInfo->getTypeLoc().getLocalSourceRange(); 75910b57cec5SDimitry Andric 75920b57cec5SDimitry Andric ScopeType = QualType(); 75930b57cec5SDimitry Andric ScopeTypeInfo = nullptr; 75940b57cec5SDimitry Andric } 75950b57cec5SDimitry Andric } 75960b57cec5SDimitry Andric 75970b57cec5SDimitry Andric Expr *Result 75980b57cec5SDimitry Andric = new (Context) CXXPseudoDestructorExpr(Context, Base, 75990b57cec5SDimitry Andric OpKind == tok::arrow, OpLoc, 76000b57cec5SDimitry Andric SS.getWithLocInContext(Context), 76010b57cec5SDimitry Andric ScopeTypeInfo, 76020b57cec5SDimitry Andric CCLoc, 76030b57cec5SDimitry Andric TildeLoc, 76040b57cec5SDimitry Andric Destructed); 76050b57cec5SDimitry Andric 76060b57cec5SDimitry Andric return Result; 76070b57cec5SDimitry Andric } 76080b57cec5SDimitry Andric 76090b57cec5SDimitry Andric ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 76100b57cec5SDimitry Andric SourceLocation OpLoc, 76110b57cec5SDimitry Andric tok::TokenKind OpKind, 76120b57cec5SDimitry Andric CXXScopeSpec &SS, 76130b57cec5SDimitry Andric UnqualifiedId &FirstTypeName, 76140b57cec5SDimitry Andric SourceLocation CCLoc, 76150b57cec5SDimitry Andric SourceLocation TildeLoc, 76160b57cec5SDimitry Andric UnqualifiedId &SecondTypeName) { 76170b57cec5SDimitry Andric assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 76180b57cec5SDimitry Andric FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 76190b57cec5SDimitry Andric "Invalid first type name in pseudo-destructor"); 76200b57cec5SDimitry Andric assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 76210b57cec5SDimitry Andric SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && 76220b57cec5SDimitry Andric "Invalid second type name in pseudo-destructor"); 76230b57cec5SDimitry Andric 76240b57cec5SDimitry Andric QualType ObjectType; 76250b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 76260b57cec5SDimitry Andric return ExprError(); 76270b57cec5SDimitry Andric 76280b57cec5SDimitry Andric // Compute the object type that we should use for name lookup purposes. Only 76290b57cec5SDimitry Andric // record types and dependent types matter. 76300b57cec5SDimitry Andric ParsedType ObjectTypePtrForLookup; 76310b57cec5SDimitry Andric if (!SS.isSet()) { 76320b57cec5SDimitry Andric if (ObjectType->isRecordType()) 76330b57cec5SDimitry Andric ObjectTypePtrForLookup = ParsedType::make(ObjectType); 76340b57cec5SDimitry Andric else if (ObjectType->isDependentType()) 76350b57cec5SDimitry Andric ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); 76360b57cec5SDimitry Andric } 76370b57cec5SDimitry Andric 76380b57cec5SDimitry Andric // Convert the name of the type being destructed (following the ~) into a 76390b57cec5SDimitry Andric // type (with source-location information). 76400b57cec5SDimitry Andric QualType DestructedType; 76410b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = nullptr; 76420b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed; 76430b57cec5SDimitry Andric if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 76440b57cec5SDimitry Andric ParsedType T = getTypeName(*SecondTypeName.Identifier, 76450b57cec5SDimitry Andric SecondTypeName.StartLocation, 76460b57cec5SDimitry Andric S, &SS, true, false, ObjectTypePtrForLookup, 76470b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 76480b57cec5SDimitry Andric if (!T && 76490b57cec5SDimitry Andric ((SS.isSet() && !computeDeclContext(SS, false)) || 76500b57cec5SDimitry Andric (!SS.isSet() && ObjectType->isDependentType()))) { 76510b57cec5SDimitry Andric // The name of the type being destroyed is a dependent name, and we 76520b57cec5SDimitry Andric // couldn't find anything useful in scope. Just store the identifier and 76530b57cec5SDimitry Andric // it's location, and we'll perform (qualified) name lookup again at 76540b57cec5SDimitry Andric // template instantiation time. 76550b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, 76560b57cec5SDimitry Andric SecondTypeName.StartLocation); 76570b57cec5SDimitry Andric } else if (!T) { 76580b57cec5SDimitry Andric Diag(SecondTypeName.StartLocation, 76590b57cec5SDimitry Andric diag::err_pseudo_dtor_destructor_non_type) 76600b57cec5SDimitry Andric << SecondTypeName.Identifier << ObjectType; 76610b57cec5SDimitry Andric if (isSFINAEContext()) 76620b57cec5SDimitry Andric return ExprError(); 76630b57cec5SDimitry Andric 76640b57cec5SDimitry Andric // Recover by assuming we had the right type all along. 76650b57cec5SDimitry Andric DestructedType = ObjectType; 76660b57cec5SDimitry Andric } else 76670b57cec5SDimitry Andric DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); 76680b57cec5SDimitry Andric } else { 76690b57cec5SDimitry Andric // Resolve the template-id to a type. 76700b57cec5SDimitry Andric TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; 76710b57cec5SDimitry Andric ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 76720b57cec5SDimitry Andric TemplateId->NumArgs); 76730b57cec5SDimitry Andric TypeResult T = ActOnTemplateIdType(S, 767455e4f9d5SDimitry Andric SS, 76750b57cec5SDimitry Andric TemplateId->TemplateKWLoc, 76760b57cec5SDimitry Andric TemplateId->Template, 76770b57cec5SDimitry Andric TemplateId->Name, 76780b57cec5SDimitry Andric TemplateId->TemplateNameLoc, 76790b57cec5SDimitry Andric TemplateId->LAngleLoc, 76800b57cec5SDimitry Andric TemplateArgsPtr, 76810b57cec5SDimitry Andric TemplateId->RAngleLoc, 76820b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 76830b57cec5SDimitry Andric if (T.isInvalid() || !T.get()) { 76840b57cec5SDimitry Andric // Recover by assuming we had the right type all along. 76850b57cec5SDimitry Andric DestructedType = ObjectType; 76860b57cec5SDimitry Andric } else 76870b57cec5SDimitry Andric DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); 76880b57cec5SDimitry Andric } 76890b57cec5SDimitry Andric 76900b57cec5SDimitry Andric // If we've performed some kind of recovery, (re-)build the type source 76910b57cec5SDimitry Andric // information. 76920b57cec5SDimitry Andric if (!DestructedType.isNull()) { 76930b57cec5SDimitry Andric if (!DestructedTypeInfo) 76940b57cec5SDimitry Andric DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, 76950b57cec5SDimitry Andric SecondTypeName.StartLocation); 76960b57cec5SDimitry Andric Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); 76970b57cec5SDimitry Andric } 76980b57cec5SDimitry Andric 76990b57cec5SDimitry Andric // Convert the name of the scope type (the type prior to '::') into a type. 77000b57cec5SDimitry Andric TypeSourceInfo *ScopeTypeInfo = nullptr; 77010b57cec5SDimitry Andric QualType ScopeType; 77020b57cec5SDimitry Andric if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || 77030b57cec5SDimitry Andric FirstTypeName.Identifier) { 77040b57cec5SDimitry Andric if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { 77050b57cec5SDimitry Andric ParsedType T = getTypeName(*FirstTypeName.Identifier, 77060b57cec5SDimitry Andric FirstTypeName.StartLocation, 77070b57cec5SDimitry Andric S, &SS, true, false, ObjectTypePtrForLookup, 77080b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 77090b57cec5SDimitry Andric if (!T) { 77100b57cec5SDimitry Andric Diag(FirstTypeName.StartLocation, 77110b57cec5SDimitry Andric diag::err_pseudo_dtor_destructor_non_type) 77120b57cec5SDimitry Andric << FirstTypeName.Identifier << ObjectType; 77130b57cec5SDimitry Andric 77140b57cec5SDimitry Andric if (isSFINAEContext()) 77150b57cec5SDimitry Andric return ExprError(); 77160b57cec5SDimitry Andric 77170b57cec5SDimitry Andric // Just drop this type. It's unnecessary anyway. 77180b57cec5SDimitry Andric ScopeType = QualType(); 77190b57cec5SDimitry Andric } else 77200b57cec5SDimitry Andric ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); 77210b57cec5SDimitry Andric } else { 77220b57cec5SDimitry Andric // Resolve the template-id to a type. 77230b57cec5SDimitry Andric TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; 77240b57cec5SDimitry Andric ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 77250b57cec5SDimitry Andric TemplateId->NumArgs); 77260b57cec5SDimitry Andric TypeResult T = ActOnTemplateIdType(S, 772755e4f9d5SDimitry Andric SS, 77280b57cec5SDimitry Andric TemplateId->TemplateKWLoc, 77290b57cec5SDimitry Andric TemplateId->Template, 77300b57cec5SDimitry Andric TemplateId->Name, 77310b57cec5SDimitry Andric TemplateId->TemplateNameLoc, 77320b57cec5SDimitry Andric TemplateId->LAngleLoc, 77330b57cec5SDimitry Andric TemplateArgsPtr, 77340b57cec5SDimitry Andric TemplateId->RAngleLoc, 77350b57cec5SDimitry Andric /*IsCtorOrDtorName*/true); 77360b57cec5SDimitry Andric if (T.isInvalid() || !T.get()) { 77370b57cec5SDimitry Andric // Recover by dropping this type. 77380b57cec5SDimitry Andric ScopeType = QualType(); 77390b57cec5SDimitry Andric } else 77400b57cec5SDimitry Andric ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); 77410b57cec5SDimitry Andric } 77420b57cec5SDimitry Andric } 77430b57cec5SDimitry Andric 77440b57cec5SDimitry Andric if (!ScopeType.isNull() && !ScopeTypeInfo) 77450b57cec5SDimitry Andric ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, 77460b57cec5SDimitry Andric FirstTypeName.StartLocation); 77470b57cec5SDimitry Andric 77480b57cec5SDimitry Andric 77490b57cec5SDimitry Andric return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, 77500b57cec5SDimitry Andric ScopeTypeInfo, CCLoc, TildeLoc, 77510b57cec5SDimitry Andric Destructed); 77520b57cec5SDimitry Andric } 77530b57cec5SDimitry Andric 77540b57cec5SDimitry Andric ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 77550b57cec5SDimitry Andric SourceLocation OpLoc, 77560b57cec5SDimitry Andric tok::TokenKind OpKind, 77570b57cec5SDimitry Andric SourceLocation TildeLoc, 77580b57cec5SDimitry Andric const DeclSpec& DS) { 77590b57cec5SDimitry Andric QualType ObjectType; 77600b57cec5SDimitry Andric if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) 77610b57cec5SDimitry Andric return ExprError(); 77620b57cec5SDimitry Andric 7763e8d8bef9SDimitry Andric if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { 7764e8d8bef9SDimitry Andric Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); 7765e8d8bef9SDimitry Andric return true; 7766e8d8bef9SDimitry Andric } 7767e8d8bef9SDimitry Andric 7768349cc55cSDimitry Andric QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false); 77690b57cec5SDimitry Andric 77700b57cec5SDimitry Andric TypeLocBuilder TLB; 77710b57cec5SDimitry Andric DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); 777204eeddc0SDimitry Andric DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); 777304eeddc0SDimitry Andric DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); 77740b57cec5SDimitry Andric TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); 77750b57cec5SDimitry Andric PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); 77760b57cec5SDimitry Andric 77770b57cec5SDimitry Andric return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), 77780b57cec5SDimitry Andric nullptr, SourceLocation(), TildeLoc, 77790b57cec5SDimitry Andric Destructed); 77800b57cec5SDimitry Andric } 77810b57cec5SDimitry Andric 77820b57cec5SDimitry Andric ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, 77830b57cec5SDimitry Andric CXXConversionDecl *Method, 77840b57cec5SDimitry Andric bool HadMultipleCandidates) { 77850b57cec5SDimitry Andric // Convert the expression to match the conversion function's implicit object 77860b57cec5SDimitry Andric // parameter. 77870b57cec5SDimitry Andric ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr, 77880b57cec5SDimitry Andric FoundDecl, Method); 77890b57cec5SDimitry Andric if (Exp.isInvalid()) 77900b57cec5SDimitry Andric return true; 77910b57cec5SDimitry Andric 77920b57cec5SDimitry Andric if (Method->getParent()->isLambda() && 77930b57cec5SDimitry Andric Method->getConversionType()->isBlockPointerType()) { 7794a7dea167SDimitry Andric // This is a lambda conversion to block pointer; check if the argument 77950b57cec5SDimitry Andric // was a LambdaExpr. 77960b57cec5SDimitry Andric Expr *SubE = E; 77970b57cec5SDimitry Andric CastExpr *CE = dyn_cast<CastExpr>(SubE); 77980b57cec5SDimitry Andric if (CE && CE->getCastKind() == CK_NoOp) 77990b57cec5SDimitry Andric SubE = CE->getSubExpr(); 78000b57cec5SDimitry Andric SubE = SubE->IgnoreParens(); 78010b57cec5SDimitry Andric if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE)) 78020b57cec5SDimitry Andric SubE = BE->getSubExpr(); 78030b57cec5SDimitry Andric if (isa<LambdaExpr>(SubE)) { 78040b57cec5SDimitry Andric // For the conversion to block pointer on a lambda expression, we 78050b57cec5SDimitry Andric // construct a special BlockLiteral instead; this doesn't really make 78060b57cec5SDimitry Andric // a difference in ARC, but outside of ARC the resulting block literal 78070b57cec5SDimitry Andric // follows the normal lifetime rules for block literals instead of being 78080b57cec5SDimitry Andric // autoreleased. 78090b57cec5SDimitry Andric PushExpressionEvaluationContext( 78100b57cec5SDimitry Andric ExpressionEvaluationContext::PotentiallyEvaluated); 78110b57cec5SDimitry Andric ExprResult BlockExp = BuildBlockForLambdaConversion( 78120b57cec5SDimitry Andric Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); 78130b57cec5SDimitry Andric PopExpressionEvaluationContext(); 78140b57cec5SDimitry Andric 78155ffd83dbSDimitry Andric // FIXME: This note should be produced by a CodeSynthesisContext. 78160b57cec5SDimitry Andric if (BlockExp.isInvalid()) 78170b57cec5SDimitry Andric Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv); 78180b57cec5SDimitry Andric return BlockExp; 78190b57cec5SDimitry Andric } 78200b57cec5SDimitry Andric } 78210b57cec5SDimitry Andric 78220b57cec5SDimitry Andric MemberExpr *ME = 78230b57cec5SDimitry Andric BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(), 78240b57cec5SDimitry Andric NestedNameSpecifierLoc(), SourceLocation(), Method, 78250b57cec5SDimitry Andric DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), 78260b57cec5SDimitry Andric HadMultipleCandidates, DeclarationNameInfo(), 7827fe6060f1SDimitry Andric Context.BoundMemberTy, VK_PRValue, OK_Ordinary); 78280b57cec5SDimitry Andric 78290b57cec5SDimitry Andric QualType ResultType = Method->getReturnType(); 78300b57cec5SDimitry Andric ExprValueKind VK = Expr::getValueKindForType(ResultType); 78310b57cec5SDimitry Andric ResultType = ResultType.getNonLValueExprType(Context); 78320b57cec5SDimitry Andric 78330b57cec5SDimitry Andric CXXMemberCallExpr *CE = CXXMemberCallExpr::Create( 7834e8d8bef9SDimitry Andric Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(), 7835e8d8bef9SDimitry Andric CurFPFeatureOverrides()); 78360b57cec5SDimitry Andric 78370b57cec5SDimitry Andric if (CheckFunctionCall(Method, CE, 78380b57cec5SDimitry Andric Method->getType()->castAs<FunctionProtoType>())) 78390b57cec5SDimitry Andric return ExprError(); 78400b57cec5SDimitry Andric 7841fe6060f1SDimitry Andric return CheckForImmediateInvocation(CE, CE->getMethodDecl()); 78420b57cec5SDimitry Andric } 78430b57cec5SDimitry Andric 78440b57cec5SDimitry Andric ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 78450b57cec5SDimitry Andric SourceLocation RParen) { 78460b57cec5SDimitry Andric // If the operand is an unresolved lookup expression, the expression is ill- 78470b57cec5SDimitry Andric // formed per [over.over]p1, because overloaded function names cannot be used 78480b57cec5SDimitry Andric // without arguments except in explicit contexts. 78490b57cec5SDimitry Andric ExprResult R = CheckPlaceholderExpr(Operand); 78500b57cec5SDimitry Andric if (R.isInvalid()) 78510b57cec5SDimitry Andric return R; 78520b57cec5SDimitry Andric 7853a7dea167SDimitry Andric R = CheckUnevaluatedOperand(R.get()); 7854a7dea167SDimitry Andric if (R.isInvalid()) 7855a7dea167SDimitry Andric return ExprError(); 7856a7dea167SDimitry Andric 78570b57cec5SDimitry Andric Operand = R.get(); 78580b57cec5SDimitry Andric 7859e8d8bef9SDimitry Andric if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() && 7860e8d8bef9SDimitry Andric Operand->HasSideEffects(Context, false)) { 78610b57cec5SDimitry Andric // The expression operand for noexcept is in an unevaluated expression 78620b57cec5SDimitry Andric // context, so side effects could result in unintended consequences. 78630b57cec5SDimitry Andric Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); 78640b57cec5SDimitry Andric } 78650b57cec5SDimitry Andric 78660b57cec5SDimitry Andric CanThrowResult CanThrow = canThrow(Operand); 78670b57cec5SDimitry Andric return new (Context) 78680b57cec5SDimitry Andric CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); 78690b57cec5SDimitry Andric } 78700b57cec5SDimitry Andric 78710b57cec5SDimitry Andric ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, 78720b57cec5SDimitry Andric Expr *Operand, SourceLocation RParen) { 78730b57cec5SDimitry Andric return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); 78740b57cec5SDimitry Andric } 78750b57cec5SDimitry Andric 7876fe6060f1SDimitry Andric static void MaybeDecrementCount( 7877fe6060f1SDimitry Andric Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { 7878fe6060f1SDimitry Andric DeclRefExpr *LHS = nullptr; 7879fe6060f1SDimitry Andric if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 7880fe6060f1SDimitry Andric if (BO->getLHS()->getType()->isDependentType() || 7881fe6060f1SDimitry Andric BO->getRHS()->getType()->isDependentType()) { 7882fe6060f1SDimitry Andric if (BO->getOpcode() != BO_Assign) 7883fe6060f1SDimitry Andric return; 7884fe6060f1SDimitry Andric } else if (!BO->isAssignmentOp()) 7885fe6060f1SDimitry Andric return; 7886fe6060f1SDimitry Andric LHS = dyn_cast<DeclRefExpr>(BO->getLHS()); 7887fe6060f1SDimitry Andric } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) { 7888fe6060f1SDimitry Andric if (COCE->getOperator() != OO_Equal) 7889fe6060f1SDimitry Andric return; 7890fe6060f1SDimitry Andric LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0)); 7891fe6060f1SDimitry Andric } 7892fe6060f1SDimitry Andric if (!LHS) 7893fe6060f1SDimitry Andric return; 7894fe6060f1SDimitry Andric VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl()); 7895fe6060f1SDimitry Andric if (!VD) 7896fe6060f1SDimitry Andric return; 7897fe6060f1SDimitry Andric auto iter = RefsMinusAssignments.find(VD); 7898fe6060f1SDimitry Andric if (iter == RefsMinusAssignments.end()) 7899fe6060f1SDimitry Andric return; 7900fe6060f1SDimitry Andric iter->getSecond()--; 7901fe6060f1SDimitry Andric } 7902fe6060f1SDimitry Andric 79030b57cec5SDimitry Andric /// Perform the conversions required for an expression used in a 79040b57cec5SDimitry Andric /// context that ignores the result. 79050b57cec5SDimitry Andric ExprResult Sema::IgnoredValueConversions(Expr *E) { 7906fe6060f1SDimitry Andric MaybeDecrementCount(E, RefsMinusAssignments); 7907fe6060f1SDimitry Andric 79080b57cec5SDimitry Andric if (E->hasPlaceholderType()) { 79090b57cec5SDimitry Andric ExprResult result = CheckPlaceholderExpr(E); 79100b57cec5SDimitry Andric if (result.isInvalid()) return E; 79110b57cec5SDimitry Andric E = result.get(); 79120b57cec5SDimitry Andric } 79130b57cec5SDimitry Andric 79140b57cec5SDimitry Andric // C99 6.3.2.1: 79150b57cec5SDimitry Andric // [Except in specific positions,] an lvalue that does not have 79160b57cec5SDimitry Andric // array type is converted to the value stored in the 79170b57cec5SDimitry Andric // designated object (and is no longer an lvalue). 7918fe6060f1SDimitry Andric if (E->isPRValue()) { 79190b57cec5SDimitry Andric // In C, function designators (i.e. expressions of function type) 79200b57cec5SDimitry Andric // are r-values, but we still want to do function-to-pointer decay 79210b57cec5SDimitry Andric // on them. This is both technically correct and convenient for 79220b57cec5SDimitry Andric // some clients. 79230b57cec5SDimitry Andric if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) 79240b57cec5SDimitry Andric return DefaultFunctionArrayConversion(E); 79250b57cec5SDimitry Andric 79260b57cec5SDimitry Andric return E; 79270b57cec5SDimitry Andric } 79280b57cec5SDimitry Andric 79290b57cec5SDimitry Andric if (getLangOpts().CPlusPlus) { 79300b57cec5SDimitry Andric // The C++11 standard defines the notion of a discarded-value expression; 79310b57cec5SDimitry Andric // normally, we don't need to do anything to handle it, but if it is a 79320b57cec5SDimitry Andric // volatile lvalue with a special form, we perform an lvalue-to-rvalue 79330b57cec5SDimitry Andric // conversion. 79345ffd83dbSDimitry Andric if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) { 79350b57cec5SDimitry Andric ExprResult Res = DefaultLvalueConversion(E); 79360b57cec5SDimitry Andric if (Res.isInvalid()) 79370b57cec5SDimitry Andric return E; 79380b57cec5SDimitry Andric E = Res.get(); 7939a7dea167SDimitry Andric } else { 7940a7dea167SDimitry Andric // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 7941a7dea167SDimitry Andric // it occurs as a discarded-value expression. 7942a7dea167SDimitry Andric CheckUnusedVolatileAssignment(E); 7943a7dea167SDimitry Andric } 79440b57cec5SDimitry Andric 79450b57cec5SDimitry Andric // C++1z: 79460b57cec5SDimitry Andric // If the expression is a prvalue after this optional conversion, the 79470b57cec5SDimitry Andric // temporary materialization conversion is applied. 79480b57cec5SDimitry Andric // 79490b57cec5SDimitry Andric // We skip this step: IR generation is able to synthesize the storage for 79500b57cec5SDimitry Andric // itself in the aggregate case, and adding the extra node to the AST is 79510b57cec5SDimitry Andric // just clutter. 79520b57cec5SDimitry Andric // FIXME: We don't emit lifetime markers for the temporaries due to this. 79530b57cec5SDimitry Andric // FIXME: Do any other AST consumers care about this? 79540b57cec5SDimitry Andric return E; 79550b57cec5SDimitry Andric } 79560b57cec5SDimitry Andric 79570b57cec5SDimitry Andric // GCC seems to also exclude expressions of incomplete enum type. 79580b57cec5SDimitry Andric if (const EnumType *T = E->getType()->getAs<EnumType>()) { 79590b57cec5SDimitry Andric if (!T->getDecl()->isComplete()) { 79600b57cec5SDimitry Andric // FIXME: stupid workaround for a codegen bug! 79610b57cec5SDimitry Andric E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); 79620b57cec5SDimitry Andric return E; 79630b57cec5SDimitry Andric } 79640b57cec5SDimitry Andric } 79650b57cec5SDimitry Andric 79660b57cec5SDimitry Andric ExprResult Res = DefaultFunctionArrayLvalueConversion(E); 79670b57cec5SDimitry Andric if (Res.isInvalid()) 79680b57cec5SDimitry Andric return E; 79690b57cec5SDimitry Andric E = Res.get(); 79700b57cec5SDimitry Andric 79710b57cec5SDimitry Andric if (!E->getType()->isVoidType()) 79720b57cec5SDimitry Andric RequireCompleteType(E->getExprLoc(), E->getType(), 79730b57cec5SDimitry Andric diag::err_incomplete_type); 79740b57cec5SDimitry Andric return E; 79750b57cec5SDimitry Andric } 79760b57cec5SDimitry Andric 7977a7dea167SDimitry Andric ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { 7978a7dea167SDimitry Andric // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if 7979a7dea167SDimitry Andric // it occurs as an unevaluated operand. 7980a7dea167SDimitry Andric CheckUnusedVolatileAssignment(E); 7981a7dea167SDimitry Andric 7982a7dea167SDimitry Andric return E; 7983a7dea167SDimitry Andric } 7984a7dea167SDimitry Andric 79850b57cec5SDimitry Andric // If we can unambiguously determine whether Var can never be used 79860b57cec5SDimitry Andric // in a constant expression, return true. 79870b57cec5SDimitry Andric // - if the variable and its initializer are non-dependent, then 79880b57cec5SDimitry Andric // we can unambiguously check if the variable is a constant expression. 79890b57cec5SDimitry Andric // - if the initializer is not value dependent - we can determine whether 79900b57cec5SDimitry Andric // it can be used to initialize a constant expression. If Init can not 79910b57cec5SDimitry Andric // be used to initialize a constant expression we conclude that Var can 79920b57cec5SDimitry Andric // never be a constant expression. 79930b57cec5SDimitry Andric // - FXIME: if the initializer is dependent, we can still do some analysis and 79940b57cec5SDimitry Andric // identify certain cases unambiguously as non-const by using a Visitor: 79950b57cec5SDimitry Andric // - such as those that involve odr-use of a ParmVarDecl, involve a new 79960b57cec5SDimitry Andric // delete, lambda-expr, dynamic-cast, reinterpret-cast etc... 79970b57cec5SDimitry Andric static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, 79980b57cec5SDimitry Andric ASTContext &Context) { 79990b57cec5SDimitry Andric if (isa<ParmVarDecl>(Var)) return true; 80000b57cec5SDimitry Andric const VarDecl *DefVD = nullptr; 80010b57cec5SDimitry Andric 80020b57cec5SDimitry Andric // If there is no initializer - this can not be a constant expression. 80030b57cec5SDimitry Andric if (!Var->getAnyInitializer(DefVD)) return true; 80040b57cec5SDimitry Andric assert(DefVD); 80050b57cec5SDimitry Andric if (DefVD->isWeak()) return false; 80060b57cec5SDimitry Andric EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt(); 80070b57cec5SDimitry Andric 80080b57cec5SDimitry Andric Expr *Init = cast<Expr>(Eval->Value); 80090b57cec5SDimitry Andric 80100b57cec5SDimitry Andric if (Var->getType()->isDependentType() || Init->isValueDependent()) { 80110b57cec5SDimitry Andric // FIXME: Teach the constant evaluator to deal with the non-dependent parts 80120b57cec5SDimitry Andric // of value-dependent expressions, and use it here to determine whether the 80130b57cec5SDimitry Andric // initializer is a potential constant expression. 80140b57cec5SDimitry Andric return false; 80150b57cec5SDimitry Andric } 80160b57cec5SDimitry Andric 80170b57cec5SDimitry Andric return !Var->isUsableInConstantExpressions(Context); 80180b57cec5SDimitry Andric } 80190b57cec5SDimitry Andric 80200b57cec5SDimitry Andric /// Check if the current lambda has any potential captures 80210b57cec5SDimitry Andric /// that must be captured by any of its enclosing lambdas that are ready to 80220b57cec5SDimitry Andric /// capture. If there is a lambda that can capture a nested 80230b57cec5SDimitry Andric /// potential-capture, go ahead and do so. Also, check to see if any 80240b57cec5SDimitry Andric /// variables are uncaptureable or do not involve an odr-use so do not 80250b57cec5SDimitry Andric /// need to be captured. 80260b57cec5SDimitry Andric 80270b57cec5SDimitry Andric static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( 80280b57cec5SDimitry Andric Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { 80290b57cec5SDimitry Andric 80300b57cec5SDimitry Andric assert(!S.isUnevaluatedContext()); 80310b57cec5SDimitry Andric assert(S.CurContext->isDependentContext()); 80320b57cec5SDimitry Andric #ifndef NDEBUG 80330b57cec5SDimitry Andric DeclContext *DC = S.CurContext; 80340b57cec5SDimitry Andric while (DC && isa<CapturedDecl>(DC)) 80350b57cec5SDimitry Andric DC = DC->getParent(); 80360b57cec5SDimitry Andric assert( 80370b57cec5SDimitry Andric CurrentLSI->CallOperator == DC && 80380b57cec5SDimitry Andric "The current call operator must be synchronized with Sema's CurContext"); 80390b57cec5SDimitry Andric #endif // NDEBUG 80400b57cec5SDimitry Andric 80410b57cec5SDimitry Andric const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); 80420b57cec5SDimitry Andric 80430b57cec5SDimitry Andric // All the potentially captureable variables in the current nested 80440b57cec5SDimitry Andric // lambda (within a generic outer lambda), must be captured by an 80450b57cec5SDimitry Andric // outer lambda that is enclosed within a non-dependent context. 80460b57cec5SDimitry Andric CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) { 80470b57cec5SDimitry Andric // If the variable is clearly identified as non-odr-used and the full 80480b57cec5SDimitry Andric // expression is not instantiation dependent, only then do we not 80490b57cec5SDimitry Andric // need to check enclosing lambda's for speculative captures. 80500b57cec5SDimitry Andric // For e.g.: 80510b57cec5SDimitry Andric // Even though 'x' is not odr-used, it should be captured. 80520b57cec5SDimitry Andric // int test() { 80530b57cec5SDimitry Andric // const int x = 10; 80540b57cec5SDimitry Andric // auto L = [=](auto a) { 80550b57cec5SDimitry Andric // (void) +x + a; 80560b57cec5SDimitry Andric // }; 80570b57cec5SDimitry Andric // } 80580b57cec5SDimitry Andric if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && 80590b57cec5SDimitry Andric !IsFullExprInstantiationDependent) 80600b57cec5SDimitry Andric return; 80610b57cec5SDimitry Andric 80620b57cec5SDimitry Andric // If we have a capture-capable lambda for the variable, go ahead and 80630b57cec5SDimitry Andric // capture the variable in that lambda (and all its enclosing lambdas). 80640b57cec5SDimitry Andric if (const Optional<unsigned> Index = 80650b57cec5SDimitry Andric getStackIndexOfNearestEnclosingCaptureCapableLambda( 80660b57cec5SDimitry Andric S.FunctionScopes, Var, S)) 80670b57cec5SDimitry Andric S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), 80680b57cec5SDimitry Andric Index.getValue()); 80690b57cec5SDimitry Andric const bool IsVarNeverAConstantExpression = 80700b57cec5SDimitry Andric VariableCanNeverBeAConstantExpression(Var, S.Context); 80710b57cec5SDimitry Andric if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { 80720b57cec5SDimitry Andric // This full expression is not instantiation dependent or the variable 80730b57cec5SDimitry Andric // can not be used in a constant expression - which means 80740b57cec5SDimitry Andric // this variable must be odr-used here, so diagnose a 80750b57cec5SDimitry Andric // capture violation early, if the variable is un-captureable. 80760b57cec5SDimitry Andric // This is purely for diagnosing errors early. Otherwise, this 80770b57cec5SDimitry Andric // error would get diagnosed when the lambda becomes capture ready. 80780b57cec5SDimitry Andric QualType CaptureType, DeclRefType; 80790b57cec5SDimitry Andric SourceLocation ExprLoc = VarExpr->getExprLoc(); 80800b57cec5SDimitry Andric if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 80810b57cec5SDimitry Andric /*EllipsisLoc*/ SourceLocation(), 80820b57cec5SDimitry Andric /*BuildAndDiagnose*/false, CaptureType, 80830b57cec5SDimitry Andric DeclRefType, nullptr)) { 80840b57cec5SDimitry Andric // We will never be able to capture this variable, and we need 80850b57cec5SDimitry Andric // to be able to in any and all instantiations, so diagnose it. 80860b57cec5SDimitry Andric S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, 80870b57cec5SDimitry Andric /*EllipsisLoc*/ SourceLocation(), 80880b57cec5SDimitry Andric /*BuildAndDiagnose*/true, CaptureType, 80890b57cec5SDimitry Andric DeclRefType, nullptr); 80900b57cec5SDimitry Andric } 80910b57cec5SDimitry Andric } 80920b57cec5SDimitry Andric }); 80930b57cec5SDimitry Andric 80940b57cec5SDimitry Andric // Check if 'this' needs to be captured. 80950b57cec5SDimitry Andric if (CurrentLSI->hasPotentialThisCapture()) { 80960b57cec5SDimitry Andric // If we have a capture-capable lambda for 'this', go ahead and capture 80970b57cec5SDimitry Andric // 'this' in that lambda (and all its enclosing lambdas). 80980b57cec5SDimitry Andric if (const Optional<unsigned> Index = 80990b57cec5SDimitry Andric getStackIndexOfNearestEnclosingCaptureCapableLambda( 81000b57cec5SDimitry Andric S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { 81010b57cec5SDimitry Andric const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue(); 81020b57cec5SDimitry Andric S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, 81030b57cec5SDimitry Andric /*Explicit*/ false, /*BuildAndDiagnose*/ true, 81040b57cec5SDimitry Andric &FunctionScopeIndexOfCapturableLambda); 81050b57cec5SDimitry Andric } 81060b57cec5SDimitry Andric } 81070b57cec5SDimitry Andric 81080b57cec5SDimitry Andric // Reset all the potential captures at the end of each full-expression. 81090b57cec5SDimitry Andric CurrentLSI->clearPotentialCaptures(); 81100b57cec5SDimitry Andric } 81110b57cec5SDimitry Andric 81120b57cec5SDimitry Andric static ExprResult attemptRecovery(Sema &SemaRef, 81130b57cec5SDimitry Andric const TypoCorrectionConsumer &Consumer, 81140b57cec5SDimitry Andric const TypoCorrection &TC) { 81150b57cec5SDimitry Andric LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(), 81160b57cec5SDimitry Andric Consumer.getLookupResult().getLookupKind()); 81170b57cec5SDimitry Andric const CXXScopeSpec *SS = Consumer.getSS(); 81180b57cec5SDimitry Andric CXXScopeSpec NewSS; 81190b57cec5SDimitry Andric 81200b57cec5SDimitry Andric // Use an approprate CXXScopeSpec for building the expr. 81210b57cec5SDimitry Andric if (auto *NNS = TC.getCorrectionSpecifier()) 81220b57cec5SDimitry Andric NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange()); 81230b57cec5SDimitry Andric else if (SS && !TC.WillReplaceSpecifier()) 81240b57cec5SDimitry Andric NewSS = *SS; 81250b57cec5SDimitry Andric 81260b57cec5SDimitry Andric if (auto *ND = TC.getFoundDecl()) { 81270b57cec5SDimitry Andric R.setLookupName(ND->getDeclName()); 81280b57cec5SDimitry Andric R.addDecl(ND); 81290b57cec5SDimitry Andric if (ND->isCXXClassMember()) { 81300b57cec5SDimitry Andric // Figure out the correct naming class to add to the LookupResult. 81310b57cec5SDimitry Andric CXXRecordDecl *Record = nullptr; 81320b57cec5SDimitry Andric if (auto *NNS = TC.getCorrectionSpecifier()) 81330b57cec5SDimitry Andric Record = NNS->getAsType()->getAsCXXRecordDecl(); 81340b57cec5SDimitry Andric if (!Record) 81350b57cec5SDimitry Andric Record = 81360b57cec5SDimitry Andric dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext()); 81370b57cec5SDimitry Andric if (Record) 81380b57cec5SDimitry Andric R.setNamingClass(Record); 81390b57cec5SDimitry Andric 81400b57cec5SDimitry Andric // Detect and handle the case where the decl might be an implicit 81410b57cec5SDimitry Andric // member. 81420b57cec5SDimitry Andric bool MightBeImplicitMember; 81430b57cec5SDimitry Andric if (!Consumer.isAddressOfOperand()) 81440b57cec5SDimitry Andric MightBeImplicitMember = true; 81450b57cec5SDimitry Andric else if (!NewSS.isEmpty()) 81460b57cec5SDimitry Andric MightBeImplicitMember = false; 81470b57cec5SDimitry Andric else if (R.isOverloadedResult()) 81480b57cec5SDimitry Andric MightBeImplicitMember = false; 81490b57cec5SDimitry Andric else if (R.isUnresolvableResult()) 81500b57cec5SDimitry Andric MightBeImplicitMember = true; 81510b57cec5SDimitry Andric else 81520b57cec5SDimitry Andric MightBeImplicitMember = isa<FieldDecl>(ND) || 81530b57cec5SDimitry Andric isa<IndirectFieldDecl>(ND) || 81540b57cec5SDimitry Andric isa<MSPropertyDecl>(ND); 81550b57cec5SDimitry Andric 81560b57cec5SDimitry Andric if (MightBeImplicitMember) 81570b57cec5SDimitry Andric return SemaRef.BuildPossibleImplicitMemberExpr( 81580b57cec5SDimitry Andric NewSS, /*TemplateKWLoc*/ SourceLocation(), R, 81590b57cec5SDimitry Andric /*TemplateArgs*/ nullptr, /*S*/ nullptr); 81600b57cec5SDimitry Andric } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) { 81610b57cec5SDimitry Andric return SemaRef.LookupInObjCMethod(R, Consumer.getScope(), 81620b57cec5SDimitry Andric Ivar->getIdentifier()); 81630b57cec5SDimitry Andric } 81640b57cec5SDimitry Andric } 81650b57cec5SDimitry Andric 81660b57cec5SDimitry Andric return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false, 81670b57cec5SDimitry Andric /*AcceptInvalidDecl*/ true); 81680b57cec5SDimitry Andric } 81690b57cec5SDimitry Andric 81700b57cec5SDimitry Andric namespace { 81710b57cec5SDimitry Andric class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { 81720b57cec5SDimitry Andric llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; 81730b57cec5SDimitry Andric 81740b57cec5SDimitry Andric public: 81750b57cec5SDimitry Andric explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs) 81760b57cec5SDimitry Andric : TypoExprs(TypoExprs) {} 81770b57cec5SDimitry Andric bool VisitTypoExpr(TypoExpr *TE) { 81780b57cec5SDimitry Andric TypoExprs.insert(TE); 81790b57cec5SDimitry Andric return true; 81800b57cec5SDimitry Andric } 81810b57cec5SDimitry Andric }; 81820b57cec5SDimitry Andric 81830b57cec5SDimitry Andric class TransformTypos : public TreeTransform<TransformTypos> { 81840b57cec5SDimitry Andric typedef TreeTransform<TransformTypos> BaseTransform; 81850b57cec5SDimitry Andric 81860b57cec5SDimitry Andric VarDecl *InitDecl; // A decl to avoid as a correction because it is in the 81870b57cec5SDimitry Andric // process of being initialized. 81880b57cec5SDimitry Andric llvm::function_ref<ExprResult(Expr *)> ExprFilter; 81890b57cec5SDimitry Andric llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs; 81900b57cec5SDimitry Andric llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache; 81910b57cec5SDimitry Andric llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution; 81920b57cec5SDimitry Andric 81930b57cec5SDimitry Andric /// Emit diagnostics for all of the TypoExprs encountered. 8194a7dea167SDimitry Andric /// 81950b57cec5SDimitry Andric /// If the TypoExprs were successfully corrected, then the diagnostics should 81960b57cec5SDimitry Andric /// suggest the corrections. Otherwise the diagnostics will not suggest 81970b57cec5SDimitry Andric /// anything (having been passed an empty TypoCorrection). 8198a7dea167SDimitry Andric /// 8199a7dea167SDimitry Andric /// If we've failed to correct due to ambiguous corrections, we need to 8200a7dea167SDimitry Andric /// be sure to pass empty corrections and replacements. Otherwise it's 8201a7dea167SDimitry Andric /// possible that the Consumer has a TypoCorrection that failed to ambiguity 8202a7dea167SDimitry Andric /// and we don't want to report those diagnostics. 8203a7dea167SDimitry Andric void EmitAllDiagnostics(bool IsAmbiguous) { 82040b57cec5SDimitry Andric for (TypoExpr *TE : TypoExprs) { 82050b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(TE); 82060b57cec5SDimitry Andric if (State.DiagHandler) { 8207a7dea167SDimitry Andric TypoCorrection TC = IsAmbiguous 8208a7dea167SDimitry Andric ? TypoCorrection() : State.Consumer->getCurrentCorrection(); 8209a7dea167SDimitry Andric ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE]; 82100b57cec5SDimitry Andric 82110b57cec5SDimitry Andric // Extract the NamedDecl from the transformed TypoExpr and add it to the 82120b57cec5SDimitry Andric // TypoCorrection, replacing the existing decls. This ensures the right 82130b57cec5SDimitry Andric // NamedDecl is used in diagnostics e.g. in the case where overload 82140b57cec5SDimitry Andric // resolution was used to select one from several possible decls that 82150b57cec5SDimitry Andric // had been stored in the TypoCorrection. 82160b57cec5SDimitry Andric if (auto *ND = getDeclFromExpr( 82170b57cec5SDimitry Andric Replacement.isInvalid() ? nullptr : Replacement.get())) 82180b57cec5SDimitry Andric TC.setCorrectionDecl(ND); 82190b57cec5SDimitry Andric 82200b57cec5SDimitry Andric State.DiagHandler(TC); 82210b57cec5SDimitry Andric } 82220b57cec5SDimitry Andric SemaRef.clearDelayedTypo(TE); 82230b57cec5SDimitry Andric } 82240b57cec5SDimitry Andric } 82250b57cec5SDimitry Andric 8226590d96feSDimitry Andric /// Try to advance the typo correction state of the first unfinished TypoExpr. 8227590d96feSDimitry Andric /// We allow advancement of the correction stream by removing it from the 8228590d96feSDimitry Andric /// TransformCache which allows `TransformTypoExpr` to advance during the 8229590d96feSDimitry Andric /// next transformation attempt. 8230590d96feSDimitry Andric /// 8231590d96feSDimitry Andric /// Any substitution attempts for the previous TypoExprs (which must have been 8232590d96feSDimitry Andric /// finished) will need to be retried since it's possible that they will now 8233590d96feSDimitry Andric /// be invalid given the latest advancement. 8234590d96feSDimitry Andric /// 8235590d96feSDimitry Andric /// We need to be sure that we're making progress - it's possible that the 8236590d96feSDimitry Andric /// tree is so malformed that the transform never makes it to the 8237590d96feSDimitry Andric /// `TransformTypoExpr`. 8238590d96feSDimitry Andric /// 8239590d96feSDimitry Andric /// Returns true if there are any untried correction combinations. 82400b57cec5SDimitry Andric bool CheckAndAdvanceTypoExprCorrectionStreams() { 82410b57cec5SDimitry Andric for (auto TE : TypoExprs) { 82420b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(TE); 82430b57cec5SDimitry Andric TransformCache.erase(TE); 8244590d96feSDimitry Andric if (!State.Consumer->hasMadeAnyCorrectionProgress()) 8245590d96feSDimitry Andric return false; 82460b57cec5SDimitry Andric if (!State.Consumer->finished()) 82470b57cec5SDimitry Andric return true; 82480b57cec5SDimitry Andric State.Consumer->resetCorrectionStream(); 82490b57cec5SDimitry Andric } 82500b57cec5SDimitry Andric return false; 82510b57cec5SDimitry Andric } 82520b57cec5SDimitry Andric 82530b57cec5SDimitry Andric NamedDecl *getDeclFromExpr(Expr *E) { 82540b57cec5SDimitry Andric if (auto *OE = dyn_cast_or_null<OverloadExpr>(E)) 82550b57cec5SDimitry Andric E = OverloadResolution[OE]; 82560b57cec5SDimitry Andric 82570b57cec5SDimitry Andric if (!E) 82580b57cec5SDimitry Andric return nullptr; 82590b57cec5SDimitry Andric if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 82600b57cec5SDimitry Andric return DRE->getFoundDecl(); 82610b57cec5SDimitry Andric if (auto *ME = dyn_cast<MemberExpr>(E)) 82620b57cec5SDimitry Andric return ME->getFoundDecl(); 82630b57cec5SDimitry Andric // FIXME: Add any other expr types that could be be seen by the delayed typo 82640b57cec5SDimitry Andric // correction TreeTransform for which the corresponding TypoCorrection could 82650b57cec5SDimitry Andric // contain multiple decls. 82660b57cec5SDimitry Andric return nullptr; 82670b57cec5SDimitry Andric } 82680b57cec5SDimitry Andric 82690b57cec5SDimitry Andric ExprResult TryTransform(Expr *E) { 82700b57cec5SDimitry Andric Sema::SFINAETrap Trap(SemaRef); 82710b57cec5SDimitry Andric ExprResult Res = TransformExpr(E); 82720b57cec5SDimitry Andric if (Trap.hasErrorOccurred() || Res.isInvalid()) 82730b57cec5SDimitry Andric return ExprError(); 82740b57cec5SDimitry Andric 82750b57cec5SDimitry Andric return ExprFilter(Res.get()); 82760b57cec5SDimitry Andric } 82770b57cec5SDimitry Andric 8278a7dea167SDimitry Andric // Since correcting typos may intoduce new TypoExprs, this function 8279a7dea167SDimitry Andric // checks for new TypoExprs and recurses if it finds any. Note that it will 8280a7dea167SDimitry Andric // only succeed if it is able to correct all typos in the given expression. 8281a7dea167SDimitry Andric ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { 8282a7dea167SDimitry Andric if (Res.isInvalid()) { 8283a7dea167SDimitry Andric return Res; 8284a7dea167SDimitry Andric } 8285a7dea167SDimitry Andric // Check to see if any new TypoExprs were created. If so, we need to recurse 8286a7dea167SDimitry Andric // to check their validity. 8287a7dea167SDimitry Andric Expr *FixedExpr = Res.get(); 8288a7dea167SDimitry Andric 8289a7dea167SDimitry Andric auto SavedTypoExprs = std::move(TypoExprs); 8290a7dea167SDimitry Andric auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs); 8291a7dea167SDimitry Andric TypoExprs.clear(); 8292a7dea167SDimitry Andric AmbiguousTypoExprs.clear(); 8293a7dea167SDimitry Andric 8294a7dea167SDimitry Andric FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr); 8295a7dea167SDimitry Andric if (!TypoExprs.empty()) { 8296a7dea167SDimitry Andric // Recurse to handle newly created TypoExprs. If we're not able to 8297a7dea167SDimitry Andric // handle them, discard these TypoExprs. 8298a7dea167SDimitry Andric ExprResult RecurResult = 8299a7dea167SDimitry Andric RecursiveTransformLoop(FixedExpr, IsAmbiguous); 8300a7dea167SDimitry Andric if (RecurResult.isInvalid()) { 8301a7dea167SDimitry Andric Res = ExprError(); 8302a7dea167SDimitry Andric // Recursive corrections didn't work, wipe them away and don't add 8303a7dea167SDimitry Andric // them to the TypoExprs set. Remove them from Sema's TypoExpr list 8304a7dea167SDimitry Andric // since we don't want to clear them twice. Note: it's possible the 8305a7dea167SDimitry Andric // TypoExprs were created recursively and thus won't be in our 8306a7dea167SDimitry Andric // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`. 8307a7dea167SDimitry Andric auto &SemaTypoExprs = SemaRef.TypoExprs; 8308a7dea167SDimitry Andric for (auto TE : TypoExprs) { 8309a7dea167SDimitry Andric TransformCache.erase(TE); 8310a7dea167SDimitry Andric SemaRef.clearDelayedTypo(TE); 8311a7dea167SDimitry Andric 8312a7dea167SDimitry Andric auto SI = find(SemaTypoExprs, TE); 8313a7dea167SDimitry Andric if (SI != SemaTypoExprs.end()) { 8314a7dea167SDimitry Andric SemaTypoExprs.erase(SI); 8315a7dea167SDimitry Andric } 8316a7dea167SDimitry Andric } 8317a7dea167SDimitry Andric } else { 8318a7dea167SDimitry Andric // TypoExpr is valid: add newly created TypoExprs since we were 8319a7dea167SDimitry Andric // able to correct them. 8320a7dea167SDimitry Andric Res = RecurResult; 8321a7dea167SDimitry Andric SavedTypoExprs.set_union(TypoExprs); 8322a7dea167SDimitry Andric } 8323a7dea167SDimitry Andric } 8324a7dea167SDimitry Andric 8325a7dea167SDimitry Andric TypoExprs = std::move(SavedTypoExprs); 8326a7dea167SDimitry Andric AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs); 8327a7dea167SDimitry Andric 8328a7dea167SDimitry Andric return Res; 8329a7dea167SDimitry Andric } 8330a7dea167SDimitry Andric 8331a7dea167SDimitry Andric // Try to transform the given expression, looping through the correction 8332a7dea167SDimitry Andric // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`. 8333a7dea167SDimitry Andric // 8334a7dea167SDimitry Andric // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to 8335a7dea167SDimitry Andric // true and this method immediately will return an `ExprError`. 8336a7dea167SDimitry Andric ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) { 8337a7dea167SDimitry Andric ExprResult Res; 8338a7dea167SDimitry Andric auto SavedTypoExprs = std::move(SemaRef.TypoExprs); 8339a7dea167SDimitry Andric SemaRef.TypoExprs.clear(); 8340a7dea167SDimitry Andric 8341a7dea167SDimitry Andric while (true) { 8342a7dea167SDimitry Andric Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 8343a7dea167SDimitry Andric 8344a7dea167SDimitry Andric // Recursion encountered an ambiguous correction. This means that our 8345a7dea167SDimitry Andric // correction itself is ambiguous, so stop now. 8346a7dea167SDimitry Andric if (IsAmbiguous) 8347a7dea167SDimitry Andric break; 8348a7dea167SDimitry Andric 8349a7dea167SDimitry Andric // If the transform is still valid after checking for any new typos, 8350a7dea167SDimitry Andric // it's good to go. 8351a7dea167SDimitry Andric if (!Res.isInvalid()) 8352a7dea167SDimitry Andric break; 8353a7dea167SDimitry Andric 8354a7dea167SDimitry Andric // The transform was invalid, see if we have any TypoExprs with untried 8355a7dea167SDimitry Andric // correction candidates. 8356a7dea167SDimitry Andric if (!CheckAndAdvanceTypoExprCorrectionStreams()) 8357a7dea167SDimitry Andric break; 8358a7dea167SDimitry Andric } 8359a7dea167SDimitry Andric 8360a7dea167SDimitry Andric // If we found a valid result, double check to make sure it's not ambiguous. 8361a7dea167SDimitry Andric if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { 8362480093f4SDimitry Andric auto SavedTransformCache = 8363480093f4SDimitry Andric llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); 8364480093f4SDimitry Andric 8365a7dea167SDimitry Andric // Ensure none of the TypoExprs have multiple typo correction candidates 8366a7dea167SDimitry Andric // with the same edit length that pass all the checks and filters. 8367a7dea167SDimitry Andric while (!AmbiguousTypoExprs.empty()) { 8368a7dea167SDimitry Andric auto TE = AmbiguousTypoExprs.back(); 8369a7dea167SDimitry Andric 8370a7dea167SDimitry Andric // TryTransform itself can create new Typos, adding them to the TypoExpr map 8371a7dea167SDimitry Andric // and invalidating our TypoExprState, so always fetch it instead of storing. 8372a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); 8373a7dea167SDimitry Andric 8374a7dea167SDimitry Andric TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); 8375a7dea167SDimitry Andric TypoCorrection Next; 8376a7dea167SDimitry Andric do { 8377a7dea167SDimitry Andric // Fetch the next correction by erasing the typo from the cache and calling 8378a7dea167SDimitry Andric // `TryTransform` which will iterate through corrections in 8379a7dea167SDimitry Andric // `TransformTypoExpr`. 8380a7dea167SDimitry Andric TransformCache.erase(TE); 8381a7dea167SDimitry Andric ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous); 8382a7dea167SDimitry Andric 8383a7dea167SDimitry Andric if (!AmbigRes.isInvalid() || IsAmbiguous) { 8384a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream(); 8385a7dea167SDimitry Andric SavedTransformCache.erase(TE); 8386a7dea167SDimitry Andric Res = ExprError(); 8387a7dea167SDimitry Andric IsAmbiguous = true; 8388a7dea167SDimitry Andric break; 8389a7dea167SDimitry Andric } 8390a7dea167SDimitry Andric } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) && 8391a7dea167SDimitry Andric Next.getEditDistance(false) == TC.getEditDistance(false)); 8392a7dea167SDimitry Andric 8393a7dea167SDimitry Andric if (IsAmbiguous) 8394a7dea167SDimitry Andric break; 8395a7dea167SDimitry Andric 8396a7dea167SDimitry Andric AmbiguousTypoExprs.remove(TE); 8397a7dea167SDimitry Andric SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition(); 8398fe6060f1SDimitry Andric TransformCache[TE] = SavedTransformCache[TE]; 8399a7dea167SDimitry Andric } 8400a7dea167SDimitry Andric TransformCache = std::move(SavedTransformCache); 8401a7dea167SDimitry Andric } 8402a7dea167SDimitry Andric 8403a7dea167SDimitry Andric // Wipe away any newly created TypoExprs that we don't know about. Since we 8404a7dea167SDimitry Andric // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only 8405a7dea167SDimitry Andric // possible if a `TypoExpr` is created during a transformation but then 8406a7dea167SDimitry Andric // fails before we can discover it. 8407a7dea167SDimitry Andric auto &SemaTypoExprs = SemaRef.TypoExprs; 8408a7dea167SDimitry Andric for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) { 8409a7dea167SDimitry Andric auto TE = *Iterator; 8410a7dea167SDimitry Andric auto FI = find(TypoExprs, TE); 8411a7dea167SDimitry Andric if (FI != TypoExprs.end()) { 8412a7dea167SDimitry Andric Iterator++; 8413a7dea167SDimitry Andric continue; 8414a7dea167SDimitry Andric } 8415a7dea167SDimitry Andric SemaRef.clearDelayedTypo(TE); 8416a7dea167SDimitry Andric Iterator = SemaTypoExprs.erase(Iterator); 8417a7dea167SDimitry Andric } 8418a7dea167SDimitry Andric SemaRef.TypoExprs = std::move(SavedTypoExprs); 8419a7dea167SDimitry Andric 8420a7dea167SDimitry Andric return Res; 8421a7dea167SDimitry Andric } 8422a7dea167SDimitry Andric 84230b57cec5SDimitry Andric public: 84240b57cec5SDimitry Andric TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter) 84250b57cec5SDimitry Andric : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {} 84260b57cec5SDimitry Andric 84270b57cec5SDimitry Andric ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc, 84280b57cec5SDimitry Andric MultiExprArg Args, 84290b57cec5SDimitry Andric SourceLocation RParenLoc, 84300b57cec5SDimitry Andric Expr *ExecConfig = nullptr) { 84310b57cec5SDimitry Andric auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args, 84320b57cec5SDimitry Andric RParenLoc, ExecConfig); 84330b57cec5SDimitry Andric if (auto *OE = dyn_cast<OverloadExpr>(Callee)) { 84340b57cec5SDimitry Andric if (Result.isUsable()) { 84350b57cec5SDimitry Andric Expr *ResultCall = Result.get(); 84360b57cec5SDimitry Andric if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall)) 84370b57cec5SDimitry Andric ResultCall = BE->getSubExpr(); 84380b57cec5SDimitry Andric if (auto *CE = dyn_cast<CallExpr>(ResultCall)) 84390b57cec5SDimitry Andric OverloadResolution[OE] = CE->getCallee(); 84400b57cec5SDimitry Andric } 84410b57cec5SDimitry Andric } 84420b57cec5SDimitry Andric return Result; 84430b57cec5SDimitry Andric } 84440b57cec5SDimitry Andric 84450b57cec5SDimitry Andric ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); } 84460b57cec5SDimitry Andric 84470b57cec5SDimitry Andric ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); } 84480b57cec5SDimitry Andric 84490b57cec5SDimitry Andric ExprResult Transform(Expr *E) { 8450a7dea167SDimitry Andric bool IsAmbiguous = false; 8451a7dea167SDimitry Andric ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous); 84520b57cec5SDimitry Andric 84530b57cec5SDimitry Andric if (!Res.isUsable()) 84540b57cec5SDimitry Andric FindTypoExprs(TypoExprs).TraverseStmt(E); 84550b57cec5SDimitry Andric 8456a7dea167SDimitry Andric EmitAllDiagnostics(IsAmbiguous); 84570b57cec5SDimitry Andric 84580b57cec5SDimitry Andric return Res; 84590b57cec5SDimitry Andric } 84600b57cec5SDimitry Andric 84610b57cec5SDimitry Andric ExprResult TransformTypoExpr(TypoExpr *E) { 84620b57cec5SDimitry Andric // If the TypoExpr hasn't been seen before, record it. Otherwise, return the 84630b57cec5SDimitry Andric // cached transformation result if there is one and the TypoExpr isn't the 84640b57cec5SDimitry Andric // first one that was encountered. 84650b57cec5SDimitry Andric auto &CacheEntry = TransformCache[E]; 84660b57cec5SDimitry Andric if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) { 84670b57cec5SDimitry Andric return CacheEntry; 84680b57cec5SDimitry Andric } 84690b57cec5SDimitry Andric 84700b57cec5SDimitry Andric auto &State = SemaRef.getTypoExprState(E); 84710b57cec5SDimitry Andric assert(State.Consumer && "Cannot transform a cleared TypoExpr"); 84720b57cec5SDimitry Andric 84730b57cec5SDimitry Andric // For the first TypoExpr and an uncached TypoExpr, find the next likely 84740b57cec5SDimitry Andric // typo correction and return it. 84750b57cec5SDimitry Andric while (TypoCorrection TC = State.Consumer->getNextCorrection()) { 84760b57cec5SDimitry Andric if (InitDecl && TC.getFoundDecl() == InitDecl) 84770b57cec5SDimitry Andric continue; 84780b57cec5SDimitry Andric // FIXME: If we would typo-correct to an invalid declaration, it's 84790b57cec5SDimitry Andric // probably best to just suppress all errors from this typo correction. 84800b57cec5SDimitry Andric ExprResult NE = State.RecoveryHandler ? 84810b57cec5SDimitry Andric State.RecoveryHandler(SemaRef, E, TC) : 84820b57cec5SDimitry Andric attemptRecovery(SemaRef, *State.Consumer, TC); 84830b57cec5SDimitry Andric if (!NE.isInvalid()) { 84840b57cec5SDimitry Andric // Check whether there may be a second viable correction with the same 84850b57cec5SDimitry Andric // edit distance; if so, remember this TypoExpr may have an ambiguous 84860b57cec5SDimitry Andric // correction so it can be more thoroughly vetted later. 84870b57cec5SDimitry Andric TypoCorrection Next; 84880b57cec5SDimitry Andric if ((Next = State.Consumer->peekNextCorrection()) && 84890b57cec5SDimitry Andric Next.getEditDistance(false) == TC.getEditDistance(false)) { 84900b57cec5SDimitry Andric AmbiguousTypoExprs.insert(E); 84910b57cec5SDimitry Andric } else { 84920b57cec5SDimitry Andric AmbiguousTypoExprs.remove(E); 84930b57cec5SDimitry Andric } 84940b57cec5SDimitry Andric assert(!NE.isUnset() && 84950b57cec5SDimitry Andric "Typo was transformed into a valid-but-null ExprResult"); 84960b57cec5SDimitry Andric return CacheEntry = NE; 84970b57cec5SDimitry Andric } 84980b57cec5SDimitry Andric } 84990b57cec5SDimitry Andric return CacheEntry = ExprError(); 85000b57cec5SDimitry Andric } 85010b57cec5SDimitry Andric }; 85020b57cec5SDimitry Andric } 85030b57cec5SDimitry Andric 85040b57cec5SDimitry Andric ExprResult 85050b57cec5SDimitry Andric Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, 85065ffd83dbSDimitry Andric bool RecoverUncorrectedTypos, 85070b57cec5SDimitry Andric llvm::function_ref<ExprResult(Expr *)> Filter) { 85080b57cec5SDimitry Andric // If the current evaluation context indicates there are uncorrected typos 85090b57cec5SDimitry Andric // and the current expression isn't guaranteed to not have typos, try to 85100b57cec5SDimitry Andric // resolve any TypoExpr nodes that might be in the expression. 85110b57cec5SDimitry Andric if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos && 85120b57cec5SDimitry Andric (E->isTypeDependent() || E->isValueDependent() || 85130b57cec5SDimitry Andric E->isInstantiationDependent())) { 85140b57cec5SDimitry Andric auto TyposResolved = DelayedTypos.size(); 85150b57cec5SDimitry Andric auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E); 85160b57cec5SDimitry Andric TyposResolved -= DelayedTypos.size(); 85170b57cec5SDimitry Andric if (Result.isInvalid() || Result.get() != E) { 85180b57cec5SDimitry Andric ExprEvalContexts.back().NumTypos -= TyposResolved; 85195ffd83dbSDimitry Andric if (Result.isInvalid() && RecoverUncorrectedTypos) { 85205ffd83dbSDimitry Andric struct TyposReplace : TreeTransform<TyposReplace> { 85215ffd83dbSDimitry Andric TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {} 85225ffd83dbSDimitry Andric ExprResult TransformTypoExpr(clang::TypoExpr *E) { 85235ffd83dbSDimitry Andric return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(), 85245ffd83dbSDimitry Andric E->getEndLoc(), {}); 85255ffd83dbSDimitry Andric } 85265ffd83dbSDimitry Andric } TT(*this); 85275ffd83dbSDimitry Andric return TT.TransformExpr(E); 85285ffd83dbSDimitry Andric } 85290b57cec5SDimitry Andric return Result; 85300b57cec5SDimitry Andric } 85310b57cec5SDimitry Andric assert(TyposResolved == 0 && "Corrected typo but got same Expr back?"); 85320b57cec5SDimitry Andric } 85330b57cec5SDimitry Andric return E; 85340b57cec5SDimitry Andric } 85350b57cec5SDimitry Andric 85360b57cec5SDimitry Andric ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, 85370b57cec5SDimitry Andric bool DiscardedValue, 85380b57cec5SDimitry Andric bool IsConstexpr) { 85390b57cec5SDimitry Andric ExprResult FullExpr = FE; 85400b57cec5SDimitry Andric 85410b57cec5SDimitry Andric if (!FullExpr.get()) 85420b57cec5SDimitry Andric return ExprError(); 85430b57cec5SDimitry Andric 85440b57cec5SDimitry Andric if (DiagnoseUnexpandedParameterPack(FullExpr.get())) 85450b57cec5SDimitry Andric return ExprError(); 85460b57cec5SDimitry Andric 85470b57cec5SDimitry Andric if (DiscardedValue) { 85480b57cec5SDimitry Andric // Top-level expressions default to 'id' when we're in a debugger. 85490b57cec5SDimitry Andric if (getLangOpts().DebuggerCastResultToId && 85500b57cec5SDimitry Andric FullExpr.get()->getType() == Context.UnknownAnyTy) { 85510b57cec5SDimitry Andric FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); 85520b57cec5SDimitry Andric if (FullExpr.isInvalid()) 85530b57cec5SDimitry Andric return ExprError(); 85540b57cec5SDimitry Andric } 85550b57cec5SDimitry Andric 85560b57cec5SDimitry Andric FullExpr = CheckPlaceholderExpr(FullExpr.get()); 85570b57cec5SDimitry Andric if (FullExpr.isInvalid()) 85580b57cec5SDimitry Andric return ExprError(); 85590b57cec5SDimitry Andric 85600b57cec5SDimitry Andric FullExpr = IgnoredValueConversions(FullExpr.get()); 85610b57cec5SDimitry Andric if (FullExpr.isInvalid()) 85620b57cec5SDimitry Andric return ExprError(); 85630b57cec5SDimitry Andric 8564349cc55cSDimitry Andric DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr); 85650b57cec5SDimitry Andric } 85660b57cec5SDimitry Andric 85675ffd83dbSDimitry Andric FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr, 85685ffd83dbSDimitry Andric /*RecoverUncorrectedTypos=*/true); 85690b57cec5SDimitry Andric if (FullExpr.isInvalid()) 85700b57cec5SDimitry Andric return ExprError(); 85710b57cec5SDimitry Andric 85720b57cec5SDimitry Andric CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); 85730b57cec5SDimitry Andric 85740b57cec5SDimitry Andric // At the end of this full expression (which could be a deeply nested 85750b57cec5SDimitry Andric // lambda), if there is a potential capture within the nested lambda, 85760b57cec5SDimitry Andric // have the outer capture-able lambda try and capture it. 85770b57cec5SDimitry Andric // Consider the following code: 85780b57cec5SDimitry Andric // void f(int, int); 85790b57cec5SDimitry Andric // void f(const int&, double); 85800b57cec5SDimitry Andric // void foo() { 85810b57cec5SDimitry Andric // const int x = 10, y = 20; 85820b57cec5SDimitry Andric // auto L = [=](auto a) { 85830b57cec5SDimitry Andric // auto M = [=](auto b) { 85840b57cec5SDimitry Andric // f(x, b); <-- requires x to be captured by L and M 85850b57cec5SDimitry Andric // f(y, a); <-- requires y to be captured by L, but not all Ms 85860b57cec5SDimitry Andric // }; 85870b57cec5SDimitry Andric // }; 85880b57cec5SDimitry Andric // } 85890b57cec5SDimitry Andric 85900b57cec5SDimitry Andric // FIXME: Also consider what happens for something like this that involves 85910b57cec5SDimitry Andric // the gnu-extension statement-expressions or even lambda-init-captures: 85920b57cec5SDimitry Andric // void f() { 85930b57cec5SDimitry Andric // const int n = 0; 85940b57cec5SDimitry Andric // auto L = [&](auto a) { 85950b57cec5SDimitry Andric // +n + ({ 0; a; }); 85960b57cec5SDimitry Andric // }; 85970b57cec5SDimitry Andric // } 85980b57cec5SDimitry Andric // 85990b57cec5SDimitry Andric // Here, we see +n, and then the full-expression 0; ends, so we don't 86000b57cec5SDimitry Andric // capture n (and instead remove it from our list of potential captures), 86010b57cec5SDimitry Andric // and then the full-expression +n + ({ 0; }); ends, but it's too late 86020b57cec5SDimitry Andric // for us to see that we need to capture n after all. 86030b57cec5SDimitry Andric 86040b57cec5SDimitry Andric LambdaScopeInfo *const CurrentLSI = 86050b57cec5SDimitry Andric getCurLambda(/*IgnoreCapturedRegions=*/true); 86060b57cec5SDimitry Andric // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer 86070b57cec5SDimitry Andric // even if CurContext is not a lambda call operator. Refer to that Bug Report 86080b57cec5SDimitry Andric // for an example of the code that might cause this asynchrony. 86090b57cec5SDimitry Andric // By ensuring we are in the context of a lambda's call operator 86100b57cec5SDimitry Andric // we can fix the bug (we only need to check whether we need to capture 86110b57cec5SDimitry Andric // if we are within a lambda's body); but per the comments in that 86120b57cec5SDimitry Andric // PR, a proper fix would entail : 86130b57cec5SDimitry Andric // "Alternative suggestion: 86140b57cec5SDimitry Andric // - Add to Sema an integer holding the smallest (outermost) scope 86150b57cec5SDimitry Andric // index that we are *lexically* within, and save/restore/set to 86160b57cec5SDimitry Andric // FunctionScopes.size() in InstantiatingTemplate's 86170b57cec5SDimitry Andric // constructor/destructor. 86180b57cec5SDimitry Andric // - Teach the handful of places that iterate over FunctionScopes to 86190b57cec5SDimitry Andric // stop at the outermost enclosing lexical scope." 86200b57cec5SDimitry Andric DeclContext *DC = CurContext; 86210b57cec5SDimitry Andric while (DC && isa<CapturedDecl>(DC)) 86220b57cec5SDimitry Andric DC = DC->getParent(); 86230b57cec5SDimitry Andric const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); 86240b57cec5SDimitry Andric if (IsInLambdaDeclContext && CurrentLSI && 86250b57cec5SDimitry Andric CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) 86260b57cec5SDimitry Andric CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, 86270b57cec5SDimitry Andric *this); 86280b57cec5SDimitry Andric return MaybeCreateExprWithCleanups(FullExpr); 86290b57cec5SDimitry Andric } 86300b57cec5SDimitry Andric 86310b57cec5SDimitry Andric StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { 86320b57cec5SDimitry Andric if (!FullStmt) return StmtError(); 86330b57cec5SDimitry Andric 86340b57cec5SDimitry Andric return MaybeCreateStmtWithCleanups(FullStmt); 86350b57cec5SDimitry Andric } 86360b57cec5SDimitry Andric 86370b57cec5SDimitry Andric Sema::IfExistsResult 86380b57cec5SDimitry Andric Sema::CheckMicrosoftIfExistsSymbol(Scope *S, 86390b57cec5SDimitry Andric CXXScopeSpec &SS, 86400b57cec5SDimitry Andric const DeclarationNameInfo &TargetNameInfo) { 86410b57cec5SDimitry Andric DeclarationName TargetName = TargetNameInfo.getName(); 86420b57cec5SDimitry Andric if (!TargetName) 86430b57cec5SDimitry Andric return IER_DoesNotExist; 86440b57cec5SDimitry Andric 86450b57cec5SDimitry Andric // If the name itself is dependent, then the result is dependent. 86460b57cec5SDimitry Andric if (TargetName.isDependentName()) 86470b57cec5SDimitry Andric return IER_Dependent; 86480b57cec5SDimitry Andric 86490b57cec5SDimitry Andric // Do the redeclaration lookup in the current scope. 86500b57cec5SDimitry Andric LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, 86510b57cec5SDimitry Andric Sema::NotForRedeclaration); 86520b57cec5SDimitry Andric LookupParsedName(R, S, &SS); 86530b57cec5SDimitry Andric R.suppressDiagnostics(); 86540b57cec5SDimitry Andric 86550b57cec5SDimitry Andric switch (R.getResultKind()) { 86560b57cec5SDimitry Andric case LookupResult::Found: 86570b57cec5SDimitry Andric case LookupResult::FoundOverloaded: 86580b57cec5SDimitry Andric case LookupResult::FoundUnresolvedValue: 86590b57cec5SDimitry Andric case LookupResult::Ambiguous: 86600b57cec5SDimitry Andric return IER_Exists; 86610b57cec5SDimitry Andric 86620b57cec5SDimitry Andric case LookupResult::NotFound: 86630b57cec5SDimitry Andric return IER_DoesNotExist; 86640b57cec5SDimitry Andric 86650b57cec5SDimitry Andric case LookupResult::NotFoundInCurrentInstantiation: 86660b57cec5SDimitry Andric return IER_Dependent; 86670b57cec5SDimitry Andric } 86680b57cec5SDimitry Andric 86690b57cec5SDimitry Andric llvm_unreachable("Invalid LookupResult Kind!"); 86700b57cec5SDimitry Andric } 86710b57cec5SDimitry Andric 86720b57cec5SDimitry Andric Sema::IfExistsResult 86730b57cec5SDimitry Andric Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 86740b57cec5SDimitry Andric bool IsIfExists, CXXScopeSpec &SS, 86750b57cec5SDimitry Andric UnqualifiedId &Name) { 86760b57cec5SDimitry Andric DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); 86770b57cec5SDimitry Andric 86780b57cec5SDimitry Andric // Check for an unexpanded parameter pack. 86790b57cec5SDimitry Andric auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; 86800b57cec5SDimitry Andric if (DiagnoseUnexpandedParameterPack(SS, UPPC) || 86810b57cec5SDimitry Andric DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) 86820b57cec5SDimitry Andric return IER_Error; 86830b57cec5SDimitry Andric 86840b57cec5SDimitry Andric return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); 86850b57cec5SDimitry Andric } 868655e4f9d5SDimitry Andric 868755e4f9d5SDimitry Andric concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { 868855e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/true, 868955e4f9d5SDimitry Andric /*NoexceptLoc=*/SourceLocation(), 869055e4f9d5SDimitry Andric /*ReturnTypeRequirement=*/{}); 869155e4f9d5SDimitry Andric } 869255e4f9d5SDimitry Andric 869355e4f9d5SDimitry Andric concepts::Requirement * 869455e4f9d5SDimitry Andric Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, 869555e4f9d5SDimitry Andric SourceLocation NameLoc, IdentifierInfo *TypeName, 869655e4f9d5SDimitry Andric TemplateIdAnnotation *TemplateId) { 869755e4f9d5SDimitry Andric assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) && 869855e4f9d5SDimitry Andric "Exactly one of TypeName and TemplateId must be specified."); 869955e4f9d5SDimitry Andric TypeSourceInfo *TSI = nullptr; 870055e4f9d5SDimitry Andric if (TypeName) { 870155e4f9d5SDimitry Andric QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc, 870255e4f9d5SDimitry Andric SS.getWithLocInContext(Context), *TypeName, 870304eeddc0SDimitry Andric NameLoc, &TSI, /*DeducedTSTContext=*/false); 870455e4f9d5SDimitry Andric if (T.isNull()) 870555e4f9d5SDimitry Andric return nullptr; 870655e4f9d5SDimitry Andric } else { 870755e4f9d5SDimitry Andric ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), 870855e4f9d5SDimitry Andric TemplateId->NumArgs); 870955e4f9d5SDimitry Andric TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS, 871055e4f9d5SDimitry Andric TemplateId->TemplateKWLoc, 871155e4f9d5SDimitry Andric TemplateId->Template, TemplateId->Name, 871255e4f9d5SDimitry Andric TemplateId->TemplateNameLoc, 871355e4f9d5SDimitry Andric TemplateId->LAngleLoc, ArgsPtr, 871455e4f9d5SDimitry Andric TemplateId->RAngleLoc); 871555e4f9d5SDimitry Andric if (T.isInvalid()) 871655e4f9d5SDimitry Andric return nullptr; 871755e4f9d5SDimitry Andric if (GetTypeFromParser(T.get(), &TSI).isNull()) 871855e4f9d5SDimitry Andric return nullptr; 871955e4f9d5SDimitry Andric } 872055e4f9d5SDimitry Andric return BuildTypeRequirement(TSI); 872155e4f9d5SDimitry Andric } 872255e4f9d5SDimitry Andric 872355e4f9d5SDimitry Andric concepts::Requirement * 872455e4f9d5SDimitry Andric Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { 872555e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, 872655e4f9d5SDimitry Andric /*ReturnTypeRequirement=*/{}); 872755e4f9d5SDimitry Andric } 872855e4f9d5SDimitry Andric 872955e4f9d5SDimitry Andric concepts::Requirement * 873055e4f9d5SDimitry Andric Sema::ActOnCompoundRequirement( 873155e4f9d5SDimitry Andric Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, 873255e4f9d5SDimitry Andric TemplateIdAnnotation *TypeConstraint, unsigned Depth) { 873355e4f9d5SDimitry Andric // C++2a [expr.prim.req.compound] p1.3.3 873455e4f9d5SDimitry Andric // [..] the expression is deduced against an invented function template 873555e4f9d5SDimitry Andric // F [...] F is a void function template with a single type template 873655e4f9d5SDimitry Andric // parameter T declared with the constrained-parameter. Form a new 873755e4f9d5SDimitry Andric // cv-qualifier-seq cv by taking the union of const and volatile specifiers 873855e4f9d5SDimitry Andric // around the constrained-parameter. F has a single parameter whose 873955e4f9d5SDimitry Andric // type-specifier is cv T followed by the abstract-declarator. [...] 874055e4f9d5SDimitry Andric // 874155e4f9d5SDimitry Andric // The cv part is done in the calling function - we get the concept with 874255e4f9d5SDimitry Andric // arguments and the abstract declarator with the correct CV qualification and 874355e4f9d5SDimitry Andric // have to synthesize T and the single parameter of F. 874455e4f9d5SDimitry Andric auto &II = Context.Idents.get("expr-type"); 874555e4f9d5SDimitry Andric auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext, 874655e4f9d5SDimitry Andric SourceLocation(), 874755e4f9d5SDimitry Andric SourceLocation(), Depth, 874855e4f9d5SDimitry Andric /*Index=*/0, &II, 874955e4f9d5SDimitry Andric /*Typename=*/true, 875055e4f9d5SDimitry Andric /*ParameterPack=*/false, 875155e4f9d5SDimitry Andric /*HasTypeConstraint=*/true); 875255e4f9d5SDimitry Andric 8753fe6060f1SDimitry Andric if (BuildTypeConstraint(SS, TypeConstraint, TParam, 875404eeddc0SDimitry Andric /*EllipsisLoc=*/SourceLocation(), 8755fe6060f1SDimitry Andric /*AllowUnexpandedPack=*/true)) 875655e4f9d5SDimitry Andric // Just produce a requirement with no type requirements. 875755e4f9d5SDimitry Andric return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {}); 875855e4f9d5SDimitry Andric 875955e4f9d5SDimitry Andric auto *TPL = TemplateParameterList::Create(Context, SourceLocation(), 876055e4f9d5SDimitry Andric SourceLocation(), 876155e4f9d5SDimitry Andric ArrayRef<NamedDecl *>(TParam), 876255e4f9d5SDimitry Andric SourceLocation(), 876355e4f9d5SDimitry Andric /*RequiresClause=*/nullptr); 876455e4f9d5SDimitry Andric return BuildExprRequirement( 876555e4f9d5SDimitry Andric E, /*IsSimple=*/false, NoexceptLoc, 876655e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement(TPL)); 876755e4f9d5SDimitry Andric } 876855e4f9d5SDimitry Andric 876955e4f9d5SDimitry Andric concepts::ExprRequirement * 877055e4f9d5SDimitry Andric Sema::BuildExprRequirement( 877155e4f9d5SDimitry Andric Expr *E, bool IsSimple, SourceLocation NoexceptLoc, 877255e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 877355e4f9d5SDimitry Andric auto Status = concepts::ExprRequirement::SS_Satisfied; 877455e4f9d5SDimitry Andric ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; 877555e4f9d5SDimitry Andric if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent()) 877655e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_Dependent; 877755e4f9d5SDimitry Andric else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) 877855e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_NoexceptNotMet; 877955e4f9d5SDimitry Andric else if (ReturnTypeRequirement.isSubstitutionFailure()) 878055e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; 878155e4f9d5SDimitry Andric else if (ReturnTypeRequirement.isTypeConstraint()) { 878255e4f9d5SDimitry Andric // C++2a [expr.prim.req]p1.3.3 878355e4f9d5SDimitry Andric // The immediately-declared constraint ([temp]) of decltype((E)) shall 878455e4f9d5SDimitry Andric // be satisfied. 878555e4f9d5SDimitry Andric TemplateParameterList *TPL = 878655e4f9d5SDimitry Andric ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); 878755e4f9d5SDimitry Andric QualType MatchedType = 8788349cc55cSDimitry Andric Context.getReferenceQualifiedType(E).getCanonicalType(); 878955e4f9d5SDimitry Andric llvm::SmallVector<TemplateArgument, 1> Args; 879055e4f9d5SDimitry Andric Args.push_back(TemplateArgument(MatchedType)); 879155e4f9d5SDimitry Andric TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args); 879255e4f9d5SDimitry Andric MultiLevelTemplateArgumentList MLTAL(TAL); 879355e4f9d5SDimitry Andric for (unsigned I = 0; I < TPL->getDepth(); ++I) 879455e4f9d5SDimitry Andric MLTAL.addOuterRetainedLevel(); 879555e4f9d5SDimitry Andric Expr *IDC = 879655e4f9d5SDimitry Andric cast<TemplateTypeParmDecl>(TPL->getParam(0))->getTypeConstraint() 879755e4f9d5SDimitry Andric ->getImmediatelyDeclaredConstraint(); 879855e4f9d5SDimitry Andric ExprResult Constraint = SubstExpr(IDC, MLTAL); 879955e4f9d5SDimitry Andric assert(!Constraint.isInvalid() && 880055e4f9d5SDimitry Andric "Substitution cannot fail as it is simply putting a type template " 880155e4f9d5SDimitry Andric "argument into a concept specialization expression's parameter."); 880255e4f9d5SDimitry Andric 880355e4f9d5SDimitry Andric SubstitutedConstraintExpr = 880455e4f9d5SDimitry Andric cast<ConceptSpecializationExpr>(Constraint.get()); 880555e4f9d5SDimitry Andric if (!SubstitutedConstraintExpr->isSatisfied()) 880655e4f9d5SDimitry Andric Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; 880755e4f9d5SDimitry Andric } 880855e4f9d5SDimitry Andric return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, 880955e4f9d5SDimitry Andric ReturnTypeRequirement, Status, 881055e4f9d5SDimitry Andric SubstitutedConstraintExpr); 881155e4f9d5SDimitry Andric } 881255e4f9d5SDimitry Andric 881355e4f9d5SDimitry Andric concepts::ExprRequirement * 881455e4f9d5SDimitry Andric Sema::BuildExprRequirement( 881555e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, 881655e4f9d5SDimitry Andric bool IsSimple, SourceLocation NoexceptLoc, 881755e4f9d5SDimitry Andric concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { 881855e4f9d5SDimitry Andric return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, 881955e4f9d5SDimitry Andric IsSimple, NoexceptLoc, 882055e4f9d5SDimitry Andric ReturnTypeRequirement); 882155e4f9d5SDimitry Andric } 882255e4f9d5SDimitry Andric 882355e4f9d5SDimitry Andric concepts::TypeRequirement * 882455e4f9d5SDimitry Andric Sema::BuildTypeRequirement(TypeSourceInfo *Type) { 882555e4f9d5SDimitry Andric return new (Context) concepts::TypeRequirement(Type); 882655e4f9d5SDimitry Andric } 882755e4f9d5SDimitry Andric 882855e4f9d5SDimitry Andric concepts::TypeRequirement * 882955e4f9d5SDimitry Andric Sema::BuildTypeRequirement( 883055e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { 883155e4f9d5SDimitry Andric return new (Context) concepts::TypeRequirement(SubstDiag); 883255e4f9d5SDimitry Andric } 883355e4f9d5SDimitry Andric 883455e4f9d5SDimitry Andric concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { 883555e4f9d5SDimitry Andric return BuildNestedRequirement(Constraint); 883655e4f9d5SDimitry Andric } 883755e4f9d5SDimitry Andric 883855e4f9d5SDimitry Andric concepts::NestedRequirement * 883955e4f9d5SDimitry Andric Sema::BuildNestedRequirement(Expr *Constraint) { 884055e4f9d5SDimitry Andric ConstraintSatisfaction Satisfaction; 884155e4f9d5SDimitry Andric if (!Constraint->isInstantiationDependent() && 884213138422SDimitry Andric CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{}, 884313138422SDimitry Andric Constraint->getSourceRange(), Satisfaction)) 884455e4f9d5SDimitry Andric return nullptr; 884555e4f9d5SDimitry Andric return new (Context) concepts::NestedRequirement(Context, Constraint, 884655e4f9d5SDimitry Andric Satisfaction); 884755e4f9d5SDimitry Andric } 884855e4f9d5SDimitry Andric 884955e4f9d5SDimitry Andric concepts::NestedRequirement * 885055e4f9d5SDimitry Andric Sema::BuildNestedRequirement( 885155e4f9d5SDimitry Andric concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { 885255e4f9d5SDimitry Andric return new (Context) concepts::NestedRequirement(SubstDiag); 885355e4f9d5SDimitry Andric } 885455e4f9d5SDimitry Andric 885555e4f9d5SDimitry Andric RequiresExprBodyDecl * 885655e4f9d5SDimitry Andric Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, 885755e4f9d5SDimitry Andric ArrayRef<ParmVarDecl *> LocalParameters, 885855e4f9d5SDimitry Andric Scope *BodyScope) { 885955e4f9d5SDimitry Andric assert(BodyScope); 886055e4f9d5SDimitry Andric 886155e4f9d5SDimitry Andric RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext, 886255e4f9d5SDimitry Andric RequiresKWLoc); 886355e4f9d5SDimitry Andric 886455e4f9d5SDimitry Andric PushDeclContext(BodyScope, Body); 886555e4f9d5SDimitry Andric 886655e4f9d5SDimitry Andric for (ParmVarDecl *Param : LocalParameters) { 886755e4f9d5SDimitry Andric if (Param->hasDefaultArg()) 886855e4f9d5SDimitry Andric // C++2a [expr.prim.req] p4 886955e4f9d5SDimitry Andric // [...] A local parameter of a requires-expression shall not have a 887055e4f9d5SDimitry Andric // default argument. [...] 887155e4f9d5SDimitry Andric Diag(Param->getDefaultArgRange().getBegin(), 887255e4f9d5SDimitry Andric diag::err_requires_expr_local_parameter_default_argument); 887355e4f9d5SDimitry Andric // Ignore default argument and move on 887455e4f9d5SDimitry Andric 887555e4f9d5SDimitry Andric Param->setDeclContext(Body); 887655e4f9d5SDimitry Andric // If this has an identifier, add it to the scope stack. 887755e4f9d5SDimitry Andric if (Param->getIdentifier()) { 887855e4f9d5SDimitry Andric CheckShadow(BodyScope, Param); 887955e4f9d5SDimitry Andric PushOnScopeChains(Param, BodyScope); 888055e4f9d5SDimitry Andric } 888155e4f9d5SDimitry Andric } 888255e4f9d5SDimitry Andric return Body; 888355e4f9d5SDimitry Andric } 888455e4f9d5SDimitry Andric 888555e4f9d5SDimitry Andric void Sema::ActOnFinishRequiresExpr() { 888655e4f9d5SDimitry Andric assert(CurContext && "DeclContext imbalance!"); 888755e4f9d5SDimitry Andric CurContext = CurContext->getLexicalParent(); 888855e4f9d5SDimitry Andric assert(CurContext && "Popped translation unit!"); 888955e4f9d5SDimitry Andric } 889055e4f9d5SDimitry Andric 889155e4f9d5SDimitry Andric ExprResult 889255e4f9d5SDimitry Andric Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc, 889355e4f9d5SDimitry Andric RequiresExprBodyDecl *Body, 889455e4f9d5SDimitry Andric ArrayRef<ParmVarDecl *> LocalParameters, 889555e4f9d5SDimitry Andric ArrayRef<concepts::Requirement *> Requirements, 889655e4f9d5SDimitry Andric SourceLocation ClosingBraceLoc) { 8897e8d8bef9SDimitry Andric auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters, 889855e4f9d5SDimitry Andric Requirements, ClosingBraceLoc); 8899e8d8bef9SDimitry Andric if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE)) 8900e8d8bef9SDimitry Andric return ExprError(); 8901e8d8bef9SDimitry Andric return RE; 890255e4f9d5SDimitry Andric } 8903