Path: blob/main/contrib/llvm-project/clang/lib/Sema/SemaExpr.cpp
35233 views
//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements semantic analysis for expressions.9//10//===----------------------------------------------------------------------===//1112#include "CheckExprLifetime.h"13#include "TreeTransform.h"14#include "UsedDeclVisitor.h"15#include "clang/AST/ASTConsumer.h"16#include "clang/AST/ASTContext.h"17#include "clang/AST/ASTLambda.h"18#include "clang/AST/ASTMutationListener.h"19#include "clang/AST/CXXInheritance.h"20#include "clang/AST/DeclObjC.h"21#include "clang/AST/DeclTemplate.h"22#include "clang/AST/EvaluatedExprVisitor.h"23#include "clang/AST/Expr.h"24#include "clang/AST/ExprCXX.h"25#include "clang/AST/ExprObjC.h"26#include "clang/AST/ExprOpenMP.h"27#include "clang/AST/OperationKinds.h"28#include "clang/AST/ParentMapContext.h"29#include "clang/AST/RecursiveASTVisitor.h"30#include "clang/AST/Type.h"31#include "clang/AST/TypeLoc.h"32#include "clang/Basic/Builtins.h"33#include "clang/Basic/DiagnosticSema.h"34#include "clang/Basic/PartialDiagnostic.h"35#include "clang/Basic/SourceManager.h"36#include "clang/Basic/Specifiers.h"37#include "clang/Basic/TargetInfo.h"38#include "clang/Basic/TypeTraits.h"39#include "clang/Lex/LiteralSupport.h"40#include "clang/Lex/Preprocessor.h"41#include "clang/Sema/AnalysisBasedWarnings.h"42#include "clang/Sema/DeclSpec.h"43#include "clang/Sema/DelayedDiagnostic.h"44#include "clang/Sema/Designator.h"45#include "clang/Sema/EnterExpressionEvaluationContext.h"46#include "clang/Sema/Initialization.h"47#include "clang/Sema/Lookup.h"48#include "clang/Sema/Overload.h"49#include "clang/Sema/ParsedTemplate.h"50#include "clang/Sema/Scope.h"51#include "clang/Sema/ScopeInfo.h"52#include "clang/Sema/SemaCUDA.h"53#include "clang/Sema/SemaFixItUtils.h"54#include "clang/Sema/SemaInternal.h"55#include "clang/Sema/SemaObjC.h"56#include "clang/Sema/SemaOpenMP.h"57#include "clang/Sema/SemaPseudoObject.h"58#include "clang/Sema/Template.h"59#include "llvm/ADT/STLExtras.h"60#include "llvm/ADT/STLForwardCompat.h"61#include "llvm/ADT/StringExtras.h"62#include "llvm/Support/Casting.h"63#include "llvm/Support/ConvertUTF.h"64#include "llvm/Support/SaveAndRestore.h"65#include "llvm/Support/TypeSize.h"66#include <optional>6768using namespace clang;69using namespace sema;7071bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {72// See if this is an auto-typed variable whose initializer we are parsing.73if (ParsingInitForAutoVars.count(D))74return false;7576// See if this is a deleted function.77if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {78if (FD->isDeleted())79return false;8081// If the function has a deduced return type, and we can't deduce it,82// then we can't use it either.83if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&84DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))85return false;8687// See if this is an aligned allocation/deallocation function that is88// unavailable.89if (TreatUnavailableAsInvalid &&90isUnavailableAlignedAllocationFunction(*FD))91return false;92}9394// See if this function is unavailable.95if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&96cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)97return false;9899if (isa<UnresolvedUsingIfExistsDecl>(D))100return false;101102return true;103}104105static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {106// Warn if this is used but marked unused.107if (const auto *A = D->getAttr<UnusedAttr>()) {108// [[maybe_unused]] should not diagnose uses, but __attribute__((unused))109// should diagnose them.110if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&111A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {112const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());113if (DC && !DC->hasAttr<UnusedAttr>())114S.Diag(Loc, diag::warn_used_but_marked_unused) << D;115}116}117}118119void Sema::NoteDeletedFunction(FunctionDecl *Decl) {120assert(Decl && Decl->isDeleted());121122if (Decl->isDefaulted()) {123// If the method was explicitly defaulted, point at that declaration.124if (!Decl->isImplicit())125Diag(Decl->getLocation(), diag::note_implicitly_deleted);126127// Try to diagnose why this special member function was implicitly128// deleted. This might fail, if that reason no longer applies.129DiagnoseDeletedDefaultedFunction(Decl);130return;131}132133auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);134if (Ctor && Ctor->isInheritingConstructor())135return NoteDeletedInheritingConstructor(Ctor);136137Diag(Decl->getLocation(), diag::note_availability_specified_here)138<< Decl << 1;139}140141/// Determine whether a FunctionDecl was ever declared with an142/// explicit storage class.143static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {144for (auto *I : D->redecls()) {145if (I->getStorageClass() != SC_None)146return true;147}148return false;149}150151/// Check whether we're in an extern inline function and referring to a152/// variable or function with internal linkage (C11 6.7.4p3).153///154/// This is only a warning because we used to silently accept this code, but155/// in many cases it will not behave correctly. This is not enabled in C++ mode156/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)157/// and so while there may still be user mistakes, most of the time we can't158/// prove that there are errors.159static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,160const NamedDecl *D,161SourceLocation Loc) {162// This is disabled under C++; there are too many ways for this to fire in163// contexts where the warning is a false positive, or where it is technically164// correct but benign.165if (S.getLangOpts().CPlusPlus)166return;167168// Check if this is an inlined function or method.169FunctionDecl *Current = S.getCurFunctionDecl();170if (!Current)171return;172if (!Current->isInlined())173return;174if (!Current->isExternallyVisible())175return;176177// Check if the decl has internal linkage.178if (D->getFormalLinkage() != Linkage::Internal)179return;180181// Downgrade from ExtWarn to Extension if182// (1) the supposedly external inline function is in the main file,183// and probably won't be included anywhere else.184// (2) the thing we're referencing is a pure function.185// (3) the thing we're referencing is another inline function.186// This last can give us false negatives, but it's better than warning on187// wrappers for simple C library functions.188const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);189bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);190if (!DowngradeWarning && UsedFn)191DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();192193S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet194: diag::ext_internal_in_extern_inline)195<< /*IsVar=*/!UsedFn << D;196197S.MaybeSuggestAddingStaticToDecl(Current);198199S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)200<< D;201}202203void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {204const FunctionDecl *First = Cur->getFirstDecl();205206// Suggest "static" on the function, if possible.207if (!hasAnyExplicitStorageClass(First)) {208SourceLocation DeclBegin = First->getSourceRange().getBegin();209Diag(DeclBegin, diag::note_convert_inline_to_static)210<< Cur << FixItHint::CreateInsertion(DeclBegin, "static ");211}212}213214bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,215const ObjCInterfaceDecl *UnknownObjCClass,216bool ObjCPropertyAccess,217bool AvoidPartialAvailabilityChecks,218ObjCInterfaceDecl *ClassReceiver,219bool SkipTrailingRequiresClause) {220SourceLocation Loc = Locs.front();221if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {222// If there were any diagnostics suppressed by template argument deduction,223// emit them now.224auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());225if (Pos != SuppressedDiagnostics.end()) {226for (const PartialDiagnosticAt &Suppressed : Pos->second)227Diag(Suppressed.first, Suppressed.second);228229// Clear out the list of suppressed diagnostics, so that we don't emit230// them again for this specialization. However, we don't obsolete this231// entry from the table, because we want to avoid ever emitting these232// diagnostics again.233Pos->second.clear();234}235236// C++ [basic.start.main]p3:237// The function 'main' shall not be used within a program.238if (cast<FunctionDecl>(D)->isMain())239Diag(Loc, diag::ext_main_used);240241diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);242}243244// See if this is an auto-typed variable whose initializer we are parsing.245if (ParsingInitForAutoVars.count(D)) {246if (isa<BindingDecl>(D)) {247Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)248<< D->getDeclName();249} else {250Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)251<< D->getDeclName() << cast<VarDecl>(D)->getType();252}253return true;254}255256if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {257// See if this is a deleted function.258if (FD->isDeleted()) {259auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);260if (Ctor && Ctor->isInheritingConstructor())261Diag(Loc, diag::err_deleted_inherited_ctor_use)262<< Ctor->getParent()263<< Ctor->getInheritedConstructor().getConstructor()->getParent();264else {265StringLiteral *Msg = FD->getDeletedMessage();266Diag(Loc, diag::err_deleted_function_use)267<< (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());268}269NoteDeletedFunction(FD);270return true;271}272273// [expr.prim.id]p4274// A program that refers explicitly or implicitly to a function with a275// trailing requires-clause whose constraint-expression is not satisfied,276// other than to declare it, is ill-formed. [...]277//278// See if this is a function with constraints that need to be satisfied.279// Check this before deducing the return type, as it might instantiate the280// definition.281if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {282ConstraintSatisfaction Satisfaction;283if (CheckFunctionConstraints(FD, Satisfaction, Loc,284/*ForOverloadResolution*/ true))285// A diagnostic will have already been generated (non-constant286// constraint expression, for example)287return true;288if (!Satisfaction.IsSatisfied) {289Diag(Loc,290diag::err_reference_to_function_with_unsatisfied_constraints)291<< D;292DiagnoseUnsatisfiedConstraint(Satisfaction);293return true;294}295}296297// If the function has a deduced return type, and we can't deduce it,298// then we can't use it either.299if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&300DeduceReturnType(FD, Loc))301return true;302303if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))304return true;305306}307308if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {309// Lambdas are only default-constructible or assignable in C++2a onwards.310if (MD->getParent()->isLambda() &&311((isa<CXXConstructorDecl>(MD) &&312cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||313MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {314Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)315<< !isa<CXXConstructorDecl>(MD);316}317}318319auto getReferencedObjCProp = [](const NamedDecl *D) ->320const ObjCPropertyDecl * {321if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))322return MD->findPropertyDecl();323return nullptr;324};325if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {326if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))327return true;328} else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {329return true;330}331332// [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions333// Only the variables omp_in and omp_out are allowed in the combiner.334// Only the variables omp_priv and omp_orig are allowed in the335// initializer-clause.336auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);337if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&338isa<VarDecl>(D)) {339Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)340<< getCurFunction()->HasOMPDeclareReductionCombiner;341Diag(D->getLocation(), diag::note_entity_declared_at) << D;342return true;343}344345// [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions346// List-items in map clauses on this construct may only refer to the declared347// variable var and entities that could be referenced by a procedure defined348// at the same location.349// [OpenMP 5.2] Also allow iterator declared variables.350if (LangOpts.OpenMP && isa<VarDecl>(D) &&351!OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {352Diag(Loc, diag::err_omp_declare_mapper_wrong_var)353<< OpenMP().getOpenMPDeclareMapperVarName();354Diag(D->getLocation(), diag::note_entity_declared_at) << D;355return true;356}357358if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {359Diag(Loc, diag::err_use_of_empty_using_if_exists);360Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);361return true;362}363364DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,365AvoidPartialAvailabilityChecks, ClassReceiver);366367DiagnoseUnusedOfDecl(*this, D, Loc);368369diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);370371if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {372if (getLangOpts().getFPEvalMethod() !=373LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&374PP.getLastFPEvalPragmaLocation().isValid() &&375PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())376Diag(D->getLocation(),377diag::err_type_available_only_in_default_eval_method)378<< D->getName();379}380381if (auto *VD = dyn_cast<ValueDecl>(D))382checkTypeSupport(VD->getType(), Loc, VD);383384if (LangOpts.SYCLIsDevice ||385(LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {386if (!Context.getTargetInfo().isTLSSupported())387if (const auto *VD = dyn_cast<VarDecl>(D))388if (VD->getTLSKind() != VarDecl::TLS_None)389targetDiag(*Locs.begin(), diag::err_thread_unsupported);390}391392if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&393!isUnevaluatedContext()) {394// C++ [expr.prim.req.nested] p3395// A local parameter shall only appear as an unevaluated operand396// (Clause 8) within the constraint-expression.397Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)398<< D;399Diag(D->getLocation(), diag::note_entity_declared_at) << D;400return true;401}402403return false;404}405406void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,407ArrayRef<Expr *> Args) {408const SentinelAttr *Attr = D->getAttr<SentinelAttr>();409if (!Attr)410return;411412// The number of formal parameters of the declaration.413unsigned NumFormalParams;414415// The kind of declaration. This is also an index into a %select in416// the diagnostic.417enum { CK_Function, CK_Method, CK_Block } CalleeKind;418419if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {420NumFormalParams = MD->param_size();421CalleeKind = CK_Method;422} else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {423NumFormalParams = FD->param_size();424CalleeKind = CK_Function;425} else if (const auto *VD = dyn_cast<VarDecl>(D)) {426QualType Ty = VD->getType();427const FunctionType *Fn = nullptr;428if (const auto *PtrTy = Ty->getAs<PointerType>()) {429Fn = PtrTy->getPointeeType()->getAs<FunctionType>();430if (!Fn)431return;432CalleeKind = CK_Function;433} else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {434Fn = PtrTy->getPointeeType()->castAs<FunctionType>();435CalleeKind = CK_Block;436} else {437return;438}439440if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))441NumFormalParams = proto->getNumParams();442else443NumFormalParams = 0;444} else {445return;446}447448// "NullPos" is the number of formal parameters at the end which449// effectively count as part of the variadic arguments. This is450// useful if you would prefer to not have *any* formal parameters,451// but the language forces you to have at least one.452unsigned NullPos = Attr->getNullPos();453assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");454NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);455456// The number of arguments which should follow the sentinel.457unsigned NumArgsAfterSentinel = Attr->getSentinel();458459// If there aren't enough arguments for all the formal parameters,460// the sentinel, and the args after the sentinel, complain.461if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {462Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();463Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);464return;465}466467// Otherwise, find the sentinel expression.468const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];469if (!SentinelExpr)470return;471if (SentinelExpr->isValueDependent())472return;473if (Context.isSentinelNullExpr(SentinelExpr))474return;475476// Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',477// or 'NULL' if those are actually defined in the context. Only use478// 'nil' for ObjC methods, where it's much more likely that the479// variadic arguments form a list of object pointers.480SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());481std::string NullValue;482if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))483NullValue = "nil";484else if (getLangOpts().CPlusPlus11)485NullValue = "nullptr";486else if (PP.isMacroDefined("NULL"))487NullValue = "NULL";488else489NullValue = "(void*) 0";490491if (MissingNilLoc.isInvalid())492Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);493else494Diag(MissingNilLoc, diag::warn_missing_sentinel)495<< int(CalleeKind)496<< FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);497Diag(D->getLocation(), diag::note_sentinel_here)498<< int(CalleeKind) << Attr->getRange();499}500501SourceRange Sema::getExprRange(Expr *E) const {502return E ? E->getSourceRange() : SourceRange();503}504505//===----------------------------------------------------------------------===//506// Standard Promotions and Conversions507//===----------------------------------------------------------------------===//508509/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).510ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {511// Handle any placeholder expressions which made it here.512if (E->hasPlaceholderType()) {513ExprResult result = CheckPlaceholderExpr(E);514if (result.isInvalid()) return ExprError();515E = result.get();516}517518QualType Ty = E->getType();519assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");520521if (Ty->isFunctionType()) {522if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))523if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))524if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))525return ExprError();526527E = ImpCastExprToType(E, Context.getPointerType(Ty),528CK_FunctionToPointerDecay).get();529} else if (Ty->isArrayType()) {530// In C90 mode, arrays only promote to pointers if the array expression is531// an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has532// type 'array of type' is converted to an expression that has type 'pointer533// to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression534// that has type 'array of type' ...". The relevant change is "an lvalue"535// (C90) to "an expression" (C99).536//537// C++ 4.2p1:538// An lvalue or rvalue of type "array of N T" or "array of unknown bound of539// T" can be converted to an rvalue of type "pointer to T".540//541if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {542ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),543CK_ArrayToPointerDecay);544if (Res.isInvalid())545return ExprError();546E = Res.get();547}548}549return E;550}551552static void CheckForNullPointerDereference(Sema &S, Expr *E) {553// Check to see if we are dereferencing a null pointer. If so,554// and if not volatile-qualified, this is undefined behavior that the555// optimizer will delete, so warn about it. People sometimes try to use this556// to get a deterministic trap and are surprised by clang's behavior. This557// only handles the pattern "*null", which is a very syntactic check.558const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());559if (UO && UO->getOpcode() == UO_Deref &&560UO->getSubExpr()->getType()->isPointerType()) {561const LangAS AS =562UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();563if ((!isTargetAddressSpace(AS) ||564(isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&565UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(566S.Context, Expr::NPC_ValueDependentIsNotNull) &&567!UO->getType().isVolatileQualified()) {568S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,569S.PDiag(diag::warn_indirection_through_null)570<< UO->getSubExpr()->getSourceRange());571S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,572S.PDiag(diag::note_indirection_through_null));573}574}575}576577static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,578SourceLocation AssignLoc,579const Expr* RHS) {580const ObjCIvarDecl *IV = OIRE->getDecl();581if (!IV)582return;583584DeclarationName MemberName = IV->getDeclName();585IdentifierInfo *Member = MemberName.getAsIdentifierInfo();586if (!Member || !Member->isStr("isa"))587return;588589const Expr *Base = OIRE->getBase();590QualType BaseType = Base->getType();591if (OIRE->isArrow())592BaseType = BaseType->getPointeeType();593if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())594if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {595ObjCInterfaceDecl *ClassDeclared = nullptr;596ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);597if (!ClassDeclared->getSuperClass()598&& (*ClassDeclared->ivar_begin()) == IV) {599if (RHS) {600NamedDecl *ObjectSetClass =601S.LookupSingleName(S.TUScope,602&S.Context.Idents.get("object_setClass"),603SourceLocation(), S.LookupOrdinaryName);604if (ObjectSetClass) {605SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());606S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)607<< FixItHint::CreateInsertion(OIRE->getBeginLoc(),608"object_setClass(")609<< FixItHint::CreateReplacement(610SourceRange(OIRE->getOpLoc(), AssignLoc), ",")611<< FixItHint::CreateInsertion(RHSLocEnd, ")");612}613else614S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);615} else {616NamedDecl *ObjectGetClass =617S.LookupSingleName(S.TUScope,618&S.Context.Idents.get("object_getClass"),619SourceLocation(), S.LookupOrdinaryName);620if (ObjectGetClass)621S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)622<< FixItHint::CreateInsertion(OIRE->getBeginLoc(),623"object_getClass(")624<< FixItHint::CreateReplacement(625SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");626else627S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);628}629S.Diag(IV->getLocation(), diag::note_ivar_decl);630}631}632}633634ExprResult Sema::DefaultLvalueConversion(Expr *E) {635// Handle any placeholder expressions which made it here.636if (E->hasPlaceholderType()) {637ExprResult result = CheckPlaceholderExpr(E);638if (result.isInvalid()) return ExprError();639E = result.get();640}641642// C++ [conv.lval]p1:643// A glvalue of a non-function, non-array type T can be644// converted to a prvalue.645if (!E->isGLValue()) return E;646647QualType T = E->getType();648assert(!T.isNull() && "r-value conversion on typeless expression?");649650// lvalue-to-rvalue conversion cannot be applied to types that decay to651// pointers (i.e. function or array types).652if (T->canDecayToPointerType())653return E;654655// We don't want to throw lvalue-to-rvalue casts on top of656// expressions of certain types in C++.657if (getLangOpts().CPlusPlus) {658if (T == Context.OverloadTy || T->isRecordType() ||659(T->isDependentType() && !T->isAnyPointerType() &&660!T->isMemberPointerType()))661return E;662}663664// The C standard is actually really unclear on this point, and665// DR106 tells us what the result should be but not why. It's666// generally best to say that void types just doesn't undergo667// lvalue-to-rvalue at all. Note that expressions of unqualified668// 'void' type are never l-values, but qualified void can be.669if (T->isVoidType())670return E;671672// OpenCL usually rejects direct accesses to values of 'half' type.673if (getLangOpts().OpenCL &&674!getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&675T->isHalfType()) {676Diag(E->getExprLoc(), diag::err_opencl_half_load_store)677<< 0 << T;678return ExprError();679}680681CheckForNullPointerDereference(*this, E);682if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {683NamedDecl *ObjectGetClass = LookupSingleName(TUScope,684&Context.Idents.get("object_getClass"),685SourceLocation(), LookupOrdinaryName);686if (ObjectGetClass)687Diag(E->getExprLoc(), diag::warn_objc_isa_use)688<< FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")689<< FixItHint::CreateReplacement(690SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");691else692Diag(E->getExprLoc(), diag::warn_objc_isa_use);693}694else if (const ObjCIvarRefExpr *OIRE =695dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))696DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);697698// C++ [conv.lval]p1:699// [...] If T is a non-class type, the type of the prvalue is the700// cv-unqualified version of T. Otherwise, the type of the701// rvalue is T.702//703// C99 6.3.2.1p2:704// If the lvalue has qualified type, the value has the unqualified705// version of the type of the lvalue; otherwise, the value has the706// type of the lvalue.707if (T.hasQualifiers())708T = T.getUnqualifiedType();709710// Under the MS ABI, lock down the inheritance model now.711if (T->isMemberPointerType() &&712Context.getTargetInfo().getCXXABI().isMicrosoft())713(void)isCompleteType(E->getExprLoc(), T);714715ExprResult Res = CheckLValueToRValueConversionOperand(E);716if (Res.isInvalid())717return Res;718E = Res.get();719720// Loading a __weak object implicitly retains the value, so we need a cleanup to721// balance that.722if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)723Cleanup.setExprNeedsCleanups(true);724725if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)726Cleanup.setExprNeedsCleanups(true);727728// C++ [conv.lval]p3:729// If T is cv std::nullptr_t, the result is a null pointer constant.730CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;731Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,732CurFPFeatureOverrides());733734// C11 6.3.2.1p2:735// ... if the lvalue has atomic type, the value has the non-atomic version736// of the type of the lvalue ...737if (const AtomicType *Atomic = T->getAs<AtomicType>()) {738T = Atomic->getValueType().getUnqualifiedType();739Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),740nullptr, VK_PRValue, FPOptionsOverride());741}742743return Res;744}745746ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {747ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);748if (Res.isInvalid())749return ExprError();750Res = DefaultLvalueConversion(Res.get());751if (Res.isInvalid())752return ExprError();753return Res;754}755756ExprResult Sema::CallExprUnaryConversions(Expr *E) {757QualType Ty = E->getType();758ExprResult Res = E;759// Only do implicit cast for a function type, but not for a pointer760// to function type.761if (Ty->isFunctionType()) {762Res = ImpCastExprToType(E, Context.getPointerType(Ty),763CK_FunctionToPointerDecay);764if (Res.isInvalid())765return ExprError();766}767Res = DefaultLvalueConversion(Res.get());768if (Res.isInvalid())769return ExprError();770return Res.get();771}772773/// UsualUnaryConversions - Performs various conversions that are common to most774/// operators (C99 6.3). The conversions of array and function types are775/// sometimes suppressed. For example, the array->pointer conversion doesn't776/// apply if the array is an argument to the sizeof or address (&) operators.777/// In these instances, this routine should *not* be called.778ExprResult Sema::UsualUnaryConversions(Expr *E) {779// First, convert to an r-value.780ExprResult Res = DefaultFunctionArrayLvalueConversion(E);781if (Res.isInvalid())782return ExprError();783E = Res.get();784785QualType Ty = E->getType();786assert(!Ty.isNull() && "UsualUnaryConversions - missing type");787788LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();789if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&790(getLangOpts().getFPEvalMethod() !=791LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||792PP.getLastFPEvalPragmaLocation().isValid())) {793switch (EvalMethod) {794default:795llvm_unreachable("Unrecognized float evaluation method");796break;797case LangOptions::FEM_UnsetOnCommandLine:798llvm_unreachable("Float evaluation method should be set by now");799break;800case LangOptions::FEM_Double:801if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)802// Widen the expression to double.803return Ty->isComplexType()804? ImpCastExprToType(E,805Context.getComplexType(Context.DoubleTy),806CK_FloatingComplexCast)807: ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);808break;809case LangOptions::FEM_Extended:810if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)811// Widen the expression to long double.812return Ty->isComplexType()813? ImpCastExprToType(814E, Context.getComplexType(Context.LongDoubleTy),815CK_FloatingComplexCast)816: ImpCastExprToType(E, Context.LongDoubleTy,817CK_FloatingCast);818break;819}820}821822// Half FP have to be promoted to float unless it is natively supported823if (Ty->isHalfType() && !getLangOpts().NativeHalfType)824return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);825826// Try to perform integral promotions if the object has a theoretically827// promotable type.828if (Ty->isIntegralOrUnscopedEnumerationType()) {829// C99 6.3.1.1p2:830//831// The following may be used in an expression wherever an int or832// unsigned int may be used:833// - an object or expression with an integer type whose integer834// conversion rank is less than or equal to the rank of int835// and unsigned int.836// - A bit-field of type _Bool, int, signed int, or unsigned int.837//838// If an int can represent all values of the original type, the839// value is converted to an int; otherwise, it is converted to an840// unsigned int. These are called the integer promotions. All841// other types are unchanged by the integer promotions.842843QualType PTy = Context.isPromotableBitField(E);844if (!PTy.isNull()) {845E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();846return E;847}848if (Context.isPromotableIntegerType(Ty)) {849QualType PT = Context.getPromotedIntegerType(Ty);850E = ImpCastExprToType(E, PT, CK_IntegralCast).get();851return E;852}853}854return E;855}856857/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that858/// do not have a prototype. Arguments that have type float or __fp16859/// are promoted to double. All other argument types are converted by860/// UsualUnaryConversions().861ExprResult Sema::DefaultArgumentPromotion(Expr *E) {862QualType Ty = E->getType();863assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");864865ExprResult Res = UsualUnaryConversions(E);866if (Res.isInvalid())867return ExprError();868E = Res.get();869870// If this is a 'float' or '__fp16' (CVR qualified or typedef)871// promote to double.872// Note that default argument promotion applies only to float (and873// half/fp16); it does not apply to _Float16.874const BuiltinType *BTy = Ty->getAs<BuiltinType>();875if (BTy && (BTy->getKind() == BuiltinType::Half ||876BTy->getKind() == BuiltinType::Float)) {877if (getLangOpts().OpenCL &&878!getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {879if (BTy->getKind() == BuiltinType::Half) {880E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();881}882} else {883E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();884}885}886if (BTy &&887getLangOpts().getExtendIntArgs() ==888LangOptions::ExtendArgsKind::ExtendTo64 &&889Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&890Context.getTypeSizeInChars(BTy) <891Context.getTypeSizeInChars(Context.LongLongTy)) {892E = (Ty->isUnsignedIntegerType())893? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)894.get()895: ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();896assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&897"Unexpected typesize for LongLongTy");898}899900// C++ performs lvalue-to-rvalue conversion as a default argument901// promotion, even on class types, but note:902// C++11 [conv.lval]p2:903// When an lvalue-to-rvalue conversion occurs in an unevaluated904// operand or a subexpression thereof the value contained in the905// referenced object is not accessed. Otherwise, if the glvalue906// has a class type, the conversion copy-initializes a temporary907// of type T from the glvalue and the result of the conversion908// is a prvalue for the temporary.909// FIXME: add some way to gate this entire thing for correctness in910// potentially potentially evaluated contexts.911if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {912ExprResult Temp = PerformCopyInitialization(913InitializedEntity::InitializeTemporary(E->getType()),914E->getExprLoc(), E);915if (Temp.isInvalid())916return ExprError();917E = Temp.get();918}919920return E;921}922923Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {924if (Ty->isIncompleteType()) {925// C++11 [expr.call]p7:926// After these conversions, if the argument does not have arithmetic,927// enumeration, pointer, pointer to member, or class type, the program928// is ill-formed.929//930// Since we've already performed array-to-pointer and function-to-pointer931// decay, the only such type in C++ is cv void. This also handles932// initializer lists as variadic arguments.933if (Ty->isVoidType())934return VAK_Invalid;935936if (Ty->isObjCObjectType())937return VAK_Invalid;938return VAK_Valid;939}940941if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)942return VAK_Invalid;943944if (Context.getTargetInfo().getTriple().isWasm() &&945Ty.isWebAssemblyReferenceType()) {946return VAK_Invalid;947}948949if (Ty.isCXX98PODType(Context))950return VAK_Valid;951952// C++11 [expr.call]p7:953// Passing a potentially-evaluated argument of class type (Clause 9)954// having a non-trivial copy constructor, a non-trivial move constructor,955// or a non-trivial destructor, with no corresponding parameter,956// is conditionally-supported with implementation-defined semantics.957if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())958if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())959if (!Record->hasNonTrivialCopyConstructor() &&960!Record->hasNonTrivialMoveConstructor() &&961!Record->hasNonTrivialDestructor())962return VAK_ValidInCXX11;963964if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())965return VAK_Valid;966967if (Ty->isObjCObjectType())968return VAK_Invalid;969970if (getLangOpts().MSVCCompat)971return VAK_MSVCUndefined;972973// FIXME: In C++11, these cases are conditionally-supported, meaning we're974// permitted to reject them. We should consider doing so.975return VAK_Undefined;976}977978void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {979// Don't allow one to pass an Objective-C interface to a vararg.980const QualType &Ty = E->getType();981VarArgKind VAK = isValidVarArgType(Ty);982983// Complain about passing non-POD types through varargs.984switch (VAK) {985case VAK_ValidInCXX11:986DiagRuntimeBehavior(987E->getBeginLoc(), nullptr,988PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);989[[fallthrough]];990case VAK_Valid:991if (Ty->isRecordType()) {992// This is unlikely to be what the user intended. If the class has a993// 'c_str' member function, the user probably meant to call that.994DiagRuntimeBehavior(E->getBeginLoc(), nullptr,995PDiag(diag::warn_pass_class_arg_to_vararg)996<< Ty << CT << hasCStrMethod(E) << ".c_str()");997}998break;9991000case VAK_Undefined:1001case VAK_MSVCUndefined:1002DiagRuntimeBehavior(E->getBeginLoc(), nullptr,1003PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)1004<< getLangOpts().CPlusPlus11 << Ty << CT);1005break;10061007case VAK_Invalid:1008if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)1009Diag(E->getBeginLoc(),1010diag::err_cannot_pass_non_trivial_c_struct_to_vararg)1011<< Ty << CT;1012else if (Ty->isObjCObjectType())1013DiagRuntimeBehavior(E->getBeginLoc(), nullptr,1014PDiag(diag::err_cannot_pass_objc_interface_to_vararg)1015<< Ty << CT);1016else1017Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)1018<< isa<InitListExpr>(E) << Ty << CT;1019break;1020}1021}10221023ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,1024FunctionDecl *FDecl) {1025if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {1026// Strip the unbridged-cast placeholder expression off, if applicable.1027if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&1028(CT == VariadicMethod ||1029(FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {1030E = ObjC().stripARCUnbridgedCast(E);10311032// Otherwise, do normal placeholder checking.1033} else {1034ExprResult ExprRes = CheckPlaceholderExpr(E);1035if (ExprRes.isInvalid())1036return ExprError();1037E = ExprRes.get();1038}1039}10401041ExprResult ExprRes = DefaultArgumentPromotion(E);1042if (ExprRes.isInvalid())1043return ExprError();10441045// Copy blocks to the heap.1046if (ExprRes.get()->getType()->isBlockPointerType())1047maybeExtendBlockObject(ExprRes);10481049E = ExprRes.get();10501051// Diagnostics regarding non-POD argument types are1052// emitted along with format string checking in Sema::CheckFunctionCall().1053if (isValidVarArgType(E->getType()) == VAK_Undefined) {1054// Turn this into a trap.1055CXXScopeSpec SS;1056SourceLocation TemplateKWLoc;1057UnqualifiedId Name;1058Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),1059E->getBeginLoc());1060ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,1061/*HasTrailingLParen=*/true,1062/*IsAddressOfOperand=*/false);1063if (TrapFn.isInvalid())1064return ExprError();10651066ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(),1067std::nullopt, E->getEndLoc());1068if (Call.isInvalid())1069return ExprError();10701071ExprResult Comma =1072ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);1073if (Comma.isInvalid())1074return ExprError();1075return Comma.get();1076}10771078if (!getLangOpts().CPlusPlus &&1079RequireCompleteType(E->getExprLoc(), E->getType(),1080diag::err_call_incomplete_argument))1081return ExprError();10821083return E;1084}10851086/// Convert complex integers to complex floats and real integers to1087/// real floats as required for complex arithmetic. Helper function of1088/// UsualArithmeticConversions()1089///1090/// \return false if the integer expression is an integer type and is1091/// successfully converted to the (complex) float type.1092static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,1093ExprResult &ComplexExpr,1094QualType IntTy,1095QualType ComplexTy,1096bool SkipCast) {1097if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;1098if (SkipCast) return false;1099if (IntTy->isIntegerType()) {1100QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();1101IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);1102} else {1103assert(IntTy->isComplexIntegerType());1104IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,1105CK_IntegralComplexToFloatingComplex);1106}1107return false;1108}11091110// This handles complex/complex, complex/float, or float/complex.1111// When both operands are complex, the shorter operand is converted to the1112// type of the longer, and that is the type of the result. This corresponds1113// to what is done when combining two real floating-point operands.1114// The fun begins when size promotion occur across type domains.1115// From H&S 6.3.4: When one operand is complex and the other is a real1116// floating-point type, the less precise type is converted, within it's1117// real or complex domain, to the precision of the other type. For example,1118// when combining a "long double" with a "double _Complex", the1119// "double _Complex" is promoted to "long double _Complex".1120static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,1121QualType ShorterType,1122QualType LongerType,1123bool PromotePrecision) {1124bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());1125QualType Result =1126LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);11271128if (PromotePrecision) {1129if (isa<ComplexType>(ShorterType.getCanonicalType())) {1130Shorter =1131S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);1132} else {1133if (LongerIsComplex)1134LongerType = LongerType->castAs<ComplexType>()->getElementType();1135Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);1136}1137}1138return Result;1139}11401141/// Handle arithmetic conversion with complex types. Helper function of1142/// UsualArithmeticConversions()1143static QualType handleComplexConversion(Sema &S, ExprResult &LHS,1144ExprResult &RHS, QualType LHSType,1145QualType RHSType, bool IsCompAssign) {1146// Handle (complex) integer types.1147if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,1148/*SkipCast=*/false))1149return LHSType;1150if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,1151/*SkipCast=*/IsCompAssign))1152return RHSType;11531154// Compute the rank of the two types, regardless of whether they are complex.1155int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);1156if (Order < 0)1157// Promote the precision of the LHS if not an assignment.1158return handleComplexFloatConversion(S, LHS, LHSType, RHSType,1159/*PromotePrecision=*/!IsCompAssign);1160// Promote the precision of the RHS unless it is already the same as the LHS.1161return handleComplexFloatConversion(S, RHS, RHSType, LHSType,1162/*PromotePrecision=*/Order > 0);1163}11641165/// Handle arithmetic conversion from integer to float. Helper function1166/// of UsualArithmeticConversions()1167static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,1168ExprResult &IntExpr,1169QualType FloatTy, QualType IntTy,1170bool ConvertFloat, bool ConvertInt) {1171if (IntTy->isIntegerType()) {1172if (ConvertInt)1173// Convert intExpr to the lhs floating point type.1174IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,1175CK_IntegralToFloating);1176return FloatTy;1177}11781179// Convert both sides to the appropriate complex float.1180assert(IntTy->isComplexIntegerType());1181QualType result = S.Context.getComplexType(FloatTy);11821183// _Complex int -> _Complex float1184if (ConvertInt)1185IntExpr = S.ImpCastExprToType(IntExpr.get(), result,1186CK_IntegralComplexToFloatingComplex);11871188// float -> _Complex float1189if (ConvertFloat)1190FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,1191CK_FloatingRealToComplex);11921193return result;1194}11951196/// Handle arithmethic conversion with floating point types. Helper1197/// function of UsualArithmeticConversions()1198static QualType handleFloatConversion(Sema &S, ExprResult &LHS,1199ExprResult &RHS, QualType LHSType,1200QualType RHSType, bool IsCompAssign) {1201bool LHSFloat = LHSType->isRealFloatingType();1202bool RHSFloat = RHSType->isRealFloatingType();12031204// N1169 4.1.4: If one of the operands has a floating type and the other1205// operand has a fixed-point type, the fixed-point operand1206// is converted to the floating type [...]1207if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {1208if (LHSFloat)1209RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);1210else if (!IsCompAssign)1211LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);1212return LHSFloat ? LHSType : RHSType;1213}12141215// If we have two real floating types, convert the smaller operand1216// to the bigger result.1217if (LHSFloat && RHSFloat) {1218int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);1219if (order > 0) {1220RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);1221return LHSType;1222}12231224assert(order < 0 && "illegal float comparison");1225if (!IsCompAssign)1226LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);1227return RHSType;1228}12291230if (LHSFloat) {1231// Half FP has to be promoted to float unless it is natively supported1232if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)1233LHSType = S.Context.FloatTy;12341235return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,1236/*ConvertFloat=*/!IsCompAssign,1237/*ConvertInt=*/ true);1238}1239assert(RHSFloat);1240return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,1241/*ConvertFloat=*/ true,1242/*ConvertInt=*/!IsCompAssign);1243}12441245/// Diagnose attempts to convert between __float128, __ibm128 and1246/// long double if there is no support for such conversion.1247/// Helper function of UsualArithmeticConversions().1248static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,1249QualType RHSType) {1250// No issue if either is not a floating point type.1251if (!LHSType->isFloatingType() || !RHSType->isFloatingType())1252return false;12531254// No issue if both have the same 128-bit float semantics.1255auto *LHSComplex = LHSType->getAs<ComplexType>();1256auto *RHSComplex = RHSType->getAs<ComplexType>();12571258QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;1259QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;12601261const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);1262const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);12631264if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||1265&RHSSem != &llvm::APFloat::IEEEquad()) &&1266(&LHSSem != &llvm::APFloat::IEEEquad() ||1267&RHSSem != &llvm::APFloat::PPCDoubleDouble()))1268return false;12691270return true;1271}12721273typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);12741275namespace {1276/// These helper callbacks are placed in an anonymous namespace to1277/// permit their use as function template parameters.1278ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {1279return S.ImpCastExprToType(op, toType, CK_IntegralCast);1280}12811282ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {1283return S.ImpCastExprToType(op, S.Context.getComplexType(toType),1284CK_IntegralComplexCast);1285}1286}12871288/// Handle integer arithmetic conversions. Helper function of1289/// UsualArithmeticConversions()1290template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>1291static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,1292ExprResult &RHS, QualType LHSType,1293QualType RHSType, bool IsCompAssign) {1294// The rules for this case are in C99 6.3.1.81295int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);1296bool LHSSigned = LHSType->hasSignedIntegerRepresentation();1297bool RHSSigned = RHSType->hasSignedIntegerRepresentation();1298if (LHSSigned == RHSSigned) {1299// Same signedness; use the higher-ranked type1300if (order >= 0) {1301RHS = (*doRHSCast)(S, RHS.get(), LHSType);1302return LHSType;1303} else if (!IsCompAssign)1304LHS = (*doLHSCast)(S, LHS.get(), RHSType);1305return RHSType;1306} else if (order != (LHSSigned ? 1 : -1)) {1307// The unsigned type has greater than or equal rank to the1308// signed type, so use the unsigned type1309if (RHSSigned) {1310RHS = (*doRHSCast)(S, RHS.get(), LHSType);1311return LHSType;1312} else if (!IsCompAssign)1313LHS = (*doLHSCast)(S, LHS.get(), RHSType);1314return RHSType;1315} else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {1316// The two types are different widths; if we are here, that1317// means the signed type is larger than the unsigned type, so1318// use the signed type.1319if (LHSSigned) {1320RHS = (*doRHSCast)(S, RHS.get(), LHSType);1321return LHSType;1322} else if (!IsCompAssign)1323LHS = (*doLHSCast)(S, LHS.get(), RHSType);1324return RHSType;1325} else {1326// The signed type is higher-ranked than the unsigned type,1327// but isn't actually any bigger (like unsigned int and long1328// on most 32-bit systems). Use the unsigned type corresponding1329// to the signed type.1330QualType result =1331S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);1332RHS = (*doRHSCast)(S, RHS.get(), result);1333if (!IsCompAssign)1334LHS = (*doLHSCast)(S, LHS.get(), result);1335return result;1336}1337}13381339/// Handle conversions with GCC complex int extension. Helper function1340/// of UsualArithmeticConversions()1341static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,1342ExprResult &RHS, QualType LHSType,1343QualType RHSType,1344bool IsCompAssign) {1345const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();1346const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();13471348if (LHSComplexInt && RHSComplexInt) {1349QualType LHSEltType = LHSComplexInt->getElementType();1350QualType RHSEltType = RHSComplexInt->getElementType();1351QualType ScalarType =1352handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>1353(S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);13541355return S.Context.getComplexType(ScalarType);1356}13571358if (LHSComplexInt) {1359QualType LHSEltType = LHSComplexInt->getElementType();1360QualType ScalarType =1361handleIntegerConversion<doComplexIntegralCast, doIntegralCast>1362(S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);1363QualType ComplexType = S.Context.getComplexType(ScalarType);1364RHS = S.ImpCastExprToType(RHS.get(), ComplexType,1365CK_IntegralRealToComplex);13661367return ComplexType;1368}13691370assert(RHSComplexInt);13711372QualType RHSEltType = RHSComplexInt->getElementType();1373QualType ScalarType =1374handleIntegerConversion<doIntegralCast, doComplexIntegralCast>1375(S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);1376QualType ComplexType = S.Context.getComplexType(ScalarType);13771378if (!IsCompAssign)1379LHS = S.ImpCastExprToType(LHS.get(), ComplexType,1380CK_IntegralRealToComplex);1381return ComplexType;1382}13831384/// Return the rank of a given fixed point or integer type. The value itself1385/// doesn't matter, but the values must be increasing with proper increasing1386/// rank as described in N1169 4.1.1.1387static unsigned GetFixedPointRank(QualType Ty) {1388const auto *BTy = Ty->getAs<BuiltinType>();1389assert(BTy && "Expected a builtin type.");13901391switch (BTy->getKind()) {1392case BuiltinType::ShortFract:1393case BuiltinType::UShortFract:1394case BuiltinType::SatShortFract:1395case BuiltinType::SatUShortFract:1396return 1;1397case BuiltinType::Fract:1398case BuiltinType::UFract:1399case BuiltinType::SatFract:1400case BuiltinType::SatUFract:1401return 2;1402case BuiltinType::LongFract:1403case BuiltinType::ULongFract:1404case BuiltinType::SatLongFract:1405case BuiltinType::SatULongFract:1406return 3;1407case BuiltinType::ShortAccum:1408case BuiltinType::UShortAccum:1409case BuiltinType::SatShortAccum:1410case BuiltinType::SatUShortAccum:1411return 4;1412case BuiltinType::Accum:1413case BuiltinType::UAccum:1414case BuiltinType::SatAccum:1415case BuiltinType::SatUAccum:1416return 5;1417case BuiltinType::LongAccum:1418case BuiltinType::ULongAccum:1419case BuiltinType::SatLongAccum:1420case BuiltinType::SatULongAccum:1421return 6;1422default:1423if (BTy->isInteger())1424return 0;1425llvm_unreachable("Unexpected fixed point or integer type");1426}1427}14281429/// handleFixedPointConversion - Fixed point operations between fixed1430/// point types and integers or other fixed point types do not fall under1431/// usual arithmetic conversion since these conversions could result in loss1432/// of precsision (N1169 4.1.4). These operations should be calculated with1433/// the full precision of their result type (N1169 4.1.6.2.1).1434static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,1435QualType RHSTy) {1436assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&1437"Expected at least one of the operands to be a fixed point type");1438assert((LHSTy->isFixedPointOrIntegerType() ||1439RHSTy->isFixedPointOrIntegerType()) &&1440"Special fixed point arithmetic operation conversions are only "1441"applied to ints or other fixed point types");14421443// If one operand has signed fixed-point type and the other operand has1444// unsigned fixed-point type, then the unsigned fixed-point operand is1445// converted to its corresponding signed fixed-point type and the resulting1446// type is the type of the converted operand.1447if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())1448LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);1449else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())1450RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);14511452// The result type is the type with the highest rank, whereby a fixed-point1453// conversion rank is always greater than an integer conversion rank; if the1454// type of either of the operands is a saturating fixedpoint type, the result1455// type shall be the saturating fixed-point type corresponding to the type1456// with the highest rank; the resulting value is converted (taking into1457// account rounding and overflow) to the precision of the resulting type.1458// Same ranks between signed and unsigned types are resolved earlier, so both1459// types are either signed or both unsigned at this point.1460unsigned LHSTyRank = GetFixedPointRank(LHSTy);1461unsigned RHSTyRank = GetFixedPointRank(RHSTy);14621463QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;14641465if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())1466ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);14671468return ResultTy;1469}14701471/// Check that the usual arithmetic conversions can be performed on this pair of1472/// expressions that might be of enumeration type.1473static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,1474SourceLocation Loc,1475Sema::ArithConvKind ACK) {1476// C++2a [expr.arith.conv]p1:1477// If one operand is of enumeration type and the other operand is of a1478// different enumeration type or a floating-point type, this behavior is1479// deprecated ([depr.arith.conv.enum]).1480//1481// Warn on this in all language modes. Produce a deprecation warning in C++20.1482// Eventually we will presumably reject these cases (in C++23 onwards?).1483QualType L = LHS->getEnumCoercedType(S.Context),1484R = RHS->getEnumCoercedType(S.Context);1485bool LEnum = L->isUnscopedEnumerationType(),1486REnum = R->isUnscopedEnumerationType();1487bool IsCompAssign = ACK == Sema::ACK_CompAssign;1488if ((!IsCompAssign && LEnum && R->isFloatingType()) ||1489(REnum && L->isFloatingType())) {1490S.Diag(Loc, S.getLangOpts().CPlusPlus261491? diag::err_arith_conv_enum_float_cxx261492: S.getLangOpts().CPlusPlus201493? diag::warn_arith_conv_enum_float_cxx201494: diag::warn_arith_conv_enum_float)1495<< LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum1496<< L << R;1497} else if (!IsCompAssign && LEnum && REnum &&1498!S.Context.hasSameUnqualifiedType(L, R)) {1499unsigned DiagID;1500// In C++ 26, usual arithmetic conversions between 2 different enum types1501// are ill-formed.1502if (S.getLangOpts().CPlusPlus26)1503DiagID = diag::err_conv_mixed_enum_types_cxx26;1504else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||1505!R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {1506// If either enumeration type is unnamed, it's less likely that the1507// user cares about this, but this situation is still deprecated in1508// C++2a. Use a different warning group.1509DiagID = S.getLangOpts().CPlusPlus201510? diag::warn_arith_conv_mixed_anon_enum_types_cxx201511: diag::warn_arith_conv_mixed_anon_enum_types;1512} else if (ACK == Sema::ACK_Conditional) {1513// Conditional expressions are separated out because they have1514// historically had a different warning flag.1515DiagID = S.getLangOpts().CPlusPlus201516? diag::warn_conditional_mixed_enum_types_cxx201517: diag::warn_conditional_mixed_enum_types;1518} else if (ACK == Sema::ACK_Comparison) {1519// Comparison expressions are separated out because they have1520// historically had a different warning flag.1521DiagID = S.getLangOpts().CPlusPlus201522? diag::warn_comparison_mixed_enum_types_cxx201523: diag::warn_comparison_mixed_enum_types;1524} else {1525DiagID = S.getLangOpts().CPlusPlus201526? diag::warn_arith_conv_mixed_enum_types_cxx201527: diag::warn_arith_conv_mixed_enum_types;1528}1529S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()1530<< (int)ACK << L << R;1531}1532}15331534/// UsualArithmeticConversions - Performs various conversions that are common to1535/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this1536/// routine returns the first non-arithmetic type found. The client is1537/// responsible for emitting appropriate error diagnostics.1538QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,1539SourceLocation Loc,1540ArithConvKind ACK) {1541checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);15421543if (ACK != ACK_CompAssign) {1544LHS = UsualUnaryConversions(LHS.get());1545if (LHS.isInvalid())1546return QualType();1547}15481549RHS = UsualUnaryConversions(RHS.get());1550if (RHS.isInvalid())1551return QualType();15521553// For conversion purposes, we ignore any qualifiers.1554// For example, "const float" and "float" are equivalent.1555QualType LHSType = LHS.get()->getType().getUnqualifiedType();1556QualType RHSType = RHS.get()->getType().getUnqualifiedType();15571558// For conversion purposes, we ignore any atomic qualifier on the LHS.1559if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())1560LHSType = AtomicLHS->getValueType();15611562// If both types are identical, no conversion is needed.1563if (Context.hasSameType(LHSType, RHSType))1564return Context.getCommonSugaredType(LHSType, RHSType);15651566// If either side is a non-arithmetic type (e.g. a pointer), we are done.1567// The caller can deal with this (e.g. pointer + int).1568if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())1569return QualType();15701571// Apply unary and bitfield promotions to the LHS's type.1572QualType LHSUnpromotedType = LHSType;1573if (Context.isPromotableIntegerType(LHSType))1574LHSType = Context.getPromotedIntegerType(LHSType);1575QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());1576if (!LHSBitfieldPromoteTy.isNull())1577LHSType = LHSBitfieldPromoteTy;1578if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)1579LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);15801581// If both types are identical, no conversion is needed.1582if (Context.hasSameType(LHSType, RHSType))1583return Context.getCommonSugaredType(LHSType, RHSType);15841585// At this point, we have two different arithmetic types.15861587// Diagnose attempts to convert between __ibm128, __float128 and long double1588// where such conversions currently can't be handled.1589if (unsupportedTypeConversion(*this, LHSType, RHSType))1590return QualType();15911592// Handle complex types first (C99 6.3.1.8p1).1593if (LHSType->isComplexType() || RHSType->isComplexType())1594return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,1595ACK == ACK_CompAssign);15961597// Now handle "real" floating types (i.e. float, double, long double).1598if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())1599return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,1600ACK == ACK_CompAssign);16011602// Handle GCC complex int extension.1603if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())1604return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,1605ACK == ACK_CompAssign);16061607if (LHSType->isFixedPointType() || RHSType->isFixedPointType())1608return handleFixedPointConversion(*this, LHSType, RHSType);16091610// Finally, we have two differing integer types.1611return handleIntegerConversion<doIntegralCast, doIntegralCast>1612(*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);1613}16141615//===----------------------------------------------------------------------===//1616// Semantic Analysis for various Expression Types1617//===----------------------------------------------------------------------===//161816191620ExprResult Sema::ActOnGenericSelectionExpr(1621SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,1622bool PredicateIsExpr, void *ControllingExprOrType,1623ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {1624unsigned NumAssocs = ArgTypes.size();1625assert(NumAssocs == ArgExprs.size());16261627TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];1628for (unsigned i = 0; i < NumAssocs; ++i) {1629if (ArgTypes[i])1630(void) GetTypeFromParser(ArgTypes[i], &Types[i]);1631else1632Types[i] = nullptr;1633}16341635// If we have a controlling type, we need to convert it from a parsed type1636// into a semantic type and then pass that along.1637if (!PredicateIsExpr) {1638TypeSourceInfo *ControllingType;1639(void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),1640&ControllingType);1641assert(ControllingType && "couldn't get the type out of the parser");1642ControllingExprOrType = ControllingType;1643}16441645ExprResult ER = CreateGenericSelectionExpr(1646KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,1647llvm::ArrayRef(Types, NumAssocs), ArgExprs);1648delete [] Types;1649return ER;1650}16511652ExprResult Sema::CreateGenericSelectionExpr(1653SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,1654bool PredicateIsExpr, void *ControllingExprOrType,1655ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {1656unsigned NumAssocs = Types.size();1657assert(NumAssocs == Exprs.size());1658assert(ControllingExprOrType &&1659"Must have either a controlling expression or a controlling type");16601661Expr *ControllingExpr = nullptr;1662TypeSourceInfo *ControllingType = nullptr;1663if (PredicateIsExpr) {1664// Decay and strip qualifiers for the controlling expression type, and1665// handle placeholder type replacement. See committee discussion from WG141666// DR423.1667EnterExpressionEvaluationContext Unevaluated(1668*this, Sema::ExpressionEvaluationContext::Unevaluated);1669ExprResult R = DefaultFunctionArrayLvalueConversion(1670reinterpret_cast<Expr *>(ControllingExprOrType));1671if (R.isInvalid())1672return ExprError();1673ControllingExpr = R.get();1674} else {1675// The extension form uses the type directly rather than converting it.1676ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);1677if (!ControllingType)1678return ExprError();1679}16801681bool TypeErrorFound = false,1682IsResultDependent = ControllingExpr1683? ControllingExpr->isTypeDependent()1684: ControllingType->getType()->isDependentType(),1685ContainsUnexpandedParameterPack =1686ControllingExpr1687? ControllingExpr->containsUnexpandedParameterPack()1688: ControllingType->getType()->containsUnexpandedParameterPack();16891690// The controlling expression is an unevaluated operand, so side effects are1691// likely unintended.1692if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&1693ControllingExpr->HasSideEffects(Context, false))1694Diag(ControllingExpr->getExprLoc(),1695diag::warn_side_effects_unevaluated_context);16961697for (unsigned i = 0; i < NumAssocs; ++i) {1698if (Exprs[i]->containsUnexpandedParameterPack())1699ContainsUnexpandedParameterPack = true;17001701if (Types[i]) {1702if (Types[i]->getType()->containsUnexpandedParameterPack())1703ContainsUnexpandedParameterPack = true;17041705if (Types[i]->getType()->isDependentType()) {1706IsResultDependent = true;1707} else {1708// We relax the restriction on use of incomplete types and non-object1709// types with the type-based extension of _Generic. Allowing incomplete1710// objects means those can be used as "tags" for a type-safe way to map1711// to a value. Similarly, matching on function types rather than1712// function pointer types can be useful. However, the restriction on VM1713// types makes sense to retain as there are open questions about how1714// the selection can be made at compile time.1715//1716// C11 6.5.1.1p2 "The type name in a generic association shall specify a1717// complete object type other than a variably modified type."1718unsigned D = 0;1719if (ControllingExpr && Types[i]->getType()->isIncompleteType())1720D = diag::err_assoc_type_incomplete;1721else if (ControllingExpr && !Types[i]->getType()->isObjectType())1722D = diag::err_assoc_type_nonobject;1723else if (Types[i]->getType()->isVariablyModifiedType())1724D = diag::err_assoc_type_variably_modified;1725else if (ControllingExpr) {1726// Because the controlling expression undergoes lvalue conversion,1727// array conversion, and function conversion, an association which is1728// of array type, function type, or is qualified can never be1729// reached. We will warn about this so users are less surprised by1730// the unreachable association. However, we don't have to handle1731// function types; that's not an object type, so it's handled above.1732//1733// The logic is somewhat different for C++ because C++ has different1734// lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,1735// If T is a non-class type, the type of the prvalue is the cv-1736// unqualified version of T. Otherwise, the type of the prvalue is T.1737// The result of these rules is that all qualified types in an1738// association in C are unreachable, and in C++, only qualified non-1739// class types are unreachable.1740//1741// NB: this does not apply when the first operand is a type rather1742// than an expression, because the type form does not undergo1743// conversion.1744unsigned Reason = 0;1745QualType QT = Types[i]->getType();1746if (QT->isArrayType())1747Reason = 1;1748else if (QT.hasQualifiers() &&1749(!LangOpts.CPlusPlus || !QT->isRecordType()))1750Reason = 2;17511752if (Reason)1753Diag(Types[i]->getTypeLoc().getBeginLoc(),1754diag::warn_unreachable_association)1755<< QT << (Reason - 1);1756}17571758if (D != 0) {1759Diag(Types[i]->getTypeLoc().getBeginLoc(), D)1760<< Types[i]->getTypeLoc().getSourceRange()1761<< Types[i]->getType();1762TypeErrorFound = true;1763}17641765// C11 6.5.1.1p2 "No two generic associations in the same generic1766// selection shall specify compatible types."1767for (unsigned j = i+1; j < NumAssocs; ++j)1768if (Types[j] && !Types[j]->getType()->isDependentType() &&1769Context.typesAreCompatible(Types[i]->getType(),1770Types[j]->getType())) {1771Diag(Types[j]->getTypeLoc().getBeginLoc(),1772diag::err_assoc_compatible_types)1773<< Types[j]->getTypeLoc().getSourceRange()1774<< Types[j]->getType()1775<< Types[i]->getType();1776Diag(Types[i]->getTypeLoc().getBeginLoc(),1777diag::note_compat_assoc)1778<< Types[i]->getTypeLoc().getSourceRange()1779<< Types[i]->getType();1780TypeErrorFound = true;1781}1782}1783}1784}1785if (TypeErrorFound)1786return ExprError();17871788// If we determined that the generic selection is result-dependent, don't1789// try to compute the result expression.1790if (IsResultDependent) {1791if (ControllingExpr)1792return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,1793Types, Exprs, DefaultLoc, RParenLoc,1794ContainsUnexpandedParameterPack);1795return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,1796Exprs, DefaultLoc, RParenLoc,1797ContainsUnexpandedParameterPack);1798}17991800SmallVector<unsigned, 1> CompatIndices;1801unsigned DefaultIndex = -1U;1802// Look at the canonical type of the controlling expression in case it was a1803// deduced type like __auto_type. However, when issuing diagnostics, use the1804// type the user wrote in source rather than the canonical one.1805for (unsigned i = 0; i < NumAssocs; ++i) {1806if (!Types[i])1807DefaultIndex = i;1808else if (ControllingExpr &&1809Context.typesAreCompatible(1810ControllingExpr->getType().getCanonicalType(),1811Types[i]->getType()))1812CompatIndices.push_back(i);1813else if (ControllingType &&1814Context.typesAreCompatible(1815ControllingType->getType().getCanonicalType(),1816Types[i]->getType()))1817CompatIndices.push_back(i);1818}18191820auto GetControllingRangeAndType = [](Expr *ControllingExpr,1821TypeSourceInfo *ControllingType) {1822// We strip parens here because the controlling expression is typically1823// parenthesized in macro definitions.1824if (ControllingExpr)1825ControllingExpr = ControllingExpr->IgnoreParens();18261827SourceRange SR = ControllingExpr1828? ControllingExpr->getSourceRange()1829: ControllingType->getTypeLoc().getSourceRange();1830QualType QT = ControllingExpr ? ControllingExpr->getType()1831: ControllingType->getType();18321833return std::make_pair(SR, QT);1834};18351836// C11 6.5.1.1p2 "The controlling expression of a generic selection shall have1837// type compatible with at most one of the types named in its generic1838// association list."1839if (CompatIndices.size() > 1) {1840auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);1841SourceRange SR = P.first;1842Diag(SR.getBegin(), diag::err_generic_sel_multi_match)1843<< SR << P.second << (unsigned)CompatIndices.size();1844for (unsigned I : CompatIndices) {1845Diag(Types[I]->getTypeLoc().getBeginLoc(),1846diag::note_compat_assoc)1847<< Types[I]->getTypeLoc().getSourceRange()1848<< Types[I]->getType();1849}1850return ExprError();1851}18521853// C11 6.5.1.1p2 "If a generic selection has no default generic association,1854// its controlling expression shall have type compatible with exactly one of1855// the types named in its generic association list."1856if (DefaultIndex == -1U && CompatIndices.size() == 0) {1857auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);1858SourceRange SR = P.first;1859Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;1860return ExprError();1861}18621863// C11 6.5.1.1p3 "If a generic selection has a generic association with a1864// type name that is compatible with the type of the controlling expression,1865// then the result expression of the generic selection is the expression1866// in that generic association. Otherwise, the result expression of the1867// generic selection is the expression in the default generic association."1868unsigned ResultIndex =1869CompatIndices.size() ? CompatIndices[0] : DefaultIndex;18701871if (ControllingExpr) {1872return GenericSelectionExpr::Create(1873Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,1874ContainsUnexpandedParameterPack, ResultIndex);1875}1876return GenericSelectionExpr::Create(1877Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,1878ContainsUnexpandedParameterPack, ResultIndex);1879}18801881static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {1882switch (Kind) {1883default:1884llvm_unreachable("unexpected TokenKind");1885case tok::kw___func__:1886return PredefinedIdentKind::Func; // [C99 6.4.2.2]1887case tok::kw___FUNCTION__:1888return PredefinedIdentKind::Function;1889case tok::kw___FUNCDNAME__:1890return PredefinedIdentKind::FuncDName; // [MS]1891case tok::kw___FUNCSIG__:1892return PredefinedIdentKind::FuncSig; // [MS]1893case tok::kw_L__FUNCTION__:1894return PredefinedIdentKind::LFunction; // [MS]1895case tok::kw_L__FUNCSIG__:1896return PredefinedIdentKind::LFuncSig; // [MS]1897case tok::kw___PRETTY_FUNCTION__:1898return PredefinedIdentKind::PrettyFunction; // [GNU]1899}1900}19011902/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used1903/// to determine the value of a PredefinedExpr. This can be either a1904/// block, lambda, captured statement, function, otherwise a nullptr.1905static Decl *getPredefinedExprDecl(DeclContext *DC) {1906while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))1907DC = DC->getParent();1908return cast_or_null<Decl>(DC);1909}19101911/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the1912/// location of the token and the offset of the ud-suffix within it.1913static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,1914unsigned Offset) {1915return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),1916S.getLangOpts());1917}19181919/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up1920/// the corresponding cooked (non-raw) literal operator, and build a call to it.1921static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,1922IdentifierInfo *UDSuffix,1923SourceLocation UDSuffixLoc,1924ArrayRef<Expr*> Args,1925SourceLocation LitEndLoc) {1926assert(Args.size() <= 2 && "too many arguments for literal operator");19271928QualType ArgTy[2];1929for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {1930ArgTy[ArgIdx] = Args[ArgIdx]->getType();1931if (ArgTy[ArgIdx]->isArrayType())1932ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);1933}19341935DeclarationName OpName =1936S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);1937DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);1938OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);19391940LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);1941if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),1942/*AllowRaw*/ false, /*AllowTemplate*/ false,1943/*AllowStringTemplatePack*/ false,1944/*DiagnoseMissing*/ true) == Sema::LOLR_Error)1945return ExprError();19461947return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);1948}19491950ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {1951// StringToks needs backing storage as it doesn't hold array elements itself1952std::vector<Token> ExpandedToks;1953if (getLangOpts().MicrosoftExt)1954StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);19551956StringLiteralParser Literal(StringToks, PP,1957StringLiteralEvalMethod::Unevaluated);1958if (Literal.hadError)1959return ExprError();19601961SmallVector<SourceLocation, 4> StringTokLocs;1962for (const Token &Tok : StringToks)1963StringTokLocs.push_back(Tok.getLocation());19641965StringLiteral *Lit = StringLiteral::Create(1966Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},1967&StringTokLocs[0], StringTokLocs.size());19681969if (!Literal.getUDSuffix().empty()) {1970SourceLocation UDSuffixLoc =1971getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],1972Literal.getUDSuffixOffset());1973return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));1974}19751976return Lit;1977}19781979std::vector<Token>1980Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {1981// MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function1982// local macros that expand to string literals that may be concatenated.1983// These macros are expanded here (in Sema), because StringLiteralParser1984// (in Lex) doesn't know the enclosing function (because it hasn't been1985// parsed yet).1986assert(getLangOpts().MicrosoftExt);19871988// Note: Although function local macros are defined only inside functions,1989// we ensure a valid `CurrentDecl` even outside of a function. This allows1990// expansion of macros into empty string literals without additional checks.1991Decl *CurrentDecl = getPredefinedExprDecl(CurContext);1992if (!CurrentDecl)1993CurrentDecl = Context.getTranslationUnitDecl();19941995std::vector<Token> ExpandedToks;1996ExpandedToks.reserve(Toks.size());1997for (const Token &Tok : Toks) {1998if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {1999assert(tok::isStringLiteral(Tok.getKind()));2000ExpandedToks.emplace_back(Tok);2001continue;2002}2003if (isa<TranslationUnitDecl>(CurrentDecl))2004Diag(Tok.getLocation(), diag::ext_predef_outside_function);2005// Stringify predefined expression2006Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)2007<< Tok.getKind();2008SmallString<64> Str;2009llvm::raw_svector_ostream OS(Str);2010Token &Exp = ExpandedToks.emplace_back();2011Exp.startToken();2012if (Tok.getKind() == tok::kw_L__FUNCTION__ ||2013Tok.getKind() == tok::kw_L__FUNCSIG__) {2014OS << 'L';2015Exp.setKind(tok::wide_string_literal);2016} else {2017Exp.setKind(tok::string_literal);2018}2019OS << '"'2020<< Lexer::Stringify(PredefinedExpr::ComputeName(2021getPredefinedExprKind(Tok.getKind()), CurrentDecl))2022<< '"';2023PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());2024}2025return ExpandedToks;2026}20272028ExprResult2029Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {2030assert(!StringToks.empty() && "Must have at least one string!");20312032// StringToks needs backing storage as it doesn't hold array elements itself2033std::vector<Token> ExpandedToks;2034if (getLangOpts().MicrosoftExt)2035StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);20362037StringLiteralParser Literal(StringToks, PP);2038if (Literal.hadError)2039return ExprError();20402041SmallVector<SourceLocation, 4> StringTokLocs;2042for (const Token &Tok : StringToks)2043StringTokLocs.push_back(Tok.getLocation());20442045QualType CharTy = Context.CharTy;2046StringLiteralKind Kind = StringLiteralKind::Ordinary;2047if (Literal.isWide()) {2048CharTy = Context.getWideCharType();2049Kind = StringLiteralKind::Wide;2050} else if (Literal.isUTF8()) {2051if (getLangOpts().Char8)2052CharTy = Context.Char8Ty;2053else if (getLangOpts().C23)2054CharTy = Context.UnsignedCharTy;2055Kind = StringLiteralKind::UTF8;2056} else if (Literal.isUTF16()) {2057CharTy = Context.Char16Ty;2058Kind = StringLiteralKind::UTF16;2059} else if (Literal.isUTF32()) {2060CharTy = Context.Char32Ty;2061Kind = StringLiteralKind::UTF32;2062} else if (Literal.isPascal()) {2063CharTy = Context.UnsignedCharTy;2064}20652066// Warn on u8 string literals before C++20 and C23, whose type2067// was an array of char before but becomes an array of char8_t.2068// In C++20, it cannot be used where a pointer to char is expected.2069// In C23, it might have an unexpected value if char was signed.2070if (Kind == StringLiteralKind::UTF8 &&2071(getLangOpts().CPlusPlus2072? !getLangOpts().CPlusPlus20 && !getLangOpts().Char82073: !getLangOpts().C23)) {2074Diag(StringTokLocs.front(), getLangOpts().CPlusPlus2075? diag::warn_cxx20_compat_utf8_string2076: diag::warn_c23_compat_utf8_string);20772078// Create removals for all 'u8' prefixes in the string literal(s). This2079// ensures C++20/C23 compatibility (but may change the program behavior when2080// built by non-Clang compilers for which the execution character set is2081// not always UTF-8).2082auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);2083SourceLocation RemovalDiagLoc;2084for (const Token &Tok : StringToks) {2085if (Tok.getKind() == tok::utf8_string_literal) {2086if (RemovalDiagLoc.isInvalid())2087RemovalDiagLoc = Tok.getLocation();2088RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(2089Tok.getLocation(),2090Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,2091getSourceManager(), getLangOpts())));2092}2093}2094Diag(RemovalDiagLoc, RemovalDiag);2095}20962097QualType StrTy =2098Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());20992100// Pass &StringTokLocs[0], StringTokLocs.size() to factory!2101StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),2102Kind, Literal.Pascal, StrTy,2103&StringTokLocs[0],2104StringTokLocs.size());2105if (Literal.getUDSuffix().empty())2106return Lit;21072108// We're building a user-defined literal.2109IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());2110SourceLocation UDSuffixLoc =2111getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],2112Literal.getUDSuffixOffset());21132114// Make sure we're allowed user-defined literals here.2115if (!UDLScope)2116return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));21172118// C++11 [lex.ext]p5: The literal L is treated as a call of the form2119// operator "" X (str, len)2120QualType SizeType = Context.getSizeType();21212122DeclarationName OpName =2123Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);2124DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);2125OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);21262127QualType ArgTy[] = {2128Context.getArrayDecayedType(StrTy), SizeType2129};21302131LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);2132switch (LookupLiteralOperator(UDLScope, R, ArgTy,2133/*AllowRaw*/ false, /*AllowTemplate*/ true,2134/*AllowStringTemplatePack*/ true,2135/*DiagnoseMissing*/ true, Lit)) {21362137case LOLR_Cooked: {2138llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());2139IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,2140StringTokLocs[0]);2141Expr *Args[] = { Lit, LenArg };21422143return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());2144}21452146case LOLR_Template: {2147TemplateArgumentListInfo ExplicitArgs;2148TemplateArgument Arg(Lit);2149TemplateArgumentLocInfo ArgInfo(Lit);2150ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));2151return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,2152StringTokLocs.back(), &ExplicitArgs);2153}21542155case LOLR_StringTemplatePack: {2156TemplateArgumentListInfo ExplicitArgs;21572158unsigned CharBits = Context.getIntWidth(CharTy);2159bool CharIsUnsigned = CharTy->isUnsignedIntegerType();2160llvm::APSInt Value(CharBits, CharIsUnsigned);21612162TemplateArgument TypeArg(CharTy);2163TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));2164ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));21652166for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {2167Value = Lit->getCodeUnit(I);2168TemplateArgument Arg(Context, Value, CharTy);2169TemplateArgumentLocInfo ArgInfo;2170ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));2171}2172return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,2173StringTokLocs.back(), &ExplicitArgs);2174}2175case LOLR_Raw:2176case LOLR_ErrorNoDiagnostic:2177llvm_unreachable("unexpected literal operator lookup result");2178case LOLR_Error:2179return ExprError();2180}2181llvm_unreachable("unexpected literal operator lookup result");2182}21832184DeclRefExpr *2185Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,2186SourceLocation Loc,2187const CXXScopeSpec *SS) {2188DeclarationNameInfo NameInfo(D->getDeclName(), Loc);2189return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);2190}21912192DeclRefExpr *2193Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,2194const DeclarationNameInfo &NameInfo,2195const CXXScopeSpec *SS, NamedDecl *FoundD,2196SourceLocation TemplateKWLoc,2197const TemplateArgumentListInfo *TemplateArgs) {2198NestedNameSpecifierLoc NNS =2199SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();2200return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,2201TemplateArgs);2202}22032204// CUDA/HIP: Check whether a captured reference variable is referencing a2205// host variable in a device or host device lambda.2206static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,2207VarDecl *VD) {2208if (!S.getLangOpts().CUDA || !VD->hasInit())2209return false;2210assert(VD->getType()->isReferenceType());22112212// Check whether the reference variable is referencing a host variable.2213auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());2214if (!DRE)2215return false;2216auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());2217if (!Referee || !Referee->hasGlobalStorage() ||2218Referee->hasAttr<CUDADeviceAttr>())2219return false;22202221// Check whether the current function is a device or host device lambda.2222// Check whether the reference variable is a capture by getDeclContext()2223// since refersToEnclosingVariableOrCapture() is not ready at this point.2224auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);2225if (MD && MD->getParent()->isLambda() &&2226MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&2227VD->getDeclContext() != MD)2228return true;22292230return false;2231}22322233NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {2234// A declaration named in an unevaluated operand never constitutes an odr-use.2235if (isUnevaluatedContext())2236return NOUR_Unevaluated;22372238// C++2a [basic.def.odr]p4:2239// A variable x whose name appears as a potentially-evaluated expression e2240// is odr-used by e unless [...] x is a reference that is usable in2241// constant expressions.2242// CUDA/HIP:2243// If a reference variable referencing a host variable is captured in a2244// device or host device lambda, the value of the referee must be copied2245// to the capture and the reference variable must be treated as odr-use2246// since the value of the referee is not known at compile time and must2247// be loaded from the captured.2248if (VarDecl *VD = dyn_cast<VarDecl>(D)) {2249if (VD->getType()->isReferenceType() &&2250!(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&2251!isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&2252VD->isUsableInConstantExpressions(Context))2253return NOUR_Constant;2254}22552256// All remaining non-variable cases constitute an odr-use. For variables, we2257// need to wait and see how the expression is used.2258return NOUR_None;2259}22602261DeclRefExpr *2262Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,2263const DeclarationNameInfo &NameInfo,2264NestedNameSpecifierLoc NNS, NamedDecl *FoundD,2265SourceLocation TemplateKWLoc,2266const TemplateArgumentListInfo *TemplateArgs) {2267bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&2268NeedToCaptureVariable(D, NameInfo.getLoc());22692270DeclRefExpr *E = DeclRefExpr::Create(2271Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,2272VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));2273MarkDeclRefReferenced(E);22742275// C++ [except.spec]p17:2276// An exception-specification is considered to be needed when:2277// - in an expression, the function is the unique lookup result or2278// the selected member of a set of overloaded functions.2279//2280// We delay doing this until after we've built the function reference and2281// marked it as used so that:2282// a) if the function is defaulted, we get errors from defining it before /2283// instead of errors from computing its exception specification, and2284// b) if the function is a defaulted comparison, we can use the body we2285// build when defining it as input to the exception specification2286// computation rather than computing a new body.2287if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {2288if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {2289if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))2290E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));2291}2292}22932294if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&2295Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&2296!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))2297getCurFunction()->recordUseOfWeak(E);22982299const auto *FD = dyn_cast<FieldDecl>(D);2300if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))2301FD = IFD->getAnonField();2302if (FD) {2303UnusedPrivateFields.remove(FD);2304// Just in case we're building an illegal pointer-to-member.2305if (FD->isBitField())2306E->setObjectKind(OK_BitField);2307}23082309// C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier2310// designates a bit-field.2311if (const auto *BD = dyn_cast<BindingDecl>(D))2312if (const auto *BE = BD->getBinding())2313E->setObjectKind(BE->getObjectKind());23142315return E;2316}23172318void2319Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,2320TemplateArgumentListInfo &Buffer,2321DeclarationNameInfo &NameInfo,2322const TemplateArgumentListInfo *&TemplateArgs) {2323if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {2324Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);2325Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);23262327ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),2328Id.TemplateId->NumArgs);2329translateTemplateArguments(TemplateArgsPtr, Buffer);23302331TemplateName TName = Id.TemplateId->Template.get();2332SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;2333NameInfo = Context.getNameForTemplate(TName, TNameLoc);2334TemplateArgs = &Buffer;2335} else {2336NameInfo = GetNameFromUnqualifiedId(Id);2337TemplateArgs = nullptr;2338}2339}23402341static void emitEmptyLookupTypoDiagnostic(2342const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,2343DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,2344unsigned DiagnosticID, unsigned DiagnosticSuggestID) {2345DeclContext *Ctx =2346SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);2347if (!TC) {2348// Emit a special diagnostic for failed member lookups.2349// FIXME: computing the declaration context might fail here (?)2350if (Ctx)2351SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx2352<< SS.getRange();2353else2354SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;2355return;2356}23572358std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());2359bool DroppedSpecifier =2360TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;2361unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()2362? diag::note_implicit_param_decl2363: diag::note_previous_decl;2364if (!Ctx)2365SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,2366SemaRef.PDiag(NoteID));2367else2368SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)2369<< Typo << Ctx << DroppedSpecifier2370<< SS.getRange(),2371SemaRef.PDiag(NoteID));2372}23732374bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {2375// During a default argument instantiation the CurContext points2376// to a CXXMethodDecl; but we can't apply a this-> fixit inside a2377// function parameter list, hence add an explicit check.2378bool isDefaultArgument =2379!CodeSynthesisContexts.empty() &&2380CodeSynthesisContexts.back().Kind ==2381CodeSynthesisContext::DefaultFunctionArgumentInstantiation;2382const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);2383bool isInstance = CurMethod && CurMethod->isInstance() &&2384R.getNamingClass() == CurMethod->getParent() &&2385!isDefaultArgument;23862387// There are two ways we can find a class-scope declaration during template2388// instantiation that we did not find in the template definition: if it is a2389// member of a dependent base class, or if it is declared after the point of2390// use in the same class. Distinguish these by comparing the class in which2391// the member was found to the naming class of the lookup.2392unsigned DiagID = diag::err_found_in_dependent_base;2393unsigned NoteID = diag::note_member_declared_at;2394if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {2395DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class2396: diag::err_found_later_in_class;2397} else if (getLangOpts().MSVCCompat) {2398DiagID = diag::ext_found_in_dependent_base;2399NoteID = diag::note_dependent_member_use;2400}24012402if (isInstance) {2403// Give a code modification hint to insert 'this->'.2404Diag(R.getNameLoc(), DiagID)2405<< R.getLookupName()2406<< FixItHint::CreateInsertion(R.getNameLoc(), "this->");2407CheckCXXThisCapture(R.getNameLoc());2408} else {2409// FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming2410// they're not shadowed).2411Diag(R.getNameLoc(), DiagID) << R.getLookupName();2412}24132414for (const NamedDecl *D : R)2415Diag(D->getLocation(), NoteID);24162417// Return true if we are inside a default argument instantiation2418// and the found name refers to an instance member function, otherwise2419// the caller will try to create an implicit member call and this is wrong2420// for default arguments.2421//2422// FIXME: Is this special case necessary? We could allow the caller to2423// diagnose this.2424if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {2425Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;2426return true;2427}24282429// Tell the callee to try to recover.2430return false;2431}24322433bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,2434CorrectionCandidateCallback &CCC,2435TemplateArgumentListInfo *ExplicitTemplateArgs,2436ArrayRef<Expr *> Args, DeclContext *LookupCtx,2437TypoExpr **Out) {2438DeclarationName Name = R.getLookupName();24392440unsigned diagnostic = diag::err_undeclared_var_use;2441unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;2442if (Name.getNameKind() == DeclarationName::CXXOperatorName ||2443Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||2444Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {2445diagnostic = diag::err_undeclared_use;2446diagnostic_suggest = diag::err_undeclared_use_suggest;2447}24482449// If the original lookup was an unqualified lookup, fake an2450// unqualified lookup. This is useful when (for example) the2451// original lookup would not have found something because it was a2452// dependent name.2453DeclContext *DC =2454LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);2455while (DC) {2456if (isa<CXXRecordDecl>(DC)) {2457LookupQualifiedName(R, DC);24582459if (!R.empty()) {2460// Don't give errors about ambiguities in this lookup.2461R.suppressDiagnostics();24622463// If there's a best viable function among the results, only mention2464// that one in the notes.2465OverloadCandidateSet Candidates(R.getNameLoc(),2466OverloadCandidateSet::CSK_Normal);2467AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);2468OverloadCandidateSet::iterator Best;2469if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==2470OR_Success) {2471R.clear();2472R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());2473R.resolveKind();2474}24752476return DiagnoseDependentMemberLookup(R);2477}24782479R.clear();2480}24812482DC = DC->getLookupParent();2483}24842485// We didn't find anything, so try to correct for a typo.2486TypoCorrection Corrected;2487if (S && Out) {2488SourceLocation TypoLoc = R.getNameLoc();2489assert(!ExplicitTemplateArgs &&2490"Diagnosing an empty lookup with explicit template args!");2491*Out = CorrectTypoDelayed(2492R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,2493[=](const TypoCorrection &TC) {2494emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,2495diagnostic, diagnostic_suggest);2496},2497nullptr, CTK_ErrorRecovery, LookupCtx);2498if (*Out)2499return true;2500} else if (S && (Corrected =2501CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,2502&SS, CCC, CTK_ErrorRecovery, LookupCtx))) {2503std::string CorrectedStr(Corrected.getAsString(getLangOpts()));2504bool DroppedSpecifier =2505Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;2506R.setLookupName(Corrected.getCorrection());25072508bool AcceptableWithRecovery = false;2509bool AcceptableWithoutRecovery = false;2510NamedDecl *ND = Corrected.getFoundDecl();2511if (ND) {2512if (Corrected.isOverloaded()) {2513OverloadCandidateSet OCS(R.getNameLoc(),2514OverloadCandidateSet::CSK_Normal);2515OverloadCandidateSet::iterator Best;2516for (NamedDecl *CD : Corrected) {2517if (FunctionTemplateDecl *FTD =2518dyn_cast<FunctionTemplateDecl>(CD))2519AddTemplateOverloadCandidate(2520FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,2521Args, OCS);2522else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))2523if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)2524AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),2525Args, OCS);2526}2527switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {2528case OR_Success:2529ND = Best->FoundDecl;2530Corrected.setCorrectionDecl(ND);2531break;2532default:2533// FIXME: Arbitrarily pick the first declaration for the note.2534Corrected.setCorrectionDecl(ND);2535break;2536}2537}2538R.addDecl(ND);2539if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {2540CXXRecordDecl *Record = nullptr;2541if (Corrected.getCorrectionSpecifier()) {2542const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();2543Record = Ty->getAsCXXRecordDecl();2544}2545if (!Record)2546Record = cast<CXXRecordDecl>(2547ND->getDeclContext()->getRedeclContext());2548R.setNamingClass(Record);2549}25502551auto *UnderlyingND = ND->getUnderlyingDecl();2552AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||2553isa<FunctionTemplateDecl>(UnderlyingND);2554// FIXME: If we ended up with a typo for a type name or2555// Objective-C class name, we're in trouble because the parser2556// is in the wrong place to recover. Suggest the typo2557// correction, but don't make it a fix-it since we're not going2558// to recover well anyway.2559AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||2560getAsTypeTemplateDecl(UnderlyingND) ||2561isa<ObjCInterfaceDecl>(UnderlyingND);2562} else {2563// FIXME: We found a keyword. Suggest it, but don't provide a fix-it2564// because we aren't able to recover.2565AcceptableWithoutRecovery = true;2566}25672568if (AcceptableWithRecovery || AcceptableWithoutRecovery) {2569unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()2570? diag::note_implicit_param_decl2571: diag::note_previous_decl;2572if (SS.isEmpty())2573diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,2574PDiag(NoteID), AcceptableWithRecovery);2575else2576diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)2577<< Name << computeDeclContext(SS, false)2578<< DroppedSpecifier << SS.getRange(),2579PDiag(NoteID), AcceptableWithRecovery);25802581// Tell the callee whether to try to recover.2582return !AcceptableWithRecovery;2583}2584}2585R.clear();25862587// Emit a special diagnostic for failed member lookups.2588// FIXME: computing the declaration context might fail here (?)2589if (!SS.isEmpty()) {2590Diag(R.getNameLoc(), diag::err_no_member)2591<< Name << computeDeclContext(SS, false)2592<< SS.getRange();2593return true;2594}25952596// Give up, we can't recover.2597Diag(R.getNameLoc(), diagnostic) << Name;2598return true;2599}26002601/// In Microsoft mode, if we are inside a template class whose parent class has2602/// dependent base classes, and we can't resolve an unqualified identifier, then2603/// assume the identifier is a member of a dependent base class. We can only2604/// recover successfully in static methods, instance methods, and other contexts2605/// where 'this' is available. This doesn't precisely match MSVC's2606/// instantiation model, but it's close enough.2607static Expr *2608recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,2609DeclarationNameInfo &NameInfo,2610SourceLocation TemplateKWLoc,2611const TemplateArgumentListInfo *TemplateArgs) {2612// Only try to recover from lookup into dependent bases in static methods or2613// contexts where 'this' is available.2614QualType ThisType = S.getCurrentThisType();2615const CXXRecordDecl *RD = nullptr;2616if (!ThisType.isNull())2617RD = ThisType->getPointeeType()->getAsCXXRecordDecl();2618else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))2619RD = MD->getParent();2620if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())2621return nullptr;26222623// Diagnose this as unqualified lookup into a dependent base class. If 'this'2624// is available, suggest inserting 'this->' as a fixit.2625SourceLocation Loc = NameInfo.getLoc();2626auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);2627DB << NameInfo.getName() << RD;26282629if (!ThisType.isNull()) {2630DB << FixItHint::CreateInsertion(Loc, "this->");2631return CXXDependentScopeMemberExpr::Create(2632Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,2633/*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,2634/*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);2635}26362637// Synthesize a fake NNS that points to the derived class. This will2638// perform name lookup during template instantiation.2639CXXScopeSpec SS;2640auto *NNS =2641NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());2642SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));2643return DependentScopeDeclRefExpr::Create(2644Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,2645TemplateArgs);2646}26472648ExprResult2649Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,2650SourceLocation TemplateKWLoc, UnqualifiedId &Id,2651bool HasTrailingLParen, bool IsAddressOfOperand,2652CorrectionCandidateCallback *CCC,2653bool IsInlineAsmIdentifier, Token *KeywordReplacement) {2654assert(!(IsAddressOfOperand && HasTrailingLParen) &&2655"cannot be direct & operand and have a trailing lparen");2656if (SS.isInvalid())2657return ExprError();26582659TemplateArgumentListInfo TemplateArgsBuffer;26602661// Decompose the UnqualifiedId into the following data.2662DeclarationNameInfo NameInfo;2663const TemplateArgumentListInfo *TemplateArgs;2664DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);26652666DeclarationName Name = NameInfo.getName();2667IdentifierInfo *II = Name.getAsIdentifierInfo();2668SourceLocation NameLoc = NameInfo.getLoc();26692670if (II && II->isEditorPlaceholder()) {2671// FIXME: When typed placeholders are supported we can create a typed2672// placeholder expression node.2673return ExprError();2674}26752676// This specially handles arguments of attributes appertains to a type of C2677// struct field such that the name lookup within a struct finds the member2678// name, which is not the case for other contexts in C.2679if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {2680// See if this is reference to a field of struct.2681LookupResult R(*this, NameInfo, LookupMemberName);2682// LookupName handles a name lookup from within anonymous struct.2683if (LookupName(R, S)) {2684if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {2685QualType type = VD->getType().getNonReferenceType();2686// This will eventually be translated into MemberExpr upon2687// the use of instantiated struct fields.2688return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);2689}2690}2691}26922693// Perform the required lookup.2694LookupResult R(*this, NameInfo,2695(Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)2696? LookupObjCImplicitSelfParam2697: LookupOrdinaryName);2698if (TemplateKWLoc.isValid() || TemplateArgs) {2699// Lookup the template name again to correctly establish the context in2700// which it was found. This is really unfortunate as we already did the2701// lookup to determine that it was a template name in the first place. If2702// this becomes a performance hit, we can work harder to preserve those2703// results until we get here but it's likely not worth it.2704AssumedTemplateKind AssumedTemplate;2705if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),2706/*EnteringContext=*/false, TemplateKWLoc,2707&AssumedTemplate))2708return ExprError();27092710if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())2711return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,2712IsAddressOfOperand, TemplateArgs);2713} else {2714bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();2715LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),2716/*AllowBuiltinCreation=*/!IvarLookupFollowUp);27172718// If the result might be in a dependent base class, this is a dependent2719// id-expression.2720if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())2721return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,2722IsAddressOfOperand, TemplateArgs);27232724// If this reference is in an Objective-C method, then we need to do2725// some special Objective-C lookup, too.2726if (IvarLookupFollowUp) {2727ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));2728if (E.isInvalid())2729return ExprError();27302731if (Expr *Ex = E.getAs<Expr>())2732return Ex;2733}2734}27352736if (R.isAmbiguous())2737return ExprError();27382739// This could be an implicitly declared function reference if the language2740// mode allows it as a feature.2741if (R.empty() && HasTrailingLParen && II &&2742getLangOpts().implicitFunctionsAllowed()) {2743NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);2744if (D) R.addDecl(D);2745}27462747// Determine whether this name might be a candidate for2748// argument-dependent lookup.2749bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);27502751if (R.empty() && !ADL) {2752if (SS.isEmpty() && getLangOpts().MSVCCompat) {2753if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,2754TemplateKWLoc, TemplateArgs))2755return E;2756}27572758// Don't diagnose an empty lookup for inline assembly.2759if (IsInlineAsmIdentifier)2760return ExprError();27612762// If this name wasn't predeclared and if this is not a function2763// call, diagnose the problem.2764TypoExpr *TE = nullptr;2765DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()2766: nullptr);2767DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;2768assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&2769"Typo correction callback misconfigured");2770if (CCC) {2771// Make sure the callback knows what the typo being diagnosed is.2772CCC->setTypoName(II);2773if (SS.isValid())2774CCC->setTypoNNS(SS.getScopeRep());2775}2776// FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for2777// a template name, but we happen to have always already looked up the name2778// before we get here if it must be a template name.2779if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,2780std::nullopt, nullptr, &TE)) {2781if (TE && KeywordReplacement) {2782auto &State = getTypoExprState(TE);2783auto BestTC = State.Consumer->getNextCorrection();2784if (BestTC.isKeyword()) {2785auto *II = BestTC.getCorrectionAsIdentifierInfo();2786if (State.DiagHandler)2787State.DiagHandler(BestTC);2788KeywordReplacement->startToken();2789KeywordReplacement->setKind(II->getTokenID());2790KeywordReplacement->setIdentifierInfo(II);2791KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());2792// Clean up the state associated with the TypoExpr, since it has2793// now been diagnosed (without a call to CorrectDelayedTyposInExpr).2794clearDelayedTypo(TE);2795// Signal that a correction to a keyword was performed by returning a2796// valid-but-null ExprResult.2797return (Expr*)nullptr;2798}2799State.Consumer->resetCorrectionStream();2800}2801return TE ? TE : ExprError();2802}28032804assert(!R.empty() &&2805"DiagnoseEmptyLookup returned false but added no results");28062807// If we found an Objective-C instance variable, let2808// LookupInObjCMethod build the appropriate expression to2809// reference the ivar.2810if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {2811R.clear();2812ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));2813// In a hopelessly buggy code, Objective-C instance variable2814// lookup fails and no expression will be built to reference it.2815if (!E.isInvalid() && !E.get())2816return ExprError();2817return E;2818}2819}28202821// This is guaranteed from this point on.2822assert(!R.empty() || ADL);28232824// Check whether this might be a C++ implicit instance member access.2825// C++ [class.mfct.non-static]p3:2826// When an id-expression that is not part of a class member access2827// syntax and not used to form a pointer to member is used in the2828// body of a non-static member function of class X, if name lookup2829// resolves the name in the id-expression to a non-static non-type2830// member of some class C, the id-expression is transformed into a2831// class member access expression using (*this) as the2832// postfix-expression to the left of the . operator.2833//2834// But we don't actually need to do this for '&' operands if R2835// resolved to a function or overloaded function set, because the2836// expression is ill-formed if it actually works out to be a2837// non-static member function:2838//2839// C++ [expr.ref]p4:2840// Otherwise, if E1.E2 refers to a non-static member function. . .2841// [t]he expression can be used only as the left-hand operand of a2842// member function call.2843//2844// There are other safeguards against such uses, but it's important2845// to get this right here so that we don't end up making a2846// spuriously dependent expression if we're inside a dependent2847// instance method.2848if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))2849return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,2850S);28512852if (TemplateArgs || TemplateKWLoc.isValid()) {28532854// In C++1y, if this is a variable template id, then check it2855// in BuildTemplateIdExpr().2856// The single lookup result must be a variable template declaration.2857if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&2858Id.TemplateId->Kind == TNK_Var_template) {2859assert(R.getAsSingle<VarTemplateDecl>() &&2860"There should only be one declaration found.");2861}28622863return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);2864}28652866return BuildDeclarationNameExpr(SS, R, ADL);2867}28682869ExprResult Sema::BuildQualifiedDeclarationNameExpr(2870CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,2871bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {2872LookupResult R(*this, NameInfo, LookupOrdinaryName);2873LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());28742875if (R.isAmbiguous())2876return ExprError();28772878if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())2879return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),2880NameInfo, /*TemplateArgs=*/nullptr);28812882if (R.empty()) {2883// Don't diagnose problems with invalid record decl, the secondary no_member2884// diagnostic during template instantiation is likely bogus, e.g. if a class2885// is invalid because it's derived from an invalid base class, then missing2886// members were likely supposed to be inherited.2887DeclContext *DC = computeDeclContext(SS);2888if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))2889if (CD->isInvalidDecl())2890return ExprError();2891Diag(NameInfo.getLoc(), diag::err_no_member)2892<< NameInfo.getName() << DC << SS.getRange();2893return ExprError();2894}28952896if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {2897// Diagnose a missing typename if this resolved unambiguously to a type in2898// a dependent context. If we can recover with a type, downgrade this to2899// a warning in Microsoft compatibility mode.2900unsigned DiagID = diag::err_typename_missing;2901if (RecoveryTSI && getLangOpts().MSVCCompat)2902DiagID = diag::ext_typename_missing;2903SourceLocation Loc = SS.getBeginLoc();2904auto D = Diag(Loc, DiagID);2905D << SS.getScopeRep() << NameInfo.getName().getAsString()2906<< SourceRange(Loc, NameInfo.getEndLoc());29072908// Don't recover if the caller isn't expecting us to or if we're in a SFINAE2909// context.2910if (!RecoveryTSI)2911return ExprError();29122913// Only issue the fixit if we're prepared to recover.2914D << FixItHint::CreateInsertion(Loc, "typename ");29152916// Recover by pretending this was an elaborated type.2917QualType Ty = Context.getTypeDeclType(TD);2918TypeLocBuilder TLB;2919TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());29202921QualType ET = getElaboratedType(ElaboratedTypeKeyword::None, SS, Ty);2922ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);2923QTL.setElaboratedKeywordLoc(SourceLocation());2924QTL.setQualifierLoc(SS.getWithLocInContext(Context));29252926*RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);29272928return ExprEmpty();2929}29302931// If necessary, build an implicit class member access.2932if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))2933return BuildPossibleImplicitMemberExpr(SS,2934/*TemplateKWLoc=*/SourceLocation(),2935R, /*TemplateArgs=*/nullptr,2936/*S=*/nullptr);29372938return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);2939}29402941ExprResult2942Sema::PerformObjectMemberConversion(Expr *From,2943NestedNameSpecifier *Qualifier,2944NamedDecl *FoundDecl,2945NamedDecl *Member) {2946const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());2947if (!RD)2948return From;29492950QualType DestRecordType;2951QualType DestType;2952QualType FromRecordType;2953QualType FromType = From->getType();2954bool PointerConversions = false;2955if (isa<FieldDecl>(Member)) {2956DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));2957auto FromPtrType = FromType->getAs<PointerType>();2958DestRecordType = Context.getAddrSpaceQualType(2959DestRecordType, FromPtrType2960? FromType->getPointeeType().getAddressSpace()2961: FromType.getAddressSpace());29622963if (FromPtrType) {2964DestType = Context.getPointerType(DestRecordType);2965FromRecordType = FromPtrType->getPointeeType();2966PointerConversions = true;2967} else {2968DestType = DestRecordType;2969FromRecordType = FromType;2970}2971} else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {2972if (!Method->isImplicitObjectMemberFunction())2973return From;29742975DestType = Method->getThisType().getNonReferenceType();2976DestRecordType = Method->getFunctionObjectParameterType();29772978if (FromType->getAs<PointerType>()) {2979FromRecordType = FromType->getPointeeType();2980PointerConversions = true;2981} else {2982FromRecordType = FromType;2983DestType = DestRecordType;2984}29852986LangAS FromAS = FromRecordType.getAddressSpace();2987LangAS DestAS = DestRecordType.getAddressSpace();2988if (FromAS != DestAS) {2989QualType FromRecordTypeWithoutAS =2990Context.removeAddrSpaceQualType(FromRecordType);2991QualType FromTypeWithDestAS =2992Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);2993if (PointerConversions)2994FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);2995From = ImpCastExprToType(From, FromTypeWithDestAS,2996CK_AddressSpaceConversion, From->getValueKind())2997.get();2998}2999} else {3000// No conversion necessary.3001return From;3002}30033004if (DestType->isDependentType() || FromType->isDependentType())3005return From;30063007// If the unqualified types are the same, no conversion is necessary.3008if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))3009return From;30103011SourceRange FromRange = From->getSourceRange();3012SourceLocation FromLoc = FromRange.getBegin();30133014ExprValueKind VK = From->getValueKind();30153016// C++ [class.member.lookup]p8:3017// [...] Ambiguities can often be resolved by qualifying a name with its3018// class name.3019//3020// If the member was a qualified name and the qualified referred to a3021// specific base subobject type, we'll cast to that intermediate type3022// first and then to the object in which the member is declared. That allows3023// one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:3024//3025// class Base { public: int x; };3026// class Derived1 : public Base { };3027// class Derived2 : public Base { };3028// class VeryDerived : public Derived1, public Derived2 { void f(); };3029//3030// void VeryDerived::f() {3031// x = 17; // error: ambiguous base subobjects3032// Derived1::x = 17; // okay, pick the Base subobject of Derived13033// }3034if (Qualifier && Qualifier->getAsType()) {3035QualType QType = QualType(Qualifier->getAsType(), 0);3036assert(QType->isRecordType() && "lookup done with non-record type");30373038QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);30393040// In C++98, the qualifier type doesn't actually have to be a base3041// type of the object type, in which case we just ignore it.3042// Otherwise build the appropriate casts.3043if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {3044CXXCastPath BasePath;3045if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,3046FromLoc, FromRange, &BasePath))3047return ExprError();30483049if (PointerConversions)3050QType = Context.getPointerType(QType);3051From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,3052VK, &BasePath).get();30533054FromType = QType;3055FromRecordType = QRecordType;30563057// If the qualifier type was the same as the destination type,3058// we're done.3059if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))3060return From;3061}3062}30633064CXXCastPath BasePath;3065if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,3066FromLoc, FromRange, &BasePath,3067/*IgnoreAccess=*/true))3068return ExprError();30693070return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,3071VK, &BasePath);3072}30733074bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,3075const LookupResult &R,3076bool HasTrailingLParen) {3077// Only when used directly as the postfix-expression of a call.3078if (!HasTrailingLParen)3079return false;30803081// Never if a scope specifier was provided.3082if (SS.isNotEmpty())3083return false;30843085// Only in C++ or ObjC++.3086if (!getLangOpts().CPlusPlus)3087return false;30883089// Turn off ADL when we find certain kinds of declarations during3090// normal lookup:3091for (const NamedDecl *D : R) {3092// C++0x [basic.lookup.argdep]p3:3093// -- a declaration of a class member3094// Since using decls preserve this property, we check this on the3095// original decl.3096if (D->isCXXClassMember())3097return false;30983099// C++0x [basic.lookup.argdep]p3:3100// -- a block-scope function declaration that is not a3101// using-declaration3102// NOTE: we also trigger this for function templates (in fact, we3103// don't check the decl type at all, since all other decl types3104// turn off ADL anyway).3105if (isa<UsingShadowDecl>(D))3106D = cast<UsingShadowDecl>(D)->getTargetDecl();3107else if (D->getLexicalDeclContext()->isFunctionOrMethod())3108return false;31093110// C++0x [basic.lookup.argdep]p3:3111// -- a declaration that is neither a function or a function3112// template3113// And also for builtin functions.3114if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {3115// But also builtin functions.3116if (FDecl->getBuiltinID() && FDecl->isImplicit())3117return false;3118} else if (!isa<FunctionTemplateDecl>(D))3119return false;3120}31213122return true;3123}312431253126/// Diagnoses obvious problems with the use of the given declaration3127/// as an expression. This is only actually called for lookups that3128/// were not overloaded, and it doesn't promise that the declaration3129/// will in fact be used.3130static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,3131bool AcceptInvalid) {3132if (D->isInvalidDecl() && !AcceptInvalid)3133return true;31343135if (isa<TypedefNameDecl>(D)) {3136S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();3137return true;3138}31393140if (isa<ObjCInterfaceDecl>(D)) {3141S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();3142return true;3143}31443145if (isa<NamespaceDecl>(D)) {3146S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();3147return true;3148}31493150return false;3151}31523153// Certain multiversion types should be treated as overloaded even when there is3154// only one result.3155static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {3156assert(R.isSingleResult() && "Expected only a single result");3157const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());3158return FD &&3159(FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());3160}31613162ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,3163LookupResult &R, bool NeedsADL,3164bool AcceptInvalidDecl) {3165// If this is a single, fully-resolved result and we don't need ADL,3166// just build an ordinary singleton decl ref.3167if (!NeedsADL && R.isSingleResult() &&3168!R.getAsSingle<FunctionTemplateDecl>() &&3169!ShouldLookupResultBeMultiVersionOverload(R))3170return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),3171R.getRepresentativeDecl(), nullptr,3172AcceptInvalidDecl);31733174// We only need to check the declaration if there's exactly one3175// result, because in the overloaded case the results can only be3176// functions and function templates.3177if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&3178CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),3179AcceptInvalidDecl))3180return ExprError();31813182// Otherwise, just build an unresolved lookup expression. Suppress3183// any lookup-related diagnostics; we'll hash these out later, when3184// we've picked a target.3185R.suppressDiagnostics();31863187UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(3188Context, R.getNamingClass(), SS.getWithLocInContext(Context),3189R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),3190/*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);31913192return ULE;3193}31943195static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,3196SourceLocation loc,3197ValueDecl *var);31983199ExprResult Sema::BuildDeclarationNameExpr(3200const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,3201NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,3202bool AcceptInvalidDecl) {3203assert(D && "Cannot refer to a NULL declaration");3204assert(!isa<FunctionTemplateDecl>(D) &&3205"Cannot refer unambiguously to a function template");32063207SourceLocation Loc = NameInfo.getLoc();3208if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {3209// Recovery from invalid cases (e.g. D is an invalid Decl).3210// We use the dependent type for the RecoveryExpr to prevent bogus follow-up3211// diagnostics, as invalid decls use int as a fallback type.3212return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});3213}32143215if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {3216// Specifically diagnose references to class templates that are missing3217// a template argument list.3218diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);3219return ExprError();3220}32213222// Make sure that we're referring to a value.3223if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {3224Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();3225Diag(D->getLocation(), diag::note_declared_at);3226return ExprError();3227}32283229// Check whether this declaration can be used. Note that we suppress3230// this check when we're going to perform argument-dependent lookup3231// on this function name, because this might not be the function3232// that overload resolution actually selects.3233if (DiagnoseUseOfDecl(D, Loc))3234return ExprError();32353236auto *VD = cast<ValueDecl>(D);32373238// Only create DeclRefExpr's for valid Decl's.3239if (VD->isInvalidDecl() && !AcceptInvalidDecl)3240return ExprError();32413242// Handle members of anonymous structs and unions. If we got here,3243// and the reference is to a class member indirect field, then this3244// must be the subject of a pointer-to-member expression.3245if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);3246IndirectField && !IndirectField->isCXXClassMember())3247return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),3248IndirectField);32493250QualType type = VD->getType();3251if (type.isNull())3252return ExprError();3253ExprValueKind valueKind = VK_PRValue;32543255// In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of3256// a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,3257// is expanded by some outer '...' in the context of the use.3258type = type.getNonPackExpansionType();32593260switch (D->getKind()) {3261// Ignore all the non-ValueDecl kinds.3262#define ABSTRACT_DECL(kind)3263#define VALUE(type, base)3264#define DECL(type, base) case Decl::type:3265#include "clang/AST/DeclNodes.inc"3266llvm_unreachable("invalid value decl kind");32673268// These shouldn't make it here.3269case Decl::ObjCAtDefsField:3270llvm_unreachable("forming non-member reference to ivar?");32713272// Enum constants are always r-values and never references.3273// Unresolved using declarations are dependent.3274case Decl::EnumConstant:3275case Decl::UnresolvedUsingValue:3276case Decl::OMPDeclareReduction:3277case Decl::OMPDeclareMapper:3278valueKind = VK_PRValue;3279break;32803281// Fields and indirect fields that got here must be for3282// pointer-to-member expressions; we just call them l-values for3283// internal consistency, because this subexpression doesn't really3284// exist in the high-level semantics.3285case Decl::Field:3286case Decl::IndirectField:3287case Decl::ObjCIvar:3288assert((getLangOpts().CPlusPlus || isAttrContext()) &&3289"building reference to field in C?");32903291// These can't have reference type in well-formed programs, but3292// for internal consistency we do this anyway.3293type = type.getNonReferenceType();3294valueKind = VK_LValue;3295break;32963297// Non-type template parameters are either l-values or r-values3298// depending on the type.3299case Decl::NonTypeTemplateParm: {3300if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {3301type = reftype->getPointeeType();3302valueKind = VK_LValue; // even if the parameter is an r-value reference3303break;3304}33053306// [expr.prim.id.unqual]p2:3307// If the entity is a template parameter object for a template3308// parameter of type T, the type of the expression is const T.3309// [...] The expression is an lvalue if the entity is a [...] template3310// parameter object.3311if (type->isRecordType()) {3312type = type.getUnqualifiedType().withConst();3313valueKind = VK_LValue;3314break;3315}33163317// For non-references, we need to strip qualifiers just in case3318// the template parameter was declared as 'const int' or whatever.3319valueKind = VK_PRValue;3320type = type.getUnqualifiedType();3321break;3322}33233324case Decl::Var:3325case Decl::VarTemplateSpecialization:3326case Decl::VarTemplatePartialSpecialization:3327case Decl::Decomposition:3328case Decl::OMPCapturedExpr:3329// In C, "extern void blah;" is valid and is an r-value.3330if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&3331type->isVoidType()) {3332valueKind = VK_PRValue;3333break;3334}3335[[fallthrough]];33363337case Decl::ImplicitParam:3338case Decl::ParmVar: {3339// These are always l-values.3340valueKind = VK_LValue;3341type = type.getNonReferenceType();33423343// FIXME: Does the addition of const really only apply in3344// potentially-evaluated contexts? Since the variable isn't actually3345// captured in an unevaluated context, it seems that the answer is no.3346if (!isUnevaluatedContext()) {3347QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);3348if (!CapturedType.isNull())3349type = CapturedType;3350}33513352break;3353}33543355case Decl::Binding:3356// These are always lvalues.3357valueKind = VK_LValue;3358type = type.getNonReferenceType();3359break;33603361case Decl::Function: {3362if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {3363if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {3364type = Context.BuiltinFnTy;3365valueKind = VK_PRValue;3366break;3367}3368}33693370const FunctionType *fty = type->castAs<FunctionType>();33713372// If we're referring to a function with an __unknown_anytype3373// result type, make the entire expression __unknown_anytype.3374if (fty->getReturnType() == Context.UnknownAnyTy) {3375type = Context.UnknownAnyTy;3376valueKind = VK_PRValue;3377break;3378}33793380// Functions are l-values in C++.3381if (getLangOpts().CPlusPlus) {3382valueKind = VK_LValue;3383break;3384}33853386// C99 DR 316 says that, if a function type comes from a3387// function definition (without a prototype), that type is only3388// used for checking compatibility. Therefore, when referencing3389// the function, we pretend that we don't have the full function3390// type.3391if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))3392type = Context.getFunctionNoProtoType(fty->getReturnType(),3393fty->getExtInfo());33943395// Functions are r-values in C.3396valueKind = VK_PRValue;3397break;3398}33993400case Decl::CXXDeductionGuide:3401llvm_unreachable("building reference to deduction guide");34023403case Decl::MSProperty:3404case Decl::MSGuid:3405case Decl::TemplateParamObject:3406// FIXME: Should MSGuidDecl and template parameter objects be subject to3407// capture in OpenMP, or duplicated between host and device?3408valueKind = VK_LValue;3409break;34103411case Decl::UnnamedGlobalConstant:3412valueKind = VK_LValue;3413break;34143415case Decl::CXXMethod:3416// If we're referring to a method with an __unknown_anytype3417// result type, make the entire expression __unknown_anytype.3418// This should only be possible with a type written directly.3419if (const FunctionProtoType *proto =3420dyn_cast<FunctionProtoType>(VD->getType()))3421if (proto->getReturnType() == Context.UnknownAnyTy) {3422type = Context.UnknownAnyTy;3423valueKind = VK_PRValue;3424break;3425}34263427// C++ methods are l-values if static, r-values if non-static.3428if (cast<CXXMethodDecl>(VD)->isStatic()) {3429valueKind = VK_LValue;3430break;3431}3432[[fallthrough]];34333434case Decl::CXXConversion:3435case Decl::CXXDestructor:3436case Decl::CXXConstructor:3437valueKind = VK_PRValue;3438break;3439}34403441auto *E =3442BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,3443/*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);3444// Clang AST consumers assume a DeclRefExpr refers to a valid decl. We3445// wrap a DeclRefExpr referring to an invalid decl with a dependent-type3446// RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus3447// diagnostics).3448if (VD->isInvalidDecl() && E)3449return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});3450return E;3451}34523453static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,3454SmallString<32> &Target) {3455Target.resize(CharByteWidth * (Source.size() + 1));3456char *ResultPtr = &Target[0];3457const llvm::UTF8 *ErrorPtr;3458bool success =3459llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);3460(void)success;3461assert(success);3462Target.resize(ResultPtr - &Target[0]);3463}34643465ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,3466PredefinedIdentKind IK) {3467Decl *currentDecl = getPredefinedExprDecl(CurContext);3468if (!currentDecl) {3469Diag(Loc, diag::ext_predef_outside_function);3470currentDecl = Context.getTranslationUnitDecl();3471}34723473QualType ResTy;3474StringLiteral *SL = nullptr;3475if (cast<DeclContext>(currentDecl)->isDependentContext())3476ResTy = Context.DependentTy;3477else {3478// Pre-defined identifiers are of type char[x], where x is the length of3479// the string.3480bool ForceElaboratedPrinting =3481IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;3482auto Str =3483PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);3484unsigned Length = Str.length();34853486llvm::APInt LengthI(32, Length + 1);3487if (IK == PredefinedIdentKind::LFunction ||3488IK == PredefinedIdentKind::LFuncSig) {3489ResTy =3490Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());3491SmallString<32> RawChars;3492ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),3493Str, RawChars);3494ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,3495ArraySizeModifier::Normal,3496/*IndexTypeQuals*/ 0);3497SL = StringLiteral::Create(Context, RawChars, StringLiteralKind::Wide,3498/*Pascal*/ false, ResTy, Loc);3499} else {3500ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());3501ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,3502ArraySizeModifier::Normal,3503/*IndexTypeQuals*/ 0);3504SL = StringLiteral::Create(Context, Str, StringLiteralKind::Ordinary,3505/*Pascal*/ false, ResTy, Loc);3506}3507}35083509return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,3510SL);3511}35123513ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {3514return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));3515}35163517ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {3518SmallString<16> CharBuffer;3519bool Invalid = false;3520StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);3521if (Invalid)3522return ExprError();35233524CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),3525PP, Tok.getKind());3526if (Literal.hadError())3527return ExprError();35283529QualType Ty;3530if (Literal.isWide())3531Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.3532else if (Literal.isUTF8() && getLangOpts().C23)3533Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C233534else if (Literal.isUTF8() && getLangOpts().Char8)3535Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.3536else if (Literal.isUTF16())3537Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.3538else if (Literal.isUTF32())3539Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.3540else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())3541Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.3542else3543Ty = Context.CharTy; // 'x' -> char in C++;3544// u8'x' -> char in C11-C17 and in C++ without char8_t.35453546CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;3547if (Literal.isWide())3548Kind = CharacterLiteralKind::Wide;3549else if (Literal.isUTF16())3550Kind = CharacterLiteralKind::UTF16;3551else if (Literal.isUTF32())3552Kind = CharacterLiteralKind::UTF32;3553else if (Literal.isUTF8())3554Kind = CharacterLiteralKind::UTF8;35553556Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,3557Tok.getLocation());35583559if (Literal.getUDSuffix().empty())3560return Lit;35613562// We're building a user-defined literal.3563IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());3564SourceLocation UDSuffixLoc =3565getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());35663567// Make sure we're allowed user-defined literals here.3568if (!UDLScope)3569return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));35703571// C++11 [lex.ext]p6: The literal L is treated as a call of the form3572// operator "" X (ch)3573return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,3574Lit, Tok.getLocation());3575}35763577ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {3578unsigned IntSize = Context.getTargetInfo().getIntWidth();3579return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),3580Context.IntTy, Loc);3581}35823583static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,3584QualType Ty, SourceLocation Loc) {3585const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);35863587using llvm::APFloat;3588APFloat Val(Format);35893590llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();3591if (RM == llvm::RoundingMode::Dynamic)3592RM = llvm::RoundingMode::NearestTiesToEven;3593APFloat::opStatus result = Literal.GetFloatValue(Val, RM);35943595// Overflow is always an error, but underflow is only an error if3596// we underflowed to zero (APFloat reports denormals as underflow).3597if ((result & APFloat::opOverflow) ||3598((result & APFloat::opUnderflow) && Val.isZero())) {3599unsigned diagnostic;3600SmallString<20> buffer;3601if (result & APFloat::opOverflow) {3602diagnostic = diag::warn_float_overflow;3603APFloat::getLargest(Format).toString(buffer);3604} else {3605diagnostic = diag::warn_float_underflow;3606APFloat::getSmallest(Format).toString(buffer);3607}36083609S.Diag(Loc, diagnostic) << Ty << buffer.str();3610}36113612bool isExact = (result == APFloat::opOK);3613return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);3614}36153616bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {3617assert(E && "Invalid expression");36183619if (E->isValueDependent())3620return false;36213622QualType QT = E->getType();3623if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {3624Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;3625return true;3626}36273628llvm::APSInt ValueAPS;3629ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);36303631if (R.isInvalid())3632return true;36333634// GCC allows the value of unroll count to be 0.3635// https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says3636// "The values of 0 and 1 block any unrolling of the loop."3637// The values doesn't have to be strictly positive in '#pragma GCC unroll' and3638// '#pragma unroll' cases.3639bool ValueIsPositive =3640AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();3641if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {3642Diag(E->getExprLoc(), diag::err_requires_positive_value)3643<< toString(ValueAPS, 10) << ValueIsPositive;3644return true;3645}36463647return false;3648}36493650ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {3651// Fast path for a single digit (which is quite common). A single digit3652// cannot have a trigraph, escaped newline, radix prefix, or suffix.3653if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {3654const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);3655return ActOnIntegerConstant(Tok.getLocation(), Val);3656}36573658SmallString<128> SpellingBuffer;3659// NumericLiteralParser wants to overread by one character. Add padding to3660// the buffer in case the token is copied to the buffer. If getSpelling()3661// returns a StringRef to the memory buffer, it should have a null char at3662// the EOF, so it is also safe.3663SpellingBuffer.resize(Tok.getLength() + 1);36643665// Get the spelling of the token, which eliminates trigraphs, etc.3666bool Invalid = false;3667StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);3668if (Invalid)3669return ExprError();36703671NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),3672PP.getSourceManager(), PP.getLangOpts(),3673PP.getTargetInfo(), PP.getDiagnostics());3674if (Literal.hadError)3675return ExprError();36763677if (Literal.hasUDSuffix()) {3678// We're building a user-defined literal.3679const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());3680SourceLocation UDSuffixLoc =3681getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());36823683// Make sure we're allowed user-defined literals here.3684if (!UDLScope)3685return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));36863687QualType CookedTy;3688if (Literal.isFloatingLiteral()) {3689// C++11 [lex.ext]p4: If S contains a literal operator with parameter type3690// long double, the literal is treated as a call of the form3691// operator "" X (f L)3692CookedTy = Context.LongDoubleTy;3693} else {3694// C++11 [lex.ext]p3: If S contains a literal operator with parameter type3695// unsigned long long, the literal is treated as a call of the form3696// operator "" X (n ULL)3697CookedTy = Context.UnsignedLongLongTy;3698}36993700DeclarationName OpName =3701Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);3702DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);3703OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);37043705SourceLocation TokLoc = Tok.getLocation();37063707// Perform literal operator lookup to determine if we're building a raw3708// literal or a cooked one.3709LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);3710switch (LookupLiteralOperator(UDLScope, R, CookedTy,3711/*AllowRaw*/ true, /*AllowTemplate*/ true,3712/*AllowStringTemplatePack*/ false,3713/*DiagnoseMissing*/ !Literal.isImaginary)) {3714case LOLR_ErrorNoDiagnostic:3715// Lookup failure for imaginary constants isn't fatal, there's still the3716// GNU extension producing _Complex types.3717break;3718case LOLR_Error:3719return ExprError();3720case LOLR_Cooked: {3721Expr *Lit;3722if (Literal.isFloatingLiteral()) {3723Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());3724} else {3725llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);3726if (Literal.GetIntegerValue(ResultVal))3727Diag(Tok.getLocation(), diag::err_integer_literal_too_large)3728<< /* Unsigned */ 1;3729Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,3730Tok.getLocation());3731}3732return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);3733}37343735case LOLR_Raw: {3736// C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the3737// literal is treated as a call of the form3738// operator "" X ("n")3739unsigned Length = Literal.getUDSuffixOffset();3740QualType StrTy = Context.getConstantArrayType(3741Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),3742llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);3743Expr *Lit =3744StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),3745StringLiteralKind::Ordinary,3746/*Pascal*/ false, StrTy, &TokLoc, 1);3747return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);3748}37493750case LOLR_Template: {3751// C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator3752// template), L is treated as a call fo the form3753// operator "" X <'c1', 'c2', ... 'ck'>()3754// where n is the source character sequence c1 c2 ... ck.3755TemplateArgumentListInfo ExplicitArgs;3756unsigned CharBits = Context.getIntWidth(Context.CharTy);3757bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();3758llvm::APSInt Value(CharBits, CharIsUnsigned);3759for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {3760Value = TokSpelling[I];3761TemplateArgument Arg(Context, Value, Context.CharTy);3762TemplateArgumentLocInfo ArgInfo;3763ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));3764}3765return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,3766&ExplicitArgs);3767}3768case LOLR_StringTemplatePack:3769llvm_unreachable("unexpected literal operator lookup result");3770}3771}37723773Expr *Res;37743775if (Literal.isFixedPointLiteral()) {3776QualType Ty;37773778if (Literal.isAccum) {3779if (Literal.isHalf) {3780Ty = Context.ShortAccumTy;3781} else if (Literal.isLong) {3782Ty = Context.LongAccumTy;3783} else {3784Ty = Context.AccumTy;3785}3786} else if (Literal.isFract) {3787if (Literal.isHalf) {3788Ty = Context.ShortFractTy;3789} else if (Literal.isLong) {3790Ty = Context.LongFractTy;3791} else {3792Ty = Context.FractTy;3793}3794}37953796if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);37973798bool isSigned = !Literal.isUnsigned;3799unsigned scale = Context.getFixedPointScale(Ty);3800unsigned bit_width = Context.getTypeInfo(Ty).Width;38013802llvm::APInt Val(bit_width, 0, isSigned);3803bool Overflowed = Literal.GetFixedPointValue(Val, scale);3804bool ValIsZero = Val.isZero() && !Overflowed;38053806auto MaxVal = Context.getFixedPointMax(Ty).getValue();3807if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)3808// Clause 6.4.4 - The value of a constant shall be in the range of3809// representable values for its type, with exception for constants of a3810// fract type with a value of exactly 1; such a constant shall denote3811// the maximal value for the type.3812--Val;3813else if (Val.ugt(MaxVal) || Overflowed)3814Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);38153816Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,3817Tok.getLocation(), scale);3818} else if (Literal.isFloatingLiteral()) {3819QualType Ty;3820if (Literal.isHalf){3821if (getLangOpts().HLSL ||3822getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))3823Ty = Context.HalfTy;3824else {3825Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);3826return ExprError();3827}3828} else if (Literal.isFloat)3829Ty = Context.FloatTy;3830else if (Literal.isLong)3831Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;3832else if (Literal.isFloat16)3833Ty = Context.Float16Ty;3834else if (Literal.isFloat128)3835Ty = Context.Float128Ty;3836else if (getLangOpts().HLSL)3837Ty = Context.FloatTy;3838else3839Ty = Context.DoubleTy;38403841Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());38423843if (Ty == Context.DoubleTy) {3844if (getLangOpts().SinglePrecisionConstants) {3845if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {3846Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();3847}3848} else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(3849"cl_khr_fp64", getLangOpts())) {3850// Impose single-precision float type when cl_khr_fp64 is not enabled.3851Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)3852<< (getLangOpts().getOpenCLCompatibleVersion() >= 300);3853Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();3854}3855}3856} else if (!Literal.isIntegerLiteral()) {3857return ExprError();3858} else {3859QualType Ty;38603861// 'z/uz' literals are a C++23 feature.3862if (Literal.isSizeT)3863Diag(Tok.getLocation(), getLangOpts().CPlusPlus3864? getLangOpts().CPlusPlus233865? diag::warn_cxx20_compat_size_t_suffix3866: diag::ext_cxx23_size_t_suffix3867: diag::err_cxx23_size_t_suffix);38683869// 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,3870// but we do not currently support the suffix in C++ mode because it's not3871// entirely clear whether WG21 will prefer this suffix to return a library3872// type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'3873// literals are a C++ extension.3874if (Literal.isBitInt)3875PP.Diag(Tok.getLocation(),3876getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix3877: getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix3878: diag::ext_c23_bitint_suffix);38793880// Get the value in the widest-possible width. What is "widest" depends on3881// whether the literal is a bit-precise integer or not. For a bit-precise3882// integer type, try to scan the source to determine how many bits are3883// needed to represent the value. This may seem a bit expensive, but trying3884// to get the integer value from an overly-wide APInt is *extremely*3885// expensive, so the naive approach of assuming3886// llvm::IntegerType::MAX_INT_BITS is a big performance hit.3887unsigned BitsNeeded =3888Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(3889Literal.getLiteralDigits(), Literal.getRadix())3890: Context.getTargetInfo().getIntMaxTWidth();3891llvm::APInt ResultVal(BitsNeeded, 0);38923893if (Literal.GetIntegerValue(ResultVal)) {3894// If this value didn't fit into uintmax_t, error and force to ull.3895Diag(Tok.getLocation(), diag::err_integer_literal_too_large)3896<< /* Unsigned */ 1;3897Ty = Context.UnsignedLongLongTy;3898assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&3899"long long is not intmax_t?");3900} else {3901// If this value fits into a ULL, try to figure out what else it fits into3902// according to the rules of C99 6.4.4.1p5.39033904// Octal, Hexadecimal, and integers with a U suffix are allowed to3905// be an unsigned int.3906bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;39073908// HLSL doesn't really have `long` or `long long`. We support the `ll`3909// suffix for portability of code with C++, but both `l` and `ll` are3910// 64-bit integer types, and we want the type of `1l` and `1ll` to be the3911// same.3912if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {3913Literal.isLong = true;3914Literal.isLongLong = false;3915}39163917// Check from smallest to largest, picking the smallest type we can.3918unsigned Width = 0;39193920// Microsoft specific integer suffixes are explicitly sized.3921if (Literal.MicrosoftInteger) {3922if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {3923Width = 8;3924Ty = Context.CharTy;3925} else {3926Width = Literal.MicrosoftInteger;3927Ty = Context.getIntTypeForBitwidth(Width,3928/*Signed=*/!Literal.isUnsigned);3929}3930}39313932// Bit-precise integer literals are automagically-sized based on the3933// width required by the literal.3934if (Literal.isBitInt) {3935// The signed version has one more bit for the sign value. There are no3936// zero-width bit-precise integers, even if the literal value is 0.3937Width = std::max(ResultVal.getActiveBits(), 1u) +3938(Literal.isUnsigned ? 0u : 1u);39393940// Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,3941// and reset the type to the largest supported width.3942unsigned int MaxBitIntWidth =3943Context.getTargetInfo().getMaxBitIntWidth();3944if (Width > MaxBitIntWidth) {3945Diag(Tok.getLocation(), diag::err_integer_literal_too_large)3946<< Literal.isUnsigned;3947Width = MaxBitIntWidth;3948}39493950// Reset the result value to the smaller APInt and select the correct3951// type to be used. Note, we zext even for signed values because the3952// literal itself is always an unsigned value (a preceeding - is a3953// unary operator, not part of the literal).3954ResultVal = ResultVal.zextOrTrunc(Width);3955Ty = Context.getBitIntType(Literal.isUnsigned, Width);3956}39573958// Check C++23 size_t literals.3959if (Literal.isSizeT) {3960assert(!Literal.MicrosoftInteger &&3961"size_t literals can't be Microsoft literals");3962unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(3963Context.getTargetInfo().getSizeType());39643965// Does it fit in size_t?3966if (ResultVal.isIntN(SizeTSize)) {3967// Does it fit in ssize_t?3968if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)3969Ty = Context.getSignedSizeType();3970else if (AllowUnsigned)3971Ty = Context.getSizeType();3972Width = SizeTSize;3973}3974}39753976if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&3977!Literal.isSizeT) {3978// Are int/unsigned possibilities?3979unsigned IntSize = Context.getTargetInfo().getIntWidth();39803981// Does it fit in a unsigned int?3982if (ResultVal.isIntN(IntSize)) {3983// Does it fit in a signed int?3984if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)3985Ty = Context.IntTy;3986else if (AllowUnsigned)3987Ty = Context.UnsignedIntTy;3988Width = IntSize;3989}3990}39913992// Are long/unsigned long possibilities?3993if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {3994unsigned LongSize = Context.getTargetInfo().getLongWidth();39953996// Does it fit in a unsigned long?3997if (ResultVal.isIntN(LongSize)) {3998// Does it fit in a signed long?3999if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)4000Ty = Context.LongTy;4001else if (AllowUnsigned)4002Ty = Context.UnsignedLongTy;4003// Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p24004// is compatible.4005else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {4006const unsigned LongLongSize =4007Context.getTargetInfo().getLongLongWidth();4008Diag(Tok.getLocation(),4009getLangOpts().CPlusPlus4010? Literal.isLong4011? diag::warn_old_implicitly_unsigned_long_cxx4012: /*C++98 UB*/ diag::4013ext_old_implicitly_unsigned_long_cxx4014: diag::warn_old_implicitly_unsigned_long)4015<< (LongLongSize > LongSize ? /*will have type 'long long'*/ 04016: /*will be ill-formed*/ 1);4017Ty = Context.UnsignedLongTy;4018}4019Width = LongSize;4020}4021}40224023// Check long long if needed.4024if (Ty.isNull() && !Literal.isSizeT) {4025unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();40264027// Does it fit in a unsigned long long?4028if (ResultVal.isIntN(LongLongSize)) {4029// Does it fit in a signed long long?4030// To be compatible with MSVC, hex integer literals ending with the4031// LL or i64 suffix are always signed in Microsoft mode.4032if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||4033(getLangOpts().MSVCCompat && Literal.isLongLong)))4034Ty = Context.LongLongTy;4035else if (AllowUnsigned)4036Ty = Context.UnsignedLongLongTy;4037Width = LongLongSize;40384039// 'long long' is a C99 or C++11 feature, whether the literal4040// explicitly specified 'long long' or we needed the extra width.4041if (getLangOpts().CPlusPlus)4042Diag(Tok.getLocation(), getLangOpts().CPlusPlus114043? diag::warn_cxx98_compat_longlong4044: diag::ext_cxx11_longlong);4045else if (!getLangOpts().C99)4046Diag(Tok.getLocation(), diag::ext_c99_longlong);4047}4048}40494050// If we still couldn't decide a type, we either have 'size_t' literal4051// that is out of range, or a decimal literal that does not fit in a4052// signed long long and has no U suffix.4053if (Ty.isNull()) {4054if (Literal.isSizeT)4055Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)4056<< Literal.isUnsigned;4057else4058Diag(Tok.getLocation(),4059diag::ext_integer_literal_too_large_for_signed);4060Ty = Context.UnsignedLongLongTy;4061Width = Context.getTargetInfo().getLongLongWidth();4062}40634064if (ResultVal.getBitWidth() != Width)4065ResultVal = ResultVal.trunc(Width);4066}4067Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());4068}40694070// If this is an imaginary literal, create the ImaginaryLiteral wrapper.4071if (Literal.isImaginary) {4072Res = new (Context) ImaginaryLiteral(Res,4073Context.getComplexType(Res->getType()));40744075Diag(Tok.getLocation(), diag::ext_imaginary_constant);4076}4077return Res;4078}40794080ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {4081assert(E && "ActOnParenExpr() missing expr");4082QualType ExprTy = E->getType();4083if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&4084!E->isLValue() && ExprTy->hasFloatingRepresentation())4085return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);4086return new (Context) ParenExpr(L, R, E);4087}40884089static bool CheckVecStepTraitOperandType(Sema &S, QualType T,4090SourceLocation Loc,4091SourceRange ArgRange) {4092// [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in4093// scalar or vector data type argument..."4094// Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic4095// type (C99 6.2.5p18) or void.4096if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {4097S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)4098<< T << ArgRange;4099return true;4100}41014102assert((T->isVoidType() || !T->isIncompleteType()) &&4103"Scalar types should always be complete");4104return false;4105}41064107static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,4108SourceLocation Loc,4109SourceRange ArgRange) {4110// builtin_vectorelements supports both fixed-sized and scalable vectors.4111if (!T->isVectorType() && !T->isSizelessVectorType())4112return S.Diag(Loc, diag::err_builtin_non_vector_type)4113<< ""4114<< "__builtin_vectorelements" << T << ArgRange;41154116return false;4117}41184119static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,4120SourceLocation Loc,4121SourceRange ArgRange) {4122if (S.checkPointerAuthEnabled(Loc, ArgRange))4123return true;41244125if (!T->isFunctionType() && !T->isFunctionPointerType() &&4126!T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {4127S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;4128return true;4129}41304131return false;4132}41334134static bool CheckExtensionTraitOperandType(Sema &S, QualType T,4135SourceLocation Loc,4136SourceRange ArgRange,4137UnaryExprOrTypeTrait TraitKind) {4138// Invalid types must be hard errors for SFINAE in C++.4139if (S.LangOpts.CPlusPlus)4140return true;41414142// C99 6.5.3.4p1:4143if (T->isFunctionType() &&4144(TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||4145TraitKind == UETT_PreferredAlignOf)) {4146// sizeof(function)/alignof(function) is allowed as an extension.4147S.Diag(Loc, diag::ext_sizeof_alignof_function_type)4148<< getTraitSpelling(TraitKind) << ArgRange;4149return false;4150}41514152// Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where4153// this is an error (OpenCL v1.1 s6.3.k)4154if (T->isVoidType()) {4155unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type4156: diag::ext_sizeof_alignof_void_type;4157S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;4158return false;4159}41604161return true;4162}41634164static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,4165SourceLocation Loc,4166SourceRange ArgRange,4167UnaryExprOrTypeTrait TraitKind) {4168// Reject sizeof(interface) and sizeof(interface<proto>) if the4169// runtime doesn't allow it.4170if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {4171S.Diag(Loc, diag::err_sizeof_nonfragile_interface)4172<< T << (TraitKind == UETT_SizeOf)4173<< ArgRange;4174return true;4175}41764177return false;4178}41794180/// Check whether E is a pointer from a decayed array type (the decayed4181/// pointer type is equal to T) and emit a warning if it is.4182static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,4183const Expr *E) {4184// Don't warn if the operation changed the type.4185if (T != E->getType())4186return;41874188// Now look for array decays.4189const auto *ICE = dyn_cast<ImplicitCastExpr>(E);4190if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)4191return;41924193S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()4194<< ICE->getType()4195<< ICE->getSubExpr()->getType();4196}41974198bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,4199UnaryExprOrTypeTrait ExprKind) {4200QualType ExprTy = E->getType();4201assert(!ExprTy->isReferenceType());42024203bool IsUnevaluatedOperand =4204(ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||4205ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||4206ExprKind == UETT_VecStep);4207if (IsUnevaluatedOperand) {4208ExprResult Result = CheckUnevaluatedOperand(E);4209if (Result.isInvalid())4210return true;4211E = Result.get();4212}42134214// The operand for sizeof and alignof is in an unevaluated expression context,4215// so side effects could result in unintended consequences.4216// Exclude instantiation-dependent expressions, because 'sizeof' is sometimes4217// used to build SFINAE gadgets.4218// FIXME: Should we consider instantiation-dependent operands to 'alignof'?4219if (IsUnevaluatedOperand && !inTemplateInstantiation() &&4220!E->isInstantiationDependent() &&4221!E->getType()->isVariableArrayType() &&4222E->HasSideEffects(Context, false))4223Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);42244225if (ExprKind == UETT_VecStep)4226return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),4227E->getSourceRange());42284229if (ExprKind == UETT_VectorElements)4230return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),4231E->getSourceRange());42324233// Explicitly list some types as extensions.4234if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),4235E->getSourceRange(), ExprKind))4236return false;42374238// WebAssembly tables are always illegal operands to unary expressions and4239// type traits.4240if (Context.getTargetInfo().getTriple().isWasm() &&4241E->getType()->isWebAssemblyTableType()) {4242Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)4243<< getTraitSpelling(ExprKind);4244return true;4245}42464247// 'alignof' applied to an expression only requires the base element type of4248// the expression to be complete. 'sizeof' requires the expression's type to4249// be complete (and will attempt to complete it if it's an array of unknown4250// bound).4251if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {4252if (RequireCompleteSizedType(4253E->getExprLoc(), Context.getBaseElementType(E->getType()),4254diag::err_sizeof_alignof_incomplete_or_sizeless_type,4255getTraitSpelling(ExprKind), E->getSourceRange()))4256return true;4257} else {4258if (RequireCompleteSizedExprType(4259E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,4260getTraitSpelling(ExprKind), E->getSourceRange()))4261return true;4262}42634264// Completing the expression's type may have changed it.4265ExprTy = E->getType();4266assert(!ExprTy->isReferenceType());42674268if (ExprTy->isFunctionType()) {4269Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)4270<< getTraitSpelling(ExprKind) << E->getSourceRange();4271return true;4272}42734274if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),4275E->getSourceRange(), ExprKind))4276return true;42774278if (ExprKind == UETT_SizeOf) {4279if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {4280if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {4281QualType OType = PVD->getOriginalType();4282QualType Type = PVD->getType();4283if (Type->isPointerType() && OType->isArrayType()) {4284Diag(E->getExprLoc(), diag::warn_sizeof_array_param)4285<< Type << OType;4286Diag(PVD->getLocation(), diag::note_declared_at);4287}4288}4289}42904291// Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array4292// decays into a pointer and returns an unintended result. This is most4293// likely a typo for "sizeof(array) op x".4294if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {4295warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),4296BO->getLHS());4297warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),4298BO->getRHS());4299}4300}43014302return false;4303}43044305static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {4306// Cannot know anything else if the expression is dependent.4307if (E->isTypeDependent())4308return false;43094310if (E->getObjectKind() == OK_BitField) {4311S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)4312<< 1 << E->getSourceRange();4313return true;4314}43154316ValueDecl *D = nullptr;4317Expr *Inner = E->IgnoreParens();4318if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {4319D = DRE->getDecl();4320} else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {4321D = ME->getMemberDecl();4322}43234324// If it's a field, require the containing struct to have a4325// complete definition so that we can compute the layout.4326//4327// This can happen in C++11 onwards, either by naming the member4328// in a way that is not transformed into a member access expression4329// (in an unevaluated operand, for instance), or by naming the member4330// in a trailing-return-type.4331//4332// For the record, since __alignof__ on expressions is a GCC4333// extension, GCC seems to permit this but always gives the4334// nonsensical answer 0.4335//4336// We don't really need the layout here --- we could instead just4337// directly check for all the appropriate alignment-lowing4338// attributes --- but that would require duplicating a lot of4339// logic that just isn't worth duplicating for such a marginal4340// use-case.4341if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {4342// Fast path this check, since we at least know the record has a4343// definition if we can find a member of it.4344if (!FD->getParent()->isCompleteDefinition()) {4345S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)4346<< E->getSourceRange();4347return true;4348}43494350// Otherwise, if it's a field, and the field doesn't have4351// reference type, then it must have a complete type (or be a4352// flexible array member, which we explicitly want to4353// white-list anyway), which makes the following checks trivial.4354if (!FD->getType()->isReferenceType())4355return false;4356}43574358return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);4359}43604361bool Sema::CheckVecStepExpr(Expr *E) {4362E = E->IgnoreParens();43634364// Cannot know anything else if the expression is dependent.4365if (E->isTypeDependent())4366return false;43674368return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);4369}43704371static void captureVariablyModifiedType(ASTContext &Context, QualType T,4372CapturingScopeInfo *CSI) {4373assert(T->isVariablyModifiedType());4374assert(CSI != nullptr);43754376// We're going to walk down into the type and look for VLA expressions.4377do {4378const Type *Ty = T.getTypePtr();4379switch (Ty->getTypeClass()) {4380#define TYPE(Class, Base)4381#define ABSTRACT_TYPE(Class, Base)4382#define NON_CANONICAL_TYPE(Class, Base)4383#define DEPENDENT_TYPE(Class, Base) case Type::Class:4384#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)4385#include "clang/AST/TypeNodes.inc"4386T = QualType();4387break;4388// These types are never variably-modified.4389case Type::Builtin:4390case Type::Complex:4391case Type::Vector:4392case Type::ExtVector:4393case Type::ConstantMatrix:4394case Type::Record:4395case Type::Enum:4396case Type::TemplateSpecialization:4397case Type::ObjCObject:4398case Type::ObjCInterface:4399case Type::ObjCObjectPointer:4400case Type::ObjCTypeParam:4401case Type::Pipe:4402case Type::BitInt:4403llvm_unreachable("type class is never variably-modified!");4404case Type::Elaborated:4405T = cast<ElaboratedType>(Ty)->getNamedType();4406break;4407case Type::Adjusted:4408T = cast<AdjustedType>(Ty)->getOriginalType();4409break;4410case Type::Decayed:4411T = cast<DecayedType>(Ty)->getPointeeType();4412break;4413case Type::ArrayParameter:4414T = cast<ArrayParameterType>(Ty)->getElementType();4415break;4416case Type::Pointer:4417T = cast<PointerType>(Ty)->getPointeeType();4418break;4419case Type::BlockPointer:4420T = cast<BlockPointerType>(Ty)->getPointeeType();4421break;4422case Type::LValueReference:4423case Type::RValueReference:4424T = cast<ReferenceType>(Ty)->getPointeeType();4425break;4426case Type::MemberPointer:4427T = cast<MemberPointerType>(Ty)->getPointeeType();4428break;4429case Type::ConstantArray:4430case Type::IncompleteArray:4431// Losing element qualification here is fine.4432T = cast<ArrayType>(Ty)->getElementType();4433break;4434case Type::VariableArray: {4435// Losing element qualification here is fine.4436const VariableArrayType *VAT = cast<VariableArrayType>(Ty);44374438// Unknown size indication requires no size computation.4439// Otherwise, evaluate and record it.4440auto Size = VAT->getSizeExpr();4441if (Size && !CSI->isVLATypeCaptured(VAT) &&4442(isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))4443CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());44444445T = VAT->getElementType();4446break;4447}4448case Type::FunctionProto:4449case Type::FunctionNoProto:4450T = cast<FunctionType>(Ty)->getReturnType();4451break;4452case Type::Paren:4453case Type::TypeOf:4454case Type::UnaryTransform:4455case Type::Attributed:4456case Type::BTFTagAttributed:4457case Type::SubstTemplateTypeParm:4458case Type::MacroQualified:4459case Type::CountAttributed:4460// Keep walking after single level desugaring.4461T = T.getSingleStepDesugaredType(Context);4462break;4463case Type::Typedef:4464T = cast<TypedefType>(Ty)->desugar();4465break;4466case Type::Decltype:4467T = cast<DecltypeType>(Ty)->desugar();4468break;4469case Type::PackIndexing:4470T = cast<PackIndexingType>(Ty)->desugar();4471break;4472case Type::Using:4473T = cast<UsingType>(Ty)->desugar();4474break;4475case Type::Auto:4476case Type::DeducedTemplateSpecialization:4477T = cast<DeducedType>(Ty)->getDeducedType();4478break;4479case Type::TypeOfExpr:4480T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();4481break;4482case Type::Atomic:4483T = cast<AtomicType>(Ty)->getValueType();4484break;4485}4486} while (!T.isNull() && T->isVariablyModifiedType());4487}44884489bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,4490SourceLocation OpLoc,4491SourceRange ExprRange,4492UnaryExprOrTypeTrait ExprKind,4493StringRef KWName) {4494if (ExprType->isDependentType())4495return false;44964497// C++ [expr.sizeof]p2:4498// When applied to a reference or a reference type, the result4499// is the size of the referenced type.4500// C++11 [expr.alignof]p3:4501// When alignof is applied to a reference type, the result4502// shall be the alignment of the referenced type.4503if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())4504ExprType = Ref->getPointeeType();45054506// C11 6.5.3.4/3, C++11 [expr.alignof]p3:4507// When alignof or _Alignof is applied to an array type, the result4508// is the alignment of the element type.4509if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||4510ExprKind == UETT_OpenMPRequiredSimdAlign) {4511// If the trait is 'alignof' in C before C2y, the ability to apply the4512// trait to an incomplete array is an extension.4513if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&4514ExprType->isIncompleteArrayType())4515Diag(OpLoc, getLangOpts().C2y4516? diag::warn_c2y_compat_alignof_incomplete_array4517: diag::ext_c2y_alignof_incomplete_array);4518ExprType = Context.getBaseElementType(ExprType);4519}45204521if (ExprKind == UETT_VecStep)4522return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);45234524if (ExprKind == UETT_VectorElements)4525return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,4526ExprRange);45274528if (ExprKind == UETT_PtrAuthTypeDiscriminator)4529return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,4530ExprRange);45314532// Explicitly list some types as extensions.4533if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,4534ExprKind))4535return false;45364537if (RequireCompleteSizedType(4538OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,4539KWName, ExprRange))4540return true;45414542if (ExprType->isFunctionType()) {4543Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;4544return true;4545}45464547// WebAssembly tables are always illegal operands to unary expressions and4548// type traits.4549if (Context.getTargetInfo().getTriple().isWasm() &&4550ExprType->isWebAssemblyTableType()) {4551Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)4552<< getTraitSpelling(ExprKind);4553return true;4554}45554556if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,4557ExprKind))4558return true;45594560if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {4561if (auto *TT = ExprType->getAs<TypedefType>()) {4562for (auto I = FunctionScopes.rbegin(),4563E = std::prev(FunctionScopes.rend());4564I != E; ++I) {4565auto *CSI = dyn_cast<CapturingScopeInfo>(*I);4566if (CSI == nullptr)4567break;4568DeclContext *DC = nullptr;4569if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))4570DC = LSI->CallOperator;4571else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))4572DC = CRSI->TheCapturedDecl;4573else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))4574DC = BSI->TheDecl;4575if (DC) {4576if (DC->containsDecl(TT->getDecl()))4577break;4578captureVariablyModifiedType(Context, ExprType, CSI);4579}4580}4581}4582}45834584return false;4585}45864587ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,4588SourceLocation OpLoc,4589UnaryExprOrTypeTrait ExprKind,4590SourceRange R) {4591if (!TInfo)4592return ExprError();45934594QualType T = TInfo->getType();45954596if (!T->isDependentType() &&4597CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,4598getTraitSpelling(ExprKind)))4599return ExprError();46004601// Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to4602// properly deal with VLAs in nested calls of sizeof and typeof.4603if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&4604TInfo->getType()->isVariablyModifiedType())4605TInfo = TransformToPotentiallyEvaluated(TInfo);46064607// C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.4608return new (Context) UnaryExprOrTypeTraitExpr(4609ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());4610}46114612ExprResult4613Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,4614UnaryExprOrTypeTrait ExprKind) {4615ExprResult PE = CheckPlaceholderExpr(E);4616if (PE.isInvalid())4617return ExprError();46184619E = PE.get();46204621// Verify that the operand is valid.4622bool isInvalid = false;4623if (E->isTypeDependent()) {4624// Delay type-checking for type-dependent expressions.4625} else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {4626isInvalid = CheckAlignOfExpr(*this, E, ExprKind);4627} else if (ExprKind == UETT_VecStep) {4628isInvalid = CheckVecStepExpr(E);4629} else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {4630Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);4631isInvalid = true;4632} else if (E->refersToBitField()) { // C99 6.5.3.4p1.4633Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;4634isInvalid = true;4635} else if (ExprKind == UETT_VectorElements) {4636isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);4637} else {4638isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);4639}46404641if (isInvalid)4642return ExprError();46434644if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {4645PE = TransformToPotentiallyEvaluated(E);4646if (PE.isInvalid()) return ExprError();4647E = PE.get();4648}46494650// C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.4651return new (Context) UnaryExprOrTypeTraitExpr(4652ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());4653}46544655ExprResult4656Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,4657UnaryExprOrTypeTrait ExprKind, bool IsType,4658void *TyOrEx, SourceRange ArgRange) {4659// If error parsing type, ignore.4660if (!TyOrEx) return ExprError();46614662if (IsType) {4663TypeSourceInfo *TInfo;4664(void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);4665return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);4666}46674668Expr *ArgEx = (Expr *)TyOrEx;4669ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);4670return Result;4671}46724673bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,4674SourceLocation OpLoc, SourceRange R) {4675if (!TInfo)4676return true;4677return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,4678UETT_AlignOf, KWName);4679}46804681bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,4682SourceLocation OpLoc, SourceRange R) {4683TypeSourceInfo *TInfo;4684(void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()),4685&TInfo);4686return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);4687}46884689static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,4690bool IsReal) {4691if (V.get()->isTypeDependent())4692return S.Context.DependentTy;46934694// _Real and _Imag are only l-values for normal l-values.4695if (V.get()->getObjectKind() != OK_Ordinary) {4696V = S.DefaultLvalueConversion(V.get());4697if (V.isInvalid())4698return QualType();4699}47004701// These operators return the element type of a complex type.4702if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())4703return CT->getElementType();47044705// Otherwise they pass through real integer and floating point types here.4706if (V.get()->getType()->isArithmeticType())4707return V.get()->getType();47084709// Test for placeholders.4710ExprResult PR = S.CheckPlaceholderExpr(V.get());4711if (PR.isInvalid()) return QualType();4712if (PR.get() != V.get()) {4713V = PR;4714return CheckRealImagOperand(S, V, Loc, IsReal);4715}47164717// Reject anything else.4718S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()4719<< (IsReal ? "__real" : "__imag");4720return QualType();4721}4722472347244725ExprResult4726Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,4727tok::TokenKind Kind, Expr *Input) {4728UnaryOperatorKind Opc;4729switch (Kind) {4730default: llvm_unreachable("Unknown unary op!");4731case tok::plusplus: Opc = UO_PostInc; break;4732case tok::minusminus: Opc = UO_PostDec; break;4733}47344735// Since this might is a postfix expression, get rid of ParenListExprs.4736ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);4737if (Result.isInvalid()) return ExprError();4738Input = Result.get();47394740return BuildUnaryOp(S, OpLoc, Opc, Input);4741}47424743/// Diagnose if arithmetic on the given ObjC pointer is illegal.4744///4745/// \return true on error4746static bool checkArithmeticOnObjCPointer(Sema &S,4747SourceLocation opLoc,4748Expr *op) {4749assert(op->getType()->isObjCObjectPointerType());4750if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&4751!S.LangOpts.ObjCSubscriptingLegacyRuntime)4752return false;47534754S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)4755<< op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()4756<< op->getSourceRange();4757return true;4758}47594760static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {4761auto *BaseNoParens = Base->IgnoreParens();4762if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))4763return MSProp->getPropertyDecl()->getType()->isArrayType();4764return isa<MSPropertySubscriptExpr>(BaseNoParens);4765}47664767// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.4768// Typically this is DependentTy, but can sometimes be more precise.4769//4770// There are cases when we could determine a non-dependent type:4771// - LHS and RHS may have non-dependent types despite being type-dependent4772// (e.g. unbounded array static members of the current instantiation)4773// - one may be a dependent-sized array with known element type4774// - one may be a dependent-typed valid index (enum in current instantiation)4775//4776// We *always* return a dependent type, in such cases it is DependentTy.4777// This avoids creating type-dependent expressions with non-dependent types.4778// FIXME: is this important to avoid? See https://reviews.llvm.org/D1072754779static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,4780const ASTContext &Ctx) {4781assert(LHS->isTypeDependent() || RHS->isTypeDependent());4782QualType LTy = LHS->getType(), RTy = RHS->getType();4783QualType Result = Ctx.DependentTy;4784if (RTy->isIntegralOrUnscopedEnumerationType()) {4785if (const PointerType *PT = LTy->getAs<PointerType>())4786Result = PT->getPointeeType();4787else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())4788Result = AT->getElementType();4789} else if (LTy->isIntegralOrUnscopedEnumerationType()) {4790if (const PointerType *PT = RTy->getAs<PointerType>())4791Result = PT->getPointeeType();4792else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())4793Result = AT->getElementType();4794}4795// Ensure we return a dependent type.4796return Result->isDependentType() ? Result : Ctx.DependentTy;4797}47984799ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,4800SourceLocation lbLoc,4801MultiExprArg ArgExprs,4802SourceLocation rbLoc) {48034804if (base && !base->getType().isNull() &&4805base->hasPlaceholderType(BuiltinType::ArraySection)) {4806auto *AS = cast<ArraySectionExpr>(base);4807if (AS->isOMPArraySection())4808return OpenMP().ActOnOMPArraySectionExpr(4809base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),4810/*Length*/ nullptr,4811/*Stride=*/nullptr, rbLoc);48124813return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),4814SourceLocation(), /*Length*/ nullptr,4815rbLoc);4816}48174818// Since this might be a postfix expression, get rid of ParenListExprs.4819if (isa<ParenListExpr>(base)) {4820ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);4821if (result.isInvalid())4822return ExprError();4823base = result.get();4824}48254826// Check if base and idx form a MatrixSubscriptExpr.4827//4828// Helper to check for comma expressions, which are not allowed as indices for4829// matrix subscript expressions.4830auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {4831if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {4832Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)4833<< SourceRange(base->getBeginLoc(), rbLoc);4834return true;4835}4836return false;4837};4838// The matrix subscript operator ([][])is considered a single operator.4839// Separating the index expressions by parenthesis is not allowed.4840if (base && !base->getType().isNull() &&4841base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&4842!isa<MatrixSubscriptExpr>(base)) {4843Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)4844<< SourceRange(base->getBeginLoc(), rbLoc);4845return ExprError();4846}4847// If the base is a MatrixSubscriptExpr, try to create a new4848// MatrixSubscriptExpr.4849auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);4850if (matSubscriptE) {4851assert(ArgExprs.size() == 1);4852if (CheckAndReportCommaError(ArgExprs.front()))4853return ExprError();48544855assert(matSubscriptE->isIncomplete() &&4856"base has to be an incomplete matrix subscript");4857return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),4858matSubscriptE->getRowIdx(),4859ArgExprs.front(), rbLoc);4860}4861if (base->getType()->isWebAssemblyTableType()) {4862Diag(base->getExprLoc(), diag::err_wasm_table_art)4863<< SourceRange(base->getBeginLoc(), rbLoc) << 3;4864return ExprError();4865}48664867// Handle any non-overload placeholder types in the base and index4868// expressions. We can't handle overloads here because the other4869// operand might be an overloadable type, in which case the overload4870// resolution for the operator overload should get the first crack4871// at the overload.4872bool IsMSPropertySubscript = false;4873if (base->getType()->isNonOverloadPlaceholderType()) {4874IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);4875if (!IsMSPropertySubscript) {4876ExprResult result = CheckPlaceholderExpr(base);4877if (result.isInvalid())4878return ExprError();4879base = result.get();4880}4881}48824883// If the base is a matrix type, try to create a new MatrixSubscriptExpr.4884if (base->getType()->isMatrixType()) {4885assert(ArgExprs.size() == 1);4886if (CheckAndReportCommaError(ArgExprs.front()))4887return ExprError();48884889return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,4890rbLoc);4891}48924893if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {4894Expr *idx = ArgExprs[0];4895if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||4896(isa<CXXOperatorCallExpr>(idx) &&4897cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {4898Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)4899<< SourceRange(base->getBeginLoc(), rbLoc);4900}4901}49024903if (ArgExprs.size() == 1 &&4904ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {4905ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);4906if (result.isInvalid())4907return ExprError();4908ArgExprs[0] = result.get();4909} else {4910if (CheckArgsForPlaceholders(ArgExprs))4911return ExprError();4912}49134914// Build an unanalyzed expression if either operand is type-dependent.4915if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&4916(base->isTypeDependent() ||4917Expr::hasAnyTypeDependentArguments(ArgExprs)) &&4918!isa<PackExpansionExpr>(ArgExprs[0])) {4919return new (Context) ArraySubscriptExpr(4920base, ArgExprs.front(),4921getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),4922VK_LValue, OK_Ordinary, rbLoc);4923}49244925// MSDN, property (C++)4926// https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx4927// This attribute can also be used in the declaration of an empty array in a4928// class or structure definition. For example:4929// __declspec(property(get=GetX, put=PutX)) int x[];4930// The above statement indicates that x[] can be used with one or more array4931// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),4932// and p->x[a][b] = i will be turned into p->PutX(a, b, i);4933if (IsMSPropertySubscript) {4934assert(ArgExprs.size() == 1);4935// Build MS property subscript expression if base is MS property reference4936// or MS property subscript.4937return new (Context)4938MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,4939VK_LValue, OK_Ordinary, rbLoc);4940}49414942// Use C++ overloaded-operator rules if either operand has record4943// type. The spec says to do this if either type is *overloadable*,4944// but enum types can't declare subscript operators or conversion4945// operators, so there's nothing interesting for overload resolution4946// to do if there aren't any record types involved.4947//4948// ObjC pointers have their own subscripting logic that is not tied4949// to overload resolution and so should not take this path.4950if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&4951((base->getType()->isRecordType() ||4952(ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||4953ArgExprs[0]->getType()->isRecordType())))) {4954return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);4955}49564957ExprResult Res =4958CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);49594960if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))4961CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));49624963return Res;4964}49654966ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {4967InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);4968InitializationKind Kind =4969InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());4970InitializationSequence InitSeq(*this, Entity, Kind, E);4971return InitSeq.Perform(*this, Entity, Kind, E);4972}49734974ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,4975Expr *ColumnIdx,4976SourceLocation RBLoc) {4977ExprResult BaseR = CheckPlaceholderExpr(Base);4978if (BaseR.isInvalid())4979return BaseR;4980Base = BaseR.get();49814982ExprResult RowR = CheckPlaceholderExpr(RowIdx);4983if (RowR.isInvalid())4984return RowR;4985RowIdx = RowR.get();49864987if (!ColumnIdx)4988return new (Context) MatrixSubscriptExpr(4989Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);49904991// Build an unanalyzed expression if any of the operands is type-dependent.4992if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||4993ColumnIdx->isTypeDependent())4994return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,4995Context.DependentTy, RBLoc);49964997ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);4998if (ColumnR.isInvalid())4999return ColumnR;5000ColumnIdx = ColumnR.get();50015002// Check that IndexExpr is an integer expression. If it is a constant5003// expression, check that it is less than Dim (= the number of elements in the5004// corresponding dimension).5005auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,5006bool IsColumnIdx) -> Expr * {5007if (!IndexExpr->getType()->isIntegerType() &&5008!IndexExpr->isTypeDependent()) {5009Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)5010<< IsColumnIdx;5011return nullptr;5012}50135014if (std::optional<llvm::APSInt> Idx =5015IndexExpr->getIntegerConstantExpr(Context)) {5016if ((*Idx < 0 || *Idx >= Dim)) {5017Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)5018<< IsColumnIdx << Dim;5019return nullptr;5020}5021}50225023ExprResult ConvExpr =5024tryConvertExprToType(IndexExpr, Context.getSizeType());5025assert(!ConvExpr.isInvalid() &&5026"should be able to convert any integer type to size type");5027return ConvExpr.get();5028};50295030auto *MTy = Base->getType()->getAs<ConstantMatrixType>();5031RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);5032ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);5033if (!RowIdx || !ColumnIdx)5034return ExprError();50355036return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,5037MTy->getElementType(), RBLoc);5038}50395040void Sema::CheckAddressOfNoDeref(const Expr *E) {5041ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();5042const Expr *StrippedExpr = E->IgnoreParenImpCasts();50435044// For expressions like `&(*s).b`, the base is recorded and what should be5045// checked.5046const MemberExpr *Member = nullptr;5047while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())5048StrippedExpr = Member->getBase()->IgnoreParenImpCasts();50495050LastRecord.PossibleDerefs.erase(StrippedExpr);5051}50525053void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {5054if (isUnevaluatedContext())5055return;50565057QualType ResultTy = E->getType();5058ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();50595060// Bail if the element is an array since it is not memory access.5061if (isa<ArrayType>(ResultTy))5062return;50635064if (ResultTy->hasAttr(attr::NoDeref)) {5065LastRecord.PossibleDerefs.insert(E);5066return;5067}50685069// Check if the base type is a pointer to a member access of a struct5070// marked with noderef.5071const Expr *Base = E->getBase();5072QualType BaseTy = Base->getType();5073if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))5074// Not a pointer access5075return;50765077const MemberExpr *Member = nullptr;5078while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&5079Member->isArrow())5080Base = Member->getBase();50815082if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {5083if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))5084LastRecord.PossibleDerefs.insert(E);5085}5086}50875088ExprResult5089Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,5090Expr *Idx, SourceLocation RLoc) {5091Expr *LHSExp = Base;5092Expr *RHSExp = Idx;50935094ExprValueKind VK = VK_LValue;5095ExprObjectKind OK = OK_Ordinary;50965097// Per C++ core issue 1213, the result is an xvalue if either operand is5098// a non-lvalue array, and an lvalue otherwise.5099if (getLangOpts().CPlusPlus11) {5100for (auto *Op : {LHSExp, RHSExp}) {5101Op = Op->IgnoreImplicit();5102if (Op->getType()->isArrayType() && !Op->isLValue())5103VK = VK_XValue;5104}5105}51065107// Perform default conversions.5108if (!LHSExp->getType()->isSubscriptableVectorType()) {5109ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);5110if (Result.isInvalid())5111return ExprError();5112LHSExp = Result.get();5113}5114ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);5115if (Result.isInvalid())5116return ExprError();5117RHSExp = Result.get();51185119QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();51205121// C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent5122// to the expression *((e1)+(e2)). This means the array "Base" may actually be5123// in the subscript position. As a result, we need to derive the array base5124// and index from the expression types.5125Expr *BaseExpr, *IndexExpr;5126QualType ResultType;5127if (LHSTy->isDependentType() || RHSTy->isDependentType()) {5128BaseExpr = LHSExp;5129IndexExpr = RHSExp;5130ResultType =5131getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());5132} else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {5133BaseExpr = LHSExp;5134IndexExpr = RHSExp;5135ResultType = PTy->getPointeeType();5136} else if (const ObjCObjectPointerType *PTy =5137LHSTy->getAs<ObjCObjectPointerType>()) {5138BaseExpr = LHSExp;5139IndexExpr = RHSExp;51405141// Use custom logic if this should be the pseudo-object subscript5142// expression.5143if (!LangOpts.isSubscriptPointerArithmetic())5144return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,5145nullptr, nullptr);51465147ResultType = PTy->getPointeeType();5148} else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {5149// Handle the uncommon case of "123[Ptr]".5150BaseExpr = RHSExp;5151IndexExpr = LHSExp;5152ResultType = PTy->getPointeeType();5153} else if (const ObjCObjectPointerType *PTy =5154RHSTy->getAs<ObjCObjectPointerType>()) {5155// Handle the uncommon case of "123[Ptr]".5156BaseExpr = RHSExp;5157IndexExpr = LHSExp;5158ResultType = PTy->getPointeeType();5159if (!LangOpts.isSubscriptPointerArithmetic()) {5160Diag(LLoc, diag::err_subscript_nonfragile_interface)5161<< ResultType << BaseExpr->getSourceRange();5162return ExprError();5163}5164} else if (LHSTy->isSubscriptableVectorType()) {5165if (LHSTy->isBuiltinType() &&5166LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {5167const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();5168if (BTy->isSVEBool())5169return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)5170<< LHSExp->getSourceRange()5171<< RHSExp->getSourceRange());5172ResultType = BTy->getSveEltType(Context);5173} else {5174const VectorType *VTy = LHSTy->getAs<VectorType>();5175ResultType = VTy->getElementType();5176}5177BaseExpr = LHSExp; // vectors: V[123]5178IndexExpr = RHSExp;5179// We apply C++ DR1213 to vector subscripting too.5180if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {5181ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);5182if (Materialized.isInvalid())5183return ExprError();5184LHSExp = Materialized.get();5185}5186VK = LHSExp->getValueKind();5187if (VK != VK_PRValue)5188OK = OK_VectorComponent;51895190QualType BaseType = BaseExpr->getType();5191Qualifiers BaseQuals = BaseType.getQualifiers();5192Qualifiers MemberQuals = ResultType.getQualifiers();5193Qualifiers Combined = BaseQuals + MemberQuals;5194if (Combined != MemberQuals)5195ResultType = Context.getQualifiedType(ResultType, Combined);5196} else if (LHSTy->isArrayType()) {5197// If we see an array that wasn't promoted by5198// DefaultFunctionArrayLvalueConversion, it must be an array that5199// wasn't promoted because of the C90 rule that doesn't5200// allow promoting non-lvalue arrays. Warn, then5201// force the promotion here.5202Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)5203<< LHSExp->getSourceRange();5204LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),5205CK_ArrayToPointerDecay).get();5206LHSTy = LHSExp->getType();52075208BaseExpr = LHSExp;5209IndexExpr = RHSExp;5210ResultType = LHSTy->castAs<PointerType>()->getPointeeType();5211} else if (RHSTy->isArrayType()) {5212// Same as previous, except for 123[f().a] case5213Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)5214<< RHSExp->getSourceRange();5215RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),5216CK_ArrayToPointerDecay).get();5217RHSTy = RHSExp->getType();52185219BaseExpr = RHSExp;5220IndexExpr = LHSExp;5221ResultType = RHSTy->castAs<PointerType>()->getPointeeType();5222} else {5223return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)5224<< LHSExp->getSourceRange() << RHSExp->getSourceRange());5225}5226// C99 6.5.2.1p15227if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())5228return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)5229<< IndexExpr->getSourceRange());52305231if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||5232IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&5233!IndexExpr->isTypeDependent()) {5234std::optional<llvm::APSInt> IntegerContantExpr =5235IndexExpr->getIntegerConstantExpr(getASTContext());5236if (!IntegerContantExpr.has_value() ||5237IntegerContantExpr.value().isNegative())5238Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();5239}52405241// C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,5242// C++ [expr.sub]p1: The type "T" shall be a completely-defined object5243// type. Note that Functions are not objects, and that (in C99 parlance)5244// incomplete types are not object types.5245if (ResultType->isFunctionType()) {5246Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)5247<< ResultType << BaseExpr->getSourceRange();5248return ExprError();5249}52505251if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {5252// GNU extension: subscripting on pointer to void5253Diag(LLoc, diag::ext_gnu_subscript_void_type)5254<< BaseExpr->getSourceRange();52555256// C forbids expressions of unqualified void type from being l-values.5257// See IsCForbiddenLValueType.5258if (!ResultType.hasQualifiers())5259VK = VK_PRValue;5260} else if (!ResultType->isDependentType() &&5261!ResultType.isWebAssemblyReferenceType() &&5262RequireCompleteSizedType(5263LLoc, ResultType,5264diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))5265return ExprError();52665267assert(VK == VK_PRValue || LangOpts.CPlusPlus ||5268!ResultType.isCForbiddenLValueType());52695270if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&5271FunctionScopes.size() > 1) {5272if (auto *TT =5273LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {5274for (auto I = FunctionScopes.rbegin(),5275E = std::prev(FunctionScopes.rend());5276I != E; ++I) {5277auto *CSI = dyn_cast<CapturingScopeInfo>(*I);5278if (CSI == nullptr)5279break;5280DeclContext *DC = nullptr;5281if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))5282DC = LSI->CallOperator;5283else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))5284DC = CRSI->TheCapturedDecl;5285else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))5286DC = BSI->TheDecl;5287if (DC) {5288if (DC->containsDecl(TT->getDecl()))5289break;5290captureVariablyModifiedType(5291Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);5292}5293}5294}5295}52965297return new (Context)5298ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);5299}53005301bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,5302ParmVarDecl *Param, Expr *RewrittenInit,5303bool SkipImmediateInvocations) {5304if (Param->hasUnparsedDefaultArg()) {5305assert(!RewrittenInit && "Should not have a rewritten init expression yet");5306// If we've already cleared out the location for the default argument,5307// that means we're parsing it right now.5308if (!UnparsedDefaultArgLocs.count(Param)) {5309Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;5310Diag(CallLoc, diag::note_recursive_default_argument_used_here);5311Param->setInvalidDecl();5312return true;5313}53145315Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)5316<< FD << cast<CXXRecordDecl>(FD->getDeclContext());5317Diag(UnparsedDefaultArgLocs[Param],5318diag::note_default_argument_declared_here);5319return true;5320}53215322if (Param->hasUninstantiatedDefaultArg()) {5323assert(!RewrittenInit && "Should not have a rewitten init expression yet");5324if (InstantiateDefaultArgument(CallLoc, FD, Param))5325return true;5326}53275328Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();5329assert(Init && "default argument but no initializer?");53305331// If the default expression creates temporaries, we need to5332// push them to the current stack of expression temporaries so they'll5333// be properly destroyed.5334// FIXME: We should really be rebuilding the default argument with new5335// bound temporaries; see the comment in PR5810.5336// We don't need to do that with block decls, though, because5337// blocks in default argument expression can never capture anything.5338if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {5339// Set the "needs cleanups" bit regardless of whether there are5340// any explicit objects.5341Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());5342// Append all the objects to the cleanup list. Right now, this5343// should always be a no-op, because blocks in default argument5344// expressions should never be able to capture anything.5345assert(!InitWithCleanup->getNumObjects() &&5346"default argument expression has capturing blocks?");5347}5348// C++ [expr.const]p15.1:5349// An expression or conversion is in an immediate function context if it is5350// potentially evaluated and [...] its innermost enclosing non-block scope5351// is a function parameter scope of an immediate function.5352EnterExpressionEvaluationContext EvalContext(5353*this,5354FD->isImmediateFunction()5355? ExpressionEvaluationContext::ImmediateFunctionContext5356: ExpressionEvaluationContext::PotentiallyEvaluated,5357Param);5358ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =5359SkipImmediateInvocations;5360runWithSufficientStackSpace(CallLoc, [&] {5361MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);5362});5363return false;5364}53655366struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {5367const ASTContext &Context;5368ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}53695370bool HasImmediateCalls = false;5371bool shouldVisitImplicitCode() const { return true; }53725373bool VisitCallExpr(CallExpr *E) {5374if (const FunctionDecl *FD = E->getDirectCallee())5375HasImmediateCalls |= FD->isImmediateFunction();5376return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);5377}53785379bool VisitCXXConstructExpr(CXXConstructExpr *E) {5380if (const FunctionDecl *FD = E->getConstructor())5381HasImmediateCalls |= FD->isImmediateFunction();5382return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);5383}53845385// SourceLocExpr are not immediate invocations5386// but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr5387// need to be rebuilt so that they refer to the correct SourceLocation and5388// DeclContext.5389bool VisitSourceLocExpr(SourceLocExpr *E) {5390HasImmediateCalls = true;5391return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);5392}53935394// A nested lambda might have parameters with immediate invocations5395// in their default arguments.5396// The compound statement is not visited (as it does not constitute a5397// subexpression).5398// FIXME: We should consider visiting and transforming captures5399// with init expressions.5400bool VisitLambdaExpr(LambdaExpr *E) {5401return VisitCXXMethodDecl(E->getCallOperator());5402}54035404bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {5405return TraverseStmt(E->getExpr());5406}54075408bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {5409return TraverseStmt(E->getExpr());5410}5411};54125413struct EnsureImmediateInvocationInDefaultArgs5414: TreeTransform<EnsureImmediateInvocationInDefaultArgs> {5415EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)5416: TreeTransform(SemaRef) {}54175418// Lambda can only have immediate invocations in the default5419// args of their parameters, which is transformed upon calling the closure.5420// The body is not a subexpression, so we have nothing to do.5421// FIXME: Immediate calls in capture initializers should be transformed.5422ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }5423ExprResult TransformBlockExpr(BlockExpr *E) { return E; }54245425// Make sure we don't rebuild the this pointer as it would5426// cause it to incorrectly point it to the outermost class5427// in the case of nested struct initialization.5428ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }54295430// Rewrite to source location to refer to the context in which they are used.5431ExprResult TransformSourceLocExpr(SourceLocExpr *E) {5432DeclContext *DC = E->getParentContext();5433if (DC == SemaRef.CurContext)5434return E;54355436// FIXME: During instantiation, because the rebuild of defaults arguments5437// is not always done in the context of the template instantiator,5438// we run the risk of producing a dependent source location5439// that would never be rebuilt.5440// This usually happens during overload resolution, or in contexts5441// where the value of the source location does not matter.5442// However, we should find a better way to deal with source location5443// of function templates.5444if (!SemaRef.CurrentInstantiationScope ||5445!SemaRef.CurContext->isDependentContext() || DC->isDependentContext())5446DC = SemaRef.CurContext;54475448return getDerived().RebuildSourceLocExpr(5449E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);5450}5451};54525453ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,5454FunctionDecl *FD, ParmVarDecl *Param,5455Expr *Init) {5456assert(Param->hasDefaultArg() && "can't build nonexistent default arg");54575458bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();5459bool InLifetimeExtendingContext = isInLifetimeExtendingContext();5460std::optional<ExpressionEvaluationContextRecord::InitializationContext>5461InitializationContext =5462OutermostDeclarationWithDelayedImmediateInvocations();5463if (!InitializationContext.has_value())5464InitializationContext.emplace(CallLoc, Param, CurContext);54655466if (!Init && !Param->hasUnparsedDefaultArg()) {5467// Mark that we are replacing a default argument first.5468// If we are instantiating a template we won't have to5469// retransform immediate calls.5470// C++ [expr.const]p15.1:5471// An expression or conversion is in an immediate function context if it5472// is potentially evaluated and [...] its innermost enclosing non-block5473// scope is a function parameter scope of an immediate function.5474EnterExpressionEvaluationContext EvalContext(5475*this,5476FD->isImmediateFunction()5477? ExpressionEvaluationContext::ImmediateFunctionContext5478: ExpressionEvaluationContext::PotentiallyEvaluated,5479Param);54805481if (Param->hasUninstantiatedDefaultArg()) {5482if (InstantiateDefaultArgument(CallLoc, FD, Param))5483return ExprError();5484}5485// CWG26315486// An immediate invocation that is not evaluated where it appears is5487// evaluated and checked for whether it is a constant expression at the5488// point where the enclosing initializer is used in a function call.5489ImmediateCallVisitor V(getASTContext());5490if (!NestedDefaultChecking)5491V.TraverseDecl(Param);54925493// Rewrite the call argument that was created from the corresponding5494// parameter's default argument.5495if (V.HasImmediateCalls || InLifetimeExtendingContext) {5496if (V.HasImmediateCalls)5497ExprEvalContexts.back().DelayedDefaultInitializationContext = {5498CallLoc, Param, CurContext};5499// Pass down lifetime extending flag, and collect temporaries in5500// CreateMaterializeTemporaryExpr when we rewrite the call argument.5501keepInLifetimeExtendingContext();5502EnsureImmediateInvocationInDefaultArgs Immediate(*this);5503ExprResult Res;5504runWithSufficientStackSpace(CallLoc, [&] {5505Res = Immediate.TransformInitializer(Param->getInit(),5506/*NotCopy=*/false);5507});5508if (Res.isInvalid())5509return ExprError();5510Res = ConvertParamDefaultArgument(Param, Res.get(),5511Res.get()->getBeginLoc());5512if (Res.isInvalid())5513return ExprError();5514Init = Res.get();5515}5516}55175518if (CheckCXXDefaultArgExpr(5519CallLoc, FD, Param, Init,5520/*SkipImmediateInvocations=*/NestedDefaultChecking))5521return ExprError();55225523return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,5524Init, InitializationContext->Context);5525}55265527ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {5528assert(Field->hasInClassInitializer());55295530// If we might have already tried and failed to instantiate, don't try again.5531if (Field->isInvalidDecl())5532return ExprError();55335534CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());55355536auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());55375538std::optional<ExpressionEvaluationContextRecord::InitializationContext>5539InitializationContext =5540OutermostDeclarationWithDelayedImmediateInvocations();5541if (!InitializationContext.has_value())5542InitializationContext.emplace(Loc, Field, CurContext);55435544Expr *Init = nullptr;55455546bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();55475548EnterExpressionEvaluationContext EvalContext(5549*this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);55505551if (!Field->getInClassInitializer()) {5552// Maybe we haven't instantiated the in-class initializer. Go check the5553// pattern FieldDecl to see if it has one.5554if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {5555CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();5556DeclContext::lookup_result Lookup =5557ClassPattern->lookup(Field->getDeclName());55585559FieldDecl *Pattern = nullptr;5560for (auto *L : Lookup) {5561if ((Pattern = dyn_cast<FieldDecl>(L)))5562break;5563}5564assert(Pattern && "We must have set the Pattern!");5565if (!Pattern->hasInClassInitializer() ||5566InstantiateInClassInitializer(Loc, Field, Pattern,5567getTemplateInstantiationArgs(Field))) {5568Field->setInvalidDecl();5569return ExprError();5570}5571}5572}55735574// CWG26315575// An immediate invocation that is not evaluated where it appears is5576// evaluated and checked for whether it is a constant expression at the5577// point where the enclosing initializer is used in a [...] a constructor5578// definition, or an aggregate initialization.5579ImmediateCallVisitor V(getASTContext());5580if (!NestedDefaultChecking)5581V.TraverseDecl(Field);5582if (V.HasImmediateCalls) {5583ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,5584CurContext};5585ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =5586NestedDefaultChecking;55875588EnsureImmediateInvocationInDefaultArgs Immediate(*this);5589ExprResult Res;5590runWithSufficientStackSpace(Loc, [&] {5591Res = Immediate.TransformInitializer(Field->getInClassInitializer(),5592/*CXXDirectInit=*/false);5593});5594if (!Res.isInvalid())5595Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);5596if (Res.isInvalid()) {5597Field->setInvalidDecl();5598return ExprError();5599}5600Init = Res.get();5601}56025603if (Field->getInClassInitializer()) {5604Expr *E = Init ? Init : Field->getInClassInitializer();5605if (!NestedDefaultChecking)5606runWithSufficientStackSpace(Loc, [&] {5607MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);5608});5609// C++11 [class.base.init]p7:5610// The initialization of each base and member constitutes a5611// full-expression.5612ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);5613if (Res.isInvalid()) {5614Field->setInvalidDecl();5615return ExprError();5616}5617Init = Res.get();56185619return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,5620Field, InitializationContext->Context,5621Init);5622}56235624// DR1351:5625// If the brace-or-equal-initializer of a non-static data member5626// invokes a defaulted default constructor of its class or of an5627// enclosing class in a potentially evaluated subexpression, the5628// program is ill-formed.5629//5630// This resolution is unworkable: the exception specification of the5631// default constructor can be needed in an unevaluated context, in5632// particular, in the operand of a noexcept-expression, and we can be5633// unable to compute an exception specification for an enclosed class.5634//5635// Any attempt to resolve the exception specification of a defaulted default5636// constructor before the initializer is lexically complete will ultimately5637// come here at which point we can diagnose it.5638RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();5639Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)5640<< OutermostClass << Field;5641Diag(Field->getEndLoc(),5642diag::note_default_member_initializer_not_yet_parsed);5643// Recover by marking the field invalid, unless we're in a SFINAE context.5644if (!isSFINAEContext())5645Field->setInvalidDecl();5646return ExprError();5647}56485649Sema::VariadicCallType5650Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,5651Expr *Fn) {5652if (Proto && Proto->isVariadic()) {5653if (isa_and_nonnull<CXXConstructorDecl>(FDecl))5654return VariadicConstructor;5655else if (Fn && Fn->getType()->isBlockPointerType())5656return VariadicBlock;5657else if (FDecl) {5658if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))5659if (Method->isInstance())5660return VariadicMethod;5661} else if (Fn && Fn->getType() == Context.BoundMemberTy)5662return VariadicMethod;5663return VariadicFunction;5664}5665return VariadicDoesNotApply;5666}56675668namespace {5669class FunctionCallCCC final : public FunctionCallFilterCCC {5670public:5671FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,5672unsigned NumArgs, MemberExpr *ME)5673: FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),5674FunctionName(FuncName) {}56755676bool ValidateCandidate(const TypoCorrection &candidate) override {5677if (!candidate.getCorrectionSpecifier() ||5678candidate.getCorrectionAsIdentifierInfo() != FunctionName) {5679return false;5680}56815682return FunctionCallFilterCCC::ValidateCandidate(candidate);5683}56845685std::unique_ptr<CorrectionCandidateCallback> clone() override {5686return std::make_unique<FunctionCallCCC>(*this);5687}56885689private:5690const IdentifierInfo *const FunctionName;5691};5692}56935694static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,5695FunctionDecl *FDecl,5696ArrayRef<Expr *> Args) {5697MemberExpr *ME = dyn_cast<MemberExpr>(Fn);5698DeclarationName FuncName = FDecl->getDeclName();5699SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();57005701FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);5702if (TypoCorrection Corrected = S.CorrectTypo(5703DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,5704S.getScopeForContext(S.CurContext), nullptr, CCC,5705Sema::CTK_ErrorRecovery)) {5706if (NamedDecl *ND = Corrected.getFoundDecl()) {5707if (Corrected.isOverloaded()) {5708OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);5709OverloadCandidateSet::iterator Best;5710for (NamedDecl *CD : Corrected) {5711if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))5712S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,5713OCS);5714}5715switch (OCS.BestViableFunction(S, NameLoc, Best)) {5716case OR_Success:5717ND = Best->FoundDecl;5718Corrected.setCorrectionDecl(ND);5719break;5720default:5721break;5722}5723}5724ND = ND->getUnderlyingDecl();5725if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))5726return Corrected;5727}5728}5729return TypoCorrection();5730}57315732// [C++26][[expr.unary.op]/p45733// A pointer to member is only formed when an explicit &5734// is used and its operand is a qualified-id not enclosed in parentheses.5735static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {5736if (!isa<ParenExpr>(Fn))5737return false;57385739Fn = Fn->IgnoreParens();57405741auto *UO = dyn_cast<UnaryOperator>(Fn);5742if (!UO || UO->getOpcode() != clang::UO_AddrOf)5743return false;5744if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {5745return DRE->hasQualifier();5746}5747if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))5748return OVL->getQualifier();5749return false;5750}57515752bool5753Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,5754FunctionDecl *FDecl,5755const FunctionProtoType *Proto,5756ArrayRef<Expr *> Args,5757SourceLocation RParenLoc,5758bool IsExecConfig) {5759// Bail out early if calling a builtin with custom typechecking.5760if (FDecl)5761if (unsigned ID = FDecl->getBuiltinID())5762if (Context.BuiltinInfo.hasCustomTypechecking(ID))5763return false;57645765// C99 6.5.2.2p7 - the arguments are implicitly converted, as if by5766// assignment, to the types of the corresponding parameter, ...57675768bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);5769bool HasExplicitObjectParameter =5770!AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();5771unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;5772unsigned NumParams = Proto->getNumParams();5773bool Invalid = false;5774unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;5775unsigned FnKind = Fn->getType()->isBlockPointerType()5776? 1 /* block */5777: (IsExecConfig ? 3 /* kernel function (exec config) */5778: 0 /* function */);57795780// If too few arguments are available (and we don't have default5781// arguments for the remaining parameters), don't make the call.5782if (Args.size() < NumParams) {5783if (Args.size() < MinArgs) {5784TypoCorrection TC;5785if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {5786unsigned diag_id =5787MinArgs == NumParams && !Proto->isVariadic()5788? diag::err_typecheck_call_too_few_args_suggest5789: diag::err_typecheck_call_too_few_args_at_least_suggest;5790diagnoseTypo(5791TC, PDiag(diag_id)5792<< FnKind << MinArgs - ExplicitObjectParameterOffset5793<< static_cast<unsigned>(Args.size()) -5794ExplicitObjectParameterOffset5795<< HasExplicitObjectParameter << TC.getCorrectionRange());5796} else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&5797FDecl->getParamDecl(ExplicitObjectParameterOffset)5798->getDeclName())5799Diag(RParenLoc,5800MinArgs == NumParams && !Proto->isVariadic()5801? diag::err_typecheck_call_too_few_args_one5802: diag::err_typecheck_call_too_few_args_at_least_one)5803<< FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)5804<< HasExplicitObjectParameter << Fn->getSourceRange();5805else5806Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()5807? diag::err_typecheck_call_too_few_args5808: diag::err_typecheck_call_too_few_args_at_least)5809<< FnKind << MinArgs - ExplicitObjectParameterOffset5810<< static_cast<unsigned>(Args.size()) -5811ExplicitObjectParameterOffset5812<< HasExplicitObjectParameter << Fn->getSourceRange();58135814// Emit the location of the prototype.5815if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)5816Diag(FDecl->getLocation(), diag::note_callee_decl)5817<< FDecl << FDecl->getParametersSourceRange();58185819return true;5820}5821// We reserve space for the default arguments when we create5822// the call expression, before calling ConvertArgumentsForCall.5823assert((Call->getNumArgs() == NumParams) &&5824"We should have reserved space for the default arguments before!");5825}58265827// If too many are passed and not variadic, error on the extras and drop5828// them.5829if (Args.size() > NumParams) {5830if (!Proto->isVariadic()) {5831TypoCorrection TC;5832if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {5833unsigned diag_id =5834MinArgs == NumParams && !Proto->isVariadic()5835? diag::err_typecheck_call_too_many_args_suggest5836: diag::err_typecheck_call_too_many_args_at_most_suggest;5837diagnoseTypo(5838TC, PDiag(diag_id)5839<< FnKind << NumParams - ExplicitObjectParameterOffset5840<< static_cast<unsigned>(Args.size()) -5841ExplicitObjectParameterOffset5842<< HasExplicitObjectParameter << TC.getCorrectionRange());5843} else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&5844FDecl->getParamDecl(ExplicitObjectParameterOffset)5845->getDeclName())5846Diag(Args[NumParams]->getBeginLoc(),5847MinArgs == NumParams5848? diag::err_typecheck_call_too_many_args_one5849: diag::err_typecheck_call_too_many_args_at_most_one)5850<< FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)5851<< static_cast<unsigned>(Args.size()) -5852ExplicitObjectParameterOffset5853<< HasExplicitObjectParameter << Fn->getSourceRange()5854<< SourceRange(Args[NumParams]->getBeginLoc(),5855Args.back()->getEndLoc());5856else5857Diag(Args[NumParams]->getBeginLoc(),5858MinArgs == NumParams5859? diag::err_typecheck_call_too_many_args5860: diag::err_typecheck_call_too_many_args_at_most)5861<< FnKind << NumParams - ExplicitObjectParameterOffset5862<< static_cast<unsigned>(Args.size()) -5863ExplicitObjectParameterOffset5864<< HasExplicitObjectParameter << Fn->getSourceRange()5865<< SourceRange(Args[NumParams]->getBeginLoc(),5866Args.back()->getEndLoc());58675868// Emit the location of the prototype.5869if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)5870Diag(FDecl->getLocation(), diag::note_callee_decl)5871<< FDecl << FDecl->getParametersSourceRange();58725873// This deletes the extra arguments.5874Call->shrinkNumArgs(NumParams);5875return true;5876}5877}5878SmallVector<Expr *, 8> AllArgs;5879VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);58805881Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,5882AllArgs, CallType);5883if (Invalid)5884return true;5885unsigned TotalNumArgs = AllArgs.size();5886for (unsigned i = 0; i < TotalNumArgs; ++i)5887Call->setArg(i, AllArgs[i]);58885889Call->computeDependence();5890return false;5891}58925893bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,5894const FunctionProtoType *Proto,5895unsigned FirstParam, ArrayRef<Expr *> Args,5896SmallVectorImpl<Expr *> &AllArgs,5897VariadicCallType CallType, bool AllowExplicit,5898bool IsListInitialization) {5899unsigned NumParams = Proto->getNumParams();5900bool Invalid = false;5901size_t ArgIx = 0;5902// Continue to check argument types (even if we have too few/many args).5903for (unsigned i = FirstParam; i < NumParams; i++) {5904QualType ProtoArgType = Proto->getParamType(i);59055906Expr *Arg;5907ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;5908if (ArgIx < Args.size()) {5909Arg = Args[ArgIx++];59105911if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,5912diag::err_call_incomplete_argument, Arg))5913return true;59145915// Strip the unbridged-cast placeholder expression off, if applicable.5916bool CFAudited = false;5917if (Arg->getType() == Context.ARCUnbridgedCastTy &&5918FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&5919(!Param || !Param->hasAttr<CFConsumedAttr>()))5920Arg = ObjC().stripARCUnbridgedCast(Arg);5921else if (getLangOpts().ObjCAutoRefCount &&5922FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&5923(!Param || !Param->hasAttr<CFConsumedAttr>()))5924CFAudited = true;59255926if (Proto->getExtParameterInfo(i).isNoEscape() &&5927ProtoArgType->isBlockPointerType())5928if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))5929BE->getBlockDecl()->setDoesNotEscape();59305931InitializedEntity Entity =5932Param ? InitializedEntity::InitializeParameter(Context, Param,5933ProtoArgType)5934: InitializedEntity::InitializeParameter(5935Context, ProtoArgType, Proto->isParamConsumed(i));59365937// Remember that parameter belongs to a CF audited API.5938if (CFAudited)5939Entity.setParameterCFAudited();59405941ExprResult ArgE = PerformCopyInitialization(5942Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);5943if (ArgE.isInvalid())5944return true;59455946Arg = ArgE.getAs<Expr>();5947} else {5948assert(Param && "can't use default arguments without a known callee");59495950ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);5951if (ArgExpr.isInvalid())5952return true;59535954Arg = ArgExpr.getAs<Expr>();5955}59565957// Check for array bounds violations for each argument to the call. This5958// check only triggers warnings when the argument isn't a more complex Expr5959// with its own checking, such as a BinaryOperator.5960CheckArrayAccess(Arg);59615962// Check for violations of C99 static array rules (C99 6.7.5.3p7).5963CheckStaticArrayArgument(CallLoc, Param, Arg);59645965AllArgs.push_back(Arg);5966}59675968// If this is a variadic call, handle args passed through "...".5969if (CallType != VariadicDoesNotApply) {5970// Assume that extern "C" functions with variadic arguments that5971// return __unknown_anytype aren't *really* variadic.5972if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&5973FDecl->isExternC()) {5974for (Expr *A : Args.slice(ArgIx)) {5975QualType paramType; // ignored5976ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);5977Invalid |= arg.isInvalid();5978AllArgs.push_back(arg.get());5979}59805981// Otherwise do argument promotion, (C99 6.5.2.2p7).5982} else {5983for (Expr *A : Args.slice(ArgIx)) {5984ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);5985Invalid |= Arg.isInvalid();5986AllArgs.push_back(Arg.get());5987}5988}59895990// Check for array bounds violations.5991for (Expr *A : Args.slice(ArgIx))5992CheckArrayAccess(A);5993}5994return Invalid;5995}59965997static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {5998TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();5999if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())6000TL = DTL.getOriginalLoc();6001if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())6002S.Diag(PVD->getLocation(), diag::note_callee_static_array)6003<< ATL.getLocalSourceRange();6004}60056006void6007Sema::CheckStaticArrayArgument(SourceLocation CallLoc,6008ParmVarDecl *Param,6009const Expr *ArgExpr) {6010// Static array parameters are not supported in C++.6011if (!Param || getLangOpts().CPlusPlus)6012return;60136014QualType OrigTy = Param->getOriginalType();60156016const ArrayType *AT = Context.getAsArrayType(OrigTy);6017if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)6018return;60196020if (ArgExpr->isNullPointerConstant(Context,6021Expr::NPC_NeverValueDependent)) {6022Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();6023DiagnoseCalleeStaticArrayParam(*this, Param);6024return;6025}60266027const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);6028if (!CAT)6029return;60306031const ConstantArrayType *ArgCAT =6032Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());6033if (!ArgCAT)6034return;60356036if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),6037ArgCAT->getElementType())) {6038if (ArgCAT->getSize().ult(CAT->getSize())) {6039Diag(CallLoc, diag::warn_static_array_too_small)6040<< ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()6041<< (unsigned)CAT->getZExtSize() << 0;6042DiagnoseCalleeStaticArrayParam(*this, Param);6043}6044return;6045}60466047std::optional<CharUnits> ArgSize =6048getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);6049std::optional<CharUnits> ParmSize =6050getASTContext().getTypeSizeInCharsIfKnown(CAT);6051if (ArgSize && ParmSize && *ArgSize < *ParmSize) {6052Diag(CallLoc, diag::warn_static_array_too_small)6053<< ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()6054<< (unsigned)ParmSize->getQuantity() << 1;6055DiagnoseCalleeStaticArrayParam(*this, Param);6056}6057}60586059/// Given a function expression of unknown-any type, try to rebuild it6060/// to have a function type.6061static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);60626063/// Is the given type a placeholder that we need to lower out6064/// immediately during argument processing?6065static bool isPlaceholderToRemoveAsArg(QualType type) {6066// Placeholders are never sugared.6067const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);6068if (!placeholder) return false;60696070switch (placeholder->getKind()) {6071// Ignore all the non-placeholder types.6072#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \6073case BuiltinType::Id:6074#include "clang/Basic/OpenCLImageTypes.def"6075#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \6076case BuiltinType::Id:6077#include "clang/Basic/OpenCLExtensionTypes.def"6078// In practice we'll never use this, since all SVE types are sugared6079// via TypedefTypes rather than exposed directly as BuiltinTypes.6080#define SVE_TYPE(Name, Id, SingletonId) \6081case BuiltinType::Id:6082#include "clang/Basic/AArch64SVEACLETypes.def"6083#define PPC_VECTOR_TYPE(Name, Id, Size) \6084case BuiltinType::Id:6085#include "clang/Basic/PPCTypes.def"6086#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:6087#include "clang/Basic/RISCVVTypes.def"6088#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:6089#include "clang/Basic/WebAssemblyReferenceTypes.def"6090#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:6091#include "clang/Basic/AMDGPUTypes.def"6092#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)6093#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:6094#include "clang/AST/BuiltinTypes.def"6095return false;60966097case BuiltinType::UnresolvedTemplate:6098// We cannot lower out overload sets; they might validly be resolved6099// by the call machinery.6100case BuiltinType::Overload:6101return false;61026103// Unbridged casts in ARC can be handled in some call positions and6104// should be left in place.6105case BuiltinType::ARCUnbridgedCast:6106return false;61076108// Pseudo-objects should be converted as soon as possible.6109case BuiltinType::PseudoObject:6110return true;61116112// The debugger mode could theoretically but currently does not try6113// to resolve unknown-typed arguments based on known parameter types.6114case BuiltinType::UnknownAny:6115return true;61166117// These are always invalid as call arguments and should be reported.6118case BuiltinType::BoundMember:6119case BuiltinType::BuiltinFn:6120case BuiltinType::IncompleteMatrixIdx:6121case BuiltinType::ArraySection:6122case BuiltinType::OMPArrayShaping:6123case BuiltinType::OMPIterator:6124return true;61256126}6127llvm_unreachable("bad builtin type kind");6128}61296130bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {6131// Apply this processing to all the arguments at once instead of6132// dying at the first failure.6133bool hasInvalid = false;6134for (size_t i = 0, e = args.size(); i != e; i++) {6135if (isPlaceholderToRemoveAsArg(args[i]->getType())) {6136ExprResult result = CheckPlaceholderExpr(args[i]);6137if (result.isInvalid()) hasInvalid = true;6138else args[i] = result.get();6139}6140}6141return hasInvalid;6142}61436144/// If a builtin function has a pointer argument with no explicit address6145/// space, then it should be able to accept a pointer to any address6146/// space as input. In order to do this, we need to replace the6147/// standard builtin declaration with one that uses the same address space6148/// as the call.6149///6150/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.6151/// it does not contain any pointer arguments without6152/// an address space qualifer. Otherwise the rewritten6153/// FunctionDecl is returned.6154/// TODO: Handle pointer return types.6155static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,6156FunctionDecl *FDecl,6157MultiExprArg ArgExprs) {61586159QualType DeclType = FDecl->getType();6160const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);61616162if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||6163ArgExprs.size() < FT->getNumParams())6164return nullptr;61656166bool NeedsNewDecl = false;6167unsigned i = 0;6168SmallVector<QualType, 8> OverloadParams;61696170for (QualType ParamType : FT->param_types()) {61716172// Convert array arguments to pointer to simplify type lookup.6173ExprResult ArgRes =6174Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);6175if (ArgRes.isInvalid())6176return nullptr;6177Expr *Arg = ArgRes.get();6178QualType ArgType = Arg->getType();6179if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||6180!ArgType->isPointerType() ||6181!ArgType->getPointeeType().hasAddressSpace() ||6182isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {6183OverloadParams.push_back(ParamType);6184continue;6185}61866187QualType PointeeType = ParamType->getPointeeType();6188if (PointeeType.hasAddressSpace())6189continue;61906191NeedsNewDecl = true;6192LangAS AS = ArgType->getPointeeType().getAddressSpace();61936194PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);6195OverloadParams.push_back(Context.getPointerType(PointeeType));6196}61976198if (!NeedsNewDecl)6199return nullptr;62006201FunctionProtoType::ExtProtoInfo EPI;6202EPI.Variadic = FT->isVariadic();6203QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),6204OverloadParams, EPI);6205DeclContext *Parent = FDecl->getParent();6206FunctionDecl *OverloadDecl = FunctionDecl::Create(6207Context, Parent, FDecl->getLocation(), FDecl->getLocation(),6208FDecl->getIdentifier(), OverloadTy,6209/*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),6210false,6211/*hasPrototype=*/true);6212SmallVector<ParmVarDecl*, 16> Params;6213FT = cast<FunctionProtoType>(OverloadTy);6214for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {6215QualType ParamType = FT->getParamType(i);6216ParmVarDecl *Parm =6217ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),6218SourceLocation(), nullptr, ParamType,6219/*TInfo=*/nullptr, SC_None, nullptr);6220Parm->setScopeInfo(0, i);6221Params.push_back(Parm);6222}6223OverloadDecl->setParams(Params);6224Sema->mergeDeclAttributes(OverloadDecl, FDecl);6225return OverloadDecl;6226}62276228static void checkDirectCallValidity(Sema &S, const Expr *Fn,6229FunctionDecl *Callee,6230MultiExprArg ArgExprs) {6231// `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and6232// similar attributes) really don't like it when functions are called with an6233// invalid number of args.6234if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),6235/*PartialOverloading=*/false) &&6236!Callee->isVariadic())6237return;6238if (Callee->getMinRequiredArguments() > ArgExprs.size())6239return;62406241if (const EnableIfAttr *Attr =6242S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {6243S.Diag(Fn->getBeginLoc(),6244isa<CXXMethodDecl>(Callee)6245? diag::err_ovl_no_viable_member_function_in_call6246: diag::err_ovl_no_viable_function_in_call)6247<< Callee << Callee->getSourceRange();6248S.Diag(Callee->getLocation(),6249diag::note_ovl_candidate_disabled_by_function_cond_attr)6250<< Attr->getCond()->getSourceRange() << Attr->getMessage();6251return;6252}6253}62546255static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(6256const UnresolvedMemberExpr *const UME, Sema &S) {62576258const auto GetFunctionLevelDCIfCXXClass =6259[](Sema &S) -> const CXXRecordDecl * {6260const DeclContext *const DC = S.getFunctionLevelDeclContext();6261if (!DC || !DC->getParent())6262return nullptr;62636264// If the call to some member function was made from within a member6265// function body 'M' return return 'M's parent.6266if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))6267return MD->getParent()->getCanonicalDecl();6268// else the call was made from within a default member initializer of a6269// class, so return the class.6270if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))6271return RD->getCanonicalDecl();6272return nullptr;6273};6274// If our DeclContext is neither a member function nor a class (in the6275// case of a lambda in a default member initializer), we can't have an6276// enclosing 'this'.62776278const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);6279if (!CurParentClass)6280return false;62816282// The naming class for implicit member functions call is the class in which6283// name lookup starts.6284const CXXRecordDecl *const NamingClass =6285UME->getNamingClass()->getCanonicalDecl();6286assert(NamingClass && "Must have naming class even for implicit access");62876288// If the unresolved member functions were found in a 'naming class' that is6289// related (either the same or derived from) to the class that contains the6290// member function that itself contained the implicit member access.62916292return CurParentClass == NamingClass ||6293CurParentClass->isDerivedFrom(NamingClass);6294}62956296static void6297tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(6298Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {62996300if (!UME)6301return;63026303LambdaScopeInfo *const CurLSI = S.getCurLambda();6304// Only try and implicitly capture 'this' within a C++ Lambda if it hasn't6305// already been captured, or if this is an implicit member function call (if6306// it isn't, an attempt to capture 'this' should already have been made).6307if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||6308!UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())6309return;63106311// Check if the naming class in which the unresolved members were found is6312// related (same as or is a base of) to the enclosing class.63136314if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))6315return;631663176318DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();6319// If the enclosing function is not dependent, then this lambda is6320// capture ready, so if we can capture this, do so.6321if (!EnclosingFunctionCtx->isDependentContext()) {6322// If the current lambda and all enclosing lambdas can capture 'this' -6323// then go ahead and capture 'this' (since our unresolved overload set6324// contains at least one non-static member function).6325if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))6326S.CheckCXXThisCapture(CallLoc);6327} else if (S.CurContext->isDependentContext()) {6328// ... since this is an implicit member reference, that might potentially6329// involve a 'this' capture, mark 'this' for potential capture in6330// enclosing lambdas.6331if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)6332CurLSI->addPotentialThisCapture(CallLoc);6333}6334}63356336// Once a call is fully resolved, warn for unqualified calls to specific6337// C++ standard functions, like move and forward.6338static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,6339const CallExpr *Call) {6340// We are only checking unary move and forward so exit early here.6341if (Call->getNumArgs() != 1)6342return;63436344const Expr *E = Call->getCallee()->IgnoreParenImpCasts();6345if (!E || isa<UnresolvedLookupExpr>(E))6346return;6347const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);6348if (!DRE || !DRE->getLocation().isValid())6349return;63506351if (DRE->getQualifier())6352return;63536354const FunctionDecl *FD = Call->getDirectCallee();6355if (!FD)6356return;63576358// Only warn for some functions deemed more frequent or problematic.6359unsigned BuiltinID = FD->getBuiltinID();6360if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)6361return;63626363S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)6364<< FD->getQualifiedNameAsString()6365<< FixItHint::CreateInsertion(DRE->getLocation(), "std::");6366}63676368ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,6369MultiExprArg ArgExprs, SourceLocation RParenLoc,6370Expr *ExecConfig) {6371ExprResult Call =6372BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,6373/*IsExecConfig=*/false, /*AllowRecovery=*/true);6374if (Call.isInvalid())6375return Call;63766377// Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier6378// language modes.6379if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);6380ULE && ULE->hasExplicitTemplateArgs() &&6381ULE->decls_begin() == ULE->decls_end()) {6382Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus206383? diag::warn_cxx17_compat_adl_only_template_id6384: diag::ext_adl_only_template_id)6385<< ULE->getName();6386}63876388if (LangOpts.OpenMP)6389Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,6390ExecConfig);6391if (LangOpts.CPlusPlus) {6392if (const auto *CE = dyn_cast<CallExpr>(Call.get()))6393DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);63946395// If we previously found that the id-expression of this call refers to a6396// consteval function but the call is dependent, we should not treat is an6397// an invalid immediate call.6398if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());6399DRE && Call.get()->isValueDependent()) {6400currentEvaluationContext().ReferenceToConsteval.erase(DRE);6401}6402}6403return Call;6404}64056406ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,6407MultiExprArg ArgExprs, SourceLocation RParenLoc,6408Expr *ExecConfig, bool IsExecConfig,6409bool AllowRecovery) {6410// Since this might be a postfix expression, get rid of ParenListExprs.6411ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);6412if (Result.isInvalid()) return ExprError();6413Fn = Result.get();64146415if (CheckArgsForPlaceholders(ArgExprs))6416return ExprError();64176418if (getLangOpts().CPlusPlus) {6419// If this is a pseudo-destructor expression, build the call immediately.6420if (isa<CXXPseudoDestructorExpr>(Fn)) {6421if (!ArgExprs.empty()) {6422// Pseudo-destructor calls should not have any arguments.6423Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)6424<< FixItHint::CreateRemoval(6425SourceRange(ArgExprs.front()->getBeginLoc(),6426ArgExprs.back()->getEndLoc()));6427}64286429return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,6430VK_PRValue, RParenLoc, CurFPFeatureOverrides());6431}6432if (Fn->getType() == Context.PseudoObjectTy) {6433ExprResult result = CheckPlaceholderExpr(Fn);6434if (result.isInvalid()) return ExprError();6435Fn = result.get();6436}64376438// Determine whether this is a dependent call inside a C++ template,6439// in which case we won't do any semantic analysis now.6440if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {6441if (ExecConfig) {6442return CUDAKernelCallExpr::Create(Context, Fn,6443cast<CallExpr>(ExecConfig), ArgExprs,6444Context.DependentTy, VK_PRValue,6445RParenLoc, CurFPFeatureOverrides());6446} else {64476448tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(6449*this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),6450Fn->getBeginLoc());64516452return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,6453VK_PRValue, RParenLoc, CurFPFeatureOverrides());6454}6455}64566457// Determine whether this is a call to an object (C++ [over.call.object]).6458if (Fn->getType()->isRecordType())6459return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,6460RParenLoc);64616462if (Fn->getType() == Context.UnknownAnyTy) {6463ExprResult result = rebuildUnknownAnyFunction(*this, Fn);6464if (result.isInvalid()) return ExprError();6465Fn = result.get();6466}64676468if (Fn->getType() == Context.BoundMemberTy) {6469return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,6470RParenLoc, ExecConfig, IsExecConfig,6471AllowRecovery);6472}6473}64746475// Check for overloaded calls. This can happen even in C due to extensions.6476if (Fn->getType() == Context.OverloadTy) {6477OverloadExpr::FindResult find = OverloadExpr::find(Fn);64786479// We aren't supposed to apply this logic if there's an '&' involved.6480if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {6481if (Expr::hasAnyTypeDependentArguments(ArgExprs))6482return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,6483VK_PRValue, RParenLoc, CurFPFeatureOverrides());6484OverloadExpr *ovl = find.Expression;6485if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))6486return BuildOverloadedCallExpr(6487Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,6488/*AllowTypoCorrection=*/true, find.IsAddressOfOperand);6489return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,6490RParenLoc, ExecConfig, IsExecConfig,6491AllowRecovery);6492}6493}64946495// If we're directly calling a function, get the appropriate declaration.6496if (Fn->getType() == Context.UnknownAnyTy) {6497ExprResult result = rebuildUnknownAnyFunction(*this, Fn);6498if (result.isInvalid()) return ExprError();6499Fn = result.get();6500}65016502Expr *NakedFn = Fn->IgnoreParens();65036504bool CallingNDeclIndirectly = false;6505NamedDecl *NDecl = nullptr;6506if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {6507if (UnOp->getOpcode() == UO_AddrOf) {6508CallingNDeclIndirectly = true;6509NakedFn = UnOp->getSubExpr()->IgnoreParens();6510}6511}65126513if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {6514NDecl = DRE->getDecl();65156516FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);6517if (FDecl && FDecl->getBuiltinID()) {6518// Rewrite the function decl for this builtin by replacing parameters6519// with no explicit address space with the address space of the arguments6520// in ArgExprs.6521if ((FDecl =6522rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {6523NDecl = FDecl;6524Fn = DeclRefExpr::Create(6525Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,6526SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,6527nullptr, DRE->isNonOdrUse());6528}6529}6530} else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))6531NDecl = ME->getMemberDecl();65326533if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {6534if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(6535FD, /*Complain=*/true, Fn->getBeginLoc()))6536return ExprError();65376538checkDirectCallValidity(*this, Fn, FD, ArgExprs);65396540// If this expression is a call to a builtin function in HIP device6541// compilation, allow a pointer-type argument to default address space to be6542// passed as a pointer-type parameter to a non-default address space.6543// If Arg is declared in the default address space and Param is declared6544// in a non-default address space, perform an implicit address space cast to6545// the parameter type.6546if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&6547FD->getBuiltinID()) {6548for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();6549++Idx) {6550ParmVarDecl *Param = FD->getParamDecl(Idx);6551if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||6552!ArgExprs[Idx]->getType()->isPointerType())6553continue;65546555auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();6556auto ArgTy = ArgExprs[Idx]->getType();6557auto ArgPtTy = ArgTy->getPointeeType();6558auto ArgAS = ArgPtTy.getAddressSpace();65596560// Add address space cast if target address spaces are different6561bool NeedImplicitASC =6562ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.6563( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS6564// or from specific AS which has target AS matching that of Param.6565getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));6566if (!NeedImplicitASC)6567continue;65686569// First, ensure that the Arg is an RValue.6570if (ArgExprs[Idx]->isGLValue()) {6571ArgExprs[Idx] = ImplicitCastExpr::Create(6572Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],6573nullptr, VK_PRValue, FPOptionsOverride());6574}65756576// Construct a new arg type with address space of Param6577Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();6578ArgPtQuals.setAddressSpace(ParamAS);6579auto NewArgPtTy =6580Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);6581auto NewArgTy =6582Context.getQualifiedType(Context.getPointerType(NewArgPtTy),6583ArgTy.getQualifiers());65846585// Finally perform an implicit address space cast6586ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,6587CK_AddressSpaceConversion)6588.get();6589}6590}6591}65926593if (Context.isDependenceAllowed() &&6594(Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {6595assert(!getLangOpts().CPlusPlus);6596assert((Fn->containsErrors() ||6597llvm::any_of(ArgExprs,6598[](clang::Expr *E) { return E->containsErrors(); })) &&6599"should only occur in error-recovery path.");6600return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,6601VK_PRValue, RParenLoc, CurFPFeatureOverrides());6602}6603return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,6604ExecConfig, IsExecConfig);6605}66066607Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,6608MultiExprArg CallArgs) {6609StringRef Name = Context.BuiltinInfo.getName(Id);6610LookupResult R(*this, &Context.Idents.get(Name), Loc,6611Sema::LookupOrdinaryName);6612LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);66136614auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();6615assert(BuiltInDecl && "failed to find builtin declaration");66166617ExprResult DeclRef =6618BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);6619assert(DeclRef.isUsable() && "Builtin reference cannot fail");66206621ExprResult Call =6622BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);66236624assert(!Call.isInvalid() && "Call to builtin cannot fail!");6625return Call.get();6626}66276628ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,6629SourceLocation BuiltinLoc,6630SourceLocation RParenLoc) {6631QualType DstTy = GetTypeFromParser(ParsedDestTy);6632return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);6633}66346635ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,6636SourceLocation BuiltinLoc,6637SourceLocation RParenLoc) {6638ExprValueKind VK = VK_PRValue;6639ExprObjectKind OK = OK_Ordinary;6640QualType SrcTy = E->getType();6641if (!SrcTy->isDependentType() &&6642Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))6643return ExprError(6644Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)6645<< DestTy << SrcTy << E->getSourceRange());6646return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);6647}66486649ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,6650SourceLocation BuiltinLoc,6651SourceLocation RParenLoc) {6652TypeSourceInfo *TInfo;6653GetTypeFromParser(ParsedDestTy, &TInfo);6654return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);6655}66566657ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,6658SourceLocation LParenLoc,6659ArrayRef<Expr *> Args,6660SourceLocation RParenLoc, Expr *Config,6661bool IsExecConfig, ADLCallKind UsesADL) {6662FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);6663unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);66646665// Functions with 'interrupt' attribute cannot be called directly.6666if (FDecl) {6667if (FDecl->hasAttr<AnyX86InterruptAttr>()) {6668Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);6669return ExprError();6670}6671if (FDecl->hasAttr<ARMInterruptAttr>()) {6672Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);6673return ExprError();6674}6675}66766677// X86 interrupt handlers may only call routines with attribute6678// no_caller_saved_registers since there is no efficient way to6679// save and restore the non-GPR state.6680if (auto *Caller = getCurFunctionDecl()) {6681if (Caller->hasAttr<AnyX86InterruptAttr>() ||6682Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {6683const TargetInfo &TI = Context.getTargetInfo();6684bool HasNonGPRRegisters =6685TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");6686if (HasNonGPRRegisters &&6687(!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {6688Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)6689<< (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);6690if (FDecl)6691Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;6692}6693}6694}66956696// Promote the function operand.6697// We special-case function promotion here because we only allow promoting6698// builtin functions to function pointers in the callee of a call.6699ExprResult Result;6700QualType ResultTy;6701if (BuiltinID &&6702Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {6703// Extract the return type from the (builtin) function pointer type.6704// FIXME Several builtins still have setType in6705// Sema::CheckBuiltinFunctionCall. One should review their definitions in6706// Builtins.td to ensure they are correct before removing setType calls.6707QualType FnPtrTy = Context.getPointerType(FDecl->getType());6708Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();6709ResultTy = FDecl->getCallResultType();6710} else {6711Result = CallExprUnaryConversions(Fn);6712ResultTy = Context.BoolTy;6713}6714if (Result.isInvalid())6715return ExprError();6716Fn = Result.get();67176718// Check for a valid function type, but only if it is not a builtin which6719// requires custom type checking. These will be handled by6720// CheckBuiltinFunctionCall below just after creation of the call expression.6721const FunctionType *FuncT = nullptr;6722if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {6723retry:6724if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {6725// C99 6.5.2.2p1 - "The expression that denotes the called function shall6726// have type pointer to function".6727FuncT = PT->getPointeeType()->getAs<FunctionType>();6728if (!FuncT)6729return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)6730<< Fn->getType() << Fn->getSourceRange());6731} else if (const BlockPointerType *BPT =6732Fn->getType()->getAs<BlockPointerType>()) {6733FuncT = BPT->getPointeeType()->castAs<FunctionType>();6734} else {6735// Handle calls to expressions of unknown-any type.6736if (Fn->getType() == Context.UnknownAnyTy) {6737ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);6738if (rewrite.isInvalid())6739return ExprError();6740Fn = rewrite.get();6741goto retry;6742}67436744return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)6745<< Fn->getType() << Fn->getSourceRange());6746}6747}67486749// Get the number of parameters in the function prototype, if any.6750// We will allocate space for max(Args.size(), NumParams) arguments6751// in the call expression.6752const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);6753unsigned NumParams = Proto ? Proto->getNumParams() : 0;67546755CallExpr *TheCall;6756if (Config) {6757assert(UsesADL == ADLCallKind::NotADL &&6758"CUDAKernelCallExpr should not use ADL");6759TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),6760Args, ResultTy, VK_PRValue, RParenLoc,6761CurFPFeatureOverrides(), NumParams);6762} else {6763TheCall =6764CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,6765CurFPFeatureOverrides(), NumParams, UsesADL);6766}67676768if (!Context.isDependenceAllowed()) {6769// Forget about the nulled arguments since typo correction6770// do not handle them well.6771TheCall->shrinkNumArgs(Args.size());6772// C cannot always handle TypoExpr nodes in builtin calls and direct6773// function calls as their argument checking don't necessarily handle6774// dependent types properly, so make sure any TypoExprs have been6775// dealt with.6776ExprResult Result = CorrectDelayedTyposInExpr(TheCall);6777if (!Result.isUsable()) return ExprError();6778CallExpr *TheOldCall = TheCall;6779TheCall = dyn_cast<CallExpr>(Result.get());6780bool CorrectedTypos = TheCall != TheOldCall;6781if (!TheCall) return Result;6782Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());67836784// A new call expression node was created if some typos were corrected.6785// However it may not have been constructed with enough storage. In this6786// case, rebuild the node with enough storage. The waste of space is6787// immaterial since this only happens when some typos were corrected.6788if (CorrectedTypos && Args.size() < NumParams) {6789if (Config)6790TheCall = CUDAKernelCallExpr::Create(6791Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,6792RParenLoc, CurFPFeatureOverrides(), NumParams);6793else6794TheCall =6795CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,6796CurFPFeatureOverrides(), NumParams, UsesADL);6797}6798// We can now handle the nulled arguments for the default arguments.6799TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));6800}68016802// Bail out early if calling a builtin with custom type checking.6803if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {6804ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);6805if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))6806E = CheckForImmediateInvocation(E, FDecl);6807return E;6808}68096810if (getLangOpts().CUDA) {6811if (Config) {6812// CUDA: Kernel calls must be to global functions6813if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())6814return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)6815<< FDecl << Fn->getSourceRange());68166817// CUDA: Kernel function must have 'void' return type6818if (!FuncT->getReturnType()->isVoidType() &&6819!FuncT->getReturnType()->getAs<AutoType>() &&6820!FuncT->getReturnType()->isInstantiationDependentType())6821return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)6822<< Fn->getType() << Fn->getSourceRange());6823} else {6824// CUDA: Calls to global functions must be configured6825if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())6826return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)6827<< FDecl << Fn->getSourceRange());6828}6829}68306831// Check for a valid return type6832if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,6833FDecl))6834return ExprError();68356836// We know the result type of the call, set it.6837TheCall->setType(FuncT->getCallResultType(Context));6838TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));68396840// WebAssembly tables can't be used as arguments.6841if (Context.getTargetInfo().getTriple().isWasm()) {6842for (const Expr *Arg : Args) {6843if (Arg && Arg->getType()->isWebAssemblyTableType()) {6844return ExprError(Diag(Arg->getExprLoc(),6845diag::err_wasm_table_as_function_parameter));6846}6847}6848}68496850if (Proto) {6851if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,6852IsExecConfig))6853return ExprError();6854} else {6855assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");68566857if (FDecl) {6858// Check if we have too few/too many template arguments, based6859// on our knowledge of the function definition.6860const FunctionDecl *Def = nullptr;6861if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {6862Proto = Def->getType()->getAs<FunctionProtoType>();6863if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))6864Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)6865<< (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();6866}68676868// If the function we're calling isn't a function prototype, but we have6869// a function prototype from a prior declaratiom, use that prototype.6870if (!FDecl->hasPrototype())6871Proto = FDecl->getType()->getAs<FunctionProtoType>();6872}68736874// If we still haven't found a prototype to use but there are arguments to6875// the call, diagnose this as calling a function without a prototype.6876// However, if we found a function declaration, check to see if6877// -Wdeprecated-non-prototype was disabled where the function was declared.6878// If so, we will silence the diagnostic here on the assumption that this6879// interface is intentional and the user knows what they're doing. We will6880// also silence the diagnostic if there is a function declaration but it6881// was implicitly defined (the user already gets diagnostics about the6882// creation of the implicit function declaration, so the additional warning6883// is not helpful).6884if (!Proto && !Args.empty() &&6885(!FDecl || (!FDecl->isImplicit() &&6886!Diags.isIgnored(diag::warn_strict_uses_without_prototype,6887FDecl->getLocation()))))6888Diag(LParenLoc, diag::warn_strict_uses_without_prototype)6889<< (FDecl != nullptr) << FDecl;68906891// Promote the arguments (C99 6.5.2.2p6).6892for (unsigned i = 0, e = Args.size(); i != e; i++) {6893Expr *Arg = Args[i];68946895if (Proto && i < Proto->getNumParams()) {6896InitializedEntity Entity = InitializedEntity::InitializeParameter(6897Context, Proto->getParamType(i), Proto->isParamConsumed(i));6898ExprResult ArgE =6899PerformCopyInitialization(Entity, SourceLocation(), Arg);6900if (ArgE.isInvalid())6901return true;69026903Arg = ArgE.getAs<Expr>();69046905} else {6906ExprResult ArgE = DefaultArgumentPromotion(Arg);69076908if (ArgE.isInvalid())6909return true;69106911Arg = ArgE.getAs<Expr>();6912}69136914if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),6915diag::err_call_incomplete_argument, Arg))6916return ExprError();69176918TheCall->setArg(i, Arg);6919}6920TheCall->computeDependence();6921}69226923if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))6924if (Method->isImplicitObjectMemberFunction())6925return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)6926<< Fn->getSourceRange() << 0);69276928// Check for sentinels6929if (NDecl)6930DiagnoseSentinelCalls(NDecl, LParenLoc, Args);69316932// Warn for unions passing across security boundary (CMSE).6933if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {6934for (unsigned i = 0, e = Args.size(); i != e; i++) {6935if (const auto *RT =6936dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {6937if (RT->getDecl()->isOrContainsUnion())6938Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)6939<< 0 << i;6940}6941}6942}69436944// Do special checking on direct calls to functions.6945if (FDecl) {6946if (CheckFunctionCall(FDecl, TheCall, Proto))6947return ExprError();69486949checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);69506951if (BuiltinID)6952return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);6953} else if (NDecl) {6954if (CheckPointerCall(NDecl, TheCall, Proto))6955return ExprError();6956} else {6957if (CheckOtherCall(TheCall, Proto))6958return ExprError();6959}69606961return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);6962}69636964ExprResult6965Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,6966SourceLocation RParenLoc, Expr *InitExpr) {6967assert(Ty && "ActOnCompoundLiteral(): missing type");6968assert(InitExpr && "ActOnCompoundLiteral(): missing expression");69696970TypeSourceInfo *TInfo;6971QualType literalType = GetTypeFromParser(Ty, &TInfo);6972if (!TInfo)6973TInfo = Context.getTrivialTypeSourceInfo(literalType);69746975return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);6976}69776978ExprResult6979Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,6980SourceLocation RParenLoc, Expr *LiteralExpr) {6981QualType literalType = TInfo->getType();69826983if (literalType->isArrayType()) {6984if (RequireCompleteSizedType(6985LParenLoc, Context.getBaseElementType(literalType),6986diag::err_array_incomplete_or_sizeless_type,6987SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))6988return ExprError();6989if (literalType->isVariableArrayType()) {6990// C23 6.7.10p4: An entity of variable length array type shall not be6991// initialized except by an empty initializer.6992//6993// The C extension warnings are issued from ParseBraceInitializer() and6994// do not need to be issued here. However, we continue to issue an error6995// in the case there are initializers or we are compiling C++. We allow6996// use of VLAs in C++, but it's not clear we want to allow {} to zero6997// init a VLA in C++ in all cases (such as with non-trivial constructors).6998// FIXME: should we allow this construct in C++ when it makes sense to do6999// so?7000//7001// But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name7002// shall specify an object type or an array of unknown size, but not a7003// variable length array type. This seems odd, as it allows 'int a[size] =7004// {}', but forbids 'int *a = (int[size]){}'. As this is what the standard7005// says, this is what's implemented here for C (except for the extension7006// that permits constant foldable size arrays)70077008auto diagID = LangOpts.CPlusPlus7009? diag::err_variable_object_no_init7010: diag::err_compound_literal_with_vla_type;7011if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,7012diagID))7013return ExprError();7014}7015} else if (!literalType->isDependentType() &&7016RequireCompleteType(LParenLoc, literalType,7017diag::err_typecheck_decl_incomplete_type,7018SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))7019return ExprError();70207021InitializedEntity Entity7022= InitializedEntity::InitializeCompoundLiteralInit(TInfo);7023InitializationKind Kind7024= InitializationKind::CreateCStyleCast(LParenLoc,7025SourceRange(LParenLoc, RParenLoc),7026/*InitList=*/true);7027InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);7028ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,7029&literalType);7030if (Result.isInvalid())7031return ExprError();7032LiteralExpr = Result.get();70337034bool isFileScope = !CurContext->isFunctionOrMethod();70357036// In C, compound literals are l-values for some reason.7037// For GCC compatibility, in C++, file-scope array compound literals with7038// constant initializers are also l-values, and compound literals are7039// otherwise prvalues.7040//7041// (GCC also treats C++ list-initialized file-scope array prvalues with7042// constant initializers as l-values, but that's non-conforming, so we don't7043// follow it there.)7044//7045// FIXME: It would be better to handle the lvalue cases as materializing and7046// lifetime-extending a temporary object, but our materialized temporaries7047// representation only supports lifetime extension from a variable, not "out7048// of thin air".7049// FIXME: For C++, we might want to instead lifetime-extend only if a pointer7050// is bound to the result of applying array-to-pointer decay to the compound7051// literal.7052// FIXME: GCC supports compound literals of reference type, which should7053// obviously have a value kind derived from the kind of reference involved.7054ExprValueKind VK =7055(getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))7056? VK_PRValue7057: VK_LValue;70587059if (isFileScope)7060if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))7061for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {7062Expr *Init = ILE->getInit(i);7063ILE->setInit(i, ConstantExpr::Create(Context, Init));7064}70657066auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,7067VK, LiteralExpr, isFileScope);7068if (isFileScope) {7069if (!LiteralExpr->isTypeDependent() &&7070!LiteralExpr->isValueDependent() &&7071!literalType->isDependentType()) // C99 6.5.2.5p37072if (CheckForConstantInitializer(LiteralExpr))7073return ExprError();7074} else if (literalType.getAddressSpace() != LangAS::opencl_private &&7075literalType.getAddressSpace() != LangAS::Default) {7076// Embedded-C extensions to C99 6.5.2.5:7077// "If the compound literal occurs inside the body of a function, the7078// type name shall not be qualified by an address-space qualifier."7079Diag(LParenLoc, diag::err_compound_literal_with_address_space)7080<< SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());7081return ExprError();7082}70837084if (!isFileScope && !getLangOpts().CPlusPlus) {7085// Compound literals that have automatic storage duration are destroyed at7086// the end of the scope in C; in C++, they're just temporaries.70877088// Emit diagnostics if it is or contains a C union type that is non-trivial7089// to destruct.7090if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())7091checkNonTrivialCUnion(E->getType(), E->getExprLoc(),7092NTCUC_CompoundLiteral, NTCUK_Destruct);70937094// Diagnose jumps that enter or exit the lifetime of the compound literal.7095if (literalType.isDestructedType()) {7096Cleanup.setExprNeedsCleanups(true);7097ExprCleanupObjects.push_back(E);7098getCurFunction()->setHasBranchProtectedScope();7099}7100}71017102if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||7103E->getType().hasNonTrivialToPrimitiveCopyCUnion())7104checkNonTrivialCUnionInInitializer(E->getInitializer(),7105E->getInitializer()->getExprLoc());71067107return MaybeBindToTemporary(E);7108}71097110ExprResult7111Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,7112SourceLocation RBraceLoc) {7113// Only produce each kind of designated initialization diagnostic once.7114SourceLocation FirstDesignator;7115bool DiagnosedArrayDesignator = false;7116bool DiagnosedNestedDesignator = false;7117bool DiagnosedMixedDesignator = false;71187119// Check that any designated initializers are syntactically valid in the7120// current language mode.7121for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {7122if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {7123if (FirstDesignator.isInvalid())7124FirstDesignator = DIE->getBeginLoc();71257126if (!getLangOpts().CPlusPlus)7127break;71287129if (!DiagnosedNestedDesignator && DIE->size() > 1) {7130DiagnosedNestedDesignator = true;7131Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)7132<< DIE->getDesignatorsSourceRange();7133}71347135for (auto &Desig : DIE->designators()) {7136if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {7137DiagnosedArrayDesignator = true;7138Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)7139<< Desig.getSourceRange();7140}7141}71427143if (!DiagnosedMixedDesignator &&7144!isa<DesignatedInitExpr>(InitArgList[0])) {7145DiagnosedMixedDesignator = true;7146Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)7147<< DIE->getSourceRange();7148Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)7149<< InitArgList[0]->getSourceRange();7150}7151} else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&7152isa<DesignatedInitExpr>(InitArgList[0])) {7153DiagnosedMixedDesignator = true;7154auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);7155Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)7156<< DIE->getSourceRange();7157Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)7158<< InitArgList[I]->getSourceRange();7159}7160}71617162if (FirstDesignator.isValid()) {7163// Only diagnose designated initiaization as a C++20 extension if we didn't7164// already diagnose use of (non-C++20) C99 designator syntax.7165if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&7166!DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {7167Diag(FirstDesignator, getLangOpts().CPlusPlus207168? diag::warn_cxx17_compat_designated_init7169: diag::ext_cxx_designated_init);7170} else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {7171Diag(FirstDesignator, diag::ext_designated_init);7172}7173}71747175return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);7176}71777178ExprResult7179Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,7180SourceLocation RBraceLoc) {7181// Semantic analysis for initializers is done by ActOnDeclarator() and7182// CheckInitializer() - it requires knowledge of the object being initialized.71837184// Immediately handle non-overload placeholders. Overloads can be7185// resolved contextually, but everything else here can't.7186for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {7187if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {7188ExprResult result = CheckPlaceholderExpr(InitArgList[I]);71897190// Ignore failures; dropping the entire initializer list because7191// of one failure would be terrible for indexing/etc.7192if (result.isInvalid()) continue;71937194InitArgList[I] = result.get();7195}7196}71977198InitListExpr *E =7199new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);7200E->setType(Context.VoidTy); // FIXME: just a place holder for now.7201return E;7202}72037204void Sema::maybeExtendBlockObject(ExprResult &E) {7205assert(E.get()->getType()->isBlockPointerType());7206assert(E.get()->isPRValue());72077208// Only do this in an r-value context.7209if (!getLangOpts().ObjCAutoRefCount) return;72107211E = ImplicitCastExpr::Create(7212Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),7213/*base path*/ nullptr, VK_PRValue, FPOptionsOverride());7214Cleanup.setExprNeedsCleanups(true);7215}72167217CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {7218// Both Src and Dest are scalar types, i.e. arithmetic or pointer.7219// Also, callers should have filtered out the invalid cases with7220// pointers. Everything else should be possible.72217222QualType SrcTy = Src.get()->getType();7223if (Context.hasSameUnqualifiedType(SrcTy, DestTy))7224return CK_NoOp;72257226switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {7227case Type::STK_MemberPointer:7228llvm_unreachable("member pointer type in C");72297230case Type::STK_CPointer:7231case Type::STK_BlockPointer:7232case Type::STK_ObjCObjectPointer:7233switch (DestTy->getScalarTypeKind()) {7234case Type::STK_CPointer: {7235LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();7236LangAS DestAS = DestTy->getPointeeType().getAddressSpace();7237if (SrcAS != DestAS)7238return CK_AddressSpaceConversion;7239if (Context.hasCvrSimilarType(SrcTy, DestTy))7240return CK_NoOp;7241return CK_BitCast;7242}7243case Type::STK_BlockPointer:7244return (SrcKind == Type::STK_BlockPointer7245? CK_BitCast : CK_AnyPointerToBlockPointerCast);7246case Type::STK_ObjCObjectPointer:7247if (SrcKind == Type::STK_ObjCObjectPointer)7248return CK_BitCast;7249if (SrcKind == Type::STK_CPointer)7250return CK_CPointerToObjCPointerCast;7251maybeExtendBlockObject(Src);7252return CK_BlockPointerToObjCPointerCast;7253case Type::STK_Bool:7254return CK_PointerToBoolean;7255case Type::STK_Integral:7256return CK_PointerToIntegral;7257case Type::STK_Floating:7258case Type::STK_FloatingComplex:7259case Type::STK_IntegralComplex:7260case Type::STK_MemberPointer:7261case Type::STK_FixedPoint:7262llvm_unreachable("illegal cast from pointer");7263}7264llvm_unreachable("Should have returned before this");72657266case Type::STK_FixedPoint:7267switch (DestTy->getScalarTypeKind()) {7268case Type::STK_FixedPoint:7269return CK_FixedPointCast;7270case Type::STK_Bool:7271return CK_FixedPointToBoolean;7272case Type::STK_Integral:7273return CK_FixedPointToIntegral;7274case Type::STK_Floating:7275return CK_FixedPointToFloating;7276case Type::STK_IntegralComplex:7277case Type::STK_FloatingComplex:7278Diag(Src.get()->getExprLoc(),7279diag::err_unimplemented_conversion_with_fixed_point_type)7280<< DestTy;7281return CK_IntegralCast;7282case Type::STK_CPointer:7283case Type::STK_ObjCObjectPointer:7284case Type::STK_BlockPointer:7285case Type::STK_MemberPointer:7286llvm_unreachable("illegal cast to pointer type");7287}7288llvm_unreachable("Should have returned before this");72897290case Type::STK_Bool: // casting from bool is like casting from an integer7291case Type::STK_Integral:7292switch (DestTy->getScalarTypeKind()) {7293case Type::STK_CPointer:7294case Type::STK_ObjCObjectPointer:7295case Type::STK_BlockPointer:7296if (Src.get()->isNullPointerConstant(Context,7297Expr::NPC_ValueDependentIsNull))7298return CK_NullToPointer;7299return CK_IntegralToPointer;7300case Type::STK_Bool:7301return CK_IntegralToBoolean;7302case Type::STK_Integral:7303return CK_IntegralCast;7304case Type::STK_Floating:7305return CK_IntegralToFloating;7306case Type::STK_IntegralComplex:7307Src = ImpCastExprToType(Src.get(),7308DestTy->castAs<ComplexType>()->getElementType(),7309CK_IntegralCast);7310return CK_IntegralRealToComplex;7311case Type::STK_FloatingComplex:7312Src = ImpCastExprToType(Src.get(),7313DestTy->castAs<ComplexType>()->getElementType(),7314CK_IntegralToFloating);7315return CK_FloatingRealToComplex;7316case Type::STK_MemberPointer:7317llvm_unreachable("member pointer type in C");7318case Type::STK_FixedPoint:7319return CK_IntegralToFixedPoint;7320}7321llvm_unreachable("Should have returned before this");73227323case Type::STK_Floating:7324switch (DestTy->getScalarTypeKind()) {7325case Type::STK_Floating:7326return CK_FloatingCast;7327case Type::STK_Bool:7328return CK_FloatingToBoolean;7329case Type::STK_Integral:7330return CK_FloatingToIntegral;7331case Type::STK_FloatingComplex:7332Src = ImpCastExprToType(Src.get(),7333DestTy->castAs<ComplexType>()->getElementType(),7334CK_FloatingCast);7335return CK_FloatingRealToComplex;7336case Type::STK_IntegralComplex:7337Src = ImpCastExprToType(Src.get(),7338DestTy->castAs<ComplexType>()->getElementType(),7339CK_FloatingToIntegral);7340return CK_IntegralRealToComplex;7341case Type::STK_CPointer:7342case Type::STK_ObjCObjectPointer:7343case Type::STK_BlockPointer:7344llvm_unreachable("valid float->pointer cast?");7345case Type::STK_MemberPointer:7346llvm_unreachable("member pointer type in C");7347case Type::STK_FixedPoint:7348return CK_FloatingToFixedPoint;7349}7350llvm_unreachable("Should have returned before this");73517352case Type::STK_FloatingComplex:7353switch (DestTy->getScalarTypeKind()) {7354case Type::STK_FloatingComplex:7355return CK_FloatingComplexCast;7356case Type::STK_IntegralComplex:7357return CK_FloatingComplexToIntegralComplex;7358case Type::STK_Floating: {7359QualType ET = SrcTy->castAs<ComplexType>()->getElementType();7360if (Context.hasSameType(ET, DestTy))7361return CK_FloatingComplexToReal;7362Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);7363return CK_FloatingCast;7364}7365case Type::STK_Bool:7366return CK_FloatingComplexToBoolean;7367case Type::STK_Integral:7368Src = ImpCastExprToType(Src.get(),7369SrcTy->castAs<ComplexType>()->getElementType(),7370CK_FloatingComplexToReal);7371return CK_FloatingToIntegral;7372case Type::STK_CPointer:7373case Type::STK_ObjCObjectPointer:7374case Type::STK_BlockPointer:7375llvm_unreachable("valid complex float->pointer cast?");7376case Type::STK_MemberPointer:7377llvm_unreachable("member pointer type in C");7378case Type::STK_FixedPoint:7379Diag(Src.get()->getExprLoc(),7380diag::err_unimplemented_conversion_with_fixed_point_type)7381<< SrcTy;7382return CK_IntegralCast;7383}7384llvm_unreachable("Should have returned before this");73857386case Type::STK_IntegralComplex:7387switch (DestTy->getScalarTypeKind()) {7388case Type::STK_FloatingComplex:7389return CK_IntegralComplexToFloatingComplex;7390case Type::STK_IntegralComplex:7391return CK_IntegralComplexCast;7392case Type::STK_Integral: {7393QualType ET = SrcTy->castAs<ComplexType>()->getElementType();7394if (Context.hasSameType(ET, DestTy))7395return CK_IntegralComplexToReal;7396Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);7397return CK_IntegralCast;7398}7399case Type::STK_Bool:7400return CK_IntegralComplexToBoolean;7401case Type::STK_Floating:7402Src = ImpCastExprToType(Src.get(),7403SrcTy->castAs<ComplexType>()->getElementType(),7404CK_IntegralComplexToReal);7405return CK_IntegralToFloating;7406case Type::STK_CPointer:7407case Type::STK_ObjCObjectPointer:7408case Type::STK_BlockPointer:7409llvm_unreachable("valid complex int->pointer cast?");7410case Type::STK_MemberPointer:7411llvm_unreachable("member pointer type in C");7412case Type::STK_FixedPoint:7413Diag(Src.get()->getExprLoc(),7414diag::err_unimplemented_conversion_with_fixed_point_type)7415<< SrcTy;7416return CK_IntegralCast;7417}7418llvm_unreachable("Should have returned before this");7419}74207421llvm_unreachable("Unhandled scalar cast");7422}74237424static bool breakDownVectorType(QualType type, uint64_t &len,7425QualType &eltType) {7426// Vectors are simple.7427if (const VectorType *vecType = type->getAs<VectorType>()) {7428len = vecType->getNumElements();7429eltType = vecType->getElementType();7430assert(eltType->isScalarType());7431return true;7432}74337434// We allow lax conversion to and from non-vector types, but only if7435// they're real types (i.e. non-complex, non-pointer scalar types).7436if (!type->isRealType()) return false;74377438len = 1;7439eltType = type;7440return true;7441}74427443bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {7444assert(srcTy->isVectorType() || destTy->isVectorType());74457446auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {7447if (!FirstType->isSVESizelessBuiltinType())7448return false;74497450const auto *VecTy = SecondType->getAs<VectorType>();7451return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;7452};74537454return ValidScalableConversion(srcTy, destTy) ||7455ValidScalableConversion(destTy, srcTy);7456}74577458bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {7459if (!destTy->isMatrixType() || !srcTy->isMatrixType())7460return false;74617462const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();7463const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();74647465return matSrcType->getNumRows() == matDestType->getNumRows() &&7466matSrcType->getNumColumns() == matDestType->getNumColumns();7467}74687469bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {7470assert(DestTy->isVectorType() || SrcTy->isVectorType());74717472uint64_t SrcLen, DestLen;7473QualType SrcEltTy, DestEltTy;7474if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))7475return false;7476if (!breakDownVectorType(DestTy, DestLen, DestEltTy))7477return false;74787479// ASTContext::getTypeSize will return the size rounded up to a7480// power of 2, so instead of using that, we need to use the raw7481// element size multiplied by the element count.7482uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);7483uint64_t DestEltSize = Context.getTypeSize(DestEltTy);74847485return (SrcLen * SrcEltSize == DestLen * DestEltSize);7486}74877488bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {7489assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&7490"expected at least one type to be a vector here");74917492bool IsSrcTyAltivec =7493SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==7494VectorKind::AltiVecVector) ||7495(SrcTy->castAs<VectorType>()->getVectorKind() ==7496VectorKind::AltiVecBool) ||7497(SrcTy->castAs<VectorType>()->getVectorKind() ==7498VectorKind::AltiVecPixel));74997500bool IsDestTyAltivec = DestTy->isVectorType() &&7501((DestTy->castAs<VectorType>()->getVectorKind() ==7502VectorKind::AltiVecVector) ||7503(DestTy->castAs<VectorType>()->getVectorKind() ==7504VectorKind::AltiVecBool) ||7505(DestTy->castAs<VectorType>()->getVectorKind() ==7506VectorKind::AltiVecPixel));75077508return (IsSrcTyAltivec || IsDestTyAltivec);7509}75107511bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {7512assert(destTy->isVectorType() || srcTy->isVectorType());75137514// Disallow lax conversions between scalars and ExtVectors (these7515// conversions are allowed for other vector types because common headers7516// depend on them). Most scalar OP ExtVector cases are handled by the7517// splat path anyway, which does what we want (convert, not bitcast).7518// What this rules out for ExtVectors is crazy things like char4*float.7519if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;7520if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;75217522return areVectorTypesSameSize(srcTy, destTy);7523}75247525bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {7526assert(destTy->isVectorType() || srcTy->isVectorType());75277528switch (Context.getLangOpts().getLaxVectorConversions()) {7529case LangOptions::LaxVectorConversionKind::None:7530return false;75317532case LangOptions::LaxVectorConversionKind::Integer:7533if (!srcTy->isIntegralOrEnumerationType()) {7534auto *Vec = srcTy->getAs<VectorType>();7535if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())7536return false;7537}7538if (!destTy->isIntegralOrEnumerationType()) {7539auto *Vec = destTy->getAs<VectorType>();7540if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())7541return false;7542}7543// OK, integer (vector) -> integer (vector) bitcast.7544break;75457546case LangOptions::LaxVectorConversionKind::All:7547break;7548}75497550return areLaxCompatibleVectorTypes(srcTy, destTy);7551}75527553bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,7554CastKind &Kind) {7555if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {7556if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {7557return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)7558<< DestTy << SrcTy << R;7559}7560} else if (SrcTy->isMatrixType()) {7561return Diag(R.getBegin(),7562diag::err_invalid_conversion_between_matrix_and_type)7563<< SrcTy << DestTy << R;7564} else if (DestTy->isMatrixType()) {7565return Diag(R.getBegin(),7566diag::err_invalid_conversion_between_matrix_and_type)7567<< DestTy << SrcTy << R;7568}75697570Kind = CK_MatrixCast;7571return false;7572}75737574bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,7575CastKind &Kind) {7576assert(VectorTy->isVectorType() && "Not a vector type!");75777578if (Ty->isVectorType() || Ty->isIntegralType(Context)) {7579if (!areLaxCompatibleVectorTypes(Ty, VectorTy))7580return Diag(R.getBegin(),7581Ty->isVectorType() ?7582diag::err_invalid_conversion_between_vectors :7583diag::err_invalid_conversion_between_vector_and_integer)7584<< VectorTy << Ty << R;7585} else7586return Diag(R.getBegin(),7587diag::err_invalid_conversion_between_vector_and_scalar)7588<< VectorTy << Ty << R;75897590Kind = CK_BitCast;7591return false;7592}75937594ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {7595QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();75967597if (DestElemTy == SplattedExpr->getType())7598return SplattedExpr;75997600assert(DestElemTy->isFloatingType() ||7601DestElemTy->isIntegralOrEnumerationType());76027603CastKind CK;7604if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {7605// OpenCL requires that we convert `true` boolean expressions to -1, but7606// only when splatting vectors.7607if (DestElemTy->isFloatingType()) {7608// To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast7609// in two steps: boolean to signed integral, then to floating.7610ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,7611CK_BooleanToSignedIntegral);7612SplattedExpr = CastExprRes.get();7613CK = CK_IntegralToFloating;7614} else {7615CK = CK_BooleanToSignedIntegral;7616}7617} else {7618ExprResult CastExprRes = SplattedExpr;7619CK = PrepareScalarCast(CastExprRes, DestElemTy);7620if (CastExprRes.isInvalid())7621return ExprError();7622SplattedExpr = CastExprRes.get();7623}7624return ImpCastExprToType(SplattedExpr, DestElemTy, CK);7625}76267627ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,7628Expr *CastExpr, CastKind &Kind) {7629assert(DestTy->isExtVectorType() && "Not an extended vector type!");76307631QualType SrcTy = CastExpr->getType();76327633// If SrcTy is a VectorType, the total size must match to explicitly cast to7634// an ExtVectorType.7635// In OpenCL, casts between vectors of different types are not allowed.7636// (See OpenCL 6.2).7637if (SrcTy->isVectorType()) {7638if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||7639(getLangOpts().OpenCL &&7640!Context.hasSameUnqualifiedType(DestTy, SrcTy))) {7641Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)7642<< DestTy << SrcTy << R;7643return ExprError();7644}7645Kind = CK_BitCast;7646return CastExpr;7647}76487649// All non-pointer scalars can be cast to ExtVector type. The appropriate7650// conversion will take place first from scalar to elt type, and then7651// splat from elt type to vector.7652if (SrcTy->isPointerType())7653return Diag(R.getBegin(),7654diag::err_invalid_conversion_between_vector_and_scalar)7655<< DestTy << SrcTy << R;76567657Kind = CK_VectorSplat;7658return prepareVectorSplat(DestTy, CastExpr);7659}76607661ExprResult7662Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,7663Declarator &D, ParsedType &Ty,7664SourceLocation RParenLoc, Expr *CastExpr) {7665assert(!D.isInvalidType() && (CastExpr != nullptr) &&7666"ActOnCastExpr(): missing type or expr");76677668TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());7669if (D.isInvalidType())7670return ExprError();76717672if (getLangOpts().CPlusPlus) {7673// Check that there are no default arguments (C++ only).7674CheckExtraCXXDefaultArguments(D);7675} else {7676// Make sure any TypoExprs have been dealt with.7677ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);7678if (!Res.isUsable())7679return ExprError();7680CastExpr = Res.get();7681}76827683checkUnusedDeclAttributes(D);76847685QualType castType = castTInfo->getType();7686Ty = CreateParsedType(castType, castTInfo);76877688bool isVectorLiteral = false;76897690// Check for an altivec or OpenCL literal,7691// i.e. all the elements are integer constants.7692ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);7693ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);7694if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)7695&& castType->isVectorType() && (PE || PLE)) {7696if (PLE && PLE->getNumExprs() == 0) {7697Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);7698return ExprError();7699}7700if (PE || PLE->getNumExprs() == 1) {7701Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));7702if (!E->isTypeDependent() && !E->getType()->isVectorType())7703isVectorLiteral = true;7704}7705else7706isVectorLiteral = true;7707}77087709// If this is a vector initializer, '(' type ')' '(' init, ..., init ')'7710// then handle it as such.7711if (isVectorLiteral)7712return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);77137714// If the Expr being casted is a ParenListExpr, handle it specially.7715// This is not an AltiVec-style cast, so turn the ParenListExpr into a7716// sequence of BinOp comma operators.7717if (isa<ParenListExpr>(CastExpr)) {7718ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);7719if (Result.isInvalid()) return ExprError();7720CastExpr = Result.get();7721}77227723if (getLangOpts().CPlusPlus && !castType->isVoidType())7724Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();77257726ObjC().CheckTollFreeBridgeCast(castType, CastExpr);77277728ObjC().CheckObjCBridgeRelatedCast(castType, CastExpr);77297730DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);77317732return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);7733}77347735ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,7736SourceLocation RParenLoc, Expr *E,7737TypeSourceInfo *TInfo) {7738assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&7739"Expected paren or paren list expression");77407741Expr **exprs;7742unsigned numExprs;7743Expr *subExpr;7744SourceLocation LiteralLParenLoc, LiteralRParenLoc;7745if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {7746LiteralLParenLoc = PE->getLParenLoc();7747LiteralRParenLoc = PE->getRParenLoc();7748exprs = PE->getExprs();7749numExprs = PE->getNumExprs();7750} else { // isa<ParenExpr> by assertion at function entrance7751LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();7752LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();7753subExpr = cast<ParenExpr>(E)->getSubExpr();7754exprs = &subExpr;7755numExprs = 1;7756}77577758QualType Ty = TInfo->getType();7759assert(Ty->isVectorType() && "Expected vector type");77607761SmallVector<Expr *, 8> initExprs;7762const VectorType *VTy = Ty->castAs<VectorType>();7763unsigned numElems = VTy->getNumElements();77647765// '(...)' form of vector initialization in AltiVec: the number of7766// initializers must be one or must match the size of the vector.7767// If a single value is specified in the initializer then it will be7768// replicated to all the components of the vector7769if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,7770VTy->getElementType()))7771return ExprError();7772if (ShouldSplatAltivecScalarInCast(VTy)) {7773// The number of initializers must be one or must match the size of the7774// vector. If a single value is specified in the initializer then it will7775// be replicated to all the components of the vector7776if (numExprs == 1) {7777QualType ElemTy = VTy->getElementType();7778ExprResult Literal = DefaultLvalueConversion(exprs[0]);7779if (Literal.isInvalid())7780return ExprError();7781Literal = ImpCastExprToType(Literal.get(), ElemTy,7782PrepareScalarCast(Literal, ElemTy));7783return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());7784}7785else if (numExprs < numElems) {7786Diag(E->getExprLoc(),7787diag::err_incorrect_number_of_vector_initializers);7788return ExprError();7789}7790else7791initExprs.append(exprs, exprs + numExprs);7792}7793else {7794// For OpenCL, when the number of initializers is a single value,7795// it will be replicated to all components of the vector.7796if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&7797numExprs == 1) {7798QualType ElemTy = VTy->getElementType();7799ExprResult Literal = DefaultLvalueConversion(exprs[0]);7800if (Literal.isInvalid())7801return ExprError();7802Literal = ImpCastExprToType(Literal.get(), ElemTy,7803PrepareScalarCast(Literal, ElemTy));7804return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());7805}78067807initExprs.append(exprs, exprs + numExprs);7808}7809// FIXME: This means that pretty-printing the final AST will produce curly7810// braces instead of the original commas.7811InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,7812initExprs, LiteralRParenLoc);7813initE->setType(Ty);7814return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);7815}78167817ExprResult7818Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {7819ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);7820if (!E)7821return OrigExpr;78227823ExprResult Result(E->getExpr(0));78247825for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)7826Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),7827E->getExpr(i));78287829if (Result.isInvalid()) return ExprError();78307831return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());7832}78337834ExprResult Sema::ActOnParenListExpr(SourceLocation L,7835SourceLocation R,7836MultiExprArg Val) {7837return ParenListExpr::Create(Context, L, Val, R);7838}78397840bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,7841SourceLocation QuestionLoc) {7842const Expr *NullExpr = LHSExpr;7843const Expr *NonPointerExpr = RHSExpr;7844Expr::NullPointerConstantKind NullKind =7845NullExpr->isNullPointerConstant(Context,7846Expr::NPC_ValueDependentIsNotNull);78477848if (NullKind == Expr::NPCK_NotNull) {7849NullExpr = RHSExpr;7850NonPointerExpr = LHSExpr;7851NullKind =7852NullExpr->isNullPointerConstant(Context,7853Expr::NPC_ValueDependentIsNotNull);7854}78557856if (NullKind == Expr::NPCK_NotNull)7857return false;78587859if (NullKind == Expr::NPCK_ZeroExpression)7860return false;78617862if (NullKind == Expr::NPCK_ZeroLiteral) {7863// In this case, check to make sure that we got here from a "NULL"7864// string in the source code.7865NullExpr = NullExpr->IgnoreParenImpCasts();7866SourceLocation loc = NullExpr->getExprLoc();7867if (!findMacroSpelling(loc, "NULL"))7868return false;7869}78707871int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);7872Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)7873<< NonPointerExpr->getType() << DiagType7874<< NonPointerExpr->getSourceRange();7875return true;7876}78777878/// Return false if the condition expression is valid, true otherwise.7879static bool checkCondition(Sema &S, const Expr *Cond,7880SourceLocation QuestionLoc) {7881QualType CondTy = Cond->getType();78827883// OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.7884if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {7885S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)7886<< CondTy << Cond->getSourceRange();7887return true;7888}78897890// C99 6.5.15p27891if (CondTy->isScalarType()) return false;78927893S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)7894<< CondTy << Cond->getSourceRange();7895return true;7896}78977898/// Return false if the NullExpr can be promoted to PointerTy,7899/// true otherwise.7900static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,7901QualType PointerTy) {7902if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||7903!NullExpr.get()->isNullPointerConstant(S.Context,7904Expr::NPC_ValueDependentIsNull))7905return true;79067907NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);7908return false;7909}79107911/// Checks compatibility between two pointers and return the resulting7912/// type.7913static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,7914ExprResult &RHS,7915SourceLocation Loc) {7916QualType LHSTy = LHS.get()->getType();7917QualType RHSTy = RHS.get()->getType();79187919if (S.Context.hasSameType(LHSTy, RHSTy)) {7920// Two identical pointers types are always compatible.7921return S.Context.getCommonSugaredType(LHSTy, RHSTy);7922}79237924QualType lhptee, rhptee;79257926// Get the pointee types.7927bool IsBlockPointer = false;7928if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {7929lhptee = LHSBTy->getPointeeType();7930rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();7931IsBlockPointer = true;7932} else {7933lhptee = LHSTy->castAs<PointerType>()->getPointeeType();7934rhptee = RHSTy->castAs<PointerType>()->getPointeeType();7935}79367937// C99 6.5.15p6: If both operands are pointers to compatible types or to7938// differently qualified versions of compatible types, the result type is7939// a pointer to an appropriately qualified version of the composite7940// type.79417942// Only CVR-qualifiers exist in the standard, and the differently-qualified7943// clause doesn't make sense for our extensions. E.g. address space 2 should7944// be incompatible with address space 3: they may live on different devices or7945// anything.7946Qualifiers lhQual = lhptee.getQualifiers();7947Qualifiers rhQual = rhptee.getQualifiers();79487949LangAS ResultAddrSpace = LangAS::Default;7950LangAS LAddrSpace = lhQual.getAddressSpace();7951LangAS RAddrSpace = rhQual.getAddressSpace();79527953// OpenCL v1.1 s6.5 - Conversion between pointers to distinct address7954// spaces is disallowed.7955if (lhQual.isAddressSpaceSupersetOf(rhQual))7956ResultAddrSpace = LAddrSpace;7957else if (rhQual.isAddressSpaceSupersetOf(lhQual))7958ResultAddrSpace = RAddrSpace;7959else {7960S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)7961<< LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()7962<< RHS.get()->getSourceRange();7963return QualType();7964}79657966unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();7967auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;7968lhQual.removeCVRQualifiers();7969rhQual.removeCVRQualifiers();79707971// OpenCL v2.0 specification doesn't extend compatibility of type qualifiers7972// (C99 6.7.3) for address spaces. We assume that the check should behave in7973// the same manner as it's defined for CVR qualifiers, so for OpenCL two7974// qual types are compatible iff7975// * corresponded types are compatible7976// * CVR qualifiers are equal7977// * address spaces are equal7978// Thus for conditional operator we merge CVR and address space unqualified7979// pointees and if there is a composite type we return a pointer to it with7980// merged qualifiers.7981LHSCastKind =7982LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;7983RHSCastKind =7984RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;7985lhQual.removeAddressSpace();7986rhQual.removeAddressSpace();79877988lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);7989rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);79907991QualType CompositeTy = S.Context.mergeTypes(7992lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,7993/*BlockReturnType=*/false, /*IsConditionalOperator=*/true);79947995if (CompositeTy.isNull()) {7996// In this situation, we assume void* type. No especially good7997// reason, but this is what gcc does, and we do have to pick7998// to get a consistent AST.7999QualType incompatTy;8000incompatTy = S.Context.getPointerType(8001S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));8002LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);8003RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);80048005// FIXME: For OpenCL the warning emission and cast to void* leaves a room8006// for casts between types with incompatible address space qualifiers.8007// For the following code the compiler produces casts between global and8008// local address spaces of the corresponded innermost pointees:8009// local int *global *a;8010// global int *global *b;8011// a = (0 ? a : b); // see C99 6.5.16.1.p1.8012S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)8013<< LHSTy << RHSTy << LHS.get()->getSourceRange()8014<< RHS.get()->getSourceRange();80158016return incompatTy;8017}80188019// The pointer types are compatible.8020// In case of OpenCL ResultTy should have the address space qualifier8021// which is a superset of address spaces of both the 2nd and the 3rd8022// operands of the conditional operator.8023QualType ResultTy = [&, ResultAddrSpace]() {8024if (S.getLangOpts().OpenCL) {8025Qualifiers CompositeQuals = CompositeTy.getQualifiers();8026CompositeQuals.setAddressSpace(ResultAddrSpace);8027return S.Context8028.getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)8029.withCVRQualifiers(MergedCVRQual);8030}8031return CompositeTy.withCVRQualifiers(MergedCVRQual);8032}();8033if (IsBlockPointer)8034ResultTy = S.Context.getBlockPointerType(ResultTy);8035else8036ResultTy = S.Context.getPointerType(ResultTy);80378038LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);8039RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);8040return ResultTy;8041}80428043/// Return the resulting type when the operands are both block pointers.8044static QualType checkConditionalBlockPointerCompatibility(Sema &S,8045ExprResult &LHS,8046ExprResult &RHS,8047SourceLocation Loc) {8048QualType LHSTy = LHS.get()->getType();8049QualType RHSTy = RHS.get()->getType();80508051if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {8052if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {8053QualType destType = S.Context.getPointerType(S.Context.VoidTy);8054LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);8055RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);8056return destType;8057}8058S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)8059<< LHSTy << RHSTy << LHS.get()->getSourceRange()8060<< RHS.get()->getSourceRange();8061return QualType();8062}80638064// We have 2 block pointer types.8065return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);8066}80678068/// Return the resulting type when the operands are both pointers.8069static QualType8070checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,8071ExprResult &RHS,8072SourceLocation Loc) {8073// get the pointer types8074QualType LHSTy = LHS.get()->getType();8075QualType RHSTy = RHS.get()->getType();80768077// get the "pointed to" types8078QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();8079QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();80808081// ignore qualifiers on void (C99 6.5.15p3, clause 6)8082if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {8083// Figure out necessary qualifiers (C99 6.5.15p6)8084QualType destPointee8085= S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());8086QualType destType = S.Context.getPointerType(destPointee);8087// Add qualifiers if necessary.8088LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);8089// Promote to void*.8090RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);8091return destType;8092}8093if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {8094QualType destPointee8095= S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());8096QualType destType = S.Context.getPointerType(destPointee);8097// Add qualifiers if necessary.8098RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);8099// Promote to void*.8100LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);8101return destType;8102}81038104return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);8105}81068107/// Return false if the first expression is not an integer and the second8108/// expression is not a pointer, true otherwise.8109static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,8110Expr* PointerExpr, SourceLocation Loc,8111bool IsIntFirstExpr) {8112if (!PointerExpr->getType()->isPointerType() ||8113!Int.get()->getType()->isIntegerType())8114return false;81158116Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;8117Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();81188119S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)8120<< Expr1->getType() << Expr2->getType()8121<< Expr1->getSourceRange() << Expr2->getSourceRange();8122Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),8123CK_IntegralToPointer);8124return true;8125}81268127/// Simple conversion between integer and floating point types.8128///8129/// Used when handling the OpenCL conditional operator where the8130/// condition is a vector while the other operands are scalar.8131///8132/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar8133/// types are either integer or floating type. Between the two8134/// operands, the type with the higher rank is defined as the "result8135/// type". The other operand needs to be promoted to the same type. No8136/// other type promotion is allowed. We cannot use8137/// UsualArithmeticConversions() for this purpose, since it always8138/// promotes promotable types.8139static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,8140ExprResult &RHS,8141SourceLocation QuestionLoc) {8142LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());8143if (LHS.isInvalid())8144return QualType();8145RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());8146if (RHS.isInvalid())8147return QualType();81488149// For conversion purposes, we ignore any qualifiers.8150// For example, "const float" and "float" are equivalent.8151QualType LHSType =8152S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();8153QualType RHSType =8154S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();81558156if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {8157S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)8158<< LHSType << LHS.get()->getSourceRange();8159return QualType();8160}81618162if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {8163S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)8164<< RHSType << RHS.get()->getSourceRange();8165return QualType();8166}81678168// If both types are identical, no conversion is needed.8169if (LHSType == RHSType)8170return LHSType;81718172// Now handle "real" floating types (i.e. float, double, long double).8173if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())8174return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,8175/*IsCompAssign = */ false);81768177// Finally, we have two differing integer types.8178return handleIntegerConversion<doIntegralCast, doIntegralCast>8179(S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);8180}81818182/// Convert scalar operands to a vector that matches the8183/// condition in length.8184///8185/// Used when handling the OpenCL conditional operator where the8186/// condition is a vector while the other operands are scalar.8187///8188/// We first compute the "result type" for the scalar operands8189/// according to OpenCL v1.1 s6.3.i. Both operands are then converted8190/// into a vector of that type where the length matches the condition8191/// vector type. s6.11.6 requires that the element types of the result8192/// and the condition must have the same number of bits.8193static QualType8194OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,8195QualType CondTy, SourceLocation QuestionLoc) {8196QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);8197if (ResTy.isNull()) return QualType();81988199const VectorType *CV = CondTy->getAs<VectorType>();8200assert(CV);82018202// Determine the vector result type8203unsigned NumElements = CV->getNumElements();8204QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);82058206// Ensure that all types have the same number of bits8207if (S.Context.getTypeSize(CV->getElementType())8208!= S.Context.getTypeSize(ResTy)) {8209// Since VectorTy is created internally, it does not pretty print8210// with an OpenCL name. Instead, we just print a description.8211std::string EleTyName = ResTy.getUnqualifiedType().getAsString();8212SmallString<64> Str;8213llvm::raw_svector_ostream OS(Str);8214OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";8215S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)8216<< CondTy << OS.str();8217return QualType();8218}82198220// Convert operands to the vector result type8221LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);8222RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);82238224return VectorTy;8225}82268227/// Return false if this is a valid OpenCL condition vector8228static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,8229SourceLocation QuestionLoc) {8230// OpenCL v1.1 s6.11.6 says the elements of the vector must be of8231// integral type.8232const VectorType *CondTy = Cond->getType()->getAs<VectorType>();8233assert(CondTy);8234QualType EleTy = CondTy->getElementType();8235if (EleTy->isIntegerType()) return false;82368237S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)8238<< Cond->getType() << Cond->getSourceRange();8239return true;8240}82418242/// Return false if the vector condition type and the vector8243/// result type are compatible.8244///8245/// OpenCL v1.1 s6.11.6 requires that both vector types have the same8246/// number of elements, and their element types have the same number8247/// of bits.8248static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,8249SourceLocation QuestionLoc) {8250const VectorType *CV = CondTy->getAs<VectorType>();8251const VectorType *RV = VecResTy->getAs<VectorType>();8252assert(CV && RV);82538254if (CV->getNumElements() != RV->getNumElements()) {8255S.Diag(QuestionLoc, diag::err_conditional_vector_size)8256<< CondTy << VecResTy;8257return true;8258}82598260QualType CVE = CV->getElementType();8261QualType RVE = RV->getElementType();82628263if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {8264S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)8265<< CondTy << VecResTy;8266return true;8267}82688269return false;8270}82718272/// Return the resulting type for the conditional operator in8273/// OpenCL (aka "ternary selection operator", OpenCL v1.18274/// s6.3.i) when the condition is a vector type.8275static QualType8276OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,8277ExprResult &LHS, ExprResult &RHS,8278SourceLocation QuestionLoc) {8279Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());8280if (Cond.isInvalid())8281return QualType();8282QualType CondTy = Cond.get()->getType();82838284if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))8285return QualType();82868287// If either operand is a vector then find the vector type of the8288// result as specified in OpenCL v1.1 s6.3.i.8289if (LHS.get()->getType()->isVectorType() ||8290RHS.get()->getType()->isVectorType()) {8291bool IsBoolVecLang =8292!S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;8293QualType VecResTy =8294S.CheckVectorOperands(LHS, RHS, QuestionLoc,8295/*isCompAssign*/ false,8296/*AllowBothBool*/ true,8297/*AllowBoolConversions*/ false,8298/*AllowBooleanOperation*/ IsBoolVecLang,8299/*ReportInvalid*/ true);8300if (VecResTy.isNull())8301return QualType();8302// The result type must match the condition type as specified in8303// OpenCL v1.1 s6.11.6.8304if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))8305return QualType();8306return VecResTy;8307}83088309// Both operands are scalar.8310return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);8311}83128313/// Return true if the Expr is block type8314static bool checkBlockType(Sema &S, const Expr *E) {8315if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {8316QualType Ty = CE->getCallee()->getType();8317if (Ty->isBlockPointerType()) {8318S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);8319return true;8320}8321}8322return false;8323}83248325/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.8326/// In that case, LHS = cond.8327/// C99 6.5.158328QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,8329ExprResult &RHS, ExprValueKind &VK,8330ExprObjectKind &OK,8331SourceLocation QuestionLoc) {83328333ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());8334if (!LHSResult.isUsable()) return QualType();8335LHS = LHSResult;83368337ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());8338if (!RHSResult.isUsable()) return QualType();8339RHS = RHSResult;83408341// C++ is sufficiently different to merit its own checker.8342if (getLangOpts().CPlusPlus)8343return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);83448345VK = VK_PRValue;8346OK = OK_Ordinary;83478348if (Context.isDependenceAllowed() &&8349(Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||8350RHS.get()->isTypeDependent())) {8351assert(!getLangOpts().CPlusPlus);8352assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||8353RHS.get()->containsErrors()) &&8354"should only occur in error-recovery path.");8355return Context.DependentTy;8356}83578358// The OpenCL operator with a vector condition is sufficiently8359// different to merit its own checker.8360if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||8361Cond.get()->getType()->isExtVectorType())8362return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);83638364// First, check the condition.8365Cond = UsualUnaryConversions(Cond.get());8366if (Cond.isInvalid())8367return QualType();8368if (checkCondition(*this, Cond.get(), QuestionLoc))8369return QualType();83708371// Handle vectors.8372if (LHS.get()->getType()->isVectorType() ||8373RHS.get()->getType()->isVectorType())8374return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,8375/*AllowBothBool*/ true,8376/*AllowBoolConversions*/ false,8377/*AllowBooleanOperation*/ false,8378/*ReportInvalid*/ true);83798380QualType ResTy =8381UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);8382if (LHS.isInvalid() || RHS.isInvalid())8383return QualType();83848385// WebAssembly tables are not allowed as conditional LHS or RHS.8386QualType LHSTy = LHS.get()->getType();8387QualType RHSTy = RHS.get()->getType();8388if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {8389Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)8390<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();8391return QualType();8392}83938394// Diagnose attempts to convert between __ibm128, __float128 and long double8395// where such conversions currently can't be handled.8396if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {8397Diag(QuestionLoc,8398diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy8399<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();8400return QualType();8401}84028403// OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary8404// selection operator (?:).8405if (getLangOpts().OpenCL &&8406((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {8407return QualType();8408}84098410// If both operands have arithmetic type, do the usual arithmetic conversions8411// to find a common type: C99 6.5.15p3,5.8412if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {8413// Disallow invalid arithmetic conversions, such as those between bit-8414// precise integers types of different sizes, or between a bit-precise8415// integer and another type.8416if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {8417Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)8418<< LHSTy << RHSTy << LHS.get()->getSourceRange()8419<< RHS.get()->getSourceRange();8420return QualType();8421}84228423LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));8424RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));84258426return ResTy;8427}84288429// If both operands are the same structure or union type, the result is that8430// type.8431if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p38432if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())8433if (LHSRT->getDecl() == RHSRT->getDecl())8434// "If both the operands have structure or union type, the result has8435// that type." This implies that CV qualifiers are dropped.8436return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),8437RHSTy.getUnqualifiedType());8438// FIXME: Type of conditional expression must be complete in C mode.8439}84408441// C99 6.5.15p5: "If both operands have void type, the result has void type."8442// The following || allows only one side to be void (a GCC-ism).8443if (LHSTy->isVoidType() || RHSTy->isVoidType()) {8444QualType ResTy;8445if (LHSTy->isVoidType() && RHSTy->isVoidType()) {8446ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);8447} else if (RHSTy->isVoidType()) {8448ResTy = RHSTy;8449Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)8450<< RHS.get()->getSourceRange();8451} else {8452ResTy = LHSTy;8453Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)8454<< LHS.get()->getSourceRange();8455}8456LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);8457RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);8458return ResTy;8459}84608461// C23 6.5.15p7:8462// ... if both the second and third operands have nullptr_t type, the8463// result also has that type.8464if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))8465return ResTy;84668467// C99 6.5.15p6 - "if one operand is a null pointer constant, the result has8468// the type of the other operand."8469if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;8470if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;84718472// All objective-c pointer type analysis is done here.8473QualType compositeType =8474ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);8475if (LHS.isInvalid() || RHS.isInvalid())8476return QualType();8477if (!compositeType.isNull())8478return compositeType;847984808481// Handle block pointer types.8482if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())8483return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,8484QuestionLoc);84858486// Check constraints for C object pointers types (C99 6.5.15p3,6).8487if (LHSTy->isPointerType() && RHSTy->isPointerType())8488return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,8489QuestionLoc);84908491// GCC compatibility: soften pointer/integer mismatch. Note that8492// null pointers have been filtered out by this point.8493if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,8494/*IsIntFirstExpr=*/true))8495return RHSTy;8496if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,8497/*IsIntFirstExpr=*/false))8498return LHSTy;84998500// Emit a better diagnostic if one of the expressions is a null pointer8501// constant and the other is not a pointer type. In this case, the user most8502// likely forgot to take the address of the other expression.8503if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))8504return QualType();85058506// Finally, if the LHS and RHS types are canonically the same type, we can8507// use the common sugared type.8508if (Context.hasSameType(LHSTy, RHSTy))8509return Context.getCommonSugaredType(LHSTy, RHSTy);85108511// Otherwise, the operands are not compatible.8512Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)8513<< LHSTy << RHSTy << LHS.get()->getSourceRange()8514<< RHS.get()->getSourceRange();8515return QualType();8516}85178518/// SuggestParentheses - Emit a note with a fixit hint that wraps8519/// ParenRange in parentheses.8520static void SuggestParentheses(Sema &Self, SourceLocation Loc,8521const PartialDiagnostic &Note,8522SourceRange ParenRange) {8523SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());8524if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&8525EndLoc.isValid()) {8526Self.Diag(Loc, Note)8527<< FixItHint::CreateInsertion(ParenRange.getBegin(), "(")8528<< FixItHint::CreateInsertion(EndLoc, ")");8529} else {8530// We can't display the parentheses, so just show the bare note.8531Self.Diag(Loc, Note) << ParenRange;8532}8533}85348535static bool IsArithmeticOp(BinaryOperatorKind Opc) {8536return BinaryOperator::isAdditiveOp(Opc) ||8537BinaryOperator::isMultiplicativeOp(Opc) ||8538BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;8539// This only checks for bitwise-or and bitwise-and, but not bitwise-xor and8540// not any of the logical operators. Bitwise-xor is commonly used as a8541// logical-xor because there is no logical-xor operator. The logical8542// operators, including uses of xor, have a high false positive rate for8543// precedence warnings.8544}85458546/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary8547/// expression, either using a built-in or overloaded operator,8548/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side8549/// expression.8550static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,8551const Expr **RHSExprs) {8552// Don't strip parenthesis: we should not warn if E is in parenthesis.8553E = E->IgnoreImpCasts();8554E = E->IgnoreConversionOperatorSingleStep();8555E = E->IgnoreImpCasts();8556if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {8557E = MTE->getSubExpr();8558E = E->IgnoreImpCasts();8559}85608561// Built-in binary operator.8562if (const auto *OP = dyn_cast<BinaryOperator>(E);8563OP && IsArithmeticOp(OP->getOpcode())) {8564*Opcode = OP->getOpcode();8565*RHSExprs = OP->getRHS();8566return true;8567}85688569// Overloaded operator.8570if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {8571if (Call->getNumArgs() != 2)8572return false;85738574// Make sure this is really a binary operator that is safe to pass into8575// BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.8576OverloadedOperatorKind OO = Call->getOperator();8577if (OO < OO_Plus || OO > OO_Arrow ||8578OO == OO_PlusPlus || OO == OO_MinusMinus)8579return false;85808581BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);8582if (IsArithmeticOp(OpKind)) {8583*Opcode = OpKind;8584*RHSExprs = Call->getArg(1);8585return true;8586}8587}85888589return false;8590}85918592/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type8593/// or is a logical expression such as (x==y) which has int type, but is8594/// commonly interpreted as boolean.8595static bool ExprLooksBoolean(const Expr *E) {8596E = E->IgnoreParenImpCasts();85978598if (E->getType()->isBooleanType())8599return true;8600if (const auto *OP = dyn_cast<BinaryOperator>(E))8601return OP->isComparisonOp() || OP->isLogicalOp();8602if (const auto *OP = dyn_cast<UnaryOperator>(E))8603return OP->getOpcode() == UO_LNot;8604if (E->getType()->isPointerType())8605return true;8606// FIXME: What about overloaded operator calls returning "unspecified boolean8607// type"s (commonly pointer-to-members)?86088609return false;8610}86118612/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator8613/// and binary operator are mixed in a way that suggests the programmer assumed8614/// the conditional operator has higher precedence, for example:8615/// "int x = a + someBinaryCondition ? 1 : 2".8616static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,8617Expr *Condition, const Expr *LHSExpr,8618const Expr *RHSExpr) {8619BinaryOperatorKind CondOpcode;8620const Expr *CondRHS;86218622if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))8623return;8624if (!ExprLooksBoolean(CondRHS))8625return;86268627// The condition is an arithmetic binary expression, with a right-8628// hand side that looks boolean, so warn.86298630unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)8631? diag::warn_precedence_bitwise_conditional8632: diag::warn_precedence_conditional;86338634Self.Diag(OpLoc, DiagID)8635<< Condition->getSourceRange()8636<< BinaryOperator::getOpcodeStr(CondOpcode);86378638SuggestParentheses(8639Self, OpLoc,8640Self.PDiag(diag::note_precedence_silence)8641<< BinaryOperator::getOpcodeStr(CondOpcode),8642SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));86438644SuggestParentheses(Self, OpLoc,8645Self.PDiag(diag::note_precedence_conditional_first),8646SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));8647}86488649/// Compute the nullability of a conditional expression.8650static QualType computeConditionalNullability(QualType ResTy, bool IsBin,8651QualType LHSTy, QualType RHSTy,8652ASTContext &Ctx) {8653if (!ResTy->isAnyPointerType())8654return ResTy;86558656auto GetNullability = [](QualType Ty) {8657std::optional<NullabilityKind> Kind = Ty->getNullability();8658if (Kind) {8659// For our purposes, treat _Nullable_result as _Nullable.8660if (*Kind == NullabilityKind::NullableResult)8661return NullabilityKind::Nullable;8662return *Kind;8663}8664return NullabilityKind::Unspecified;8665};86668667auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);8668NullabilityKind MergedKind;86698670// Compute nullability of a binary conditional expression.8671if (IsBin) {8672if (LHSKind == NullabilityKind::NonNull)8673MergedKind = NullabilityKind::NonNull;8674else8675MergedKind = RHSKind;8676// Compute nullability of a normal conditional expression.8677} else {8678if (LHSKind == NullabilityKind::Nullable ||8679RHSKind == NullabilityKind::Nullable)8680MergedKind = NullabilityKind::Nullable;8681else if (LHSKind == NullabilityKind::NonNull)8682MergedKind = RHSKind;8683else if (RHSKind == NullabilityKind::NonNull)8684MergedKind = LHSKind;8685else8686MergedKind = NullabilityKind::Unspecified;8687}86888689// Return if ResTy already has the correct nullability.8690if (GetNullability(ResTy) == MergedKind)8691return ResTy;86928693// Strip all nullability from ResTy.8694while (ResTy->getNullability())8695ResTy = ResTy.getSingleStepDesugaredType(Ctx);86968697// Create a new AttributedType with the new nullability kind.8698auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);8699return Ctx.getAttributedType(NewAttr, ResTy, ResTy);8700}87018702ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,8703SourceLocation ColonLoc,8704Expr *CondExpr, Expr *LHSExpr,8705Expr *RHSExpr) {8706if (!Context.isDependenceAllowed()) {8707// C cannot handle TypoExpr nodes in the condition because it8708// doesn't handle dependent types properly, so make sure any TypoExprs have8709// been dealt with before checking the operands.8710ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);8711ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);8712ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);87138714if (!CondResult.isUsable())8715return ExprError();87168717if (LHSExpr) {8718if (!LHSResult.isUsable())8719return ExprError();8720}87218722if (!RHSResult.isUsable())8723return ExprError();87248725CondExpr = CondResult.get();8726LHSExpr = LHSResult.get();8727RHSExpr = RHSResult.get();8728}87298730// If this is the gnu "x ?: y" extension, analyze the types as though the LHS8731// was the condition.8732OpaqueValueExpr *opaqueValue = nullptr;8733Expr *commonExpr = nullptr;8734if (!LHSExpr) {8735commonExpr = CondExpr;8736// Lower out placeholder types first. This is important so that we don't8737// try to capture a placeholder. This happens in few cases in C++; such8738// as Objective-C++'s dictionary subscripting syntax.8739if (commonExpr->hasPlaceholderType()) {8740ExprResult result = CheckPlaceholderExpr(commonExpr);8741if (!result.isUsable()) return ExprError();8742commonExpr = result.get();8743}8744// We usually want to apply unary conversions *before* saving, except8745// in the special case of a C++ l-value conditional.8746if (!(getLangOpts().CPlusPlus8747&& !commonExpr->isTypeDependent()8748&& commonExpr->getValueKind() == RHSExpr->getValueKind()8749&& commonExpr->isGLValue()8750&& commonExpr->isOrdinaryOrBitFieldObject()8751&& RHSExpr->isOrdinaryOrBitFieldObject()8752&& Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {8753ExprResult commonRes = UsualUnaryConversions(commonExpr);8754if (commonRes.isInvalid())8755return ExprError();8756commonExpr = commonRes.get();8757}87588759// If the common expression is a class or array prvalue, materialize it8760// so that we can safely refer to it multiple times.8761if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||8762commonExpr->getType()->isArrayType())) {8763ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);8764if (MatExpr.isInvalid())8765return ExprError();8766commonExpr = MatExpr.get();8767}87688769opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),8770commonExpr->getType(),8771commonExpr->getValueKind(),8772commonExpr->getObjectKind(),8773commonExpr);8774LHSExpr = CondExpr = opaqueValue;8775}87768777QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();8778ExprValueKind VK = VK_PRValue;8779ExprObjectKind OK = OK_Ordinary;8780ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;8781QualType result = CheckConditionalOperands(Cond, LHS, RHS,8782VK, OK, QuestionLoc);8783if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||8784RHS.isInvalid())8785return ExprError();87868787DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),8788RHS.get());87898790CheckBoolLikeConversion(Cond.get(), QuestionLoc);87918792result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,8793Context);87948795if (!commonExpr)8796return new (Context)8797ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,8798RHS.get(), result, VK, OK);87998800return new (Context) BinaryConditionalOperator(8801commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,8802ColonLoc, result, VK, OK);8803}88048805bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {8806unsigned FromAttributes = 0, ToAttributes = 0;8807if (const auto *FromFn =8808dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))8809FromAttributes =8810FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;8811if (const auto *ToFn =8812dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))8813ToAttributes =8814ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;88158816return FromAttributes != ToAttributes;8817}88188819// Check if we have a conversion between incompatible cmse function pointer8820// types, that is, a conversion between a function pointer with the8821// cmse_nonsecure_call attribute and one without.8822static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,8823QualType ToType) {8824if (const auto *ToFn =8825dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {8826if (const auto *FromFn =8827dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {8828FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();8829FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();88308831return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();8832}8833}8834return false;8835}88368837// checkPointerTypesForAssignment - This is a very tricky routine (despite8838// being closely modeled after the C99 spec:-). The odd characteristic of this8839// routine is it effectively iqnores the qualifiers on the top level pointee.8840// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].8841// FIXME: add a couple examples in this comment.8842static Sema::AssignConvertType8843checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,8844SourceLocation Loc) {8845assert(LHSType.isCanonical() && "LHS not canonicalized!");8846assert(RHSType.isCanonical() && "RHS not canonicalized!");88478848// get the "pointed to" type (ignoring qualifiers at the top level)8849const Type *lhptee, *rhptee;8850Qualifiers lhq, rhq;8851std::tie(lhptee, lhq) =8852cast<PointerType>(LHSType)->getPointeeType().split().asPair();8853std::tie(rhptee, rhq) =8854cast<PointerType>(RHSType)->getPointeeType().split().asPair();88558856Sema::AssignConvertType ConvTy = Sema::Compatible;88578858// C99 6.5.16.1p1: This following citation is common to constraints8859// 3 & 4 (below). ...and the type *pointed to* by the left has all the8860// qualifiers of the type *pointed to* by the right;88618862// As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.8863if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&8864lhq.compatiblyIncludesObjCLifetime(rhq)) {8865// Ignore lifetime for further calculation.8866lhq.removeObjCLifetime();8867rhq.removeObjCLifetime();8868}88698870if (!lhq.compatiblyIncludes(rhq)) {8871// Treat address-space mismatches as fatal.8872if (!lhq.isAddressSpaceSupersetOf(rhq))8873return Sema::IncompatiblePointerDiscardsQualifiers;88748875// It's okay to add or remove GC or lifetime qualifiers when converting to8876// and from void*.8877else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()8878.compatiblyIncludes(8879rhq.withoutObjCGCAttr().withoutObjCLifetime())8880&& (lhptee->isVoidType() || rhptee->isVoidType()))8881; // keep old88828883// Treat lifetime mismatches as fatal.8884else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())8885ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;88868887// For GCC/MS compatibility, other qualifier mismatches are treated8888// as still compatible in C.8889else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;8890}88918892// C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or8893// incomplete type and the other is a pointer to a qualified or unqualified8894// version of void...8895if (lhptee->isVoidType()) {8896if (rhptee->isIncompleteOrObjectType())8897return ConvTy;88988899// As an extension, we allow cast to/from void* to function pointer.8900assert(rhptee->isFunctionType());8901return Sema::FunctionVoidPointer;8902}89038904if (rhptee->isVoidType()) {8905if (lhptee->isIncompleteOrObjectType())8906return ConvTy;89078908// As an extension, we allow cast to/from void* to function pointer.8909assert(lhptee->isFunctionType());8910return Sema::FunctionVoidPointer;8911}89128913if (!S.Diags.isIgnored(8914diag::warn_typecheck_convert_incompatible_function_pointer_strict,8915Loc) &&8916RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&8917!S.IsFunctionConversion(RHSType, LHSType, RHSType))8918return Sema::IncompatibleFunctionPointerStrict;89198920// C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or8921// unqualified versions of compatible types, ...8922QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);8923if (!S.Context.typesAreCompatible(ltrans, rtrans)) {8924// Check if the pointee types are compatible ignoring the sign.8925// We explicitly check for char so that we catch "char" vs8926// "unsigned char" on systems where "char" is unsigned.8927if (lhptee->isCharType())8928ltrans = S.Context.UnsignedCharTy;8929else if (lhptee->hasSignedIntegerRepresentation())8930ltrans = S.Context.getCorrespondingUnsignedType(ltrans);89318932if (rhptee->isCharType())8933rtrans = S.Context.UnsignedCharTy;8934else if (rhptee->hasSignedIntegerRepresentation())8935rtrans = S.Context.getCorrespondingUnsignedType(rtrans);89368937if (ltrans == rtrans) {8938// Types are compatible ignoring the sign. Qualifier incompatibility8939// takes priority over sign incompatibility because the sign8940// warning can be disabled.8941if (ConvTy != Sema::Compatible)8942return ConvTy;89438944return Sema::IncompatiblePointerSign;8945}89468947// If we are a multi-level pointer, it's possible that our issue is simply8948// one of qualification - e.g. char ** -> const char ** is not allowed. If8949// the eventual target type is the same and the pointers have the same8950// level of indirection, this must be the issue.8951if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {8952do {8953std::tie(lhptee, lhq) =8954cast<PointerType>(lhptee)->getPointeeType().split().asPair();8955std::tie(rhptee, rhq) =8956cast<PointerType>(rhptee)->getPointeeType().split().asPair();89578958// Inconsistent address spaces at this point is invalid, even if the8959// address spaces would be compatible.8960// FIXME: This doesn't catch address space mismatches for pointers of8961// different nesting levels, like:8962// __local int *** a;8963// int ** b = a;8964// It's not clear how to actually determine when such pointers are8965// invalidly incompatible.8966if (lhq.getAddressSpace() != rhq.getAddressSpace())8967return Sema::IncompatibleNestedPointerAddressSpaceMismatch;89688969} while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));89708971if (lhptee == rhptee)8972return Sema::IncompatibleNestedPointerQualifiers;8973}89748975// General pointer incompatibility takes priority over qualifiers.8976if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())8977return Sema::IncompatibleFunctionPointer;8978return Sema::IncompatiblePointer;8979}8980if (!S.getLangOpts().CPlusPlus &&8981S.IsFunctionConversion(ltrans, rtrans, ltrans))8982return Sema::IncompatibleFunctionPointer;8983if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))8984return Sema::IncompatibleFunctionPointer;8985if (S.IsInvalidSMECallConversion(rtrans, ltrans))8986return Sema::IncompatibleFunctionPointer;8987return ConvTy;8988}89898990/// checkBlockPointerTypesForAssignment - This routine determines whether two8991/// block pointer types are compatible or whether a block and normal pointer8992/// are compatible. It is more restrict than comparing two function pointer8993// types.8994static Sema::AssignConvertType8995checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,8996QualType RHSType) {8997assert(LHSType.isCanonical() && "LHS not canonicalized!");8998assert(RHSType.isCanonical() && "RHS not canonicalized!");89999000QualType lhptee, rhptee;90019002// get the "pointed to" type (ignoring qualifiers at the top level)9003lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();9004rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();90059006// In C++, the types have to match exactly.9007if (S.getLangOpts().CPlusPlus)9008return Sema::IncompatibleBlockPointer;90099010Sema::AssignConvertType ConvTy = Sema::Compatible;90119012// For blocks we enforce that qualifiers are identical.9013Qualifiers LQuals = lhptee.getLocalQualifiers();9014Qualifiers RQuals = rhptee.getLocalQualifiers();9015if (S.getLangOpts().OpenCL) {9016LQuals.removeAddressSpace();9017RQuals.removeAddressSpace();9018}9019if (LQuals != RQuals)9020ConvTy = Sema::CompatiblePointerDiscardsQualifiers;90219022// FIXME: OpenCL doesn't define the exact compile time semantics for a block9023// assignment.9024// The current behavior is similar to C++ lambdas. A block might be9025// assigned to a variable iff its return type and parameters are compatible9026// (C99 6.2.7) with the corresponding return type and parameters of the LHS of9027// an assignment. Presumably it should behave in way that a function pointer9028// assignment does in C, so for each parameter and return type:9029// * CVR and address space of LHS should be a superset of CVR and address9030// space of RHS.9031// * unqualified types should be compatible.9032if (S.getLangOpts().OpenCL) {9033if (!S.Context.typesAreBlockPointerCompatible(9034S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),9035S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))9036return Sema::IncompatibleBlockPointer;9037} else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))9038return Sema::IncompatibleBlockPointer;90399040return ConvTy;9041}90429043/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types9044/// for assignment compatibility.9045static Sema::AssignConvertType9046checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,9047QualType RHSType) {9048assert(LHSType.isCanonical() && "LHS was not canonicalized!");9049assert(RHSType.isCanonical() && "RHS was not canonicalized!");90509051if (LHSType->isObjCBuiltinType()) {9052// Class is not compatible with ObjC object pointers.9053if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&9054!RHSType->isObjCQualifiedClassType())9055return Sema::IncompatiblePointer;9056return Sema::Compatible;9057}9058if (RHSType->isObjCBuiltinType()) {9059if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&9060!LHSType->isObjCQualifiedClassType())9061return Sema::IncompatiblePointer;9062return Sema::Compatible;9063}9064QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();9065QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();90669067if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&9068// make an exception for id<P>9069!LHSType->isObjCQualifiedIdType())9070return Sema::CompatiblePointerDiscardsQualifiers;90719072if (S.Context.typesAreCompatible(LHSType, RHSType))9073return Sema::Compatible;9074if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())9075return Sema::IncompatibleObjCQualifiedId;9076return Sema::IncompatiblePointer;9077}90789079Sema::AssignConvertType9080Sema::CheckAssignmentConstraints(SourceLocation Loc,9081QualType LHSType, QualType RHSType) {9082// Fake up an opaque expression. We don't actually care about what9083// cast operations are required, so if CheckAssignmentConstraints9084// adds casts to this they'll be wasted, but fortunately that doesn't9085// usually happen on valid code.9086OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);9087ExprResult RHSPtr = &RHSExpr;9088CastKind K;90899090return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);9091}90929093/// This helper function returns true if QT is a vector type that has element9094/// type ElementType.9095static bool isVector(QualType QT, QualType ElementType) {9096if (const VectorType *VT = QT->getAs<VectorType>())9097return VT->getElementType().getCanonicalType() == ElementType;9098return false;9099}91009101/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently9102/// has code to accommodate several GCC extensions when type checking9103/// pointers. Here are some objectionable examples that GCC considers warnings:9104///9105/// int a, *pint;9106/// short *pshort;9107/// struct foo *pfoo;9108///9109/// pint = pshort; // warning: assignment from incompatible pointer type9110/// a = pint; // warning: assignment makes integer from pointer without a cast9111/// pint = a; // warning: assignment makes pointer from integer without a cast9112/// pint = pfoo; // warning: assignment from incompatible pointer type9113///9114/// As a result, the code for dealing with pointers is more complex than the9115/// C99 spec dictates.9116///9117/// Sets 'Kind' for any result kind except Incompatible.9118Sema::AssignConvertType9119Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,9120CastKind &Kind, bool ConvertRHS) {9121QualType RHSType = RHS.get()->getType();9122QualType OrigLHSType = LHSType;91239124// Get canonical types. We're not formatting these types, just comparing9125// them.9126LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();9127RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();91289129// Common case: no conversion required.9130if (LHSType == RHSType) {9131Kind = CK_NoOp;9132return Compatible;9133}91349135// If the LHS has an __auto_type, there are no additional type constraints9136// to be worried about.9137if (const auto *AT = dyn_cast<AutoType>(LHSType)) {9138if (AT->isGNUAutoType()) {9139Kind = CK_NoOp;9140return Compatible;9141}9142}91439144// If we have an atomic type, try a non-atomic assignment, then just add an9145// atomic qualification step.9146if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {9147Sema::AssignConvertType result =9148CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);9149if (result != Compatible)9150return result;9151if (Kind != CK_NoOp && ConvertRHS)9152RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);9153Kind = CK_NonAtomicToAtomic;9154return Compatible;9155}91569157// If the left-hand side is a reference type, then we are in a9158// (rare!) case where we've allowed the use of references in C,9159// e.g., as a parameter type in a built-in function. In this case,9160// just make sure that the type referenced is compatible with the9161// right-hand side type. The caller is responsible for adjusting9162// LHSType so that the resulting expression does not have reference9163// type.9164if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {9165if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {9166Kind = CK_LValueBitCast;9167return Compatible;9168}9169return Incompatible;9170}91719172// Allow scalar to ExtVector assignments, and assignments of an ExtVector type9173// to the same ExtVector type.9174if (LHSType->isExtVectorType()) {9175if (RHSType->isExtVectorType())9176return Incompatible;9177if (RHSType->isArithmeticType()) {9178// CK_VectorSplat does T -> vector T, so first cast to the element type.9179if (ConvertRHS)9180RHS = prepareVectorSplat(LHSType, RHS.get());9181Kind = CK_VectorSplat;9182return Compatible;9183}9184}91859186// Conversions to or from vector type.9187if (LHSType->isVectorType() || RHSType->isVectorType()) {9188if (LHSType->isVectorType() && RHSType->isVectorType()) {9189// Allow assignments of an AltiVec vector type to an equivalent GCC9190// vector type and vice versa9191if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {9192Kind = CK_BitCast;9193return Compatible;9194}91959196// If we are allowing lax vector conversions, and LHS and RHS are both9197// vectors, the total size only needs to be the same. This is a bitcast;9198// no bits are changed but the result type is different.9199if (isLaxVectorConversion(RHSType, LHSType)) {9200// The default for lax vector conversions with Altivec vectors will9201// change, so if we are converting between vector types where9202// at least one is an Altivec vector, emit a warning.9203if (Context.getTargetInfo().getTriple().isPPC() &&9204anyAltivecTypes(RHSType, LHSType) &&9205!Context.areCompatibleVectorTypes(RHSType, LHSType))9206Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)9207<< RHSType << LHSType;9208Kind = CK_BitCast;9209return IncompatibleVectors;9210}9211}92129213// When the RHS comes from another lax conversion (e.g. binops between9214// scalars and vectors) the result is canonicalized as a vector. When the9215// LHS is also a vector, the lax is allowed by the condition above. Handle9216// the case where LHS is a scalar.9217if (LHSType->isScalarType()) {9218const VectorType *VecType = RHSType->getAs<VectorType>();9219if (VecType && VecType->getNumElements() == 1 &&9220isLaxVectorConversion(RHSType, LHSType)) {9221if (Context.getTargetInfo().getTriple().isPPC() &&9222(VecType->getVectorKind() == VectorKind::AltiVecVector ||9223VecType->getVectorKind() == VectorKind::AltiVecBool ||9224VecType->getVectorKind() == VectorKind::AltiVecPixel))9225Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)9226<< RHSType << LHSType;9227ExprResult *VecExpr = &RHS;9228*VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);9229Kind = CK_BitCast;9230return Compatible;9231}9232}92339234// Allow assignments between fixed-length and sizeless SVE vectors.9235if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||9236(LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))9237if (Context.areCompatibleSveTypes(LHSType, RHSType) ||9238Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {9239Kind = CK_BitCast;9240return Compatible;9241}92429243// Allow assignments between fixed-length and sizeless RVV vectors.9244if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||9245(LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {9246if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||9247Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {9248Kind = CK_BitCast;9249return Compatible;9250}9251}92529253return Incompatible;9254}92559256// Diagnose attempts to convert between __ibm128, __float128 and long double9257// where such conversions currently can't be handled.9258if (unsupportedTypeConversion(*this, LHSType, RHSType))9259return Incompatible;92609261// Disallow assigning a _Complex to a real type in C++ mode since it simply9262// discards the imaginary part.9263if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&9264!LHSType->getAs<ComplexType>())9265return Incompatible;92669267// Arithmetic conversions.9268if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&9269!(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {9270if (ConvertRHS)9271Kind = PrepareScalarCast(RHS, LHSType);9272return Compatible;9273}92749275// Conversions to normal pointers.9276if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {9277// U* -> T*9278if (isa<PointerType>(RHSType)) {9279LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();9280LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();9281if (AddrSpaceL != AddrSpaceR)9282Kind = CK_AddressSpaceConversion;9283else if (Context.hasCvrSimilarType(RHSType, LHSType))9284Kind = CK_NoOp;9285else9286Kind = CK_BitCast;9287return checkPointerTypesForAssignment(*this, LHSType, RHSType,9288RHS.get()->getBeginLoc());9289}92909291// int -> T*9292if (RHSType->isIntegerType()) {9293Kind = CK_IntegralToPointer; // FIXME: null?9294return IntToPointer;9295}92969297// C pointers are not compatible with ObjC object pointers,9298// with two exceptions:9299if (isa<ObjCObjectPointerType>(RHSType)) {9300// - conversions to void*9301if (LHSPointer->getPointeeType()->isVoidType()) {9302Kind = CK_BitCast;9303return Compatible;9304}93059306// - conversions from 'Class' to the redefinition type9307if (RHSType->isObjCClassType() &&9308Context.hasSameType(LHSType,9309Context.getObjCClassRedefinitionType())) {9310Kind = CK_BitCast;9311return Compatible;9312}93139314Kind = CK_BitCast;9315return IncompatiblePointer;9316}93179318// U^ -> void*9319if (RHSType->getAs<BlockPointerType>()) {9320if (LHSPointer->getPointeeType()->isVoidType()) {9321LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();9322LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()9323->getPointeeType()9324.getAddressSpace();9325Kind =9326AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;9327return Compatible;9328}9329}93309331return Incompatible;9332}93339334// Conversions to block pointers.9335if (isa<BlockPointerType>(LHSType)) {9336// U^ -> T^9337if (RHSType->isBlockPointerType()) {9338LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()9339->getPointeeType()9340.getAddressSpace();9341LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()9342->getPointeeType()9343.getAddressSpace();9344Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;9345return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);9346}93479348// int or null -> T^9349if (RHSType->isIntegerType()) {9350Kind = CK_IntegralToPointer; // FIXME: null9351return IntToBlockPointer;9352}93539354// id -> T^9355if (getLangOpts().ObjC && RHSType->isObjCIdType()) {9356Kind = CK_AnyPointerToBlockPointerCast;9357return Compatible;9358}93599360// void* -> T^9361if (const PointerType *RHSPT = RHSType->getAs<PointerType>())9362if (RHSPT->getPointeeType()->isVoidType()) {9363Kind = CK_AnyPointerToBlockPointerCast;9364return Compatible;9365}93669367return Incompatible;9368}93699370// Conversions to Objective-C pointers.9371if (isa<ObjCObjectPointerType>(LHSType)) {9372// A* -> B*9373if (RHSType->isObjCObjectPointerType()) {9374Kind = CK_BitCast;9375Sema::AssignConvertType result =9376checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);9377if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&9378result == Compatible &&9379!ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))9380result = IncompatibleObjCWeakRef;9381return result;9382}93839384// int or null -> A*9385if (RHSType->isIntegerType()) {9386Kind = CK_IntegralToPointer; // FIXME: null9387return IntToPointer;9388}93899390// In general, C pointers are not compatible with ObjC object pointers,9391// with two exceptions:9392if (isa<PointerType>(RHSType)) {9393Kind = CK_CPointerToObjCPointerCast;93949395// - conversions from 'void*'9396if (RHSType->isVoidPointerType()) {9397return Compatible;9398}93999400// - conversions to 'Class' from its redefinition type9401if (LHSType->isObjCClassType() &&9402Context.hasSameType(RHSType,9403Context.getObjCClassRedefinitionType())) {9404return Compatible;9405}94069407return IncompatiblePointer;9408}94099410// Only under strict condition T^ is compatible with an Objective-C pointer.9411if (RHSType->isBlockPointerType() &&9412LHSType->isBlockCompatibleObjCPointerType(Context)) {9413if (ConvertRHS)9414maybeExtendBlockObject(RHS);9415Kind = CK_BlockPointerToObjCPointerCast;9416return Compatible;9417}94189419return Incompatible;9420}94219422// Conversion to nullptr_t (C23 only)9423if (getLangOpts().C23 && LHSType->isNullPtrType() &&9424RHS.get()->isNullPointerConstant(Context,9425Expr::NPC_ValueDependentIsNull)) {9426// null -> nullptr_t9427Kind = CK_NullToPointer;9428return Compatible;9429}94309431// Conversions from pointers that are not covered by the above.9432if (isa<PointerType>(RHSType)) {9433// T* -> _Bool9434if (LHSType == Context.BoolTy) {9435Kind = CK_PointerToBoolean;9436return Compatible;9437}94389439// T* -> int9440if (LHSType->isIntegerType()) {9441Kind = CK_PointerToIntegral;9442return PointerToInt;9443}94449445return Incompatible;9446}94479448// Conversions from Objective-C pointers that are not covered by the above.9449if (isa<ObjCObjectPointerType>(RHSType)) {9450// T* -> _Bool9451if (LHSType == Context.BoolTy) {9452Kind = CK_PointerToBoolean;9453return Compatible;9454}94559456// T* -> int9457if (LHSType->isIntegerType()) {9458Kind = CK_PointerToIntegral;9459return PointerToInt;9460}94619462return Incompatible;9463}94649465// struct A -> struct B9466if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {9467if (Context.typesAreCompatible(LHSType, RHSType)) {9468Kind = CK_NoOp;9469return Compatible;9470}9471}94729473if (LHSType->isSamplerT() && RHSType->isIntegerType()) {9474Kind = CK_IntToOCLSampler;9475return Compatible;9476}94779478return Incompatible;9479}94809481/// Constructs a transparent union from an expression that is9482/// used to initialize the transparent union.9483static void ConstructTransparentUnion(Sema &S, ASTContext &C,9484ExprResult &EResult, QualType UnionType,9485FieldDecl *Field) {9486// Build an initializer list that designates the appropriate member9487// of the transparent union.9488Expr *E = EResult.get();9489InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),9490E, SourceLocation());9491Initializer->setType(UnionType);9492Initializer->setInitializedFieldInUnion(Field);94939494// Build a compound literal constructing a value of the transparent9495// union type from this initializer list.9496TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);9497EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,9498VK_PRValue, Initializer, false);9499}95009501Sema::AssignConvertType9502Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,9503ExprResult &RHS) {9504QualType RHSType = RHS.get()->getType();95059506// If the ArgType is a Union type, we want to handle a potential9507// transparent_union GCC extension.9508const RecordType *UT = ArgType->getAsUnionType();9509if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())9510return Incompatible;95119512// The field to initialize within the transparent union.9513RecordDecl *UD = UT->getDecl();9514FieldDecl *InitField = nullptr;9515// It's compatible if the expression matches any of the fields.9516for (auto *it : UD->fields()) {9517if (it->getType()->isPointerType()) {9518// If the transparent union contains a pointer type, we allow:9519// 1) void pointer9520// 2) null pointer constant9521if (RHSType->isPointerType())9522if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {9523RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);9524InitField = it;9525break;9526}95279528if (RHS.get()->isNullPointerConstant(Context,9529Expr::NPC_ValueDependentIsNull)) {9530RHS = ImpCastExprToType(RHS.get(), it->getType(),9531CK_NullToPointer);9532InitField = it;9533break;9534}9535}95369537CastKind Kind;9538if (CheckAssignmentConstraints(it->getType(), RHS, Kind)9539== Compatible) {9540RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);9541InitField = it;9542break;9543}9544}95459546if (!InitField)9547return Incompatible;95489549ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);9550return Compatible;9551}95529553Sema::AssignConvertType9554Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,9555bool Diagnose,9556bool DiagnoseCFAudited,9557bool ConvertRHS) {9558// We need to be able to tell the caller whether we diagnosed a problem, if9559// they ask us to issue diagnostics.9560assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");95619562// If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,9563// we can't avoid *all* modifications at the moment, so we need some somewhere9564// to put the updated value.9565ExprResult LocalRHS = CallerRHS;9566ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;95679568if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {9569if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {9570if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&9571!LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {9572Diag(RHS.get()->getExprLoc(),9573diag::warn_noderef_to_dereferenceable_pointer)9574<< RHS.get()->getSourceRange();9575}9576}9577}95789579if (getLangOpts().CPlusPlus) {9580if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {9581// C++ 5.17p3: If the left operand is not of class type, the9582// expression is implicitly converted (C++ 4) to the9583// cv-unqualified type of the left operand.9584QualType RHSType = RHS.get()->getType();9585if (Diagnose) {9586RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),9587AA_Assigning);9588} else {9589ImplicitConversionSequence ICS =9590TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),9591/*SuppressUserConversions=*/false,9592AllowedExplicit::None,9593/*InOverloadResolution=*/false,9594/*CStyle=*/false,9595/*AllowObjCWritebackConversion=*/false);9596if (ICS.isFailure())9597return Incompatible;9598RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),9599ICS, AA_Assigning);9600}9601if (RHS.isInvalid())9602return Incompatible;9603Sema::AssignConvertType result = Compatible;9604if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&9605!ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))9606result = IncompatibleObjCWeakRef;9607return result;9608}96099610// FIXME: Currently, we fall through and treat C++ classes like C9611// structures.9612// FIXME: We also fall through for atomics; not sure what should9613// happen there, though.9614} else if (RHS.get()->getType() == Context.OverloadTy) {9615// As a set of extensions to C, we support overloading on functions. These9616// functions need to be resolved here.9617DeclAccessPair DAP;9618if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(9619RHS.get(), LHSType, /*Complain=*/false, DAP))9620RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);9621else9622return Incompatible;9623}96249625// This check seems unnatural, however it is necessary to ensure the proper9626// conversion of functions/arrays. If the conversion were done for all9627// DeclExpr's (created by ActOnIdExpression), it would mess up the unary9628// expressions that suppress this implicit conversion (&, sizeof). This needs9629// to happen before we check for null pointer conversions because C does not9630// undergo the same implicit conversions as C++ does above (by the calls to9631// TryImplicitConversion() and PerformImplicitConversion()) which insert the9632// lvalue to rvalue cast before checking for null pointer constraints. This9633// addresses code like: nullptr_t val; int *ptr; ptr = val;9634//9635// Suppress this for references: C++ 8.5.3p5.9636if (!LHSType->isReferenceType()) {9637// FIXME: We potentially allocate here even if ConvertRHS is false.9638RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);9639if (RHS.isInvalid())9640return Incompatible;9641}96429643// The constraints are expressed in terms of the atomic, qualified, or9644// unqualified type of the LHS.9645QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();96469647// C99 6.5.16.1p1: the left operand is a pointer and the right is9648// a null pointer constant <C23>or its type is nullptr_t;</C23>.9649if ((LHSTypeAfterConversion->isPointerType() ||9650LHSTypeAfterConversion->isObjCObjectPointerType() ||9651LHSTypeAfterConversion->isBlockPointerType()) &&9652((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||9653RHS.get()->isNullPointerConstant(Context,9654Expr::NPC_ValueDependentIsNull))) {9655if (Diagnose || ConvertRHS) {9656CastKind Kind;9657CXXCastPath Path;9658CheckPointerConversion(RHS.get(), LHSType, Kind, Path,9659/*IgnoreBaseAccess=*/false, Diagnose);9660if (ConvertRHS)9661RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);9662}9663return Compatible;9664}9665// C23 6.5.16.1p1: the left operand has type atomic, qualified, or9666// unqualified bool, and the right operand is a pointer or its type is9667// nullptr_t.9668if (getLangOpts().C23 && LHSType->isBooleanType() &&9669RHS.get()->getType()->isNullPtrType()) {9670// NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only9671// only handles nullptr -> _Bool due to needing an extra conversion9672// step.9673// We model this by converting from nullptr -> void * and then let the9674// conversion from void * -> _Bool happen naturally.9675if (Diagnose || ConvertRHS) {9676CastKind Kind;9677CXXCastPath Path;9678CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,9679/*IgnoreBaseAccess=*/false, Diagnose);9680if (ConvertRHS)9681RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,9682&Path);9683}9684}96859686// OpenCL queue_t type assignment.9687if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(9688Context, Expr::NPC_ValueDependentIsNull)) {9689RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);9690return Compatible;9691}96929693CastKind Kind;9694Sema::AssignConvertType result =9695CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);96969697// C99 6.5.16.1p2: The value of the right operand is converted to the9698// type of the assignment expression.9699// CheckAssignmentConstraints allows the left-hand side to be a reference,9700// so that we can use references in built-in functions even in C.9701// The getNonReferenceType() call makes sure that the resulting expression9702// does not have reference type.9703if (result != Incompatible && RHS.get()->getType() != LHSType) {9704QualType Ty = LHSType.getNonLValueExprType(Context);9705Expr *E = RHS.get();97069707// Check for various Objective-C errors. If we are not reporting9708// diagnostics and just checking for errors, e.g., during overload9709// resolution, return Incompatible to indicate the failure.9710if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&9711ObjC().CheckObjCConversion(SourceRange(), Ty, E,9712CheckedConversionKind::Implicit, Diagnose,9713DiagnoseCFAudited) != SemaObjC::ACR_okay) {9714if (!Diagnose)9715return Incompatible;9716}9717if (getLangOpts().ObjC &&9718(ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,9719E->getType(), E, Diagnose) ||9720ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {9721if (!Diagnose)9722return Incompatible;9723// Replace the expression with a corrected version and continue so we9724// can find further errors.9725RHS = E;9726return Compatible;9727}97289729if (ConvertRHS)9730RHS = ImpCastExprToType(E, Ty, Kind);9731}97329733return result;9734}97359736namespace {9737/// The original operand to an operator, prior to the application of the usual9738/// arithmetic conversions and converting the arguments of a builtin operator9739/// candidate.9740struct OriginalOperand {9741explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {9742if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))9743Op = MTE->getSubExpr();9744if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))9745Op = BTE->getSubExpr();9746if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {9747Orig = ICE->getSubExprAsWritten();9748Conversion = ICE->getConversionFunction();9749}9750}97519752QualType getType() const { return Orig->getType(); }97539754Expr *Orig;9755NamedDecl *Conversion;9756};9757}97589759QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,9760ExprResult &RHS) {9761OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());97629763Diag(Loc, diag::err_typecheck_invalid_operands)9764<< OrigLHS.getType() << OrigRHS.getType()9765<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();97669767// If a user-defined conversion was applied to either of the operands prior9768// to applying the built-in operator rules, tell the user about it.9769if (OrigLHS.Conversion) {9770Diag(OrigLHS.Conversion->getLocation(),9771diag::note_typecheck_invalid_operands_converted)9772<< 0 << LHS.get()->getType();9773}9774if (OrigRHS.Conversion) {9775Diag(OrigRHS.Conversion->getLocation(),9776diag::note_typecheck_invalid_operands_converted)9777<< 1 << RHS.get()->getType();9778}97799780return QualType();9781}97829783QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,9784ExprResult &RHS) {9785QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();9786QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();97879788bool LHSNatVec = LHSType->isVectorType();9789bool RHSNatVec = RHSType->isVectorType();97909791if (!(LHSNatVec && RHSNatVec)) {9792Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();9793Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();9794Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)9795<< 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()9796<< Vector->getSourceRange();9797return QualType();9798}97999800Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)9801<< 1 << LHSType << RHSType << LHS.get()->getSourceRange()9802<< RHS.get()->getSourceRange();98039804return QualType();9805}98069807/// Try to convert a value of non-vector type to a vector type by converting9808/// the type to the element type of the vector and then performing a splat.9809/// If the language is OpenCL, we only use conversions that promote scalar9810/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except9811/// for float->int.9812///9813/// OpenCL V2.0 6.2.6.p2:9814/// An error shall occur if any scalar operand type has greater rank9815/// than the type of the vector element.9816///9817/// \param scalar - if non-null, actually perform the conversions9818/// \return true if the operation fails (but without diagnosing the failure)9819static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,9820QualType scalarTy,9821QualType vectorEltTy,9822QualType vectorTy,9823unsigned &DiagID) {9824// The conversion to apply to the scalar before splatting it,9825// if necessary.9826CastKind scalarCast = CK_NoOp;98279828if (vectorEltTy->isIntegralType(S.Context)) {9829if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||9830(scalarTy->isIntegerType() &&9831S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {9832DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;9833return true;9834}9835if (!scalarTy->isIntegralType(S.Context))9836return true;9837scalarCast = CK_IntegralCast;9838} else if (vectorEltTy->isRealFloatingType()) {9839if (scalarTy->isRealFloatingType()) {9840if (S.getLangOpts().OpenCL &&9841S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {9842DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;9843return true;9844}9845scalarCast = CK_FloatingCast;9846}9847else if (scalarTy->isIntegralType(S.Context))9848scalarCast = CK_IntegralToFloating;9849else9850return true;9851} else {9852return true;9853}98549855// Adjust scalar if desired.9856if (scalar) {9857if (scalarCast != CK_NoOp)9858*scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);9859*scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);9860}9861return false;9862}98639864/// Convert vector E to a vector with the same number of elements but different9865/// element type.9866static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {9867const auto *VecTy = E->getType()->getAs<VectorType>();9868assert(VecTy && "Expression E must be a vector");9869QualType NewVecTy =9870VecTy->isExtVectorType()9871? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())9872: S.Context.getVectorType(ElementType, VecTy->getNumElements(),9873VecTy->getVectorKind());98749875// Look through the implicit cast. Return the subexpression if its type is9876// NewVecTy.9877if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))9878if (ICE->getSubExpr()->getType() == NewVecTy)9879return ICE->getSubExpr();98809881auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;9882return S.ImpCastExprToType(E, NewVecTy, Cast);9883}98849885/// Test if a (constant) integer Int can be casted to another integer type9886/// IntTy without losing precision.9887static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,9888QualType OtherIntTy) {9889QualType IntTy = Int->get()->getType().getUnqualifiedType();98909891// Reject cases where the value of the Int is unknown as that would9892// possibly cause truncation, but accept cases where the scalar can be9893// demoted without loss of precision.9894Expr::EvalResult EVResult;9895bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);9896int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);9897bool IntSigned = IntTy->hasSignedIntegerRepresentation();9898bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();98999900if (CstInt) {9901// If the scalar is constant and is of a higher order and has more active9902// bits that the vector element type, reject it.9903llvm::APSInt Result = EVResult.Val.getInt();9904unsigned NumBits = IntSigned9905? (Result.isNegative() ? Result.getSignificantBits()9906: Result.getActiveBits())9907: Result.getActiveBits();9908if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)9909return true;99109911// If the signedness of the scalar type and the vector element type9912// differs and the number of bits is greater than that of the vector9913// element reject it.9914return (IntSigned != OtherIntSigned &&9915NumBits > S.Context.getIntWidth(OtherIntTy));9916}99179918// Reject cases where the value of the scalar is not constant and it's9919// order is greater than that of the vector element type.9920return (Order < 0);9921}99229923/// Test if a (constant) integer Int can be casted to floating point type9924/// FloatTy without losing precision.9925static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,9926QualType FloatTy) {9927QualType IntTy = Int->get()->getType().getUnqualifiedType();99289929// Determine if the integer constant can be expressed as a floating point9930// number of the appropriate type.9931Expr::EvalResult EVResult;9932bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);99339934uint64_t Bits = 0;9935if (CstInt) {9936// Reject constants that would be truncated if they were converted to9937// the floating point type. Test by simple to/from conversion.9938// FIXME: Ideally the conversion to an APFloat and from an APFloat9939// could be avoided if there was a convertFromAPInt method9940// which could signal back if implicit truncation occurred.9941llvm::APSInt Result = EVResult.Val.getInt();9942llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));9943Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),9944llvm::APFloat::rmTowardZero);9945llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),9946!IntTy->hasSignedIntegerRepresentation());9947bool Ignored = false;9948Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,9949&Ignored);9950if (Result != ConvertBack)9951return true;9952} else {9953// Reject types that cannot be fully encoded into the mantissa of9954// the float.9955Bits = S.Context.getTypeSize(IntTy);9956unsigned FloatPrec = llvm::APFloat::semanticsPrecision(9957S.Context.getFloatTypeSemantics(FloatTy));9958if (Bits > FloatPrec)9959return true;9960}99619962return false;9963}99649965/// Attempt to convert and splat Scalar into a vector whose types matches9966/// Vector following GCC conversion rules. The rule is that implicit9967/// conversion can occur when Scalar can be casted to match Vector's element9968/// type without causing truncation of Scalar.9969static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,9970ExprResult *Vector) {9971QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();9972QualType VectorTy = Vector->get()->getType().getUnqualifiedType();9973QualType VectorEltTy;99749975if (const auto *VT = VectorTy->getAs<VectorType>()) {9976assert(!isa<ExtVectorType>(VT) &&9977"ExtVectorTypes should not be handled here!");9978VectorEltTy = VT->getElementType();9979} else if (VectorTy->isSveVLSBuiltinType()) {9980VectorEltTy =9981VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());9982} else {9983llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");9984}99859986// Reject cases where the vector element type or the scalar element type are9987// not integral or floating point types.9988if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())9989return true;99909991// The conversion to apply to the scalar before splatting it,9992// if necessary.9993CastKind ScalarCast = CK_NoOp;99949995// Accept cases where the vector elements are integers and the scalar is9996// an integer.9997// FIXME: Notionally if the scalar was a floating point value with a precise9998// integral representation, we could cast it to an appropriate integer9999// type and then perform the rest of the checks here. GCC will perform10000// this conversion in some cases as determined by the input language.10001// We should accept it on a language independent basis.10002if (VectorEltTy->isIntegralType(S.Context) &&10003ScalarTy->isIntegralType(S.Context) &&10004S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {1000510006if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))10007return true;1000810009ScalarCast = CK_IntegralCast;10010} else if (VectorEltTy->isIntegralType(S.Context) &&10011ScalarTy->isRealFloatingType()) {10012if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))10013ScalarCast = CK_FloatingToIntegral;10014else10015return true;10016} else if (VectorEltTy->isRealFloatingType()) {10017if (ScalarTy->isRealFloatingType()) {1001810019// Reject cases where the scalar type is not a constant and has a higher10020// Order than the vector element type.10021llvm::APFloat Result(0.0);1002210023// Determine whether this is a constant scalar. In the event that the10024// value is dependent (and thus cannot be evaluated by the constant10025// evaluator), skip the evaluation. This will then diagnose once the10026// expression is instantiated.10027bool CstScalar = Scalar->get()->isValueDependent() ||10028Scalar->get()->EvaluateAsFloat(Result, S.Context);10029int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);10030if (!CstScalar && Order < 0)10031return true;1003210033// If the scalar cannot be safely casted to the vector element type,10034// reject it.10035if (CstScalar) {10036bool Truncated = false;10037Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),10038llvm::APFloat::rmNearestTiesToEven, &Truncated);10039if (Truncated)10040return true;10041}1004210043ScalarCast = CK_FloatingCast;10044} else if (ScalarTy->isIntegralType(S.Context)) {10045if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))10046return true;1004710048ScalarCast = CK_IntegralToFloating;10049} else10050return true;10051} else if (ScalarTy->isEnumeralType())10052return true;1005310054// Adjust scalar if desired.10055if (ScalarCast != CK_NoOp)10056*Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);10057*Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);10058return false;10059}1006010061QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,10062SourceLocation Loc, bool IsCompAssign,10063bool AllowBothBool,10064bool AllowBoolConversions,10065bool AllowBoolOperation,10066bool ReportInvalid) {10067if (!IsCompAssign) {10068LHS = DefaultFunctionArrayLvalueConversion(LHS.get());10069if (LHS.isInvalid())10070return QualType();10071}10072RHS = DefaultFunctionArrayLvalueConversion(RHS.get());10073if (RHS.isInvalid())10074return QualType();1007510076// For conversion purposes, we ignore any qualifiers.10077// For example, "const float" and "float" are equivalent.10078QualType LHSType = LHS.get()->getType().getUnqualifiedType();10079QualType RHSType = RHS.get()->getType().getUnqualifiedType();1008010081const VectorType *LHSVecType = LHSType->getAs<VectorType>();10082const VectorType *RHSVecType = RHSType->getAs<VectorType>();10083assert(LHSVecType || RHSVecType);1008410085// AltiVec-style "vector bool op vector bool" combinations are allowed10086// for some operators but not others.10087if (!AllowBothBool && LHSVecType &&10088LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&10089RHSVecType->getVectorKind() == VectorKind::AltiVecBool)10090return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();1009110092// This operation may not be performed on boolean vectors.10093if (!AllowBoolOperation &&10094(LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))10095return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();1009610097// If the vector types are identical, return.10098if (Context.hasSameType(LHSType, RHSType))10099return Context.getCommonSugaredType(LHSType, RHSType);1010010101// If we have compatible AltiVec and GCC vector types, use the AltiVec type.10102if (LHSVecType && RHSVecType &&10103Context.areCompatibleVectorTypes(LHSType, RHSType)) {10104if (isa<ExtVectorType>(LHSVecType)) {10105RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);10106return LHSType;10107}1010810109if (!IsCompAssign)10110LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);10111return RHSType;10112}1011310114// AllowBoolConversions says that bool and non-bool AltiVec vectors10115// can be mixed, with the result being the non-bool type. The non-bool10116// operand must have integer element type.10117if (AllowBoolConversions && LHSVecType && RHSVecType &&10118LHSVecType->getNumElements() == RHSVecType->getNumElements() &&10119(Context.getTypeSize(LHSVecType->getElementType()) ==10120Context.getTypeSize(RHSVecType->getElementType()))) {10121if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&10122LHSVecType->getElementType()->isIntegerType() &&10123RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {10124RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);10125return LHSType;10126}10127if (!IsCompAssign &&10128LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&10129RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&10130RHSVecType->getElementType()->isIntegerType()) {10131LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);10132return RHSType;10133}10134}1013510136// Expressions containing fixed-length and sizeless SVE/RVV vectors are10137// invalid since the ambiguity can affect the ABI.10138auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,10139unsigned &SVEorRVV) {10140const VectorType *VecType = SecondType->getAs<VectorType>();10141SVEorRVV = 0;10142if (FirstType->isSizelessBuiltinType() && VecType) {10143if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||10144VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)10145return true;10146if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||10147VecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {10148SVEorRVV = 1;10149return true;10150}10151}1015210153return false;10154};1015510156unsigned SVEorRVV;10157if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||10158IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {10159Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)10160<< SVEorRVV << LHSType << RHSType;10161return QualType();10162}1016310164// Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are10165// invalid since the ambiguity can affect the ABI.10166auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,10167unsigned &SVEorRVV) {10168const VectorType *FirstVecType = FirstType->getAs<VectorType>();10169const VectorType *SecondVecType = SecondType->getAs<VectorType>();1017010171SVEorRVV = 0;10172if (FirstVecType && SecondVecType) {10173if (FirstVecType->getVectorKind() == VectorKind::Generic) {10174if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||10175SecondVecType->getVectorKind() ==10176VectorKind::SveFixedLengthPredicate)10177return true;10178if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||10179SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {10180SVEorRVV = 1;10181return true;10182}10183}10184return false;10185}1018610187if (SecondVecType &&10188SecondVecType->getVectorKind() == VectorKind::Generic) {10189if (FirstType->isSVESizelessBuiltinType())10190return true;10191if (FirstType->isRVVSizelessBuiltinType()) {10192SVEorRVV = 1;10193return true;10194}10195}1019610197return false;10198};1019910200if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||10201IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {10202Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)10203<< SVEorRVV << LHSType << RHSType;10204return QualType();10205}1020610207// If there's a vector type and a scalar, try to convert the scalar to10208// the vector element type and splat.10209unsigned DiagID = diag::err_typecheck_vector_not_convertable;10210if (!RHSVecType) {10211if (isa<ExtVectorType>(LHSVecType)) {10212if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,10213LHSVecType->getElementType(), LHSType,10214DiagID))10215return LHSType;10216} else {10217if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))10218return LHSType;10219}10220}10221if (!LHSVecType) {10222if (isa<ExtVectorType>(RHSVecType)) {10223if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),10224LHSType, RHSVecType->getElementType(),10225RHSType, DiagID))10226return RHSType;10227} else {10228if (LHS.get()->isLValue() ||10229!tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))10230return RHSType;10231}10232}1023310234// FIXME: The code below also handles conversion between vectors and10235// non-scalars, we should break this down into fine grained specific checks10236// and emit proper diagnostics.10237QualType VecType = LHSVecType ? LHSType : RHSType;10238const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;10239QualType OtherType = LHSVecType ? RHSType : LHSType;10240ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;10241if (isLaxVectorConversion(OtherType, VecType)) {10242if (Context.getTargetInfo().getTriple().isPPC() &&10243anyAltivecTypes(RHSType, LHSType) &&10244!Context.areCompatibleVectorTypes(RHSType, LHSType))10245Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;10246// If we're allowing lax vector conversions, only the total (data) size10247// needs to be the same. For non compound assignment, if one of the types is10248// scalar, the result is always the vector type.10249if (!IsCompAssign) {10250*OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);10251return VecType;10252// In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding10253// any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'10254// type. Note that this is already done by non-compound assignments in10255// CheckAssignmentConstraints. If it's a scalar type, only bitcast for10256// <1 x T> -> T. The result is also a vector type.10257} else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||10258(OtherType->isScalarType() && VT->getNumElements() == 1)) {10259ExprResult *RHSExpr = &RHS;10260*RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);10261return VecType;10262}10263}1026410265// Okay, the expression is invalid.1026610267// If there's a non-vector, non-real operand, diagnose that.10268if ((!RHSVecType && !RHSType->isRealType()) ||10269(!LHSVecType && !LHSType->isRealType())) {10270Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)10271<< LHSType << RHSType10272<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();10273return QualType();10274}1027510276// OpenCL V1.1 6.2.6.p1:10277// If the operands are of more than one vector type, then an error shall10278// occur. Implicit conversions between vector types are not permitted, per10279// section 6.2.1.10280if (getLangOpts().OpenCL &&10281RHSVecType && isa<ExtVectorType>(RHSVecType) &&10282LHSVecType && isa<ExtVectorType>(LHSVecType)) {10283Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType10284<< RHSType;10285return QualType();10286}102871028810289// If there is a vector type that is not a ExtVector and a scalar, we reach10290// this point if scalar could not be converted to the vector's element type10291// without truncation.10292if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||10293(LHSVecType && !isa<ExtVectorType>(LHSVecType))) {10294QualType Scalar = LHSVecType ? RHSType : LHSType;10295QualType Vector = LHSVecType ? LHSType : RHSType;10296unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;10297Diag(Loc,10298diag::err_typecheck_vector_not_convertable_implict_truncation)10299<< ScalarOrVector << Scalar << Vector;1030010301return QualType();10302}1030310304// Otherwise, use the generic diagnostic.10305Diag(Loc, DiagID)10306<< LHSType << RHSType10307<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();10308return QualType();10309}1031010311QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,10312SourceLocation Loc,10313bool IsCompAssign,10314ArithConvKind OperationKind) {10315if (!IsCompAssign) {10316LHS = DefaultFunctionArrayLvalueConversion(LHS.get());10317if (LHS.isInvalid())10318return QualType();10319}10320RHS = DefaultFunctionArrayLvalueConversion(RHS.get());10321if (RHS.isInvalid())10322return QualType();1032310324QualType LHSType = LHS.get()->getType().getUnqualifiedType();10325QualType RHSType = RHS.get()->getType().getUnqualifiedType();1032610327const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();10328const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();1032910330unsigned DiagID = diag::err_typecheck_invalid_operands;10331if ((OperationKind == ACK_Arithmetic) &&10332((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||10333(RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {10334Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()10335<< RHS.get()->getSourceRange();10336return QualType();10337}1033810339if (Context.hasSameType(LHSType, RHSType))10340return LHSType;1034110342if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {10343if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))10344return LHSType;10345}10346if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {10347if (LHS.get()->isLValue() ||10348!tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))10349return RHSType;10350}1035110352if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||10353(!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {10354Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)10355<< LHSType << RHSType << LHS.get()->getSourceRange()10356<< RHS.get()->getSourceRange();10357return QualType();10358}1035910360if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&10361Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=10362Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {10363Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)10364<< LHSType << RHSType << LHS.get()->getSourceRange()10365<< RHS.get()->getSourceRange();10366return QualType();10367}1036810369if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {10370QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;10371QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;10372bool ScalarOrVector =10373LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();1037410375Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)10376<< ScalarOrVector << Scalar << Vector;1037710378return QualType();10379}1038010381Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()10382<< RHS.get()->getSourceRange();10383return QualType();10384}1038510386// checkArithmeticNull - Detect when a NULL constant is used improperly in an10387// expression. These are mainly cases where the null pointer is used as an10388// integer instead of a pointer.10389static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,10390SourceLocation Loc, bool IsCompare) {10391// The canonical way to check for a GNU null is with isNullPointerConstant,10392// but we use a bit of a hack here for speed; this is a relatively10393// hot path, and isNullPointerConstant is slow.10394bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());10395bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());1039610397QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();1039810399// Avoid analyzing cases where the result will either be invalid (and10400// diagnosed as such) or entirely valid and not something to warn about.10401if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||10402NonNullType->isMemberPointerType() || NonNullType->isFunctionType())10403return;1040410405// Comparison operations would not make sense with a null pointer no matter10406// what the other expression is.10407if (!IsCompare) {10408S.Diag(Loc, diag::warn_null_in_arithmetic_operation)10409<< (LHSNull ? LHS.get()->getSourceRange() : SourceRange())10410<< (RHSNull ? RHS.get()->getSourceRange() : SourceRange());10411return;10412}1041310414// The rest of the operations only make sense with a null pointer10415// if the other expression is a pointer.10416if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||10417NonNullType->canDecayToPointerType())10418return;1041910420S.Diag(Loc, diag::warn_null_in_comparison_operation)10421<< LHSNull /* LHS is NULL */ << NonNullType10422<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();10423}1042410425static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,10426SourceLocation Loc) {10427const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);10428const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);10429if (!LUE || !RUE)10430return;10431if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||10432RUE->getKind() != UETT_SizeOf)10433return;1043410435const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();10436QualType LHSTy = LHSArg->getType();10437QualType RHSTy;1043810439if (RUE->isArgumentType())10440RHSTy = RUE->getArgumentType().getNonReferenceType();10441else10442RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();1044310444if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {10445if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))10446return;1044710448S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();10449if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {10450if (const ValueDecl *LHSArgDecl = DRE->getDecl())10451S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)10452<< LHSArgDecl;10453}10454} else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {10455QualType ArrayElemTy = ArrayTy->getElementType();10456if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||10457ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||10458RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||10459S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))10460return;10461S.Diag(Loc, diag::warn_division_sizeof_array)10462<< LHSArg->getSourceRange() << ArrayElemTy << RHSTy;10463if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {10464if (const ValueDecl *LHSArgDecl = DRE->getDecl())10465S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)10466<< LHSArgDecl;10467}1046810469S.Diag(Loc, diag::note_precedence_silence) << RHS;10470}10471}1047210473static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,10474ExprResult &RHS,10475SourceLocation Loc, bool IsDiv) {10476// Check for division/remainder by zero.10477Expr::EvalResult RHSValue;10478if (!RHS.get()->isValueDependent() &&10479RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&10480RHSValue.Val.getInt() == 0)10481S.DiagRuntimeBehavior(Loc, RHS.get(),10482S.PDiag(diag::warn_remainder_division_by_zero)10483<< IsDiv << RHS.get()->getSourceRange());10484}1048510486QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,10487SourceLocation Loc,10488bool IsCompAssign, bool IsDiv) {10489checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);1049010491QualType LHSTy = LHS.get()->getType();10492QualType RHSTy = RHS.get()->getType();10493if (LHSTy->isVectorType() || RHSTy->isVectorType())10494return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,10495/*AllowBothBool*/ getLangOpts().AltiVec,10496/*AllowBoolConversions*/ false,10497/*AllowBooleanOperation*/ false,10498/*ReportInvalid*/ true);10499if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())10500return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,10501ACK_Arithmetic);10502if (!IsDiv &&10503(LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))10504return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);10505// For division, only matrix-by-scalar is supported. Other combinations with10506// matrix types are invalid.10507if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())10508return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);1050910510QualType compType = UsualArithmeticConversions(10511LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);10512if (LHS.isInvalid() || RHS.isInvalid())10513return QualType();105141051510516if (compType.isNull() || !compType->isArithmeticType())10517return InvalidOperands(Loc, LHS, RHS);10518if (IsDiv) {10519DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);10520DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);10521}10522return compType;10523}1052410525QualType Sema::CheckRemainderOperands(10526ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {10527checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);1052810529if (LHS.get()->getType()->isVectorType() ||10530RHS.get()->getType()->isVectorType()) {10531if (LHS.get()->getType()->hasIntegerRepresentation() &&10532RHS.get()->getType()->hasIntegerRepresentation())10533return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,10534/*AllowBothBool*/ getLangOpts().AltiVec,10535/*AllowBoolConversions*/ false,10536/*AllowBooleanOperation*/ false,10537/*ReportInvalid*/ true);10538return InvalidOperands(Loc, LHS, RHS);10539}1054010541if (LHS.get()->getType()->isSveVLSBuiltinType() ||10542RHS.get()->getType()->isSveVLSBuiltinType()) {10543if (LHS.get()->getType()->hasIntegerRepresentation() &&10544RHS.get()->getType()->hasIntegerRepresentation())10545return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,10546ACK_Arithmetic);1054710548return InvalidOperands(Loc, LHS, RHS);10549}1055010551QualType compType = UsualArithmeticConversions(10552LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);10553if (LHS.isInvalid() || RHS.isInvalid())10554return QualType();1055510556if (compType.isNull() || !compType->isIntegerType())10557return InvalidOperands(Loc, LHS, RHS);10558DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);10559return compType;10560}1056110562/// Diagnose invalid arithmetic on two void pointers.10563static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,10564Expr *LHSExpr, Expr *RHSExpr) {10565S.Diag(Loc, S.getLangOpts().CPlusPlus10566? diag::err_typecheck_pointer_arith_void_type10567: diag::ext_gnu_void_ptr)10568<< 1 /* two pointers */ << LHSExpr->getSourceRange()10569<< RHSExpr->getSourceRange();10570}1057110572/// Diagnose invalid arithmetic on a void pointer.10573static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,10574Expr *Pointer) {10575S.Diag(Loc, S.getLangOpts().CPlusPlus10576? diag::err_typecheck_pointer_arith_void_type10577: diag::ext_gnu_void_ptr)10578<< 0 /* one pointer */ << Pointer->getSourceRange();10579}1058010581/// Diagnose invalid arithmetic on a null pointer.10582///10583/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'10584/// idiom, which we recognize as a GNU extension.10585///10586static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,10587Expr *Pointer, bool IsGNUIdiom) {10588if (IsGNUIdiom)10589S.Diag(Loc, diag::warn_gnu_null_ptr_arith)10590<< Pointer->getSourceRange();10591else10592S.Diag(Loc, diag::warn_pointer_arith_null_ptr)10593<< S.getLangOpts().CPlusPlus << Pointer->getSourceRange();10594}1059510596/// Diagnose invalid subraction on a null pointer.10597///10598static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,10599Expr *Pointer, bool BothNull) {10600// Null - null is valid in C++ [expr.add]p710601if (BothNull && S.getLangOpts().CPlusPlus)10602return;1060310604// Is this s a macro from a system header?10605if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))10606return;1060710608S.DiagRuntimeBehavior(Loc, Pointer,10609S.PDiag(diag::warn_pointer_sub_null_ptr)10610<< S.getLangOpts().CPlusPlus10611<< Pointer->getSourceRange());10612}1061310614/// Diagnose invalid arithmetic on two function pointers.10615static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,10616Expr *LHS, Expr *RHS) {10617assert(LHS->getType()->isAnyPointerType());10618assert(RHS->getType()->isAnyPointerType());10619S.Diag(Loc, S.getLangOpts().CPlusPlus10620? diag::err_typecheck_pointer_arith_function_type10621: diag::ext_gnu_ptr_func_arith)10622<< 1 /* two pointers */ << LHS->getType()->getPointeeType()10623// We only show the second type if it differs from the first.10624<< (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),10625RHS->getType())10626<< RHS->getType()->getPointeeType()10627<< LHS->getSourceRange() << RHS->getSourceRange();10628}1062910630/// Diagnose invalid arithmetic on a function pointer.10631static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,10632Expr *Pointer) {10633assert(Pointer->getType()->isAnyPointerType());10634S.Diag(Loc, S.getLangOpts().CPlusPlus10635? diag::err_typecheck_pointer_arith_function_type10636: diag::ext_gnu_ptr_func_arith)10637<< 0 /* one pointer */ << Pointer->getType()->getPointeeType()10638<< 0 /* one pointer, so only one type */10639<< Pointer->getSourceRange();10640}1064110642/// Emit error if Operand is incomplete pointer type10643///10644/// \returns True if pointer has incomplete type10645static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,10646Expr *Operand) {10647QualType ResType = Operand->getType();10648if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())10649ResType = ResAtomicType->getValueType();1065010651assert(ResType->isAnyPointerType());10652QualType PointeeTy = ResType->getPointeeType();10653return S.RequireCompleteSizedType(10654Loc, PointeeTy,10655diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,10656Operand->getSourceRange());10657}1065810659/// Check the validity of an arithmetic pointer operand.10660///10661/// If the operand has pointer type, this code will check for pointer types10662/// which are invalid in arithmetic operations. These will be diagnosed10663/// appropriately, including whether or not the use is supported as an10664/// extension.10665///10666/// \returns True when the operand is valid to use (even if as an extension).10667static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,10668Expr *Operand) {10669QualType ResType = Operand->getType();10670if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())10671ResType = ResAtomicType->getValueType();1067210673if (!ResType->isAnyPointerType()) return true;1067410675QualType PointeeTy = ResType->getPointeeType();10676if (PointeeTy->isVoidType()) {10677diagnoseArithmeticOnVoidPointer(S, Loc, Operand);10678return !S.getLangOpts().CPlusPlus;10679}10680if (PointeeTy->isFunctionType()) {10681diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);10682return !S.getLangOpts().CPlusPlus;10683}1068410685if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;1068610687return true;10688}1068910690/// Check the validity of a binary arithmetic operation w.r.t. pointer10691/// operands.10692///10693/// This routine will diagnose any invalid arithmetic on pointer operands much10694/// like \see checkArithmeticOpPointerOperand. However, it has special logic10695/// for emitting a single diagnostic even for operations where both LHS and RHS10696/// are (potentially problematic) pointers.10697///10698/// \returns True when the operand is valid to use (even if as an extension).10699static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,10700Expr *LHSExpr, Expr *RHSExpr) {10701bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();10702bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();10703if (!isLHSPointer && !isRHSPointer) return true;1070410705QualType LHSPointeeTy, RHSPointeeTy;10706if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();10707if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();1070810709// if both are pointers check if operation is valid wrt address spaces10710if (isLHSPointer && isRHSPointer) {10711if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {10712S.Diag(Loc,10713diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)10714<< LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/10715<< LHSExpr->getSourceRange() << RHSExpr->getSourceRange();10716return false;10717}10718}1071910720// Check for arithmetic on pointers to incomplete types.10721bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();10722bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();10723if (isLHSVoidPtr || isRHSVoidPtr) {10724if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);10725else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);10726else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);1072710728return !S.getLangOpts().CPlusPlus;10729}1073010731bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();10732bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();10733if (isLHSFuncPtr || isRHSFuncPtr) {10734if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);10735else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,10736RHSExpr);10737else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);1073810739return !S.getLangOpts().CPlusPlus;10740}1074110742if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))10743return false;10744if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))10745return false;1074610747return true;10748}1074910750/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string10751/// literal.10752static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,10753Expr *LHSExpr, Expr *RHSExpr) {10754StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());10755Expr* IndexExpr = RHSExpr;10756if (!StrExpr) {10757StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());10758IndexExpr = LHSExpr;10759}1076010761bool IsStringPlusInt = StrExpr &&10762IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();10763if (!IsStringPlusInt || IndexExpr->isValueDependent())10764return;1076510766SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());10767Self.Diag(OpLoc, diag::warn_string_plus_int)10768<< DiagRange << IndexExpr->IgnoreImpCasts()->getType();1076910770// Only print a fixit for "str" + int, not for int + "str".10771if (IndexExpr == RHSExpr) {10772SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());10773Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)10774<< FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")10775<< FixItHint::CreateReplacement(SourceRange(OpLoc), "[")10776<< FixItHint::CreateInsertion(EndLoc, "]");10777} else10778Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);10779}1078010781/// Emit a warning when adding a char literal to a string.10782static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,10783Expr *LHSExpr, Expr *RHSExpr) {10784const Expr *StringRefExpr = LHSExpr;10785const CharacterLiteral *CharExpr =10786dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());1078710788if (!CharExpr) {10789CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());10790StringRefExpr = RHSExpr;10791}1079210793if (!CharExpr || !StringRefExpr)10794return;1079510796const QualType StringType = StringRefExpr->getType();1079710798// Return if not a PointerType.10799if (!StringType->isAnyPointerType())10800return;1080110802// Return if not a CharacterType.10803if (!StringType->getPointeeType()->isAnyCharacterType())10804return;1080510806ASTContext &Ctx = Self.getASTContext();10807SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());1080810809const QualType CharType = CharExpr->getType();10810if (!CharType->isAnyCharacterType() &&10811CharType->isIntegerType() &&10812llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {10813Self.Diag(OpLoc, diag::warn_string_plus_char)10814<< DiagRange << Ctx.CharTy;10815} else {10816Self.Diag(OpLoc, diag::warn_string_plus_char)10817<< DiagRange << CharExpr->getType();10818}1081910820// Only print a fixit for str + char, not for char + str.10821if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {10822SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());10823Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)10824<< FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")10825<< FixItHint::CreateReplacement(SourceRange(OpLoc), "[")10826<< FixItHint::CreateInsertion(EndLoc, "]");10827} else {10828Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);10829}10830}1083110832/// Emit error when two pointers are incompatible.10833static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,10834Expr *LHSExpr, Expr *RHSExpr) {10835assert(LHSExpr->getType()->isAnyPointerType());10836assert(RHSExpr->getType()->isAnyPointerType());10837S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)10838<< LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()10839<< RHSExpr->getSourceRange();10840}1084110842// C99 6.5.610843QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,10844SourceLocation Loc, BinaryOperatorKind Opc,10845QualType* CompLHSTy) {10846checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);1084710848if (LHS.get()->getType()->isVectorType() ||10849RHS.get()->getType()->isVectorType()) {10850QualType compType =10851CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,10852/*AllowBothBool*/ getLangOpts().AltiVec,10853/*AllowBoolConversions*/ getLangOpts().ZVector,10854/*AllowBooleanOperation*/ false,10855/*ReportInvalid*/ true);10856if (CompLHSTy) *CompLHSTy = compType;10857return compType;10858}1085910860if (LHS.get()->getType()->isSveVLSBuiltinType() ||10861RHS.get()->getType()->isSveVLSBuiltinType()) {10862QualType compType =10863CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);10864if (CompLHSTy)10865*CompLHSTy = compType;10866return compType;10867}1086810869if (LHS.get()->getType()->isConstantMatrixType() ||10870RHS.get()->getType()->isConstantMatrixType()) {10871QualType compType =10872CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);10873if (CompLHSTy)10874*CompLHSTy = compType;10875return compType;10876}1087710878QualType compType = UsualArithmeticConversions(10879LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);10880if (LHS.isInvalid() || RHS.isInvalid())10881return QualType();1088210883// Diagnose "string literal" '+' int and string '+' "char literal".10884if (Opc == BO_Add) {10885diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());10886diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());10887}1088810889// handle the common case first (both operands are arithmetic).10890if (!compType.isNull() && compType->isArithmeticType()) {10891if (CompLHSTy) *CompLHSTy = compType;10892return compType;10893}1089410895// Type-checking. Ultimately the pointer's going to be in PExp;10896// note that we bias towards the LHS being the pointer.10897Expr *PExp = LHS.get(), *IExp = RHS.get();1089810899bool isObjCPointer;10900if (PExp->getType()->isPointerType()) {10901isObjCPointer = false;10902} else if (PExp->getType()->isObjCObjectPointerType()) {10903isObjCPointer = true;10904} else {10905std::swap(PExp, IExp);10906if (PExp->getType()->isPointerType()) {10907isObjCPointer = false;10908} else if (PExp->getType()->isObjCObjectPointerType()) {10909isObjCPointer = true;10910} else {10911return InvalidOperands(Loc, LHS, RHS);10912}10913}10914assert(PExp->getType()->isAnyPointerType());1091510916if (!IExp->getType()->isIntegerType())10917return InvalidOperands(Loc, LHS, RHS);1091810919// Adding to a null pointer results in undefined behavior.10920if (PExp->IgnoreParenCasts()->isNullPointerConstant(10921Context, Expr::NPC_ValueDependentIsNotNull)) {10922// In C++ adding zero to a null pointer is defined.10923Expr::EvalResult KnownVal;10924if (!getLangOpts().CPlusPlus ||10925(!IExp->isValueDependent() &&10926(!IExp->EvaluateAsInt(KnownVal, Context) ||10927KnownVal.Val.getInt() != 0))) {10928// Check the conditions to see if this is the 'p = nullptr + n' idiom.10929bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(10930Context, BO_Add, PExp, IExp);10931diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);10932}10933}1093410935if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))10936return QualType();1093710938if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))10939return QualType();1094010941// Arithmetic on label addresses is normally allowed, except when we add10942// a ptrauth signature to the addresses.10943if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {10944Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)10945<< /*addition*/ 1;10946return QualType();10947}1094810949// Check array bounds for pointer arithemtic10950CheckArrayAccess(PExp, IExp);1095110952if (CompLHSTy) {10953QualType LHSTy = Context.isPromotableBitField(LHS.get());10954if (LHSTy.isNull()) {10955LHSTy = LHS.get()->getType();10956if (Context.isPromotableIntegerType(LHSTy))10957LHSTy = Context.getPromotedIntegerType(LHSTy);10958}10959*CompLHSTy = LHSTy;10960}1096110962return PExp->getType();10963}1096410965// C99 6.5.610966QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,10967SourceLocation Loc,10968QualType* CompLHSTy) {10969checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);1097010971if (LHS.get()->getType()->isVectorType() ||10972RHS.get()->getType()->isVectorType()) {10973QualType compType =10974CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,10975/*AllowBothBool*/ getLangOpts().AltiVec,10976/*AllowBoolConversions*/ getLangOpts().ZVector,10977/*AllowBooleanOperation*/ false,10978/*ReportInvalid*/ true);10979if (CompLHSTy) *CompLHSTy = compType;10980return compType;10981}1098210983if (LHS.get()->getType()->isSveVLSBuiltinType() ||10984RHS.get()->getType()->isSveVLSBuiltinType()) {10985QualType compType =10986CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);10987if (CompLHSTy)10988*CompLHSTy = compType;10989return compType;10990}1099110992if (LHS.get()->getType()->isConstantMatrixType() ||10993RHS.get()->getType()->isConstantMatrixType()) {10994QualType compType =10995CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);10996if (CompLHSTy)10997*CompLHSTy = compType;10998return compType;10999}1100011001QualType compType = UsualArithmeticConversions(11002LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);11003if (LHS.isInvalid() || RHS.isInvalid())11004return QualType();1100511006// Enforce type constraints: C99 6.5.6p3.1100711008// Handle the common case first (both operands are arithmetic).11009if (!compType.isNull() && compType->isArithmeticType()) {11010if (CompLHSTy) *CompLHSTy = compType;11011return compType;11012}1101311014// Either ptr - int or ptr - ptr.11015if (LHS.get()->getType()->isAnyPointerType()) {11016QualType lpointee = LHS.get()->getType()->getPointeeType();1101711018// Diagnose bad cases where we step over interface counts.11019if (LHS.get()->getType()->isObjCObjectPointerType() &&11020checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))11021return QualType();1102211023// Arithmetic on label addresses is normally allowed, except when we add11024// a ptrauth signature to the addresses.11025if (isa<AddrLabelExpr>(LHS.get()) &&11026getLangOpts().PointerAuthIndirectGotos) {11027Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)11028<< /*subtraction*/ 0;11029return QualType();11030}1103111032// The result type of a pointer-int computation is the pointer type.11033if (RHS.get()->getType()->isIntegerType()) {11034// Subtracting from a null pointer should produce a warning.11035// The last argument to the diagnose call says this doesn't match the11036// GNU int-to-pointer idiom.11037if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,11038Expr::NPC_ValueDependentIsNotNull)) {11039// In C++ adding zero to a null pointer is defined.11040Expr::EvalResult KnownVal;11041if (!getLangOpts().CPlusPlus ||11042(!RHS.get()->isValueDependent() &&11043(!RHS.get()->EvaluateAsInt(KnownVal, Context) ||11044KnownVal.Val.getInt() != 0))) {11045diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);11046}11047}1104811049if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))11050return QualType();1105111052// Check array bounds for pointer arithemtic11053CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,11054/*AllowOnePastEnd*/true, /*IndexNegated*/true);1105511056if (CompLHSTy) *CompLHSTy = LHS.get()->getType();11057return LHS.get()->getType();11058}1105911060// Handle pointer-pointer subtractions.11061if (const PointerType *RHSPTy11062= RHS.get()->getType()->getAs<PointerType>()) {11063QualType rpointee = RHSPTy->getPointeeType();1106411065if (getLangOpts().CPlusPlus) {11066// Pointee types must be the same: C++ [expr.add]11067if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {11068diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());11069}11070} else {11071// Pointee types must be compatible C99 6.5.6p311072if (!Context.typesAreCompatible(11073Context.getCanonicalType(lpointee).getUnqualifiedType(),11074Context.getCanonicalType(rpointee).getUnqualifiedType())) {11075diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());11076return QualType();11077}11078}1107911080if (!checkArithmeticBinOpPointerOperands(*this, Loc,11081LHS.get(), RHS.get()))11082return QualType();1108311084bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(11085Context, Expr::NPC_ValueDependentIsNotNull);11086bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(11087Context, Expr::NPC_ValueDependentIsNotNull);1108811089// Subtracting nullptr or from nullptr is suspect11090if (LHSIsNullPtr)11091diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);11092if (RHSIsNullPtr)11093diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);1109411095// The pointee type may have zero size. As an extension, a structure or11096// union may have zero size or an array may have zero length. In this11097// case subtraction does not make sense.11098if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {11099CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);11100if (ElementSize.isZero()) {11101Diag(Loc,diag::warn_sub_ptr_zero_size_types)11102<< rpointee.getUnqualifiedType()11103<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11104}11105}1110611107if (CompLHSTy) *CompLHSTy = LHS.get()->getType();11108return Context.getPointerDiffType();11109}11110}1111111112return InvalidOperands(Loc, LHS, RHS);11113}1111411115static bool isScopedEnumerationType(QualType T) {11116if (const EnumType *ET = T->getAs<EnumType>())11117return ET->getDecl()->isScoped();11118return false;11119}1112011121static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,11122SourceLocation Loc, BinaryOperatorKind Opc,11123QualType LHSType) {11124// OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),11125// so skip remaining warnings as we don't want to modify values within Sema.11126if (S.getLangOpts().OpenCL)11127return;1112811129// Check right/shifter operand11130Expr::EvalResult RHSResult;11131if (RHS.get()->isValueDependent() ||11132!RHS.get()->EvaluateAsInt(RHSResult, S.Context))11133return;11134llvm::APSInt Right = RHSResult.Val.getInt();1113511136if (Right.isNegative()) {11137S.DiagRuntimeBehavior(Loc, RHS.get(),11138S.PDiag(diag::warn_shift_negative)11139<< RHS.get()->getSourceRange());11140return;11141}1114211143QualType LHSExprType = LHS.get()->getType();11144uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);11145if (LHSExprType->isBitIntType())11146LeftSize = S.Context.getIntWidth(LHSExprType);11147else if (LHSExprType->isFixedPointType()) {11148auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);11149LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();11150}11151if (Right.uge(LeftSize)) {11152S.DiagRuntimeBehavior(Loc, RHS.get(),11153S.PDiag(diag::warn_shift_gt_typewidth)11154<< RHS.get()->getSourceRange());11155return;11156}1115711158// FIXME: We probably need to handle fixed point types specially here.11159if (Opc != BO_Shl || LHSExprType->isFixedPointType())11160return;1116111162// When left shifting an ICE which is signed, we can check for overflow which11163// according to C++ standards prior to C++2a has undefined behavior11164// ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one11165// more than the maximum value representable in the result type, so never11166// warn for those. (FIXME: Unsigned left-shift overflow in a constant11167// expression is still probably a bug.)11168Expr::EvalResult LHSResult;11169if (LHS.get()->isValueDependent() ||11170LHSType->hasUnsignedIntegerRepresentation() ||11171!LHS.get()->EvaluateAsInt(LHSResult, S.Context))11172return;11173llvm::APSInt Left = LHSResult.Val.getInt();1117411175// Don't warn if signed overflow is defined, then all the rest of the11176// diagnostics will not be triggered because the behavior is defined.11177// Also don't warn in C++20 mode (and newer), as signed left shifts11178// always wrap and never overflow.11179if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)11180return;1118111182// If LHS does not have a non-negative value then, the11183// behavior is undefined before C++2a. Warn about it.11184if (Left.isNegative()) {11185S.DiagRuntimeBehavior(Loc, LHS.get(),11186S.PDiag(diag::warn_shift_lhs_negative)11187<< LHS.get()->getSourceRange());11188return;11189}1119011191llvm::APInt ResultBits =11192static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();11193if (ResultBits.ule(LeftSize))11194return;11195llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());11196Result = Result.shl(Right);1119711198// Print the bit representation of the signed integer as an unsigned11199// hexadecimal number.11200SmallString<40> HexResult;11201Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);1120211203// If we are only missing a sign bit, this is less likely to result in actual11204// bugs -- if the result is cast back to an unsigned type, it will have the11205// expected value. Thus we place this behind a different warning that can be11206// turned off separately if needed.11207if (ResultBits - 1 == LeftSize) {11208S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)11209<< HexResult << LHSType11210<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11211return;11212}1121311214S.Diag(Loc, diag::warn_shift_result_gt_typewidth)11215<< HexResult.str() << Result.getSignificantBits() << LHSType11216<< Left.getBitWidth() << LHS.get()->getSourceRange()11217<< RHS.get()->getSourceRange();11218}1121911220/// Return the resulting type when a vector is shifted11221/// by a scalar or vector shift amount.11222static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,11223SourceLocation Loc, bool IsCompAssign) {11224// OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.11225if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&11226!LHS.get()->getType()->isVectorType()) {11227S.Diag(Loc, diag::err_shift_rhs_only_vector)11228<< RHS.get()->getType() << LHS.get()->getType()11229<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11230return QualType();11231}1123211233if (!IsCompAssign) {11234LHS = S.UsualUnaryConversions(LHS.get());11235if (LHS.isInvalid()) return QualType();11236}1123711238RHS = S.UsualUnaryConversions(RHS.get());11239if (RHS.isInvalid()) return QualType();1124011241QualType LHSType = LHS.get()->getType();11242// Note that LHS might be a scalar because the routine calls not only in11243// OpenCL case.11244const VectorType *LHSVecTy = LHSType->getAs<VectorType>();11245QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;1124611247// Note that RHS might not be a vector.11248QualType RHSType = RHS.get()->getType();11249const VectorType *RHSVecTy = RHSType->getAs<VectorType>();11250QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;1125111252// Do not allow shifts for boolean vectors.11253if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||11254(RHSVecTy && RHSVecTy->isExtVectorBoolType())) {11255S.Diag(Loc, diag::err_typecheck_invalid_operands)11256<< LHS.get()->getType() << RHS.get()->getType()11257<< LHS.get()->getSourceRange();11258return QualType();11259}1126011261// The operands need to be integers.11262if (!LHSEleType->isIntegerType()) {11263S.Diag(Loc, diag::err_typecheck_expect_int)11264<< LHS.get()->getType() << LHS.get()->getSourceRange();11265return QualType();11266}1126711268if (!RHSEleType->isIntegerType()) {11269S.Diag(Loc, diag::err_typecheck_expect_int)11270<< RHS.get()->getType() << RHS.get()->getSourceRange();11271return QualType();11272}1127311274if (!LHSVecTy) {11275assert(RHSVecTy);11276if (IsCompAssign)11277return RHSType;11278if (LHSEleType != RHSEleType) {11279LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);11280LHSEleType = RHSEleType;11281}11282QualType VecTy =11283S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());11284LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);11285LHSType = VecTy;11286} else if (RHSVecTy) {11287// OpenCL v1.1 s6.3.j says that for vector types, the operators11288// are applied component-wise. So if RHS is a vector, then ensure11289// that the number of elements is the same as LHS...11290if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {11291S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)11292<< LHS.get()->getType() << RHS.get()->getType()11293<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11294return QualType();11295}11296if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {11297const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();11298const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();11299if (LHSBT != RHSBT &&11300S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {11301S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)11302<< LHS.get()->getType() << RHS.get()->getType()11303<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11304}11305}11306} else {11307// ...else expand RHS to match the number of elements in LHS.11308QualType VecTy =11309S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());11310RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);11311}1131211313return LHSType;11314}1131511316static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,11317ExprResult &RHS, SourceLocation Loc,11318bool IsCompAssign) {11319if (!IsCompAssign) {11320LHS = S.UsualUnaryConversions(LHS.get());11321if (LHS.isInvalid())11322return QualType();11323}1132411325RHS = S.UsualUnaryConversions(RHS.get());11326if (RHS.isInvalid())11327return QualType();1132811329QualType LHSType = LHS.get()->getType();11330const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();11331QualType LHSEleType = LHSType->isSveVLSBuiltinType()11332? LHSBuiltinTy->getSveEltType(S.getASTContext())11333: LHSType;1133411335// Note that RHS might not be a vector11336QualType RHSType = RHS.get()->getType();11337const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();11338QualType RHSEleType = RHSType->isSveVLSBuiltinType()11339? RHSBuiltinTy->getSveEltType(S.getASTContext())11340: RHSType;1134111342if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||11343(RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {11344S.Diag(Loc, diag::err_typecheck_invalid_operands)11345<< LHSType << RHSType << LHS.get()->getSourceRange();11346return QualType();11347}1134811349if (!LHSEleType->isIntegerType()) {11350S.Diag(Loc, diag::err_typecheck_expect_int)11351<< LHS.get()->getType() << LHS.get()->getSourceRange();11352return QualType();11353}1135411355if (!RHSEleType->isIntegerType()) {11356S.Diag(Loc, diag::err_typecheck_expect_int)11357<< RHS.get()->getType() << RHS.get()->getSourceRange();11358return QualType();11359}1136011361if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&11362(S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=11363S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {11364S.Diag(Loc, diag::err_typecheck_invalid_operands)11365<< LHSType << RHSType << LHS.get()->getSourceRange()11366<< RHS.get()->getSourceRange();11367return QualType();11368}1136911370if (!LHSType->isSveVLSBuiltinType()) {11371assert(RHSType->isSveVLSBuiltinType());11372if (IsCompAssign)11373return RHSType;11374if (LHSEleType != RHSEleType) {11375LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);11376LHSEleType = RHSEleType;11377}11378const llvm::ElementCount VecSize =11379S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;11380QualType VecTy =11381S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());11382LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);11383LHSType = VecTy;11384} else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {11385if (S.Context.getTypeSize(RHSBuiltinTy) !=11386S.Context.getTypeSize(LHSBuiltinTy)) {11387S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)11388<< LHSType << RHSType << LHS.get()->getSourceRange()11389<< RHS.get()->getSourceRange();11390return QualType();11391}11392} else {11393const llvm::ElementCount VecSize =11394S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;11395if (LHSEleType != RHSEleType) {11396RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);11397RHSEleType = LHSEleType;11398}11399QualType VecTy =11400S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());11401RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);11402}1140311404return LHSType;11405}1140611407// C99 6.5.711408QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,11409SourceLocation Loc, BinaryOperatorKind Opc,11410bool IsCompAssign) {11411checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);1141211413// Vector shifts promote their scalar inputs to vector type.11414if (LHS.get()->getType()->isVectorType() ||11415RHS.get()->getType()->isVectorType()) {11416if (LangOpts.ZVector) {11417// The shift operators for the z vector extensions work basically11418// like general shifts, except that neither the LHS nor the RHS is11419// allowed to be a "vector bool".11420if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())11421if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)11422return InvalidOperands(Loc, LHS, RHS);11423if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())11424if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)11425return InvalidOperands(Loc, LHS, RHS);11426}11427return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);11428}1142911430if (LHS.get()->getType()->isSveVLSBuiltinType() ||11431RHS.get()->getType()->isSveVLSBuiltinType())11432return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);1143311434// Shifts don't perform usual arithmetic conversions, they just do integer11435// promotions on each operand. C99 6.5.7p31143611437// For the LHS, do usual unary conversions, but then reset them away11438// if this is a compound assignment.11439ExprResult OldLHS = LHS;11440LHS = UsualUnaryConversions(LHS.get());11441if (LHS.isInvalid())11442return QualType();11443QualType LHSType = LHS.get()->getType();11444if (IsCompAssign) LHS = OldLHS;1144511446// The RHS is simpler.11447RHS = UsualUnaryConversions(RHS.get());11448if (RHS.isInvalid())11449return QualType();11450QualType RHSType = RHS.get()->getType();1145111452// C99 6.5.7p2: Each of the operands shall have integer type.11453// Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.11454if ((!LHSType->isFixedPointOrIntegerType() &&11455!LHSType->hasIntegerRepresentation()) ||11456!RHSType->hasIntegerRepresentation())11457return InvalidOperands(Loc, LHS, RHS);1145811459// C++0x: Don't allow scoped enums. FIXME: Use something better than11460// hasIntegerRepresentation() above instead of this.11461if (isScopedEnumerationType(LHSType) ||11462isScopedEnumerationType(RHSType)) {11463return InvalidOperands(Loc, LHS, RHS);11464}11465DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);1146611467// "The type of the result is that of the promoted left operand."11468return LHSType;11469}1147011471/// Diagnose bad pointer comparisons.11472static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,11473ExprResult &LHS, ExprResult &RHS,11474bool IsError) {11475S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers11476: diag::ext_typecheck_comparison_of_distinct_pointers)11477<< LHS.get()->getType() << RHS.get()->getType()11478<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11479}1148011481/// Returns false if the pointers are converted to a composite type,11482/// true otherwise.11483static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,11484ExprResult &LHS, ExprResult &RHS) {11485// C++ [expr.rel]p2:11486// [...] Pointer conversions (4.10) and qualification11487// conversions (4.4) are performed on pointer operands (or on11488// a pointer operand and a null pointer constant) to bring11489// them to their composite pointer type. [...]11490//11491// C++ [expr.eq]p1 uses the same notion for (in)equality11492// comparisons of pointers.1149311494QualType LHSType = LHS.get()->getType();11495QualType RHSType = RHS.get()->getType();11496assert(LHSType->isPointerType() || RHSType->isPointerType() ||11497LHSType->isMemberPointerType() || RHSType->isMemberPointerType());1149811499QualType T = S.FindCompositePointerType(Loc, LHS, RHS);11500if (T.isNull()) {11501if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&11502(RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))11503diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);11504else11505S.InvalidOperands(Loc, LHS, RHS);11506return true;11507}1150811509return false;11510}1151111512static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,11513ExprResult &LHS,11514ExprResult &RHS,11515bool IsError) {11516S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void11517: diag::ext_typecheck_comparison_of_fptr_to_void)11518<< LHS.get()->getType() << RHS.get()->getType()11519<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11520}1152111522static bool isObjCObjectLiteral(ExprResult &E) {11523switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {11524case Stmt::ObjCArrayLiteralClass:11525case Stmt::ObjCDictionaryLiteralClass:11526case Stmt::ObjCStringLiteralClass:11527case Stmt::ObjCBoxedExprClass:11528return true;11529default:11530// Note that ObjCBoolLiteral is NOT an object literal!11531return false;11532}11533}1153411535static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {11536const ObjCObjectPointerType *Type =11537LHS->getType()->getAs<ObjCObjectPointerType>();1153811539// If this is not actually an Objective-C object, bail out.11540if (!Type)11541return false;1154211543// Get the LHS object's interface type.11544QualType InterfaceType = Type->getPointeeType();1154511546// If the RHS isn't an Objective-C object, bail out.11547if (!RHS->getType()->isObjCObjectPointerType())11548return false;1154911550// Try to find the -isEqual: method.11551Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();11552ObjCMethodDecl *Method =11553S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,11554/*IsInstance=*/true);11555if (!Method) {11556if (Type->isObjCIdType()) {11557// For 'id', just check the global pool.11558Method =11559S.ObjC().LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),11560/*receiverId=*/true);11561} else {11562// Check protocols.11563Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,11564/*IsInstance=*/true);11565}11566}1156711568if (!Method)11569return false;1157011571QualType T = Method->parameters()[0]->getType();11572if (!T->isObjCObjectPointerType())11573return false;1157411575QualType R = Method->getReturnType();11576if (!R->isScalarType())11577return false;1157811579return true;11580}1158111582static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,11583ExprResult &LHS, ExprResult &RHS,11584BinaryOperator::Opcode Opc){11585Expr *Literal;11586Expr *Other;11587if (isObjCObjectLiteral(LHS)) {11588Literal = LHS.get();11589Other = RHS.get();11590} else {11591Literal = RHS.get();11592Other = LHS.get();11593}1159411595// Don't warn on comparisons against nil.11596Other = Other->IgnoreParenCasts();11597if (Other->isNullPointerConstant(S.getASTContext(),11598Expr::NPC_ValueDependentIsNotNull))11599return;1160011601// This should be kept in sync with warn_objc_literal_comparison.11602// LK_String should always be after the other literals, since it has its own11603// warning flag.11604SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);11605assert(LiteralKind != SemaObjC::LK_Block);11606if (LiteralKind == SemaObjC::LK_None) {11607llvm_unreachable("Unknown Objective-C object literal kind");11608}1160911610if (LiteralKind == SemaObjC::LK_String)11611S.Diag(Loc, diag::warn_objc_string_literal_comparison)11612<< Literal->getSourceRange();11613else11614S.Diag(Loc, diag::warn_objc_literal_comparison)11615<< LiteralKind << Literal->getSourceRange();1161611617if (BinaryOperator::isEqualityOp(Opc) &&11618hasIsEqualMethod(S, LHS.get(), RHS.get())) {11619SourceLocation Start = LHS.get()->getBeginLoc();11620SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());11621CharSourceRange OpRange =11622CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));1162311624S.Diag(Loc, diag::note_objc_literal_comparison_isequal)11625<< FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")11626<< FixItHint::CreateReplacement(OpRange, " isEqual:")11627<< FixItHint::CreateInsertion(End, "]");11628}11629}1163011631/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.11632static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,11633ExprResult &RHS, SourceLocation Loc,11634BinaryOperatorKind Opc) {11635// Check that left hand side is !something.11636UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());11637if (!UO || UO->getOpcode() != UO_LNot) return;1163811639// Only check if the right hand side is non-bool arithmetic type.11640if (RHS.get()->isKnownToHaveBooleanValue()) return;1164111642// Make sure that the something in !something is not bool.11643Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();11644if (SubExpr->isKnownToHaveBooleanValue()) return;1164511646// Emit warning.11647bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;11648S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)11649<< Loc << IsBitwiseOp;1165011651// First note suggest !(x < y)11652SourceLocation FirstOpen = SubExpr->getBeginLoc();11653SourceLocation FirstClose = RHS.get()->getEndLoc();11654FirstClose = S.getLocForEndOfToken(FirstClose);11655if (FirstClose.isInvalid())11656FirstOpen = SourceLocation();11657S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)11658<< IsBitwiseOp11659<< FixItHint::CreateInsertion(FirstOpen, "(")11660<< FixItHint::CreateInsertion(FirstClose, ")");1166111662// Second note suggests (!x) < y11663SourceLocation SecondOpen = LHS.get()->getBeginLoc();11664SourceLocation SecondClose = LHS.get()->getEndLoc();11665SecondClose = S.getLocForEndOfToken(SecondClose);11666if (SecondClose.isInvalid())11667SecondOpen = SourceLocation();11668S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)11669<< FixItHint::CreateInsertion(SecondOpen, "(")11670<< FixItHint::CreateInsertion(SecondClose, ")");11671}1167211673// Returns true if E refers to a non-weak array.11674static bool checkForArray(const Expr *E) {11675const ValueDecl *D = nullptr;11676if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {11677D = DR->getDecl();11678} else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {11679if (Mem->isImplicitAccess())11680D = Mem->getMemberDecl();11681}11682if (!D)11683return false;11684return D->getType()->isArrayType() && !D->isWeak();11685}1168611687/// Diagnose some forms of syntactically-obvious tautological comparison.11688static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,11689Expr *LHS, Expr *RHS,11690BinaryOperatorKind Opc) {11691Expr *LHSStripped = LHS->IgnoreParenImpCasts();11692Expr *RHSStripped = RHS->IgnoreParenImpCasts();1169311694QualType LHSType = LHS->getType();11695QualType RHSType = RHS->getType();11696if (LHSType->hasFloatingRepresentation() ||11697(LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||11698S.inTemplateInstantiation())11699return;1170011701// WebAssembly Tables cannot be compared, therefore shouldn't emit11702// Tautological diagnostics.11703if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())11704return;1170511706// Comparisons between two array types are ill-formed for operator<=>, so11707// we shouldn't emit any additional warnings about it.11708if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())11709return;1171011711// For non-floating point types, check for self-comparisons of the form11712// x == x, x != x, x < x, etc. These always evaluate to a constant, and11713// often indicate logic errors in the program.11714//11715// NOTE: Don't warn about comparison expressions resulting from macro11716// expansion. Also don't warn about comparisons which are only self11717// comparisons within a template instantiation. The warnings should catch11718// obvious cases in the definition of the template anyways. The idea is to11719// warn when the typed comparison operator will always evaluate to the same11720// result.1172111722// Used for indexing into %select in warn_comparison_always11723enum {11724AlwaysConstant,11725AlwaysTrue,11726AlwaysFalse,11727AlwaysEqual, // std::strong_ordering::equal from operator<=>11728};1172911730// C++2a [depr.array.comp]:11731// Equality and relational comparisons ([expr.eq], [expr.rel]) between two11732// operands of array type are deprecated.11733if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&11734RHSStripped->getType()->isArrayType()) {11735S.Diag(Loc, diag::warn_depr_array_comparison)11736<< LHS->getSourceRange() << RHS->getSourceRange()11737<< LHSStripped->getType() << RHSStripped->getType();11738// Carry on to produce the tautological comparison warning, if this11739// expression is potentially-evaluated, we can resolve the array to a11740// non-weak declaration, and so on.11741}1174211743if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {11744if (Expr::isSameComparisonOperand(LHS, RHS)) {11745unsigned Result;11746switch (Opc) {11747case BO_EQ:11748case BO_LE:11749case BO_GE:11750Result = AlwaysTrue;11751break;11752case BO_NE:11753case BO_LT:11754case BO_GT:11755Result = AlwaysFalse;11756break;11757case BO_Cmp:11758Result = AlwaysEqual;11759break;11760default:11761Result = AlwaysConstant;11762break;11763}11764S.DiagRuntimeBehavior(Loc, nullptr,11765S.PDiag(diag::warn_comparison_always)11766<< 0 /*self-comparison*/11767<< Result);11768} else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {11769// What is it always going to evaluate to?11770unsigned Result;11771switch (Opc) {11772case BO_EQ: // e.g. array1 == array211773Result = AlwaysFalse;11774break;11775case BO_NE: // e.g. array1 != array211776Result = AlwaysTrue;11777break;11778default: // e.g. array1 <= array211779// The best we can say is 'a constant'11780Result = AlwaysConstant;11781break;11782}11783S.DiagRuntimeBehavior(Loc, nullptr,11784S.PDiag(diag::warn_comparison_always)11785<< 1 /*array comparison*/11786<< Result);11787}11788}1178911790if (isa<CastExpr>(LHSStripped))11791LHSStripped = LHSStripped->IgnoreParenCasts();11792if (isa<CastExpr>(RHSStripped))11793RHSStripped = RHSStripped->IgnoreParenCasts();1179411795// Warn about comparisons against a string constant (unless the other11796// operand is null); the user probably wants string comparison function.11797Expr *LiteralString = nullptr;11798Expr *LiteralStringStripped = nullptr;11799if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&11800!RHSStripped->isNullPointerConstant(S.Context,11801Expr::NPC_ValueDependentIsNull)) {11802LiteralString = LHS;11803LiteralStringStripped = LHSStripped;11804} else if ((isa<StringLiteral>(RHSStripped) ||11805isa<ObjCEncodeExpr>(RHSStripped)) &&11806!LHSStripped->isNullPointerConstant(S.Context,11807Expr::NPC_ValueDependentIsNull)) {11808LiteralString = RHS;11809LiteralStringStripped = RHSStripped;11810}1181111812if (LiteralString) {11813S.DiagRuntimeBehavior(Loc, nullptr,11814S.PDiag(diag::warn_stringcompare)11815<< isa<ObjCEncodeExpr>(LiteralStringStripped)11816<< LiteralString->getSourceRange());11817}11818}1181911820static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {11821switch (CK) {11822default: {11823#ifndef NDEBUG11824llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)11825<< "\n";11826#endif11827llvm_unreachable("unhandled cast kind");11828}11829case CK_UserDefinedConversion:11830return ICK_Identity;11831case CK_LValueToRValue:11832return ICK_Lvalue_To_Rvalue;11833case CK_ArrayToPointerDecay:11834return ICK_Array_To_Pointer;11835case CK_FunctionToPointerDecay:11836return ICK_Function_To_Pointer;11837case CK_IntegralCast:11838return ICK_Integral_Conversion;11839case CK_FloatingCast:11840return ICK_Floating_Conversion;11841case CK_IntegralToFloating:11842case CK_FloatingToIntegral:11843return ICK_Floating_Integral;11844case CK_IntegralComplexCast:11845case CK_FloatingComplexCast:11846case CK_FloatingComplexToIntegralComplex:11847case CK_IntegralComplexToFloatingComplex:11848return ICK_Complex_Conversion;11849case CK_FloatingComplexToReal:11850case CK_FloatingRealToComplex:11851case CK_IntegralComplexToReal:11852case CK_IntegralRealToComplex:11853return ICK_Complex_Real;11854case CK_HLSLArrayRValue:11855return ICK_HLSL_Array_RValue;11856}11857}1185811859static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,11860QualType FromType,11861SourceLocation Loc) {11862// Check for a narrowing implicit conversion.11863StandardConversionSequence SCS;11864SCS.setAsIdentityConversion();11865SCS.setToType(0, FromType);11866SCS.setToType(1, ToType);11867if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))11868SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());1186911870APValue PreNarrowingValue;11871QualType PreNarrowingType;11872switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,11873PreNarrowingType,11874/*IgnoreFloatToIntegralConversion*/ true)) {11875case NK_Dependent_Narrowing:11876// Implicit conversion to a narrower type, but the expression is11877// value-dependent so we can't tell whether it's actually narrowing.11878case NK_Not_Narrowing:11879return false;1188011881case NK_Constant_Narrowing:11882// Implicit conversion to a narrower type, and the value is not a constant11883// expression.11884S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)11885<< /*Constant*/ 111886<< PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;11887return true;1188811889case NK_Variable_Narrowing:11890// Implicit conversion to a narrower type, and the value is not a constant11891// expression.11892case NK_Type_Narrowing:11893S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)11894<< /*Constant*/ 0 << FromType << ToType;11895// TODO: It's not a constant expression, but what if the user intended it11896// to be? Can we produce notes to help them figure out why it isn't?11897return true;11898}11899llvm_unreachable("unhandled case in switch");11900}1190111902static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,11903ExprResult &LHS,11904ExprResult &RHS,11905SourceLocation Loc) {11906QualType LHSType = LHS.get()->getType();11907QualType RHSType = RHS.get()->getType();11908// Dig out the original argument type and expression before implicit casts11909// were applied. These are the types/expressions we need to check the11910// [expr.spaceship] requirements against.11911ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();11912ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();11913QualType LHSStrippedType = LHSStripped.get()->getType();11914QualType RHSStrippedType = RHSStripped.get()->getType();1191511916// C++2a [expr.spaceship]p3: If one of the operands is of type bool and the11917// other is not, the program is ill-formed.11918if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {11919S.InvalidOperands(Loc, LHSStripped, RHSStripped);11920return QualType();11921}1192211923// FIXME: Consider combining this with checkEnumArithmeticConversions.11924int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +11925RHSStrippedType->isEnumeralType();11926if (NumEnumArgs == 1) {11927bool LHSIsEnum = LHSStrippedType->isEnumeralType();11928QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;11929if (OtherTy->hasFloatingRepresentation()) {11930S.InvalidOperands(Loc, LHSStripped, RHSStripped);11931return QualType();11932}11933}11934if (NumEnumArgs == 2) {11935// C++2a [expr.spaceship]p5: If both operands have the same enumeration11936// type E, the operator yields the result of converting the operands11937// to the underlying type of E and applying <=> to the converted operands.11938if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {11939S.InvalidOperands(Loc, LHS, RHS);11940return QualType();11941}11942QualType IntType =11943LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();11944assert(IntType->isArithmeticType());1194511946// We can't use `CK_IntegralCast` when the underlying type is 'bool', so we11947// promote the boolean type, and all other promotable integer types, to11948// avoid this.11949if (S.Context.isPromotableIntegerType(IntType))11950IntType = S.Context.getPromotedIntegerType(IntType);1195111952LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);11953RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);11954LHSType = RHSType = IntType;11955}1195611957// C++2a [expr.spaceship]p4: If both operands have arithmetic types, the11958// usual arithmetic conversions are applied to the operands.11959QualType Type =11960S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);11961if (LHS.isInvalid() || RHS.isInvalid())11962return QualType();11963if (Type.isNull())11964return S.InvalidOperands(Loc, LHS, RHS);1196511966std::optional<ComparisonCategoryType> CCT =11967getComparisonCategoryForBuiltinCmp(Type);11968if (!CCT)11969return S.InvalidOperands(Loc, LHS, RHS);1197011971bool HasNarrowing = checkThreeWayNarrowingConversion(11972S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());11973HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,11974RHS.get()->getBeginLoc());11975if (HasNarrowing)11976return QualType();1197711978assert(!Type.isNull() && "composite type for <=> has not been set");1197911980return S.CheckComparisonCategoryType(11981*CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);11982}1198311984static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,11985ExprResult &RHS,11986SourceLocation Loc,11987BinaryOperatorKind Opc) {11988if (Opc == BO_Cmp)11989return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);1199011991// C99 6.5.8p3 / C99 6.5.9p411992QualType Type =11993S.UsualArithmeticConversions(LHS, RHS, Loc, Sema::ACK_Comparison);11994if (LHS.isInvalid() || RHS.isInvalid())11995return QualType();11996if (Type.isNull())11997return S.InvalidOperands(Loc, LHS, RHS);11998assert(Type->isArithmeticType() || Type->isEnumeralType());1199912000if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))12001return S.InvalidOperands(Loc, LHS, RHS);1200212003// Check for comparisons of floating point operands using != and ==.12004if (Type->hasFloatingRepresentation())12005S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);1200612007// The result of comparisons is 'bool' in C++, 'int' in C.12008return S.Context.getLogicalOperationType();12009}1201012011void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {12012if (!NullE.get()->getType()->isAnyPointerType())12013return;12014int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;12015if (!E.get()->getType()->isAnyPointerType() &&12016E.get()->isNullPointerConstant(Context,12017Expr::NPC_ValueDependentIsNotNull) ==12018Expr::NPCK_ZeroExpression) {12019if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {12020if (CL->getValue() == 0)12021Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)12022<< NullValue12023<< FixItHint::CreateReplacement(E.get()->getExprLoc(),12024NullValue ? "NULL" : "(void *)0");12025} else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {12026TypeSourceInfo *TI = CE->getTypeInfoAsWritten();12027QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();12028if (T == Context.CharTy)12029Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)12030<< NullValue12031<< FixItHint::CreateReplacement(E.get()->getExprLoc(),12032NullValue ? "NULL" : "(void *)0");12033}12034}12035}1203612037// C99 6.5.8, C++ [expr.rel]12038QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,12039SourceLocation Loc,12040BinaryOperatorKind Opc) {12041bool IsRelational = BinaryOperator::isRelationalOp(Opc);12042bool IsThreeWay = Opc == BO_Cmp;12043bool IsOrdered = IsRelational || IsThreeWay;12044auto IsAnyPointerType = [](ExprResult E) {12045QualType Ty = E.get()->getType();12046return Ty->isPointerType() || Ty->isMemberPointerType();12047};1204812049// C++2a [expr.spaceship]p6: If at least one of the operands is of pointer12050// type, array-to-pointer, ..., conversions are performed on both operands to12051// bring them to their composite type.12052// Otherwise, all comparisons expect an rvalue, so convert to rvalue before12053// any type-related checks.12054if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {12055LHS = DefaultFunctionArrayLvalueConversion(LHS.get());12056if (LHS.isInvalid())12057return QualType();12058RHS = DefaultFunctionArrayLvalueConversion(RHS.get());12059if (RHS.isInvalid())12060return QualType();12061} else {12062LHS = DefaultLvalueConversion(LHS.get());12063if (LHS.isInvalid())12064return QualType();12065RHS = DefaultLvalueConversion(RHS.get());12066if (RHS.isInvalid())12067return QualType();12068}1206912070checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);12071if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {12072CheckPtrComparisonWithNullChar(LHS, RHS);12073CheckPtrComparisonWithNullChar(RHS, LHS);12074}1207512076// Handle vector comparisons separately.12077if (LHS.get()->getType()->isVectorType() ||12078RHS.get()->getType()->isVectorType())12079return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);1208012081if (LHS.get()->getType()->isSveVLSBuiltinType() ||12082RHS.get()->getType()->isSveVLSBuiltinType())12083return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);1208412085diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);12086diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);1208712088QualType LHSType = LHS.get()->getType();12089QualType RHSType = RHS.get()->getType();12090if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&12091(RHSType->isArithmeticType() || RHSType->isEnumeralType()))12092return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);1209312094if ((LHSType->isPointerType() &&12095LHSType->getPointeeType().isWebAssemblyReferenceType()) ||12096(RHSType->isPointerType() &&12097RHSType->getPointeeType().isWebAssemblyReferenceType()))12098return InvalidOperands(Loc, LHS, RHS);1209912100const Expr::NullPointerConstantKind LHSNullKind =12101LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);12102const Expr::NullPointerConstantKind RHSNullKind =12103RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);12104bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;12105bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;1210612107auto computeResultTy = [&]() {12108if (Opc != BO_Cmp)12109return Context.getLogicalOperationType();12110assert(getLangOpts().CPlusPlus);12111assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));1211212113QualType CompositeTy = LHS.get()->getType();12114assert(!CompositeTy->isReferenceType());1211512116std::optional<ComparisonCategoryType> CCT =12117getComparisonCategoryForBuiltinCmp(CompositeTy);12118if (!CCT)12119return InvalidOperands(Loc, LHS, RHS);1212012121if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {12122// P0946R0: Comparisons between a null pointer constant and an object12123// pointer result in std::strong_equality, which is ill-formed under12124// P1959R0.12125Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)12126<< (LHSIsNull ? LHS.get()->getSourceRange()12127: RHS.get()->getSourceRange());12128return QualType();12129}1213012131return CheckComparisonCategoryType(12132*CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);12133};1213412135if (!IsOrdered && LHSIsNull != RHSIsNull) {12136bool IsEquality = Opc == BO_EQ;12137if (RHSIsNull)12138DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,12139RHS.get()->getSourceRange());12140else12141DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,12142LHS.get()->getSourceRange());12143}1214412145if (IsOrdered && LHSType->isFunctionPointerType() &&12146RHSType->isFunctionPointerType()) {12147// Valid unless a relational comparison of function pointers12148bool IsError = Opc == BO_Cmp;12149auto DiagID =12150IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers12151: getLangOpts().CPlusPlus12152? diag::warn_typecheck_ordered_comparison_of_function_pointers12153: diag::ext_typecheck_ordered_comparison_of_function_pointers;12154Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()12155<< RHS.get()->getSourceRange();12156if (IsError)12157return QualType();12158}1215912160if ((LHSType->isIntegerType() && !LHSIsNull) ||12161(RHSType->isIntegerType() && !RHSIsNull)) {12162// Skip normal pointer conversion checks in this case; we have better12163// diagnostics for this below.12164} else if (getLangOpts().CPlusPlus) {12165// Equality comparison of a function pointer to a void pointer is invalid,12166// but we allow it as an extension.12167// FIXME: If we really want to allow this, should it be part of composite12168// pointer type computation so it works in conditionals too?12169if (!IsOrdered &&12170((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||12171(RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {12172// This is a gcc extension compatibility comparison.12173// In a SFINAE context, we treat this as a hard error to maintain12174// conformance with the C++ standard.12175diagnoseFunctionPointerToVoidComparison(12176*this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());1217712178if (isSFINAEContext())12179return QualType();1218012181RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);12182return computeResultTy();12183}1218412185// C++ [expr.eq]p2:12186// If at least one operand is a pointer [...] bring them to their12187// composite pointer type.12188// C++ [expr.spaceship]p612189// If at least one of the operands is of pointer type, [...] bring them12190// to their composite pointer type.12191// C++ [expr.rel]p2:12192// If both operands are pointers, [...] bring them to their composite12193// pointer type.12194// For <=>, the only valid non-pointer types are arrays and functions, and12195// we already decayed those, so this is really the same as the relational12196// comparison rule.12197if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=12198(IsOrdered ? 2 : 1) &&12199(!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||12200RHSType->isObjCObjectPointerType()))) {12201if (convertPointersToCompositeType(*this, Loc, LHS, RHS))12202return QualType();12203return computeResultTy();12204}12205} else if (LHSType->isPointerType() &&12206RHSType->isPointerType()) { // C99 6.5.8p212207// All of the following pointer-related warnings are GCC extensions, except12208// when handling null pointer constants.12209QualType LCanPointeeTy =12210LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();12211QualType RCanPointeeTy =12212RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();1221312214// C99 6.5.9p2 and C99 6.5.8p212215if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),12216RCanPointeeTy.getUnqualifiedType())) {12217if (IsRelational) {12218// Pointers both need to point to complete or incomplete types12219if ((LCanPointeeTy->isIncompleteType() !=12220RCanPointeeTy->isIncompleteType()) &&12221!getLangOpts().C11) {12222Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)12223<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange()12224<< LHSType << RHSType << LCanPointeeTy->isIncompleteType()12225<< RCanPointeeTy->isIncompleteType();12226}12227}12228} else if (!IsRelational &&12229(LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {12230// Valid unless comparison between non-null pointer and function pointer12231if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())12232&& !LHSIsNull && !RHSIsNull)12233diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,12234/*isError*/false);12235} else {12236// Invalid12237diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);12238}12239if (LCanPointeeTy != RCanPointeeTy) {12240// Treat NULL constant as a special case in OpenCL.12241if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {12242if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {12243Diag(Loc,12244diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)12245<< LHSType << RHSType << 0 /* comparison */12246<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange();12247}12248}12249LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();12250LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();12251CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion12252: CK_BitCast;12253if (LHSIsNull && !RHSIsNull)12254LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);12255else12256RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);12257}12258return computeResultTy();12259}122601226112262// C++ [expr.eq]p4:12263// Two operands of type std::nullptr_t or one operand of type12264// std::nullptr_t and the other a null pointer constant compare12265// equal.12266// C23 6.5.9p5:12267// If both operands have type nullptr_t or one operand has type nullptr_t12268// and the other is a null pointer constant, they compare equal if the12269// former is a null pointer.12270if (!IsOrdered && LHSIsNull && RHSIsNull) {12271if (LHSType->isNullPtrType()) {12272RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12273return computeResultTy();12274}12275if (RHSType->isNullPtrType()) {12276LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12277return computeResultTy();12278}12279}1228012281if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {12282// C23 6.5.9p6:12283// Otherwise, at least one operand is a pointer. If one is a pointer and12284// the other is a null pointer constant or has type nullptr_t, they12285// compare equal12286if (LHSIsNull && RHSType->isPointerType()) {12287LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12288return computeResultTy();12289}12290if (RHSIsNull && LHSType->isPointerType()) {12291RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12292return computeResultTy();12293}12294}1229512296// Comparison of Objective-C pointers and block pointers against nullptr_t.12297// These aren't covered by the composite pointer type rules.12298if (!IsOrdered && RHSType->isNullPtrType() &&12299(LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {12300RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12301return computeResultTy();12302}12303if (!IsOrdered && LHSType->isNullPtrType() &&12304(RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {12305LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12306return computeResultTy();12307}1230812309if (getLangOpts().CPlusPlus) {12310if (IsRelational &&12311((LHSType->isNullPtrType() && RHSType->isPointerType()) ||12312(RHSType->isNullPtrType() && LHSType->isPointerType()))) {12313// HACK: Relational comparison of nullptr_t against a pointer type is12314// invalid per DR583, but we allow it within std::less<> and friends,12315// since otherwise common uses of it break.12316// FIXME: Consider removing this hack once LWG fixes std::less<> and12317// friends to have std::nullptr_t overload candidates.12318DeclContext *DC = CurContext;12319if (isa<FunctionDecl>(DC))12320DC = DC->getParent();12321if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {12322if (CTSD->isInStdNamespace() &&12323llvm::StringSwitch<bool>(CTSD->getName())12324.Cases("less", "less_equal", "greater", "greater_equal", true)12325.Default(false)) {12326if (RHSType->isNullPtrType())12327RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12328else12329LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12330return computeResultTy();12331}12332}12333}1233412335// C++ [expr.eq]p2:12336// If at least one operand is a pointer to member, [...] bring them to12337// their composite pointer type.12338if (!IsOrdered &&12339(LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {12340if (convertPointersToCompositeType(*this, Loc, LHS, RHS))12341return QualType();12342else12343return computeResultTy();12344}12345}1234612347// Handle block pointer types.12348if (!IsOrdered && LHSType->isBlockPointerType() &&12349RHSType->isBlockPointerType()) {12350QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();12351QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();1235212353if (!LHSIsNull && !RHSIsNull &&12354!Context.typesAreCompatible(lpointee, rpointee)) {12355Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)12356<< LHSType << RHSType << LHS.get()->getSourceRange()12357<< RHS.get()->getSourceRange();12358}12359RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);12360return computeResultTy();12361}1236212363// Allow block pointers to be compared with null pointer constants.12364if (!IsOrdered12365&& ((LHSType->isBlockPointerType() && RHSType->isPointerType())12366|| (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {12367if (!LHSIsNull && !RHSIsNull) {12368if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()12369->getPointeeType()->isVoidType())12370|| (LHSType->isPointerType() && LHSType->castAs<PointerType>()12371->getPointeeType()->isVoidType())))12372Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)12373<< LHSType << RHSType << LHS.get()->getSourceRange()12374<< RHS.get()->getSourceRange();12375}12376if (LHSIsNull && !RHSIsNull)12377LHS = ImpCastExprToType(LHS.get(), RHSType,12378RHSType->isPointerType() ? CK_BitCast12379: CK_AnyPointerToBlockPointerCast);12380else12381RHS = ImpCastExprToType(RHS.get(), LHSType,12382LHSType->isPointerType() ? CK_BitCast12383: CK_AnyPointerToBlockPointerCast);12384return computeResultTy();12385}1238612387if (LHSType->isObjCObjectPointerType() ||12388RHSType->isObjCObjectPointerType()) {12389const PointerType *LPT = LHSType->getAs<PointerType>();12390const PointerType *RPT = RHSType->getAs<PointerType>();12391if (LPT || RPT) {12392bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;12393bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;1239412395if (!LPtrToVoid && !RPtrToVoid &&12396!Context.typesAreCompatible(LHSType, RHSType)) {12397diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,12398/*isError*/false);12399}12400// FIXME: If LPtrToVoid, we should presumably convert the LHS rather than12401// the RHS, but we have test coverage for this behavior.12402// FIXME: Consider using convertPointersToCompositeType in C++.12403if (LHSIsNull && !RHSIsNull) {12404Expr *E = LHS.get();12405if (getLangOpts().ObjCAutoRefCount)12406ObjC().CheckObjCConversion(SourceRange(), RHSType, E,12407CheckedConversionKind::Implicit);12408LHS = ImpCastExprToType(E, RHSType,12409RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);12410}12411else {12412Expr *E = RHS.get();12413if (getLangOpts().ObjCAutoRefCount)12414ObjC().CheckObjCConversion(SourceRange(), LHSType, E,12415CheckedConversionKind::Implicit,12416/*Diagnose=*/true,12417/*DiagnoseCFAudited=*/false, Opc);12418RHS = ImpCastExprToType(E, LHSType,12419LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);12420}12421return computeResultTy();12422}12423if (LHSType->isObjCObjectPointerType() &&12424RHSType->isObjCObjectPointerType()) {12425if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))12426diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,12427/*isError*/false);12428if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))12429diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);1243012431if (LHSIsNull && !RHSIsNull)12432LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);12433else12434RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);12435return computeResultTy();12436}1243712438if (!IsOrdered && LHSType->isBlockPointerType() &&12439RHSType->isBlockCompatibleObjCPointerType(Context)) {12440LHS = ImpCastExprToType(LHS.get(), RHSType,12441CK_BlockPointerToObjCPointerCast);12442return computeResultTy();12443} else if (!IsOrdered &&12444LHSType->isBlockCompatibleObjCPointerType(Context) &&12445RHSType->isBlockPointerType()) {12446RHS = ImpCastExprToType(RHS.get(), LHSType,12447CK_BlockPointerToObjCPointerCast);12448return computeResultTy();12449}12450}12451if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||12452(LHSType->isIntegerType() && RHSType->isAnyPointerType())) {12453unsigned DiagID = 0;12454bool isError = false;12455if (LangOpts.DebuggerSupport) {12456// Under a debugger, allow the comparison of pointers to integers,12457// since users tend to want to compare addresses.12458} else if ((LHSIsNull && LHSType->isIntegerType()) ||12459(RHSIsNull && RHSType->isIntegerType())) {12460if (IsOrdered) {12461isError = getLangOpts().CPlusPlus;12462DiagID =12463isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero12464: diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;12465}12466} else if (getLangOpts().CPlusPlus) {12467DiagID = diag::err_typecheck_comparison_of_pointer_integer;12468isError = true;12469} else if (IsOrdered)12470DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;12471else12472DiagID = diag::ext_typecheck_comparison_of_pointer_integer;1247312474if (DiagID) {12475Diag(Loc, DiagID)12476<< LHSType << RHSType << LHS.get()->getSourceRange()12477<< RHS.get()->getSourceRange();12478if (isError)12479return QualType();12480}1248112482if (LHSType->isIntegerType())12483LHS = ImpCastExprToType(LHS.get(), RHSType,12484LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);12485else12486RHS = ImpCastExprToType(RHS.get(), LHSType,12487RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);12488return computeResultTy();12489}1249012491// Handle block pointers.12492if (!IsOrdered && RHSIsNull12493&& LHSType->isBlockPointerType() && RHSType->isIntegerType()) {12494RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12495return computeResultTy();12496}12497if (!IsOrdered && LHSIsNull12498&& LHSType->isIntegerType() && RHSType->isBlockPointerType()) {12499LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12500return computeResultTy();12501}1250212503if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {12504if (LHSType->isClkEventT() && RHSType->isClkEventT()) {12505return computeResultTy();12506}1250712508if (LHSType->isQueueT() && RHSType->isQueueT()) {12509return computeResultTy();12510}1251112512if (LHSIsNull && RHSType->isQueueT()) {12513LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12514return computeResultTy();12515}1251612517if (LHSType->isQueueT() && RHSIsNull) {12518RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12519return computeResultTy();12520}12521}1252212523return InvalidOperands(Loc, LHS, RHS);12524}1252512526QualType Sema::GetSignedVectorType(QualType V) {12527const VectorType *VTy = V->castAs<VectorType>();12528unsigned TypeSize = Context.getTypeSize(VTy->getElementType());1252912530if (isa<ExtVectorType>(VTy)) {12531if (VTy->isExtVectorBoolType())12532return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());12533if (TypeSize == Context.getTypeSize(Context.CharTy))12534return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());12535if (TypeSize == Context.getTypeSize(Context.ShortTy))12536return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());12537if (TypeSize == Context.getTypeSize(Context.IntTy))12538return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());12539if (TypeSize == Context.getTypeSize(Context.Int128Ty))12540return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());12541if (TypeSize == Context.getTypeSize(Context.LongTy))12542return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());12543assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&12544"Unhandled vector element size in vector compare");12545return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());12546}1254712548if (TypeSize == Context.getTypeSize(Context.Int128Ty))12549return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),12550VectorKind::Generic);12551if (TypeSize == Context.getTypeSize(Context.LongLongTy))12552return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),12553VectorKind::Generic);12554if (TypeSize == Context.getTypeSize(Context.LongTy))12555return Context.getVectorType(Context.LongTy, VTy->getNumElements(),12556VectorKind::Generic);12557if (TypeSize == Context.getTypeSize(Context.IntTy))12558return Context.getVectorType(Context.IntTy, VTy->getNumElements(),12559VectorKind::Generic);12560if (TypeSize == Context.getTypeSize(Context.ShortTy))12561return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),12562VectorKind::Generic);12563assert(TypeSize == Context.getTypeSize(Context.CharTy) &&12564"Unhandled vector element size in vector compare");12565return Context.getVectorType(Context.CharTy, VTy->getNumElements(),12566VectorKind::Generic);12567}1256812569QualType Sema::GetSignedSizelessVectorType(QualType V) {12570const BuiltinType *VTy = V->castAs<BuiltinType>();12571assert(VTy->isSizelessBuiltinType() && "expected sizeless type");1257212573const QualType ETy = V->getSveEltType(Context);12574const auto TypeSize = Context.getTypeSize(ETy);1257512576const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);12577const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;12578return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());12579}1258012581QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,12582SourceLocation Loc,12583BinaryOperatorKind Opc) {12584if (Opc == BO_Cmp) {12585Diag(Loc, diag::err_three_way_vector_comparison);12586return QualType();12587}1258812589// Check to make sure we're operating on vectors of the same type and width,12590// Allowing one side to be a scalar of element type.12591QualType vType =12592CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,12593/*AllowBothBool*/ true,12594/*AllowBoolConversions*/ getLangOpts().ZVector,12595/*AllowBooleanOperation*/ true,12596/*ReportInvalid*/ true);12597if (vType.isNull())12598return vType;1259912600QualType LHSType = LHS.get()->getType();1260112602// Determine the return type of a vector compare. By default clang will return12603// a scalar for all vector compares except vector bool and vector pixel.12604// With the gcc compiler we will always return a vector type and with the xl12605// compiler we will always return a scalar type. This switch allows choosing12606// which behavior is prefered.12607if (getLangOpts().AltiVec) {12608switch (getLangOpts().getAltivecSrcCompat()) {12609case LangOptions::AltivecSrcCompatKind::Mixed:12610// If AltiVec, the comparison results in a numeric type, i.e.12611// bool for C++, int for C12612if (vType->castAs<VectorType>()->getVectorKind() ==12613VectorKind::AltiVecVector)12614return Context.getLogicalOperationType();12615else12616Diag(Loc, diag::warn_deprecated_altivec_src_compat);12617break;12618case LangOptions::AltivecSrcCompatKind::GCC:12619// For GCC we always return the vector type.12620break;12621case LangOptions::AltivecSrcCompatKind::XL:12622return Context.getLogicalOperationType();12623break;12624}12625}1262612627// For non-floating point types, check for self-comparisons of the form12628// x == x, x != x, x < x, etc. These always evaluate to a constant, and12629// often indicate logic errors in the program.12630diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);1263112632// Check for comparisons of floating point operands using != and ==.12633if (LHSType->hasFloatingRepresentation()) {12634assert(RHS.get()->getType()->hasFloatingRepresentation());12635CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);12636}1263712638// Return a signed type for the vector.12639return GetSignedVectorType(vType);12640}1264112642QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,12643ExprResult &RHS,12644SourceLocation Loc,12645BinaryOperatorKind Opc) {12646if (Opc == BO_Cmp) {12647Diag(Loc, diag::err_three_way_vector_comparison);12648return QualType();12649}1265012651// Check to make sure we're operating on vectors of the same type and width,12652// Allowing one side to be a scalar of element type.12653QualType vType = CheckSizelessVectorOperands(12654LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);1265512656if (vType.isNull())12657return vType;1265812659QualType LHSType = LHS.get()->getType();1266012661// For non-floating point types, check for self-comparisons of the form12662// x == x, x != x, x < x, etc. These always evaluate to a constant, and12663// often indicate logic errors in the program.12664diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);1266512666// Check for comparisons of floating point operands using != and ==.12667if (LHSType->hasFloatingRepresentation()) {12668assert(RHS.get()->getType()->hasFloatingRepresentation());12669CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);12670}1267112672const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();12673const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();1267412675if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&12676RHSBuiltinTy->isSVEBool())12677return LHSType;1267812679// Return a signed type for the vector.12680return GetSignedSizelessVectorType(vType);12681}1268212683static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,12684const ExprResult &XorRHS,12685const SourceLocation Loc) {12686// Do not diagnose macros.12687if (Loc.isMacroID())12688return;1268912690// Do not diagnose if both LHS and RHS are macros.12691if (XorLHS.get()->getExprLoc().isMacroID() &&12692XorRHS.get()->getExprLoc().isMacroID())12693return;1269412695bool Negative = false;12696bool ExplicitPlus = false;12697const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());12698const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());1269912700if (!LHSInt)12701return;12702if (!RHSInt) {12703// Check negative literals.12704if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {12705UnaryOperatorKind Opc = UO->getOpcode();12706if (Opc != UO_Minus && Opc != UO_Plus)12707return;12708RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());12709if (!RHSInt)12710return;12711Negative = (Opc == UO_Minus);12712ExplicitPlus = !Negative;12713} else {12714return;12715}12716}1271712718const llvm::APInt &LeftSideValue = LHSInt->getValue();12719llvm::APInt RightSideValue = RHSInt->getValue();12720if (LeftSideValue != 2 && LeftSideValue != 10)12721return;1272212723if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())12724return;1272512726CharSourceRange ExprRange = CharSourceRange::getCharRange(12727LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));12728llvm::StringRef ExprStr =12729Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());1273012731CharSourceRange XorRange =12732CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));12733llvm::StringRef XorStr =12734Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());12735// Do not diagnose if xor keyword/macro is used.12736if (XorStr == "xor")12737return;1273812739std::string LHSStr = std::string(Lexer::getSourceText(12740CharSourceRange::getTokenRange(LHSInt->getSourceRange()),12741S.getSourceManager(), S.getLangOpts()));12742std::string RHSStr = std::string(Lexer::getSourceText(12743CharSourceRange::getTokenRange(RHSInt->getSourceRange()),12744S.getSourceManager(), S.getLangOpts()));1274512746if (Negative) {12747RightSideValue = -RightSideValue;12748RHSStr = "-" + RHSStr;12749} else if (ExplicitPlus) {12750RHSStr = "+" + RHSStr;12751}1275212753StringRef LHSStrRef = LHSStr;12754StringRef RHSStrRef = RHSStr;12755// Do not diagnose literals with digit separators, binary, hexadecimal, octal12756// literals.12757if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||12758RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||12759LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||12760RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||12761(LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||12762(RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||12763LHSStrRef.contains('\'') || RHSStrRef.contains('\''))12764return;1276512766bool SuggestXor =12767S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");12768const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;12769int64_t RightSideIntValue = RightSideValue.getSExtValue();12770if (LeftSideValue == 2 && RightSideIntValue >= 0) {12771std::string SuggestedExpr = "1 << " + RHSStr;12772bool Overflow = false;12773llvm::APInt One = (LeftSideValue - 1);12774llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);12775if (Overflow) {12776if (RightSideIntValue < 64)12777S.Diag(Loc, diag::warn_xor_used_as_pow_base)12778<< ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)12779<< FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);12780else if (RightSideIntValue == 64)12781S.Diag(Loc, diag::warn_xor_used_as_pow)12782<< ExprStr << toString(XorValue, 10, true);12783else12784return;12785} else {12786S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)12787<< ExprStr << toString(XorValue, 10, true) << SuggestedExpr12788<< toString(PowValue, 10, true)12789<< FixItHint::CreateReplacement(12790ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);12791}1279212793S.Diag(Loc, diag::note_xor_used_as_pow_silence)12794<< ("0x2 ^ " + RHSStr) << SuggestXor;12795} else if (LeftSideValue == 10) {12796std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);12797S.Diag(Loc, diag::warn_xor_used_as_pow_base)12798<< ExprStr << toString(XorValue, 10, true) << SuggestedValue12799<< FixItHint::CreateReplacement(ExprRange, SuggestedValue);12800S.Diag(Loc, diag::note_xor_used_as_pow_silence)12801<< ("0xA ^ " + RHSStr) << SuggestXor;12802}12803}1280412805QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,12806SourceLocation Loc) {12807// Ensure that either both operands are of the same vector type, or12808// one operand is of a vector type and the other is of its element type.12809QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,12810/*AllowBothBool*/ true,12811/*AllowBoolConversions*/ false,12812/*AllowBooleanOperation*/ false,12813/*ReportInvalid*/ false);12814if (vType.isNull())12815return InvalidOperands(Loc, LHS, RHS);12816if (getLangOpts().OpenCL &&12817getLangOpts().getOpenCLCompatibleVersion() < 120 &&12818vType->hasFloatingRepresentation())12819return InvalidOperands(Loc, LHS, RHS);12820// FIXME: The check for C++ here is for GCC compatibility. GCC rejects the12821// usage of the logical operators && and || with vectors in C. This12822// check could be notionally dropped.12823if (!getLangOpts().CPlusPlus &&12824!(isa<ExtVectorType>(vType->getAs<VectorType>())))12825return InvalidLogicalVectorOperands(Loc, LHS, RHS);1282612827return GetSignedVectorType(LHS.get()->getType());12828}1282912830QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,12831SourceLocation Loc,12832bool IsCompAssign) {12833if (!IsCompAssign) {12834LHS = DefaultFunctionArrayLvalueConversion(LHS.get());12835if (LHS.isInvalid())12836return QualType();12837}12838RHS = DefaultFunctionArrayLvalueConversion(RHS.get());12839if (RHS.isInvalid())12840return QualType();1284112842// For conversion purposes, we ignore any qualifiers.12843// For example, "const float" and "float" are equivalent.12844QualType LHSType = LHS.get()->getType().getUnqualifiedType();12845QualType RHSType = RHS.get()->getType().getUnqualifiedType();1284612847const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();12848const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();12849assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");1285012851if (Context.hasSameType(LHSType, RHSType))12852return Context.getCommonSugaredType(LHSType, RHSType);1285312854// Type conversion may change LHS/RHS. Keep copies to the original results, in12855// case we have to return InvalidOperands.12856ExprResult OriginalLHS = LHS;12857ExprResult OriginalRHS = RHS;12858if (LHSMatType && !RHSMatType) {12859RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());12860if (!RHS.isInvalid())12861return LHSType;1286212863return InvalidOperands(Loc, OriginalLHS, OriginalRHS);12864}1286512866if (!LHSMatType && RHSMatType) {12867LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());12868if (!LHS.isInvalid())12869return RHSType;12870return InvalidOperands(Loc, OriginalLHS, OriginalRHS);12871}1287212873return InvalidOperands(Loc, LHS, RHS);12874}1287512876QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,12877SourceLocation Loc,12878bool IsCompAssign) {12879if (!IsCompAssign) {12880LHS = DefaultFunctionArrayLvalueConversion(LHS.get());12881if (LHS.isInvalid())12882return QualType();12883}12884RHS = DefaultFunctionArrayLvalueConversion(RHS.get());12885if (RHS.isInvalid())12886return QualType();1288712888auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();12889auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();12890assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");1289112892if (LHSMatType && RHSMatType) {12893if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())12894return InvalidOperands(Loc, LHS, RHS);1289512896if (Context.hasSameType(LHSMatType, RHSMatType))12897return Context.getCommonSugaredType(12898LHS.get()->getType().getUnqualifiedType(),12899RHS.get()->getType().getUnqualifiedType());1290012901QualType LHSELTy = LHSMatType->getElementType(),12902RHSELTy = RHSMatType->getElementType();12903if (!Context.hasSameType(LHSELTy, RHSELTy))12904return InvalidOperands(Loc, LHS, RHS);1290512906return Context.getConstantMatrixType(12907Context.getCommonSugaredType(LHSELTy, RHSELTy),12908LHSMatType->getNumRows(), RHSMatType->getNumColumns());12909}12910return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);12911}1291212913static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {12914switch (Opc) {12915default:12916return false;12917case BO_And:12918case BO_AndAssign:12919case BO_Or:12920case BO_OrAssign:12921case BO_Xor:12922case BO_XorAssign:12923return true;12924}12925}1292612927inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,12928SourceLocation Loc,12929BinaryOperatorKind Opc) {12930checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);1293112932bool IsCompAssign =12933Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;1293412935bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);1293612937if (LHS.get()->getType()->isVectorType() ||12938RHS.get()->getType()->isVectorType()) {12939if (LHS.get()->getType()->hasIntegerRepresentation() &&12940RHS.get()->getType()->hasIntegerRepresentation())12941return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,12942/*AllowBothBool*/ true,12943/*AllowBoolConversions*/ getLangOpts().ZVector,12944/*AllowBooleanOperation*/ LegalBoolVecOperator,12945/*ReportInvalid*/ true);12946return InvalidOperands(Loc, LHS, RHS);12947}1294812949if (LHS.get()->getType()->isSveVLSBuiltinType() ||12950RHS.get()->getType()->isSveVLSBuiltinType()) {12951if (LHS.get()->getType()->hasIntegerRepresentation() &&12952RHS.get()->getType()->hasIntegerRepresentation())12953return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,12954ACK_BitwiseOp);12955return InvalidOperands(Loc, LHS, RHS);12956}1295712958if (LHS.get()->getType()->isSveVLSBuiltinType() ||12959RHS.get()->getType()->isSveVLSBuiltinType()) {12960if (LHS.get()->getType()->hasIntegerRepresentation() &&12961RHS.get()->getType()->hasIntegerRepresentation())12962return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,12963ACK_BitwiseOp);12964return InvalidOperands(Loc, LHS, RHS);12965}1296612967if (Opc == BO_And)12968diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);1296912970if (LHS.get()->getType()->hasFloatingRepresentation() ||12971RHS.get()->getType()->hasFloatingRepresentation())12972return InvalidOperands(Loc, LHS, RHS);1297312974ExprResult LHSResult = LHS, RHSResult = RHS;12975QualType compType = UsualArithmeticConversions(12976LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);12977if (LHSResult.isInvalid() || RHSResult.isInvalid())12978return QualType();12979LHS = LHSResult.get();12980RHS = RHSResult.get();1298112982if (Opc == BO_Xor)12983diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);1298412985if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())12986return compType;12987return InvalidOperands(Loc, LHS, RHS);12988}1298912990// C99 6.5.[13,14]12991inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,12992SourceLocation Loc,12993BinaryOperatorKind Opc) {12994// Check vector operands differently.12995if (LHS.get()->getType()->isVectorType() ||12996RHS.get()->getType()->isVectorType())12997return CheckVectorLogicalOperands(LHS, RHS, Loc);1299812999bool EnumConstantInBoolContext = false;13000for (const ExprResult &HS : {LHS, RHS}) {13001if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {13002const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());13003if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)13004EnumConstantInBoolContext = true;13005}13006}1300713008if (EnumConstantInBoolContext)13009Diag(Loc, diag::warn_enum_constant_in_bool_context);1301013011// WebAssembly tables can't be used with logical operators.13012QualType LHSTy = LHS.get()->getType();13013QualType RHSTy = RHS.get()->getType();13014const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);13015const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);13016if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||13017(RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {13018return InvalidOperands(Loc, LHS, RHS);13019}1302013021// Diagnose cases where the user write a logical and/or but probably meant a13022// bitwise one. We do this when the LHS is a non-bool integer and the RHS13023// is a constant.13024if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&13025!LHS.get()->getType()->isBooleanType() &&13026RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&13027// Don't warn in macros or template instantiations.13028!Loc.isMacroID() && !inTemplateInstantiation()) {13029// If the RHS can be constant folded, and if it constant folds to something13030// that isn't 0 or 1 (which indicate a potential logical operation that13031// happened to fold to true/false) then warn.13032// Parens on the RHS are ignored.13033Expr::EvalResult EVResult;13034if (RHS.get()->EvaluateAsInt(EVResult, Context)) {13035llvm::APSInt Result = EVResult.Val.getInt();13036if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&13037!RHS.get()->getExprLoc().isMacroID()) ||13038(Result != 0 && Result != 1)) {13039Diag(Loc, diag::warn_logical_instead_of_bitwise)13040<< RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");13041// Suggest replacing the logical operator with the bitwise version13042Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)13043<< (Opc == BO_LAnd ? "&" : "|")13044<< FixItHint::CreateReplacement(13045SourceRange(Loc, getLocForEndOfToken(Loc)),13046Opc == BO_LAnd ? "&" : "|");13047if (Opc == BO_LAnd)13048// Suggest replacing "Foo() && kNonZero" with "Foo()"13049Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)13050<< FixItHint::CreateRemoval(13051SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),13052RHS.get()->getEndLoc()));13053}13054}13055}1305613057if (!Context.getLangOpts().CPlusPlus) {13058// OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do13059// not operate on the built-in scalar and vector float types.13060if (Context.getLangOpts().OpenCL &&13061Context.getLangOpts().OpenCLVersion < 120) {13062if (LHS.get()->getType()->isFloatingType() ||13063RHS.get()->getType()->isFloatingType())13064return InvalidOperands(Loc, LHS, RHS);13065}1306613067LHS = UsualUnaryConversions(LHS.get());13068if (LHS.isInvalid())13069return QualType();1307013071RHS = UsualUnaryConversions(RHS.get());13072if (RHS.isInvalid())13073return QualType();1307413075if (!LHS.get()->getType()->isScalarType() ||13076!RHS.get()->getType()->isScalarType())13077return InvalidOperands(Loc, LHS, RHS);1307813079return Context.IntTy;13080}1308113082// The following is safe because we only use this method for13083// non-overloadable operands.1308413085// C++ [expr.log.and]p113086// C++ [expr.log.or]p113087// The operands are both contextually converted to type bool.13088ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());13089if (LHSRes.isInvalid())13090return InvalidOperands(Loc, LHS, RHS);13091LHS = LHSRes;1309213093ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());13094if (RHSRes.isInvalid())13095return InvalidOperands(Loc, LHS, RHS);13096RHS = RHSRes;1309713098// C++ [expr.log.and]p213099// C++ [expr.log.or]p213100// The result is a bool.13101return Context.BoolTy;13102}1310313104static bool IsReadonlyMessage(Expr *E, Sema &S) {13105const MemberExpr *ME = dyn_cast<MemberExpr>(E);13106if (!ME) return false;13107if (!isa<FieldDecl>(ME->getMemberDecl())) return false;13108ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(13109ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());13110if (!Base) return false;13111return Base->getMethodDecl() != nullptr;13112}1311313114/// Is the given expression (which must be 'const') a reference to a13115/// variable which was originally non-const, but which has become13116/// 'const' due to being captured within a block?13117enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };13118static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {13119assert(E->isLValue() && E->getType().isConstQualified());13120E = E->IgnoreParens();1312113122// Must be a reference to a declaration from an enclosing scope.13123DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);13124if (!DRE) return NCCK_None;13125if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;1312613127// The declaration must be a variable which is not declared 'const'.13128VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());13129if (!var) return NCCK_None;13130if (var->getType().isConstQualified()) return NCCK_None;13131assert(var->hasLocalStorage() && "capture added 'const' to non-local?");1313213133// Decide whether the first capture was for a block or a lambda.13134DeclContext *DC = S.CurContext, *Prev = nullptr;13135// Decide whether the first capture was for a block or a lambda.13136while (DC) {13137// For init-capture, it is possible that the variable belongs to the13138// template pattern of the current context.13139if (auto *FD = dyn_cast<FunctionDecl>(DC))13140if (var->isInitCapture() &&13141FD->getTemplateInstantiationPattern() == var->getDeclContext())13142break;13143if (DC == var->getDeclContext())13144break;13145Prev = DC;13146DC = DC->getParent();13147}13148// Unless we have an init-capture, we've gone one step too far.13149if (!var->isInitCapture())13150DC = Prev;13151return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);13152}1315313154static bool IsTypeModifiable(QualType Ty, bool IsDereference) {13155Ty = Ty.getNonReferenceType();13156if (IsDereference && Ty->isPointerType())13157Ty = Ty->getPointeeType();13158return !Ty.isConstQualified();13159}1316013161// Update err_typecheck_assign_const and note_typecheck_assign_const13162// when this enum is changed.13163enum {13164ConstFunction,13165ConstVariable,13166ConstMember,13167ConstMethod,13168NestedConstMember,13169ConstUnknown, // Keep as last element13170};1317113172/// Emit the "read-only variable not assignable" error and print notes to give13173/// more information about why the variable is not assignable, such as pointing13174/// to the declaration of a const variable, showing that a method is const, or13175/// that the function is returning a const reference.13176static void DiagnoseConstAssignment(Sema &S, const Expr *E,13177SourceLocation Loc) {13178SourceRange ExprRange = E->getSourceRange();1317913180// Only emit one error on the first const found. All other consts will emit13181// a note to the error.13182bool DiagnosticEmitted = false;1318313184// Track if the current expression is the result of a dereference, and if the13185// next checked expression is the result of a dereference.13186bool IsDereference = false;13187bool NextIsDereference = false;1318813189// Loop to process MemberExpr chains.13190while (true) {13191IsDereference = NextIsDereference;1319213193E = E->IgnoreImplicit()->IgnoreParenImpCasts();13194if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {13195NextIsDereference = ME->isArrow();13196const ValueDecl *VD = ME->getMemberDecl();13197if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {13198// Mutable fields can be modified even if the class is const.13199if (Field->isMutable()) {13200assert(DiagnosticEmitted && "Expected diagnostic not emitted.");13201break;13202}1320313204if (!IsTypeModifiable(Field->getType(), IsDereference)) {13205if (!DiagnosticEmitted) {13206S.Diag(Loc, diag::err_typecheck_assign_const)13207<< ExprRange << ConstMember << false /*static*/ << Field13208<< Field->getType();13209DiagnosticEmitted = true;13210}13211S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)13212<< ConstMember << false /*static*/ << Field << Field->getType()13213<< Field->getSourceRange();13214}13215E = ME->getBase();13216continue;13217} else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {13218if (VDecl->getType().isConstQualified()) {13219if (!DiagnosticEmitted) {13220S.Diag(Loc, diag::err_typecheck_assign_const)13221<< ExprRange << ConstMember << true /*static*/ << VDecl13222<< VDecl->getType();13223DiagnosticEmitted = true;13224}13225S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)13226<< ConstMember << true /*static*/ << VDecl << VDecl->getType()13227<< VDecl->getSourceRange();13228}13229// Static fields do not inherit constness from parents.13230break;13231}13232break; // End MemberExpr13233} else if (const ArraySubscriptExpr *ASE =13234dyn_cast<ArraySubscriptExpr>(E)) {13235E = ASE->getBase()->IgnoreParenImpCasts();13236continue;13237} else if (const ExtVectorElementExpr *EVE =13238dyn_cast<ExtVectorElementExpr>(E)) {13239E = EVE->getBase()->IgnoreParenImpCasts();13240continue;13241}13242break;13243}1324413245if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {13246// Function calls13247const FunctionDecl *FD = CE->getDirectCallee();13248if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {13249if (!DiagnosticEmitted) {13250S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange13251<< ConstFunction << FD;13252DiagnosticEmitted = true;13253}13254S.Diag(FD->getReturnTypeSourceRange().getBegin(),13255diag::note_typecheck_assign_const)13256<< ConstFunction << FD << FD->getReturnType()13257<< FD->getReturnTypeSourceRange();13258}13259} else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {13260// Point to variable declaration.13261if (const ValueDecl *VD = DRE->getDecl()) {13262if (!IsTypeModifiable(VD->getType(), IsDereference)) {13263if (!DiagnosticEmitted) {13264S.Diag(Loc, diag::err_typecheck_assign_const)13265<< ExprRange << ConstVariable << VD << VD->getType();13266DiagnosticEmitted = true;13267}13268S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)13269<< ConstVariable << VD << VD->getType() << VD->getSourceRange();13270}13271}13272} else if (isa<CXXThisExpr>(E)) {13273if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {13274if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {13275if (MD->isConst()) {13276if (!DiagnosticEmitted) {13277S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange13278<< ConstMethod << MD;13279DiagnosticEmitted = true;13280}13281S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)13282<< ConstMethod << MD << MD->getSourceRange();13283}13284}13285}13286}1328713288if (DiagnosticEmitted)13289return;1329013291// Can't determine a more specific message, so display the generic error.13292S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;13293}1329413295enum OriginalExprKind {13296OEK_Variable,13297OEK_Member,13298OEK_LValue13299};1330013301static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,13302const RecordType *Ty,13303SourceLocation Loc, SourceRange Range,13304OriginalExprKind OEK,13305bool &DiagnosticEmitted) {13306std::vector<const RecordType *> RecordTypeList;13307RecordTypeList.push_back(Ty);13308unsigned NextToCheckIndex = 0;13309// We walk the record hierarchy breadth-first to ensure that we print13310// diagnostics in field nesting order.13311while (RecordTypeList.size() > NextToCheckIndex) {13312bool IsNested = NextToCheckIndex > 0;13313for (const FieldDecl *Field :13314RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {13315// First, check every field for constness.13316QualType FieldTy = Field->getType();13317if (FieldTy.isConstQualified()) {13318if (!DiagnosticEmitted) {13319S.Diag(Loc, diag::err_typecheck_assign_const)13320<< Range << NestedConstMember << OEK << VD13321<< IsNested << Field;13322DiagnosticEmitted = true;13323}13324S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)13325<< NestedConstMember << IsNested << Field13326<< FieldTy << Field->getSourceRange();13327}1332813329// Then we append it to the list to check next in order.13330FieldTy = FieldTy.getCanonicalType();13331if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {13332if (!llvm::is_contained(RecordTypeList, FieldRecTy))13333RecordTypeList.push_back(FieldRecTy);13334}13335}13336++NextToCheckIndex;13337}13338}1333913340/// Emit an error for the case where a record we are trying to assign to has a13341/// const-qualified field somewhere in its hierarchy.13342static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,13343SourceLocation Loc) {13344QualType Ty = E->getType();13345assert(Ty->isRecordType() && "lvalue was not record?");13346SourceRange Range = E->getSourceRange();13347const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();13348bool DiagEmitted = false;1334913350if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))13351DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,13352Range, OEK_Member, DiagEmitted);13353else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))13354DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,13355Range, OEK_Variable, DiagEmitted);13356else13357DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,13358Range, OEK_LValue, DiagEmitted);13359if (!DiagEmitted)13360DiagnoseConstAssignment(S, E, Loc);13361}1336213363/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,13364/// emit an error and return true. If so, return false.13365static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {13366assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));1336713368S.CheckShadowingDeclModification(E, Loc);1336913370SourceLocation OrigLoc = Loc;13371Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,13372&Loc);13373if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))13374IsLV = Expr::MLV_InvalidMessageExpression;13375if (IsLV == Expr::MLV_Valid)13376return false;1337713378unsigned DiagID = 0;13379bool NeedType = false;13380switch (IsLV) { // C99 6.5.16p213381case Expr::MLV_ConstQualified:13382// Use a specialized diagnostic when we're assigning to an object13383// from an enclosing function or block.13384if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {13385if (NCCK == NCCK_Block)13386DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;13387else13388DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;13389break;13390}1339113392// In ARC, use some specialized diagnostics for occasions where we13393// infer 'const'. These are always pseudo-strong variables.13394if (S.getLangOpts().ObjCAutoRefCount) {13395DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());13396if (declRef && isa<VarDecl>(declRef->getDecl())) {13397VarDecl *var = cast<VarDecl>(declRef->getDecl());1339813399// Use the normal diagnostic if it's pseudo-__strong but the13400// user actually wrote 'const'.13401if (var->isARCPseudoStrong() &&13402(!var->getTypeSourceInfo() ||13403!var->getTypeSourceInfo()->getType().isConstQualified())) {13404// There are three pseudo-strong cases:13405// - self13406ObjCMethodDecl *method = S.getCurMethodDecl();13407if (method && var == method->getSelfDecl()) {13408DiagID = method->isClassMethod()13409? diag::err_typecheck_arc_assign_self_class_method13410: diag::err_typecheck_arc_assign_self;1341113412// - Objective-C externally_retained attribute.13413} else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||13414isa<ParmVarDecl>(var)) {13415DiagID = diag::err_typecheck_arc_assign_externally_retained;1341613417// - fast enumeration variables13418} else {13419DiagID = diag::err_typecheck_arr_assign_enumeration;13420}1342113422SourceRange Assign;13423if (Loc != OrigLoc)13424Assign = SourceRange(OrigLoc, OrigLoc);13425S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;13426// We need to preserve the AST regardless, so migration tool13427// can do its job.13428return false;13429}13430}13431}1343213433// If none of the special cases above are triggered, then this is a13434// simple const assignment.13435if (DiagID == 0) {13436DiagnoseConstAssignment(S, E, Loc);13437return true;13438}1343913440break;13441case Expr::MLV_ConstAddrSpace:13442DiagnoseConstAssignment(S, E, Loc);13443return true;13444case Expr::MLV_ConstQualifiedField:13445DiagnoseRecursiveConstFields(S, E, Loc);13446return true;13447case Expr::MLV_ArrayType:13448case Expr::MLV_ArrayTemporary:13449DiagID = diag::err_typecheck_array_not_modifiable_lvalue;13450NeedType = true;13451break;13452case Expr::MLV_NotObjectType:13453DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;13454NeedType = true;13455break;13456case Expr::MLV_LValueCast:13457DiagID = diag::err_typecheck_lvalue_casts_not_supported;13458break;13459case Expr::MLV_Valid:13460llvm_unreachable("did not take early return for MLV_Valid");13461case Expr::MLV_InvalidExpression:13462case Expr::MLV_MemberFunction:13463case Expr::MLV_ClassTemporary:13464DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;13465break;13466case Expr::MLV_IncompleteType:13467case Expr::MLV_IncompleteVoidType:13468return S.RequireCompleteType(Loc, E->getType(),13469diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);13470case Expr::MLV_DuplicateVectorComponents:13471DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;13472break;13473case Expr::MLV_NoSetterProperty:13474llvm_unreachable("readonly properties should be processed differently");13475case Expr::MLV_InvalidMessageExpression:13476DiagID = diag::err_readonly_message_assignment;13477break;13478case Expr::MLV_SubObjCPropertySetting:13479DiagID = diag::err_no_subobject_property_setting;13480break;13481}1348213483SourceRange Assign;13484if (Loc != OrigLoc)13485Assign = SourceRange(OrigLoc, OrigLoc);13486if (NeedType)13487S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;13488else13489S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;13490return true;13491}1349213493static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,13494SourceLocation Loc,13495Sema &Sema) {13496if (Sema.inTemplateInstantiation())13497return;13498if (Sema.isUnevaluatedContext())13499return;13500if (Loc.isInvalid() || Loc.isMacroID())13501return;13502if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())13503return;1350413505// C / C++ fields13506MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);13507MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);13508if (ML && MR) {13509if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))13510return;13511const ValueDecl *LHSDecl =13512cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());13513const ValueDecl *RHSDecl =13514cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());13515if (LHSDecl != RHSDecl)13516return;13517if (LHSDecl->getType().isVolatileQualified())13518return;13519if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())13520if (RefTy->getPointeeType().isVolatileQualified())13521return;1352213523Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;13524}1352513526// Objective-C instance variables13527ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);13528ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);13529if (OL && OR && OL->getDecl() == OR->getDecl()) {13530DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());13531DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());13532if (RL && RR && RL->getDecl() == RR->getDecl())13533Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;13534}13535}1353613537// C99 6.5.16.113538QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,13539SourceLocation Loc,13540QualType CompoundType,13541BinaryOperatorKind Opc) {13542assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));1354313544// Verify that LHS is a modifiable lvalue, and emit error if not.13545if (CheckForModifiableLvalue(LHSExpr, Loc, *this))13546return QualType();1354713548QualType LHSType = LHSExpr->getType();13549QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :13550CompoundType;13551// OpenCL v1.2 s6.1.1.1 p2:13552// The half data type can only be used to declare a pointer to a buffer that13553// contains half values13554if (getLangOpts().OpenCL &&13555!getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&13556LHSType->isHalfType()) {13557Diag(Loc, diag::err_opencl_half_load_store) << 113558<< LHSType.getUnqualifiedType();13559return QualType();13560}1356113562// WebAssembly tables can't be used on RHS of an assignment expression.13563if (RHSType->isWebAssemblyTableType()) {13564Diag(Loc, diag::err_wasm_table_art) << 0;13565return QualType();13566}1356713568AssignConvertType ConvTy;13569if (CompoundType.isNull()) {13570Expr *RHSCheck = RHS.get();1357113572CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);1357313574QualType LHSTy(LHSType);13575ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);13576if (RHS.isInvalid())13577return QualType();13578// Special case of NSObject attributes on c-style pointer types.13579if (ConvTy == IncompatiblePointer &&13580((Context.isObjCNSObjectType(LHSType) &&13581RHSType->isObjCObjectPointerType()) ||13582(Context.isObjCNSObjectType(RHSType) &&13583LHSType->isObjCObjectPointerType())))13584ConvTy = Compatible;1358513586if (ConvTy == Compatible &&13587LHSType->isObjCObjectType())13588Diag(Loc, diag::err_objc_object_assignment)13589<< LHSType;1359013591// If the RHS is a unary plus or minus, check to see if they = and + are13592// right next to each other. If so, the user may have typo'd "x =+ 4"13593// instead of "x += 4".13594if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))13595RHSCheck = ICE->getSubExpr();13596if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {13597if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&13598Loc.isFileID() && UO->getOperatorLoc().isFileID() &&13599// Only if the two operators are exactly adjacent.13600Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&13601// And there is a space or other character before the subexpr of the13602// unary +/-. We don't want to warn on "x=-1".13603Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&13604UO->getSubExpr()->getBeginLoc().isFileID()) {13605Diag(Loc, diag::warn_not_compound_assign)13606<< (UO->getOpcode() == UO_Plus ? "+" : "-")13607<< SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());13608}13609}1361013611if (ConvTy == Compatible) {13612if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {13613// Warn about retain cycles where a block captures the LHS, but13614// not if the LHS is a simple variable into which the block is13615// being stored...unless that variable can be captured by reference!13616const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();13617const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);13618if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())13619ObjC().checkRetainCycles(LHSExpr, RHS.get());13620}1362113622if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||13623LHSType.isNonWeakInMRRWithObjCWeak(Context)) {13624// It is safe to assign a weak reference into a strong variable.13625// Although this code can still have problems:13626// id x = self.weakProp;13627// id y = self.weakProp;13628// we do not warn to warn spuriously when 'x' and 'y' are on separate13629// paths through the function. This should be revisited if13630// -Wrepeated-use-of-weak is made flow-sensitive.13631// For ObjCWeak only, we do not warn if the assign is to a non-weak13632// variable, which will be valid for the current autorelease scope.13633if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,13634RHS.get()->getBeginLoc()))13635getCurFunction()->markSafeWeakUse(RHS.get());1363613637} else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {13638checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());13639}13640}13641} else {13642// Compound assignment "x += y"13643ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);13644}1364513646if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,13647RHS.get(), AA_Assigning))13648return QualType();1364913650CheckForNullPointerDereference(*this, LHSExpr);1365113652AssignedEntity AE{LHSExpr};13653checkExprLifetime(*this, AE, RHS.get());1365413655if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {13656if (CompoundType.isNull()) {13657// C++2a [expr.ass]p5:13658// A simple-assignment whose left operand is of a volatile-qualified13659// type is deprecated unless the assignment is either a discarded-value13660// expression or an unevaluated operand13661ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);13662}13663}1366413665// C11 6.5.16p3: The type of an assignment expression is the type of the13666// left operand would have after lvalue conversion.13667// C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has13668// qualified type, the value has the unqualified version of the type of the13669// lvalue; additionally, if the lvalue has atomic type, the value has the13670// non-atomic version of the type of the lvalue.13671// C++ 5.17p1: the type of the assignment expression is that of its left13672// operand.13673return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();13674}1367513676// Scenarios to ignore if expression E is:13677// 1. an explicit cast expression into void13678// 2. a function call expression that returns void13679static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {13680E = E->IgnoreParens();1368113682if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {13683if (CE->getCastKind() == CK_ToVoid) {13684return true;13685}1368613687// static_cast<void> on a dependent type will not show up as CK_ToVoid.13688if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&13689CE->getSubExpr()->getType()->isDependentType()) {13690return true;13691}13692}1369313694if (const auto *CE = dyn_cast<CallExpr>(E))13695return CE->getCallReturnType(Context)->isVoidType();13696return false;13697}1369813699void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {13700// No warnings in macros13701if (Loc.isMacroID())13702return;1370313704// Don't warn in template instantiations.13705if (inTemplateInstantiation())13706return;1370713708// Scope isn't fine-grained enough to explicitly list the specific cases, so13709// instead, skip more than needed, then call back into here with the13710// CommaVisitor in SemaStmt.cpp.13711// The listed locations are the initialization and increment portions13712// of a for loop. The additional checks are on the condition of13713// if statements, do/while loops, and for loops.13714// Differences in scope flags for C89 mode requires the extra logic.13715const unsigned ForIncrementFlags =13716getLangOpts().C99 || getLangOpts().CPlusPlus13717? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope13718: Scope::ContinueScope | Scope::BreakScope;13719const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;13720const unsigned ScopeFlags = getCurScope()->getFlags();13721if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||13722(ScopeFlags & ForInitFlags) == ForInitFlags)13723return;1372413725// If there are multiple comma operators used together, get the RHS of the13726// of the comma operator as the LHS.13727while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {13728if (BO->getOpcode() != BO_Comma)13729break;13730LHS = BO->getRHS();13731}1373213733// Only allow some expressions on LHS to not warn.13734if (IgnoreCommaOperand(LHS, Context))13735return;1373613737Diag(Loc, diag::warn_comma_operator);13738Diag(LHS->getBeginLoc(), diag::note_cast_to_void)13739<< LHS->getSourceRange()13740<< FixItHint::CreateInsertion(LHS->getBeginLoc(),13741LangOpts.CPlusPlus ? "static_cast<void>("13742: "(void)(")13743<< FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),13744")");13745}1374613747// C99 6.5.1713748static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,13749SourceLocation Loc) {13750LHS = S.CheckPlaceholderExpr(LHS.get());13751RHS = S.CheckPlaceholderExpr(RHS.get());13752if (LHS.isInvalid() || RHS.isInvalid())13753return QualType();1375413755// C's comma performs lvalue conversion (C99 6.3.2.1) on both its13756// operands, but not unary promotions.13757// C++'s comma does not do any conversions at all (C++ [expr.comma]p1).1375813759// So we treat the LHS as a ignored value, and in C++ we allow the13760// containing site to determine what should be done with the RHS.13761LHS = S.IgnoredValueConversions(LHS.get());13762if (LHS.isInvalid())13763return QualType();1376413765S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);1376613767if (!S.getLangOpts().CPlusPlus) {13768RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());13769if (RHS.isInvalid())13770return QualType();13771if (!RHS.get()->getType()->isVoidType())13772S.RequireCompleteType(Loc, RHS.get()->getType(),13773diag::err_incomplete_type);13774}1377513776if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))13777S.DiagnoseCommaOperator(LHS.get(), Loc);1377813779return RHS.get()->getType();13780}1378113782/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine13783/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.13784static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,13785ExprValueKind &VK,13786ExprObjectKind &OK,13787SourceLocation OpLoc, bool IsInc,13788bool IsPrefix) {13789QualType ResType = Op->getType();13790// Atomic types can be used for increment / decrement where the non-atomic13791// versions can, so ignore the _Atomic() specifier for the purpose of13792// checking.13793if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())13794ResType = ResAtomicType->getValueType();1379513796assert(!ResType.isNull() && "no type for increment/decrement expression");1379713798if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {13799// Decrement of bool is not allowed.13800if (!IsInc) {13801S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();13802return QualType();13803}13804// Increment of bool sets it to true, but is deprecated.13805S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool13806: diag::warn_increment_bool)13807<< Op->getSourceRange();13808} else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {13809// Error on enum increments and decrements in C++ mode13810S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;13811return QualType();13812} else if (ResType->isRealType()) {13813// OK!13814} else if (ResType->isPointerType()) {13815// C99 6.5.2.4p2, 6.5.6p213816if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))13817return QualType();13818} else if (ResType->isObjCObjectPointerType()) {13819// On modern runtimes, ObjC pointer arithmetic is forbidden.13820// Otherwise, we just need a complete type.13821if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||13822checkArithmeticOnObjCPointer(S, OpLoc, Op))13823return QualType();13824} else if (ResType->isAnyComplexType()) {13825// C99 does not support ++/-- on complex types, we allow as an extension.13826S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex13827: diag::ext_c2y_increment_complex)13828<< IsInc << Op->getSourceRange();13829} else if (ResType->isPlaceholderType()) {13830ExprResult PR = S.CheckPlaceholderExpr(Op);13831if (PR.isInvalid()) return QualType();13832return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,13833IsInc, IsPrefix);13834} else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {13835// OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )13836} else if (S.getLangOpts().ZVector && ResType->isVectorType() &&13837(ResType->castAs<VectorType>()->getVectorKind() !=13838VectorKind::AltiVecBool)) {13839// The z vector extensions allow ++ and -- for non-bool vectors.13840} else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&13841ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {13842// OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.13843} else {13844S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)13845<< ResType << int(IsInc) << Op->getSourceRange();13846return QualType();13847}13848// At this point, we know we have a real, complex or pointer type.13849// Now make sure the operand is a modifiable lvalue.13850if (CheckForModifiableLvalue(Op, OpLoc, S))13851return QualType();13852if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {13853// C++2a [expr.pre.inc]p1, [expr.post.inc]p1:13854// An operand with volatile-qualified type is deprecated13855S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)13856<< IsInc << ResType;13857}13858// In C++, a prefix increment is the same type as the operand. Otherwise13859// (in C or with postfix), the increment is the unqualified type of the13860// operand.13861if (IsPrefix && S.getLangOpts().CPlusPlus) {13862VK = VK_LValue;13863OK = Op->getObjectKind();13864return ResType;13865} else {13866VK = VK_PRValue;13867return ResType.getUnqualifiedType();13868}13869}1387013871/// getPrimaryDecl - Helper function for CheckAddressOfOperand().13872/// This routine allows us to typecheck complex/recursive expressions13873/// where the declaration is needed for type checking. We only need to13874/// handle cases when the expression references a function designator13875/// or is an lvalue. Here are some examples:13876/// - &(x) => x13877/// - &*****f => f for f a function designator.13878/// - &s.xx => s13879/// - &s.zz[1].yy -> s, if zz is an array13880/// - *(x + 1) -> x, if x is an array13881/// - &"123"[2] -> 013882/// - & __real__ x -> x13883///13884/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to13885/// members.13886static ValueDecl *getPrimaryDecl(Expr *E) {13887switch (E->getStmtClass()) {13888case Stmt::DeclRefExprClass:13889return cast<DeclRefExpr>(E)->getDecl();13890case Stmt::MemberExprClass:13891// If this is an arrow operator, the address is an offset from13892// the base's value, so the object the base refers to is13893// irrelevant.13894if (cast<MemberExpr>(E)->isArrow())13895return nullptr;13896// Otherwise, the expression refers to a part of the base13897return getPrimaryDecl(cast<MemberExpr>(E)->getBase());13898case Stmt::ArraySubscriptExprClass: {13899// FIXME: This code shouldn't be necessary! We should catch the implicit13900// promotion of register arrays earlier.13901Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();13902if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {13903if (ICE->getSubExpr()->getType()->isArrayType())13904return getPrimaryDecl(ICE->getSubExpr());13905}13906return nullptr;13907}13908case Stmt::UnaryOperatorClass: {13909UnaryOperator *UO = cast<UnaryOperator>(E);1391013911switch(UO->getOpcode()) {13912case UO_Real:13913case UO_Imag:13914case UO_Extension:13915return getPrimaryDecl(UO->getSubExpr());13916default:13917return nullptr;13918}13919}13920case Stmt::ParenExprClass:13921return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());13922case Stmt::ImplicitCastExprClass:13923// If the result of an implicit cast is an l-value, we care about13924// the sub-expression; otherwise, the result here doesn't matter.13925return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());13926case Stmt::CXXUuidofExprClass:13927return cast<CXXUuidofExpr>(E)->getGuidDecl();13928default:13929return nullptr;13930}13931}1393213933namespace {13934enum {13935AO_Bit_Field = 0,13936AO_Vector_Element = 1,13937AO_Property_Expansion = 2,13938AO_Register_Variable = 3,13939AO_Matrix_Element = 4,13940AO_No_Error = 513941};13942}13943/// Diagnose invalid operand for address of operations.13944///13945/// \param Type The type of operand which cannot have its address taken.13946static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,13947Expr *E, unsigned Type) {13948S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();13949}1395013951bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,13952const Expr *Op,13953const CXXMethodDecl *MD) {13954const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());1395513956if (Op != DRE)13957return Diag(OpLoc, diag::err_parens_pointer_member_function)13958<< Op->getSourceRange();1395913960// Taking the address of a dtor is illegal per C++ [class.dtor]p2.13961if (isa<CXXDestructorDecl>(MD))13962return Diag(OpLoc, diag::err_typecheck_addrof_dtor)13963<< DRE->getSourceRange();1396413965if (DRE->getQualifier())13966return false;1396713968if (MD->getParent()->getName().empty())13969return Diag(OpLoc, diag::err_unqualified_pointer_member_function)13970<< DRE->getSourceRange();1397113972SmallString<32> Str;13973StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);13974return Diag(OpLoc, diag::err_unqualified_pointer_member_function)13975<< DRE->getSourceRange()13976<< FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);13977}1397813979QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {13980if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){13981if (PTy->getKind() == BuiltinType::Overload) {13982Expr *E = OrigOp.get()->IgnoreParens();13983if (!isa<OverloadExpr>(E)) {13984assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);13985Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)13986<< OrigOp.get()->getSourceRange();13987return QualType();13988}1398913990OverloadExpr *Ovl = cast<OverloadExpr>(E);13991if (isa<UnresolvedMemberExpr>(Ovl))13992if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {13993Diag(OpLoc, diag::err_invalid_form_pointer_member_function)13994<< OrigOp.get()->getSourceRange();13995return QualType();13996}1399713998return Context.OverloadTy;13999}1400014001if (PTy->getKind() == BuiltinType::UnknownAny)14002return Context.UnknownAnyTy;1400314004if (PTy->getKind() == BuiltinType::BoundMember) {14005Diag(OpLoc, diag::err_invalid_form_pointer_member_function)14006<< OrigOp.get()->getSourceRange();14007return QualType();14008}1400914010OrigOp = CheckPlaceholderExpr(OrigOp.get());14011if (OrigOp.isInvalid()) return QualType();14012}1401314014if (OrigOp.get()->isTypeDependent())14015return Context.DependentTy;1401614017assert(!OrigOp.get()->hasPlaceholderType());1401814019// Make sure to ignore parentheses in subsequent checks14020Expr *op = OrigOp.get()->IgnoreParens();1402114022// In OpenCL captures for blocks called as lambda functions14023// are located in the private address space. Blocks used in14024// enqueue_kernel can be located in a different address space14025// depending on a vendor implementation. Thus preventing14026// taking an address of the capture to avoid invalid AS casts.14027if (LangOpts.OpenCL) {14028auto* VarRef = dyn_cast<DeclRefExpr>(op);14029if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {14030Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);14031return QualType();14032}14033}1403414035if (getLangOpts().C99) {14036// Implement C99-only parts of addressof rules.14037if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {14038if (uOp->getOpcode() == UO_Deref)14039// Per C99 6.5.3.2, the address of a deref always returns a valid result14040// (assuming the deref expression is valid).14041return uOp->getSubExpr()->getType();14042}14043// Technically, there should be a check for array subscript14044// expressions here, but the result of one is always an lvalue anyway.14045}14046ValueDecl *dcl = getPrimaryDecl(op);1404714048if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))14049if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,14050op->getBeginLoc()))14051return QualType();1405214053Expr::LValueClassification lval = op->ClassifyLValue(Context);14054unsigned AddressOfError = AO_No_Error;1405514056if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {14057bool sfinae = (bool)isSFINAEContext();14058Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary14059: diag::ext_typecheck_addrof_temporary)14060<< op->getType() << op->getSourceRange();14061if (sfinae)14062return QualType();14063// Materialize the temporary as an lvalue so that we can take its address.14064OrigOp = op =14065CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);14066} else if (isa<ObjCSelectorExpr>(op)) {14067return Context.getPointerType(op->getType());14068} else if (lval == Expr::LV_MemberFunction) {14069// If it's an instance method, make a member pointer.14070// The expression must have exactly the form &A::foo.1407114072// If the underlying expression isn't a decl ref, give up.14073if (!isa<DeclRefExpr>(op)) {14074Diag(OpLoc, diag::err_invalid_form_pointer_member_function)14075<< OrigOp.get()->getSourceRange();14076return QualType();14077}14078DeclRefExpr *DRE = cast<DeclRefExpr>(op);14079CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());1408014081CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);1408214083QualType MPTy = Context.getMemberPointerType(14084op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());1408514086if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&14087!isUnevaluatedContext() && !MPTy->isDependentType()) {14088// When pointer authentication is enabled, argument and return types of14089// vitual member functions must be complete. This is because vitrual14090// member function pointers are implemented using virtual dispatch14091// thunks and the thunks cannot be emitted if the argument or return14092// types are incomplete.14093auto ReturnOrParamTypeIsIncomplete = [&](QualType T,14094SourceLocation DeclRefLoc,14095SourceLocation RetArgTypeLoc) {14096if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {14097Diag(DeclRefLoc,14098diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);14099Diag(RetArgTypeLoc,14100diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)14101<< T;14102return true;14103}14104return false;14105};14106QualType RetTy = MD->getReturnType();14107bool IsIncomplete =14108!RetTy->isVoidType() &&14109ReturnOrParamTypeIsIncomplete(14110RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());14111for (auto *PVD : MD->parameters())14112IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,14113PVD->getBeginLoc());14114if (IsIncomplete)14115return QualType();14116}1411714118// Under the MS ABI, lock down the inheritance model now.14119if (Context.getTargetInfo().getCXXABI().isMicrosoft())14120(void)isCompleteType(OpLoc, MPTy);14121return MPTy;14122} else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {14123// C99 6.5.3.2p114124// The operand must be either an l-value or a function designator14125if (!op->getType()->isFunctionType()) {14126// Use a special diagnostic for loads from property references.14127if (isa<PseudoObjectExpr>(op)) {14128AddressOfError = AO_Property_Expansion;14129} else {14130Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)14131<< op->getType() << op->getSourceRange();14132return QualType();14133}14134} else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {14135if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))14136CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);14137}1413814139} else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p114140// The operand cannot be a bit-field14141AddressOfError = AO_Bit_Field;14142} else if (op->getObjectKind() == OK_VectorComponent) {14143// The operand cannot be an element of a vector14144AddressOfError = AO_Vector_Element;14145} else if (op->getObjectKind() == OK_MatrixComponent) {14146// The operand cannot be an element of a matrix.14147AddressOfError = AO_Matrix_Element;14148} else if (dcl) { // C99 6.5.3.2p114149// We have an lvalue with a decl. Make sure the decl is not declared14150// with the register storage-class specifier.14151if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {14152// in C++ it is not error to take address of a register14153// variable (c++03 7.1.1P3)14154if (vd->getStorageClass() == SC_Register &&14155!getLangOpts().CPlusPlus) {14156AddressOfError = AO_Register_Variable;14157}14158} else if (isa<MSPropertyDecl>(dcl)) {14159AddressOfError = AO_Property_Expansion;14160} else if (isa<FunctionTemplateDecl>(dcl)) {14161return Context.OverloadTy;14162} else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {14163// Okay: we can take the address of a field.14164// Could be a pointer to member, though, if there is an explicit14165// scope qualifier for the class.1416614167// [C++26] [expr.prim.id.general]14168// If an id-expression E denotes a non-static non-type member14169// of some class C [...] and if E is a qualified-id, E is14170// not the un-parenthesized operand of the unary & operator [...]14171// the id-expression is transformed into a class member access expression.14172if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&14173!isa<ParenExpr>(OrigOp.get())) {14174DeclContext *Ctx = dcl->getDeclContext();14175if (Ctx && Ctx->isRecord()) {14176if (dcl->getType()->isReferenceType()) {14177Diag(OpLoc,14178diag::err_cannot_form_pointer_to_member_of_reference_type)14179<< dcl->getDeclName() << dcl->getType();14180return QualType();14181}1418214183while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())14184Ctx = Ctx->getParent();1418514186QualType MPTy = Context.getMemberPointerType(14187op->getType(),14188Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());14189// Under the MS ABI, lock down the inheritance model now.14190if (Context.getTargetInfo().getCXXABI().isMicrosoft())14191(void)isCompleteType(OpLoc, MPTy);14192return MPTy;14193}14194}14195} else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,14196MSGuidDecl, UnnamedGlobalConstantDecl>(dcl))14197llvm_unreachable("Unknown/unexpected decl type");14198}1419914200if (AddressOfError != AO_No_Error) {14201diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);14202return QualType();14203}1420414205if (lval == Expr::LV_IncompleteVoidType) {14206// Taking the address of a void variable is technically illegal, but we14207// allow it in cases which are otherwise valid.14208// Example: "extern void x; void* y = &x;".14209Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();14210}1421114212// If the operand has type "type", the result has type "pointer to type".14213if (op->getType()->isObjCObjectType())14214return Context.getObjCObjectPointerType(op->getType());1421514216// Cannot take the address of WebAssembly references or tables.14217if (Context.getTargetInfo().getTriple().isWasm()) {14218QualType OpTy = op->getType();14219if (OpTy.isWebAssemblyReferenceType()) {14220Diag(OpLoc, diag::err_wasm_ca_reference)14221<< 1 << OrigOp.get()->getSourceRange();14222return QualType();14223}14224if (OpTy->isWebAssemblyTableType()) {14225Diag(OpLoc, diag::err_wasm_table_pr)14226<< 1 << OrigOp.get()->getSourceRange();14227return QualType();14228}14229}1423014231CheckAddressOfPackedMember(op);1423214233return Context.getPointerType(op->getType());14234}1423514236static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {14237const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);14238if (!DRE)14239return;14240const Decl *D = DRE->getDecl();14241if (!D)14242return;14243const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);14244if (!Param)14245return;14246if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))14247if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())14248return;14249if (FunctionScopeInfo *FD = S.getCurFunction())14250FD->ModifiedNonNullParams.insert(Param);14251}1425214253/// CheckIndirectionOperand - Type check unary indirection (prefix '*').14254static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,14255SourceLocation OpLoc,14256bool IsAfterAmp = false) {14257ExprResult ConvResult = S.UsualUnaryConversions(Op);14258if (ConvResult.isInvalid())14259return QualType();14260Op = ConvResult.get();14261QualType OpTy = Op->getType();14262QualType Result;1426314264if (isa<CXXReinterpretCastExpr>(Op)) {14265QualType OpOrigType = Op->IgnoreParenCasts()->getType();14266S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,14267Op->getSourceRange());14268}1426914270if (const PointerType *PT = OpTy->getAs<PointerType>())14271{14272Result = PT->getPointeeType();14273}14274else if (const ObjCObjectPointerType *OPT =14275OpTy->getAs<ObjCObjectPointerType>())14276Result = OPT->getPointeeType();14277else {14278ExprResult PR = S.CheckPlaceholderExpr(Op);14279if (PR.isInvalid()) return QualType();14280if (PR.get() != Op)14281return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);14282}1428314284if (Result.isNull()) {14285S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)14286<< OpTy << Op->getSourceRange();14287return QualType();14288}1428914290if (Result->isVoidType()) {14291// C++ [expr.unary.op]p1:14292// [...] the expression to which [the unary * operator] is applied shall14293// be a pointer to an object type, or a pointer to a function type14294LangOptions LO = S.getLangOpts();14295if (LO.CPlusPlus)14296S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)14297<< OpTy << Op->getSourceRange();14298else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())14299S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)14300<< OpTy << Op->getSourceRange();14301}1430214303// Dereferences are usually l-values...14304VK = VK_LValue;1430514306// ...except that certain expressions are never l-values in C.14307if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())14308VK = VK_PRValue;1430914310return Result;14311}1431214313BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {14314BinaryOperatorKind Opc;14315switch (Kind) {14316default: llvm_unreachable("Unknown binop!");14317case tok::periodstar: Opc = BO_PtrMemD; break;14318case tok::arrowstar: Opc = BO_PtrMemI; break;14319case tok::star: Opc = BO_Mul; break;14320case tok::slash: Opc = BO_Div; break;14321case tok::percent: Opc = BO_Rem; break;14322case tok::plus: Opc = BO_Add; break;14323case tok::minus: Opc = BO_Sub; break;14324case tok::lessless: Opc = BO_Shl; break;14325case tok::greatergreater: Opc = BO_Shr; break;14326case tok::lessequal: Opc = BO_LE; break;14327case tok::less: Opc = BO_LT; break;14328case tok::greaterequal: Opc = BO_GE; break;14329case tok::greater: Opc = BO_GT; break;14330case tok::exclaimequal: Opc = BO_NE; break;14331case tok::equalequal: Opc = BO_EQ; break;14332case tok::spaceship: Opc = BO_Cmp; break;14333case tok::amp: Opc = BO_And; break;14334case tok::caret: Opc = BO_Xor; break;14335case tok::pipe: Opc = BO_Or; break;14336case tok::ampamp: Opc = BO_LAnd; break;14337case tok::pipepipe: Opc = BO_LOr; break;14338case tok::equal: Opc = BO_Assign; break;14339case tok::starequal: Opc = BO_MulAssign; break;14340case tok::slashequal: Opc = BO_DivAssign; break;14341case tok::percentequal: Opc = BO_RemAssign; break;14342case tok::plusequal: Opc = BO_AddAssign; break;14343case tok::minusequal: Opc = BO_SubAssign; break;14344case tok::lesslessequal: Opc = BO_ShlAssign; break;14345case tok::greatergreaterequal: Opc = BO_ShrAssign; break;14346case tok::ampequal: Opc = BO_AndAssign; break;14347case tok::caretequal: Opc = BO_XorAssign; break;14348case tok::pipeequal: Opc = BO_OrAssign; break;14349case tok::comma: Opc = BO_Comma; break;14350}14351return Opc;14352}1435314354static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(14355tok::TokenKind Kind) {14356UnaryOperatorKind Opc;14357switch (Kind) {14358default: llvm_unreachable("Unknown unary op!");14359case tok::plusplus: Opc = UO_PreInc; break;14360case tok::minusminus: Opc = UO_PreDec; break;14361case tok::amp: Opc = UO_AddrOf; break;14362case tok::star: Opc = UO_Deref; break;14363case tok::plus: Opc = UO_Plus; break;14364case tok::minus: Opc = UO_Minus; break;14365case tok::tilde: Opc = UO_Not; break;14366case tok::exclaim: Opc = UO_LNot; break;14367case tok::kw___real: Opc = UO_Real; break;14368case tok::kw___imag: Opc = UO_Imag; break;14369case tok::kw___extension__: Opc = UO_Extension; break;14370}14371return Opc;14372}1437314374const FieldDecl *14375Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {14376// Explore the case for adding 'this->' to the LHS of a self assignment, very14377// common for setters.14378// struct A {14379// int X;14380// -void setX(int X) { X = X; }14381// +void setX(int X) { this->X = X; }14382// };1438314384// Only consider parameters for self assignment fixes.14385if (!isa<ParmVarDecl>(SelfAssigned))14386return nullptr;14387const auto *Method =14388dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));14389if (!Method)14390return nullptr;1439114392const CXXRecordDecl *Parent = Method->getParent();14393// In theory this is fixable if the lambda explicitly captures this, but14394// that's added complexity that's rarely going to be used.14395if (Parent->isLambda())14396return nullptr;1439714398// FIXME: Use an actual Lookup operation instead of just traversing fields14399// in order to get base class fields.14400auto Field =14401llvm::find_if(Parent->fields(),14402[Name(SelfAssigned->getDeclName())](const FieldDecl *F) {14403return F->getDeclName() == Name;14404});14405return (Field != Parent->field_end()) ? *Field : nullptr;14406}1440714408/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.14409/// This warning suppressed in the event of macro expansions.14410static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,14411SourceLocation OpLoc, bool IsBuiltin) {14412if (S.inTemplateInstantiation())14413return;14414if (S.isUnevaluatedContext())14415return;14416if (OpLoc.isInvalid() || OpLoc.isMacroID())14417return;14418LHSExpr = LHSExpr->IgnoreParenImpCasts();14419RHSExpr = RHSExpr->IgnoreParenImpCasts();14420const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);14421const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);14422if (!LHSDeclRef || !RHSDeclRef ||14423LHSDeclRef->getLocation().isMacroID() ||14424RHSDeclRef->getLocation().isMacroID())14425return;14426const ValueDecl *LHSDecl =14427cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());14428const ValueDecl *RHSDecl =14429cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());14430if (LHSDecl != RHSDecl)14431return;14432if (LHSDecl->getType().isVolatileQualified())14433return;14434if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())14435if (RefTy->getPointeeType().isVolatileQualified())14436return;1443714438auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin14439: diag::warn_self_assignment_overloaded)14440<< LHSDeclRef->getType() << LHSExpr->getSourceRange()14441<< RHSExpr->getSourceRange();14442if (const FieldDecl *SelfAssignField =14443S.getSelfAssignmentClassMemberCandidate(RHSDecl))14444Diag << 1 << SelfAssignField14445<< FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");14446else14447Diag << 0;14448}1444914450/// Check if a bitwise-& is performed on an Objective-C pointer. This14451/// is usually indicative of introspection within the Objective-C pointer.14452static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,14453SourceLocation OpLoc) {14454if (!S.getLangOpts().ObjC)14455return;1445614457const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;14458const Expr *LHS = L.get();14459const Expr *RHS = R.get();1446014461if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {14462ObjCPointerExpr = LHS;14463OtherExpr = RHS;14464}14465else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {14466ObjCPointerExpr = RHS;14467OtherExpr = LHS;14468}1446914470// This warning is deliberately made very specific to reduce false14471// positives with logic that uses '&' for hashing. This logic mainly14472// looks for code trying to introspect into tagged pointers, which14473// code should generally never do.14474if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {14475unsigned Diag = diag::warn_objc_pointer_masking;14476// Determine if we are introspecting the result of performSelectorXXX.14477const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();14478// Special case messages to -performSelector and friends, which14479// can return non-pointer values boxed in a pointer value.14480// Some clients may wish to silence warnings in this subcase.14481if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {14482Selector S = ME->getSelector();14483StringRef SelArg0 = S.getNameForSlot(0);14484if (SelArg0.starts_with("performSelector"))14485Diag = diag::warn_objc_pointer_masking_performSelector;14486}1448714488S.Diag(OpLoc, Diag)14489<< ObjCPointerExpr->getSourceRange();14490}14491}1449214493static NamedDecl *getDeclFromExpr(Expr *E) {14494if (!E)14495return nullptr;14496if (auto *DRE = dyn_cast<DeclRefExpr>(E))14497return DRE->getDecl();14498if (auto *ME = dyn_cast<MemberExpr>(E))14499return ME->getMemberDecl();14500if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))14501return IRE->getDecl();14502return nullptr;14503}1450414505// This helper function promotes a binary operator's operands (which are of a14506// half vector type) to a vector of floats and then truncates the result to14507// a vector of either half or short.14508static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,14509BinaryOperatorKind Opc, QualType ResultTy,14510ExprValueKind VK, ExprObjectKind OK,14511bool IsCompAssign, SourceLocation OpLoc,14512FPOptionsOverride FPFeatures) {14513auto &Context = S.getASTContext();14514assert((isVector(ResultTy, Context.HalfTy) ||14515isVector(ResultTy, Context.ShortTy)) &&14516"Result must be a vector of half or short");14517assert(isVector(LHS.get()->getType(), Context.HalfTy) &&14518isVector(RHS.get()->getType(), Context.HalfTy) &&14519"both operands expected to be a half vector");1452014521RHS = convertVector(RHS.get(), Context.FloatTy, S);14522QualType BinOpResTy = RHS.get()->getType();1452314524// If Opc is a comparison, ResultType is a vector of shorts. In that case,14525// change BinOpResTy to a vector of ints.14526if (isVector(ResultTy, Context.ShortTy))14527BinOpResTy = S.GetSignedVectorType(BinOpResTy);1452814529if (IsCompAssign)14530return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,14531ResultTy, VK, OK, OpLoc, FPFeatures,14532BinOpResTy, BinOpResTy);1453314534LHS = convertVector(LHS.get(), Context.FloatTy, S);14535auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,14536BinOpResTy, VK, OK, OpLoc, FPFeatures);14537return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);14538}1453914540static std::pair<ExprResult, ExprResult>14541CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,14542Expr *RHSExpr) {14543ExprResult LHS = LHSExpr, RHS = RHSExpr;14544if (!S.Context.isDependenceAllowed()) {14545// C cannot handle TypoExpr nodes on either side of a binop because it14546// doesn't handle dependent types properly, so make sure any TypoExprs have14547// been dealt with before checking the operands.14548LHS = S.CorrectDelayedTyposInExpr(LHS);14549RHS = S.CorrectDelayedTyposInExpr(14550RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,14551[Opc, LHS](Expr *E) {14552if (Opc != BO_Assign)14553return ExprResult(E);14554// Avoid correcting the RHS to the same Expr as the LHS.14555Decl *D = getDeclFromExpr(E);14556return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;14557});14558}14559return std::make_pair(LHS, RHS);14560}1456114562/// Returns true if conversion between vectors of halfs and vectors of floats14563/// is needed.14564static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,14565Expr *E0, Expr *E1 = nullptr) {14566if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||14567Ctx.getTargetInfo().useFP16ConversionIntrinsics())14568return false;1456914570auto HasVectorOfHalfType = [&Ctx](Expr *E) {14571QualType Ty = E->IgnoreImplicit()->getType();1457214573// Don't promote half precision neon vectors like float16x4_t in arm_neon.h14574// to vectors of floats. Although the element type of the vectors is __fp16,14575// the vectors shouldn't be treated as storage-only types. See the14576// discussion here: https://reviews.llvm.org/rG825235c140e714577if (const VectorType *VT = Ty->getAs<VectorType>()) {14578if (VT->getVectorKind() == VectorKind::Neon)14579return false;14580return VT->getElementType().getCanonicalType() == Ctx.HalfTy;14581}14582return false;14583};1458414585return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));14586}1458714588ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,14589BinaryOperatorKind Opc,14590Expr *LHSExpr, Expr *RHSExpr) {14591if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {14592// The syntax only allows initializer lists on the RHS of assignment,14593// so we don't need to worry about accepting invalid code for14594// non-assignment operators.14595// C++11 5.17p9:14596// The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning14597// of x = {} is x = T().14598InitializationKind Kind = InitializationKind::CreateDirectList(14599RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());14600InitializedEntity Entity =14601InitializedEntity::InitializeTemporary(LHSExpr->getType());14602InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);14603ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);14604if (Init.isInvalid())14605return Init;14606RHSExpr = Init.get();14607}1460814609ExprResult LHS = LHSExpr, RHS = RHSExpr;14610QualType ResultTy; // Result type of the binary operator.14611// The following two variables are used for compound assignment operators14612QualType CompLHSTy; // Type of LHS after promotions for computation14613QualType CompResultTy; // Type of computation result14614ExprValueKind VK = VK_PRValue;14615ExprObjectKind OK = OK_Ordinary;14616bool ConvertHalfVec = false;1461714618std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);14619if (!LHS.isUsable() || !RHS.isUsable())14620return ExprError();1462114622if (getLangOpts().OpenCL) {14623QualType LHSTy = LHSExpr->getType();14624QualType RHSTy = RHSExpr->getType();14625// OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by14626// the ATOMIC_VAR_INIT macro.14627if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {14628SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());14629if (BO_Assign == Opc)14630Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;14631else14632ResultTy = InvalidOperands(OpLoc, LHS, RHS);14633return ExprError();14634}1463514636// OpenCL special types - image, sampler, pipe, and blocks are to be used14637// only with a builtin functions and therefore should be disallowed here.14638if (LHSTy->isImageType() || RHSTy->isImageType() ||14639LHSTy->isSamplerT() || RHSTy->isSamplerT() ||14640LHSTy->isPipeType() || RHSTy->isPipeType() ||14641LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {14642ResultTy = InvalidOperands(OpLoc, LHS, RHS);14643return ExprError();14644}14645}1464614647checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);14648checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);1464914650switch (Opc) {14651case BO_Assign:14652ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);14653if (getLangOpts().CPlusPlus &&14654LHS.get()->getObjectKind() != OK_ObjCProperty) {14655VK = LHS.get()->getValueKind();14656OK = LHS.get()->getObjectKind();14657}14658if (!ResultTy.isNull()) {14659DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);14660DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);1466114662// Avoid copying a block to the heap if the block is assigned to a local14663// auto variable that is declared in the same scope as the block. This14664// optimization is unsafe if the local variable is declared in an outer14665// scope. For example:14666//14667// BlockTy b;14668// {14669// b = ^{...};14670// }14671// // It is unsafe to invoke the block here if it wasn't copied to the14672// // heap.14673// b();1467414675if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))14676if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))14677if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))14678if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))14679BE->getBlockDecl()->setCanAvoidCopyToHeap();1468014681if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())14682checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),14683NTCUC_Assignment, NTCUK_Copy);14684}14685RecordModifiableNonNullParam(*this, LHS.get());14686break;14687case BO_PtrMemD:14688case BO_PtrMemI:14689ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,14690Opc == BO_PtrMemI);14691break;14692case BO_Mul:14693case BO_Div:14694ConvertHalfVec = true;14695ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,14696Opc == BO_Div);14697break;14698case BO_Rem:14699ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);14700break;14701case BO_Add:14702ConvertHalfVec = true;14703ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);14704break;14705case BO_Sub:14706ConvertHalfVec = true;14707ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);14708break;14709case BO_Shl:14710case BO_Shr:14711ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);14712break;14713case BO_LE:14714case BO_LT:14715case BO_GE:14716case BO_GT:14717ConvertHalfVec = true;14718ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);1471914720if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);14721BI && BI->isComparisonOp())14722Diag(OpLoc, diag::warn_consecutive_comparison);1472314724break;14725case BO_EQ:14726case BO_NE:14727ConvertHalfVec = true;14728ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);14729break;14730case BO_Cmp:14731ConvertHalfVec = true;14732ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);14733assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());14734break;14735case BO_And:14736checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);14737[[fallthrough]];14738case BO_Xor:14739case BO_Or:14740ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);14741break;14742case BO_LAnd:14743case BO_LOr:14744ConvertHalfVec = true;14745ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);14746break;14747case BO_MulAssign:14748case BO_DivAssign:14749ConvertHalfVec = true;14750CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,14751Opc == BO_DivAssign);14752CompLHSTy = CompResultTy;14753if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())14754ResultTy =14755CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);14756break;14757case BO_RemAssign:14758CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);14759CompLHSTy = CompResultTy;14760if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())14761ResultTy =14762CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);14763break;14764case BO_AddAssign:14765ConvertHalfVec = true;14766CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);14767if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())14768ResultTy =14769CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);14770break;14771case BO_SubAssign:14772ConvertHalfVec = true;14773CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);14774if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())14775ResultTy =14776CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);14777break;14778case BO_ShlAssign:14779case BO_ShrAssign:14780CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);14781CompLHSTy = CompResultTy;14782if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())14783ResultTy =14784CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);14785break;14786case BO_AndAssign:14787case BO_OrAssign: // fallthrough14788DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);14789[[fallthrough]];14790case BO_XorAssign:14791CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);14792CompLHSTy = CompResultTy;14793if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())14794ResultTy =14795CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);14796break;14797case BO_Comma:14798ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);14799if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {14800VK = RHS.get()->getValueKind();14801OK = RHS.get()->getObjectKind();14802}14803break;14804}14805if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())14806return ExprError();1480714808// Some of the binary operations require promoting operands of half vector to14809// float vectors and truncating the result back to half vector. For now, we do14810// this only when HalfArgsAndReturn is set (that is, when the target is arm or14811// arm64).14812assert(14813(Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==14814isVector(LHS.get()->getType(), Context.HalfTy)) &&14815"both sides are half vectors or neither sides are");14816ConvertHalfVec =14817needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());1481814819// Check for array bounds violations for both sides of the BinaryOperator14820CheckArrayAccess(LHS.get());14821CheckArrayAccess(RHS.get());1482214823if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {14824NamedDecl *ObjectSetClass = LookupSingleName(TUScope,14825&Context.Idents.get("object_setClass"),14826SourceLocation(), LookupOrdinaryName);14827if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {14828SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());14829Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)14830<< FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),14831"object_setClass(")14832<< FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),14833",")14834<< FixItHint::CreateInsertion(RHSLocEnd, ")");14835}14836else14837Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);14838}14839else if (const ObjCIvarRefExpr *OIRE =14840dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))14841DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());1484214843// Opc is not a compound assignment if CompResultTy is null.14844if (CompResultTy.isNull()) {14845if (ConvertHalfVec)14846return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,14847OpLoc, CurFPFeatureOverrides());14848return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,14849VK, OK, OpLoc, CurFPFeatureOverrides());14850}1485114852// Handle compound assignments.14853if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=14854OK_ObjCProperty) {14855VK = VK_LValue;14856OK = LHS.get()->getObjectKind();14857}1485814859// The LHS is not converted to the result type for fixed-point compound14860// assignment as the common type is computed on demand. Reset the CompLHSTy14861// to the LHS type we would have gotten after unary conversions.14862if (CompResultTy->isFixedPointType())14863CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();1486414865if (ConvertHalfVec)14866return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,14867OpLoc, CurFPFeatureOverrides());1486814869return CompoundAssignOperator::Create(14870Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,14871CurFPFeatureOverrides(), CompLHSTy, CompResultTy);14872}1487314874/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison14875/// operators are mixed in a way that suggests that the programmer forgot that14876/// comparison operators have higher precedence. The most typical example of14877/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".14878static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,14879SourceLocation OpLoc, Expr *LHSExpr,14880Expr *RHSExpr) {14881BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);14882BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);1488314884// Check that one of the sides is a comparison operator and the other isn't.14885bool isLeftComp = LHSBO && LHSBO->isComparisonOp();14886bool isRightComp = RHSBO && RHSBO->isComparisonOp();14887if (isLeftComp == isRightComp)14888return;1488914890// Bitwise operations are sometimes used as eager logical ops.14891// Don't diagnose this.14892bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();14893bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();14894if (isLeftBitwise || isRightBitwise)14895return;1489614897SourceRange DiagRange = isLeftComp14898? SourceRange(LHSExpr->getBeginLoc(), OpLoc)14899: SourceRange(OpLoc, RHSExpr->getEndLoc());14900StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();14901SourceRange ParensRange =14902isLeftComp14903? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())14904: SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());1490514906Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)14907<< DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;14908SuggestParentheses(Self, OpLoc,14909Self.PDiag(diag::note_precedence_silence) << OpStr,14910(isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());14911SuggestParentheses(Self, OpLoc,14912Self.PDiag(diag::note_precedence_bitwise_first)14913<< BinaryOperator::getOpcodeStr(Opc),14914ParensRange);14915}1491614917/// It accepts a '&&' expr that is inside a '||' one.14918/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression14919/// in parentheses.14920static void14921EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,14922BinaryOperator *Bop) {14923assert(Bop->getOpcode() == BO_LAnd);14924Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)14925<< Bop->getSourceRange() << OpLoc;14926SuggestParentheses(Self, Bop->getOperatorLoc(),14927Self.PDiag(diag::note_precedence_silence)14928<< Bop->getOpcodeStr(),14929Bop->getSourceRange());14930}1493114932/// Look for '&&' in the left hand of a '||' expr.14933static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,14934Expr *LHSExpr, Expr *RHSExpr) {14935if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {14936if (Bop->getOpcode() == BO_LAnd) {14937// If it's "string_literal && a || b" don't warn since the precedence14938// doesn't matter.14939if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))14940return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);14941} else if (Bop->getOpcode() == BO_LOr) {14942if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {14943// If it's "a || b && string_literal || c" we didn't warn earlier for14944// "a || b && string_literal", but warn now.14945if (RBop->getOpcode() == BO_LAnd &&14946isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))14947return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);14948}14949}14950}14951}1495214953/// Look for '&&' in the right hand of a '||' expr.14954static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,14955Expr *LHSExpr, Expr *RHSExpr) {14956if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {14957if (Bop->getOpcode() == BO_LAnd) {14958// If it's "a || b && string_literal" don't warn since the precedence14959// doesn't matter.14960if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))14961return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);14962}14963}14964}1496514966/// Look for bitwise op in the left or right hand of a bitwise op with14967/// lower precedence and emit a diagnostic together with a fixit hint that wraps14968/// the '&' expression in parentheses.14969static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,14970SourceLocation OpLoc, Expr *SubExpr) {14971if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {14972if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {14973S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)14974<< Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)14975<< Bop->getSourceRange() << OpLoc;14976SuggestParentheses(S, Bop->getOperatorLoc(),14977S.PDiag(diag::note_precedence_silence)14978<< Bop->getOpcodeStr(),14979Bop->getSourceRange());14980}14981}14982}1498314984static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,14985Expr *SubExpr, StringRef Shift) {14986if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {14987if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {14988StringRef Op = Bop->getOpcodeStr();14989S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)14990<< Bop->getSourceRange() << OpLoc << Shift << Op;14991SuggestParentheses(S, Bop->getOperatorLoc(),14992S.PDiag(diag::note_precedence_silence) << Op,14993Bop->getSourceRange());14994}14995}14996}1499714998static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,14999Expr *LHSExpr, Expr *RHSExpr) {15000CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);15001if (!OCE)15002return;1500315004FunctionDecl *FD = OCE->getDirectCallee();15005if (!FD || !FD->isOverloadedOperator())15006return;1500715008OverloadedOperatorKind Kind = FD->getOverloadedOperator();15009if (Kind != OO_LessLess && Kind != OO_GreaterGreater)15010return;1501115012S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)15013<< LHSExpr->getSourceRange() << RHSExpr->getSourceRange()15014<< (Kind == OO_LessLess);15015SuggestParentheses(S, OCE->getOperatorLoc(),15016S.PDiag(diag::note_precedence_silence)15017<< (Kind == OO_LessLess ? "<<" : ">>"),15018OCE->getSourceRange());15019SuggestParentheses(15020S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),15021SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));15022}1502315024/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky15025/// precedence.15026static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,15027SourceLocation OpLoc, Expr *LHSExpr,15028Expr *RHSExpr){15029// Diagnose "arg1 'bitwise' arg2 'eq' arg3".15030if (BinaryOperator::isBitwiseOp(Opc))15031DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);1503215033// Diagnose "arg1 & arg2 | arg3"15034if ((Opc == BO_Or || Opc == BO_Xor) &&15035!OpLoc.isMacroID()/* Don't warn in macros. */) {15036DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);15037DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);15038}1503915040// Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.15041// We don't warn for 'assert(a || b && "bad")' since this is safe.15042if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {15043DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);15044DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);15045}1504615047if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))15048|| Opc == BO_Shr) {15049StringRef Shift = BinaryOperator::getOpcodeStr(Opc);15050DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);15051DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);15052}1505315054// Warn on overloaded shift operators and comparisons, such as:15055// cout << 5 == 4;15056if (BinaryOperator::isComparisonOp(Opc))15057DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);15058}1505915060ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,15061tok::TokenKind Kind,15062Expr *LHSExpr, Expr *RHSExpr) {15063BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);15064assert(LHSExpr && "ActOnBinOp(): missing left expression");15065assert(RHSExpr && "ActOnBinOp(): missing right expression");1506615067// Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"15068DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);1506915070return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);15071}1507215073void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,15074UnresolvedSetImpl &Functions) {15075OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);15076if (OverOp != OO_None && OverOp != OO_Equal)15077LookupOverloadedOperatorName(OverOp, S, Functions);1507815079// In C++20 onwards, we may have a second operator to look up.15080if (getLangOpts().CPlusPlus20) {15081if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))15082LookupOverloadedOperatorName(ExtraOp, S, Functions);15083}15084}1508515086/// Build an overloaded binary operator expression in the given scope.15087static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,15088BinaryOperatorKind Opc,15089Expr *LHS, Expr *RHS) {15090switch (Opc) {15091case BO_Assign:15092// In the non-overloaded case, we warn about self-assignment (x = x) for15093// both simple assignment and certain compound assignments where algebra15094// tells us the operation yields a constant result. When the operator is15095// overloaded, we can't do the latter because we don't want to assume that15096// those algebraic identities still apply; for example, a path-building15097// library might use operator/= to append paths. But it's still reasonable15098// to assume that simple assignment is just moving/copying values around15099// and so self-assignment is likely a bug.15100DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);15101[[fallthrough]];15102case BO_DivAssign:15103case BO_RemAssign:15104case BO_SubAssign:15105case BO_AndAssign:15106case BO_OrAssign:15107case BO_XorAssign:15108CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);15109break;15110default:15111break;15112}1511315114// Find all of the overloaded operators visible from this point.15115UnresolvedSet<16> Functions;15116S.LookupBinOp(Sc, OpLoc, Opc, Functions);1511715118// Build the (potentially-overloaded, potentially-dependent)15119// binary operation.15120return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);15121}1512215123ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,15124BinaryOperatorKind Opc,15125Expr *LHSExpr, Expr *RHSExpr) {15126ExprResult LHS, RHS;15127std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);15128if (!LHS.isUsable() || !RHS.isUsable())15129return ExprError();15130LHSExpr = LHS.get();15131RHSExpr = RHS.get();1513215133// We want to end up calling one of SemaPseudoObject::checkAssignment15134// (if the LHS is a pseudo-object), BuildOverloadedBinOp (if15135// both expressions are overloadable or either is type-dependent),15136// or CreateBuiltinBinOp (in any other case). We also want to get15137// any placeholder types out of the way.1513815139// Handle pseudo-objects in the LHS.15140if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {15141// Assignments with a pseudo-object l-value need special analysis.15142if (pty->getKind() == BuiltinType::PseudoObject &&15143BinaryOperator::isAssignmentOp(Opc))15144return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);1514515146// Don't resolve overloads if the other type is overloadable.15147if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {15148// We can't actually test that if we still have a placeholder,15149// though. Fortunately, none of the exceptions we see in that15150// code below are valid when the LHS is an overload set. Note15151// that an overload set can be dependently-typed, but it never15152// instantiates to having an overloadable type.15153ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);15154if (resolvedRHS.isInvalid()) return ExprError();15155RHSExpr = resolvedRHS.get();1515615157if (RHSExpr->isTypeDependent() ||15158RHSExpr->getType()->isOverloadableType())15159return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);15160}1516115162// If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function15163// template, diagnose the missing 'template' keyword instead of diagnosing15164// an invalid use of a bound member function.15165//15166// Note that "A::x < b" might be valid if 'b' has an overloadable type due15167// to C++1z [over.over]/1.4, but we already checked for that case above.15168if (Opc == BO_LT && inTemplateInstantiation() &&15169(pty->getKind() == BuiltinType::BoundMember ||15170pty->getKind() == BuiltinType::Overload)) {15171auto *OE = dyn_cast<OverloadExpr>(LHSExpr);15172if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&15173llvm::any_of(OE->decls(), [](NamedDecl *ND) {15174return isa<FunctionTemplateDecl>(ND);15175})) {15176Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()15177: OE->getNameLoc(),15178diag::err_template_kw_missing)15179<< OE->getName().getAsString() << "";15180return ExprError();15181}15182}1518315184ExprResult LHS = CheckPlaceholderExpr(LHSExpr);15185if (LHS.isInvalid()) return ExprError();15186LHSExpr = LHS.get();15187}1518815189// Handle pseudo-objects in the RHS.15190if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {15191// An overload in the RHS can potentially be resolved by the type15192// being assigned to.15193if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {15194if (getLangOpts().CPlusPlus &&15195(LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||15196LHSExpr->getType()->isOverloadableType()))15197return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);1519815199return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);15200}1520115202// Don't resolve overloads if the other type is overloadable.15203if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&15204LHSExpr->getType()->isOverloadableType())15205return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);1520615207ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);15208if (!resolvedRHS.isUsable()) return ExprError();15209RHSExpr = resolvedRHS.get();15210}1521115212if (getLangOpts().CPlusPlus) {15213// Otherwise, build an overloaded op if either expression is type-dependent15214// or has an overloadable type.15215if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||15216LHSExpr->getType()->isOverloadableType() ||15217RHSExpr->getType()->isOverloadableType())15218return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);15219}1522015221if (getLangOpts().RecoveryAST &&15222(LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {15223assert(!getLangOpts().CPlusPlus);15224assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&15225"Should only occur in error-recovery path.");15226if (BinaryOperator::isCompoundAssignmentOp(Opc))15227// C [6.15.16] p3:15228// An assignment expression has the value of the left operand after the15229// assignment, but is not an lvalue.15230return CompoundAssignOperator::Create(15231Context, LHSExpr, RHSExpr, Opc,15232LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,15233OpLoc, CurFPFeatureOverrides());15234QualType ResultType;15235switch (Opc) {15236case BO_Assign:15237ResultType = LHSExpr->getType().getUnqualifiedType();15238break;15239case BO_LT:15240case BO_GT:15241case BO_LE:15242case BO_GE:15243case BO_EQ:15244case BO_NE:15245case BO_LAnd:15246case BO_LOr:15247// These operators have a fixed result type regardless of operands.15248ResultType = Context.IntTy;15249break;15250case BO_Comma:15251ResultType = RHSExpr->getType();15252break;15253default:15254ResultType = Context.DependentTy;15255break;15256}15257return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,15258VK_PRValue, OK_Ordinary, OpLoc,15259CurFPFeatureOverrides());15260}1526115262// Build a built-in binary operation.15263return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);15264}1526515266static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {15267if (T.isNull() || T->isDependentType())15268return false;1526915270if (!Ctx.isPromotableIntegerType(T))15271return true;1527215273return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);15274}1527515276ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,15277UnaryOperatorKind Opc, Expr *InputExpr,15278bool IsAfterAmp) {15279ExprResult Input = InputExpr;15280ExprValueKind VK = VK_PRValue;15281ExprObjectKind OK = OK_Ordinary;15282QualType resultType;15283bool CanOverflow = false;1528415285bool ConvertHalfVec = false;15286if (getLangOpts().OpenCL) {15287QualType Ty = InputExpr->getType();15288// The only legal unary operation for atomics is '&'.15289if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||15290// OpenCL special types - image, sampler, pipe, and blocks are to be used15291// only with a builtin functions and therefore should be disallowed here.15292(Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()15293|| Ty->isBlockPointerType())) {15294return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15295<< InputExpr->getType()15296<< Input.get()->getSourceRange());15297}15298}1529915300if (getLangOpts().HLSL && OpLoc.isValid()) {15301if (Opc == UO_AddrOf)15302return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);15303if (Opc == UO_Deref)15304return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);15305}1530615307if (InputExpr->isTypeDependent() &&15308InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {15309resultType = Context.DependentTy;15310} else {15311switch (Opc) {15312case UO_PreInc:15313case UO_PreDec:15314case UO_PostInc:15315case UO_PostDec:15316resultType =15317CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,15318Opc == UO_PreInc || Opc == UO_PostInc,15319Opc == UO_PreInc || Opc == UO_PreDec);15320CanOverflow = isOverflowingIntegerType(Context, resultType);15321break;15322case UO_AddrOf:15323resultType = CheckAddressOfOperand(Input, OpLoc);15324CheckAddressOfNoDeref(InputExpr);15325RecordModifiableNonNullParam(*this, InputExpr);15326break;15327case UO_Deref: {15328Input = DefaultFunctionArrayLvalueConversion(Input.get());15329if (Input.isInvalid())15330return ExprError();15331resultType =15332CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);15333break;15334}15335case UO_Plus:15336case UO_Minus:15337CanOverflow = Opc == UO_Minus &&15338isOverflowingIntegerType(Context, Input.get()->getType());15339Input = UsualUnaryConversions(Input.get());15340if (Input.isInvalid())15341return ExprError();15342// Unary plus and minus require promoting an operand of half vector to a15343// float vector and truncating the result back to a half vector. For now,15344// we do this only when HalfArgsAndReturns is set (that is, when the15345// target is arm or arm64).15346ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());1534715348// If the operand is a half vector, promote it to a float vector.15349if (ConvertHalfVec)15350Input = convertVector(Input.get(), Context.FloatTy, *this);15351resultType = Input.get()->getType();15352if (resultType->isArithmeticType()) // C99 6.5.3.3p115353break;15354else if (resultType->isVectorType() &&15355// The z vector extensions don't allow + or - with bool vectors.15356(!Context.getLangOpts().ZVector ||15357resultType->castAs<VectorType>()->getVectorKind() !=15358VectorKind::AltiVecBool))15359break;15360else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -15361break;15362else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p615363Opc == UO_Plus && resultType->isPointerType())15364break;1536515366return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15367<< resultType << Input.get()->getSourceRange());1536815369case UO_Not: // bitwise complement15370Input = UsualUnaryConversions(Input.get());15371if (Input.isInvalid())15372return ExprError();15373resultType = Input.get()->getType();15374// C99 6.5.3.3p1. We allow complex int and float as a GCC extension.15375if (resultType->isComplexType() || resultType->isComplexIntegerType())15376// C99 does not support '~' for complex conjugation.15377Diag(OpLoc, diag::ext_integer_complement_complex)15378<< resultType << Input.get()->getSourceRange();15379else if (resultType->hasIntegerRepresentation())15380break;15381else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {15382// OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate15383// on vector float types.15384QualType T = resultType->castAs<ExtVectorType>()->getElementType();15385if (!T->isIntegerType())15386return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15387<< resultType << Input.get()->getSourceRange());15388} else {15389return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15390<< resultType << Input.get()->getSourceRange());15391}15392break;1539315394case UO_LNot: // logical negation15395// Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).15396Input = DefaultFunctionArrayLvalueConversion(Input.get());15397if (Input.isInvalid())15398return ExprError();15399resultType = Input.get()->getType();1540015401// Though we still have to promote half FP to float...15402if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {15403Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)15404.get();15405resultType = Context.FloatTy;15406}1540715408// WebAsembly tables can't be used in unary expressions.15409if (resultType->isPointerType() &&15410resultType->getPointeeType().isWebAssemblyReferenceType()) {15411return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15412<< resultType << Input.get()->getSourceRange());15413}1541415415if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {15416// C99 6.5.3.3p1: ok, fallthrough;15417if (Context.getLangOpts().CPlusPlus) {15418// C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:15419// operand contextually converted to bool.15420Input = ImpCastExprToType(Input.get(), Context.BoolTy,15421ScalarTypeToBooleanCastKind(resultType));15422} else if (Context.getLangOpts().OpenCL &&15423Context.getLangOpts().OpenCLVersion < 120) {15424// OpenCL v1.1 6.3.h: The logical operator not (!) does not15425// operate on scalar float types.15426if (!resultType->isIntegerType() && !resultType->isPointerType())15427return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15428<< resultType << Input.get()->getSourceRange());15429}15430} else if (resultType->isExtVectorType()) {15431if (Context.getLangOpts().OpenCL &&15432Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {15433// OpenCL v1.1 6.3.h: The logical operator not (!) does not15434// operate on vector float types.15435QualType T = resultType->castAs<ExtVectorType>()->getElementType();15436if (!T->isIntegerType())15437return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15438<< resultType << Input.get()->getSourceRange());15439}15440// Vector logical not returns the signed variant of the operand type.15441resultType = GetSignedVectorType(resultType);15442break;15443} else if (Context.getLangOpts().CPlusPlus &&15444resultType->isVectorType()) {15445const VectorType *VTy = resultType->castAs<VectorType>();15446if (VTy->getVectorKind() != VectorKind::Generic)15447return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15448<< resultType << Input.get()->getSourceRange());1544915450// Vector logical not returns the signed variant of the operand type.15451resultType = GetSignedVectorType(resultType);15452break;15453} else {15454return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15455<< resultType << Input.get()->getSourceRange());15456}1545715458// LNot always has type int. C99 6.5.3.3p5.15459// In C++, it's bool. C++ 5.3.1p815460resultType = Context.getLogicalOperationType();15461break;15462case UO_Real:15463case UO_Imag:15464resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);15465// _Real maps ordinary l-values into ordinary l-values. _Imag maps15466// ordinary complex l-values to ordinary l-values and all other values to15467// r-values.15468if (Input.isInvalid())15469return ExprError();15470if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {15471if (Input.get()->isGLValue() &&15472Input.get()->getObjectKind() == OK_Ordinary)15473VK = Input.get()->getValueKind();15474} else if (!getLangOpts().CPlusPlus) {15475// In C, a volatile scalar is read by __imag. In C++, it is not.15476Input = DefaultLvalueConversion(Input.get());15477}15478break;15479case UO_Extension:15480resultType = Input.get()->getType();15481VK = Input.get()->getValueKind();15482OK = Input.get()->getObjectKind();15483break;15484case UO_Coawait:15485// It's unnecessary to represent the pass-through operator co_await in the15486// AST; just return the input expression instead.15487assert(!Input.get()->getType()->isDependentType() &&15488"the co_await expression must be non-dependant before "15489"building operator co_await");15490return Input;15491}15492}15493if (resultType.isNull() || Input.isInvalid())15494return ExprError();1549515496// Check for array bounds violations in the operand of the UnaryOperator,15497// except for the '*' and '&' operators that have to be handled specially15498// by CheckArrayAccess (as there are special cases like &array[arraysize]15499// that are explicitly defined as valid by the standard).15500if (Opc != UO_AddrOf && Opc != UO_Deref)15501CheckArrayAccess(Input.get());1550215503auto *UO =15504UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,15505OpLoc, CanOverflow, CurFPFeatureOverrides());1550615507if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&15508!isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&15509!isUnevaluatedContext())15510ExprEvalContexts.back().PossibleDerefs.insert(UO);1551115512// Convert the result back to a half vector.15513if (ConvertHalfVec)15514return convertVector(UO, Context.HalfTy, *this);15515return UO;15516}1551715518bool Sema::isQualifiedMemberAccess(Expr *E) {15519if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {15520if (!DRE->getQualifier())15521return false;1552215523ValueDecl *VD = DRE->getDecl();15524if (!VD->isCXXClassMember())15525return false;1552615527if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))15528return true;15529if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))15530return Method->isImplicitObjectMemberFunction();1553115532return false;15533}1553415535if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {15536if (!ULE->getQualifier())15537return false;1553815539for (NamedDecl *D : ULE->decls()) {15540if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {15541if (Method->isImplicitObjectMemberFunction())15542return true;15543} else {15544// Overload set does not contain methods.15545break;15546}15547}1554815549return false;15550}1555115552return false;15553}1555415555ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,15556UnaryOperatorKind Opc, Expr *Input,15557bool IsAfterAmp) {15558// First things first: handle placeholders so that the15559// overloaded-operator check considers the right type.15560if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {15561// Increment and decrement of pseudo-object references.15562if (pty->getKind() == BuiltinType::PseudoObject &&15563UnaryOperator::isIncrementDecrementOp(Opc))15564return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);1556515566// extension is always a builtin operator.15567if (Opc == UO_Extension)15568return CreateBuiltinUnaryOp(OpLoc, Opc, Input);1556915570// & gets special logic for several kinds of placeholder.15571// The builtin code knows what to do.15572if (Opc == UO_AddrOf &&15573(pty->getKind() == BuiltinType::Overload ||15574pty->getKind() == BuiltinType::UnknownAny ||15575pty->getKind() == BuiltinType::BoundMember))15576return CreateBuiltinUnaryOp(OpLoc, Opc, Input);1557715578// Anything else needs to be handled now.15579ExprResult Result = CheckPlaceholderExpr(Input);15580if (Result.isInvalid()) return ExprError();15581Input = Result.get();15582}1558315584if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&15585UnaryOperator::getOverloadedOperator(Opc) != OO_None &&15586!(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {15587// Find all of the overloaded operators visible from this point.15588UnresolvedSet<16> Functions;15589OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);15590if (S && OverOp != OO_None)15591LookupOverloadedOperatorName(OverOp, S, Functions);1559215593return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);15594}1559515596return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);15597}1559815599ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,15600Expr *Input, bool IsAfterAmp) {15601return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,15602IsAfterAmp);15603}1560415605ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,15606LabelDecl *TheDecl) {15607TheDecl->markUsed(Context);15608// Create the AST node. The address of a label always has type 'void*'.15609auto *Res = new (Context) AddrLabelExpr(15610OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));1561115612if (getCurFunction())15613getCurFunction()->AddrLabels.push_back(Res);1561415615return Res;15616}1561715618void Sema::ActOnStartStmtExpr() {15619PushExpressionEvaluationContext(ExprEvalContexts.back().Context);15620// Make sure we diagnose jumping into a statement expression.15621setFunctionHasBranchProtectedScope();15622}1562315624void Sema::ActOnStmtExprError() {15625// Note that function is also called by TreeTransform when leaving a15626// StmtExpr scope without rebuilding anything.1562715628DiscardCleanupsInEvaluationContext();15629PopExpressionEvaluationContext();15630}1563115632ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,15633SourceLocation RPLoc) {15634return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));15635}1563615637ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,15638SourceLocation RPLoc, unsigned TemplateDepth) {15639assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");15640CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);1564115642if (hasAnyUnrecoverableErrorsInThisFunction())15643DiscardCleanupsInEvaluationContext();15644assert(!Cleanup.exprNeedsCleanups() &&15645"cleanups within StmtExpr not correctly bound!");15646PopExpressionEvaluationContext();1564715648// FIXME: there are a variety of strange constraints to enforce here, for15649// example, it is not possible to goto into a stmt expression apparently.15650// More semantic analysis is needed.1565115652// If there are sub-stmts in the compound stmt, take the type of the last one15653// as the type of the stmtexpr.15654QualType Ty = Context.VoidTy;15655bool StmtExprMayBindToTemp = false;15656if (!Compound->body_empty()) {15657// For GCC compatibility we get the last Stmt excluding trailing NullStmts.15658if (const auto *LastStmt =15659dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {15660if (const Expr *Value = LastStmt->getExprStmt()) {15661StmtExprMayBindToTemp = true;15662Ty = Value->getType();15663}15664}15665}1566615667// FIXME: Check that expression type is complete/non-abstract; statement15668// expressions are not lvalues.15669Expr *ResStmtExpr =15670new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);15671if (StmtExprMayBindToTemp)15672return MaybeBindToTemporary(ResStmtExpr);15673return ResStmtExpr;15674}1567515676ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {15677if (ER.isInvalid())15678return ExprError();1567915680// Do function/array conversion on the last expression, but not15681// lvalue-to-rvalue. However, initialize an unqualified type.15682ER = DefaultFunctionArrayConversion(ER.get());15683if (ER.isInvalid())15684return ExprError();15685Expr *E = ER.get();1568615687if (E->isTypeDependent())15688return E;1568915690// In ARC, if the final expression ends in a consume, splice15691// the consume out and bind it later. In the alternate case15692// (when dealing with a retainable type), the result15693// initialization will create a produce. In both cases the15694// result will be +1, and we'll need to balance that out with15695// a bind.15696auto *Cast = dyn_cast<ImplicitCastExpr>(E);15697if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)15698return Cast->getSubExpr();1569915700// FIXME: Provide a better location for the initialization.15701return PerformCopyInitialization(15702InitializedEntity::InitializeStmtExprResult(15703E->getBeginLoc(), E->getType().getUnqualifiedType()),15704SourceLocation(), E);15705}1570615707ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,15708TypeSourceInfo *TInfo,15709ArrayRef<OffsetOfComponent> Components,15710SourceLocation RParenLoc) {15711QualType ArgTy = TInfo->getType();15712bool Dependent = ArgTy->isDependentType();15713SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();1571415715// We must have at least one component that refers to the type, and the first15716// one is known to be a field designator. Verify that the ArgTy represents15717// a struct/union/class.15718if (!Dependent && !ArgTy->isRecordType())15719return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)15720<< ArgTy << TypeRange);1572115722// Type must be complete per C99 7.17p3 because a declaring a variable15723// with an incomplete type would be ill-formed.15724if (!Dependent15725&& RequireCompleteType(BuiltinLoc, ArgTy,15726diag::err_offsetof_incomplete_type, TypeRange))15727return ExprError();1572815729bool DidWarnAboutNonPOD = false;15730QualType CurrentType = ArgTy;15731SmallVector<OffsetOfNode, 4> Comps;15732SmallVector<Expr*, 4> Exprs;15733for (const OffsetOfComponent &OC : Components) {15734if (OC.isBrackets) {15735// Offset of an array sub-field. TODO: Should we allow vector elements?15736if (!CurrentType->isDependentType()) {15737const ArrayType *AT = Context.getAsArrayType(CurrentType);15738if(!AT)15739return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)15740<< CurrentType);15741CurrentType = AT->getElementType();15742} else15743CurrentType = Context.DependentTy;1574415745ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));15746if (IdxRval.isInvalid())15747return ExprError();15748Expr *Idx = IdxRval.get();1574915750// The expression must be an integral expression.15751// FIXME: An integral constant expression?15752if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&15753!Idx->getType()->isIntegerType())15754return ExprError(15755Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)15756<< Idx->getSourceRange());1575715758// Record this array index.15759Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));15760Exprs.push_back(Idx);15761continue;15762}1576315764// Offset of a field.15765if (CurrentType->isDependentType()) {15766// We have the offset of a field, but we can't look into the dependent15767// type. Just record the identifier of the field.15768Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));15769CurrentType = Context.DependentTy;15770continue;15771}1577215773// We need to have a complete type to look into.15774if (RequireCompleteType(OC.LocStart, CurrentType,15775diag::err_offsetof_incomplete_type))15776return ExprError();1577715778// Look for the designated field.15779const RecordType *RC = CurrentType->getAs<RecordType>();15780if (!RC)15781return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)15782<< CurrentType);15783RecordDecl *RD = RC->getDecl();1578415785// C++ [lib.support.types]p5:15786// The macro offsetof accepts a restricted set of type arguments in this15787// International Standard. type shall be a POD structure or a POD union15788// (clause 9).15789// C++11 [support.types]p4:15790// If type is not a standard-layout class (Clause 9), the results are15791// undefined.15792if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {15793bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();15794unsigned DiagID =15795LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type15796: diag::ext_offsetof_non_pod_type;1579715798if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {15799Diag(BuiltinLoc, DiagID)15800<< SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;15801DidWarnAboutNonPOD = true;15802}15803}1580415805// Look for the field.15806LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);15807LookupQualifiedName(R, RD);15808FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();15809IndirectFieldDecl *IndirectMemberDecl = nullptr;15810if (!MemberDecl) {15811if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))15812MemberDecl = IndirectMemberDecl->getAnonField();15813}1581415815if (!MemberDecl) {15816// Lookup could be ambiguous when looking up a placeholder variable15817// __builtin_offsetof(S, _).15818// In that case we would already have emitted a diagnostic15819if (!R.isAmbiguous())15820Diag(BuiltinLoc, diag::err_no_member)15821<< OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);15822return ExprError();15823}1582415825// C99 7.17p3:15826// (If the specified member is a bit-field, the behavior is undefined.)15827//15828// We diagnose this as an error.15829if (MemberDecl->isBitField()) {15830Diag(OC.LocEnd, diag::err_offsetof_bitfield)15831<< MemberDecl->getDeclName()15832<< SourceRange(BuiltinLoc, RParenLoc);15833Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);15834return ExprError();15835}1583615837RecordDecl *Parent = MemberDecl->getParent();15838if (IndirectMemberDecl)15839Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());1584015841// If the member was found in a base class, introduce OffsetOfNodes for15842// the base class indirections.15843CXXBasePaths Paths;15844if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),15845Paths)) {15846if (Paths.getDetectedVirtual()) {15847Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)15848<< MemberDecl->getDeclName()15849<< SourceRange(BuiltinLoc, RParenLoc);15850return ExprError();15851}1585215853CXXBasePath &Path = Paths.front();15854for (const CXXBasePathElement &B : Path)15855Comps.push_back(OffsetOfNode(B.Base));15856}1585715858if (IndirectMemberDecl) {15859for (auto *FI : IndirectMemberDecl->chain()) {15860assert(isa<FieldDecl>(FI));15861Comps.push_back(OffsetOfNode(OC.LocStart,15862cast<FieldDecl>(FI), OC.LocEnd));15863}15864} else15865Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));1586615867CurrentType = MemberDecl->getType().getNonReferenceType();15868}1586915870return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,15871Comps, Exprs, RParenLoc);15872}1587315874ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,15875SourceLocation BuiltinLoc,15876SourceLocation TypeLoc,15877ParsedType ParsedArgTy,15878ArrayRef<OffsetOfComponent> Components,15879SourceLocation RParenLoc) {1588015881TypeSourceInfo *ArgTInfo;15882QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);15883if (ArgTy.isNull())15884return ExprError();1588515886if (!ArgTInfo)15887ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);1588815889return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);15890}158911589215893ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,15894Expr *CondExpr,15895Expr *LHSExpr, Expr *RHSExpr,15896SourceLocation RPLoc) {15897assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");1589815899ExprValueKind VK = VK_PRValue;15900ExprObjectKind OK = OK_Ordinary;15901QualType resType;15902bool CondIsTrue = false;15903if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {15904resType = Context.DependentTy;15905} else {15906// The conditional expression is required to be a constant expression.15907llvm::APSInt condEval(32);15908ExprResult CondICE = VerifyIntegerConstantExpression(15909CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);15910if (CondICE.isInvalid())15911return ExprError();15912CondExpr = CondICE.get();15913CondIsTrue = condEval.getZExtValue();1591415915// If the condition is > zero, then the AST type is the same as the LHSExpr.15916Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;1591715918resType = ActiveExpr->getType();15919VK = ActiveExpr->getValueKind();15920OK = ActiveExpr->getObjectKind();15921}1592215923return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,15924resType, VK, OK, RPLoc, CondIsTrue);15925}1592615927//===----------------------------------------------------------------------===//15928// Clang Extensions.15929//===----------------------------------------------------------------------===//1593015931void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {15932BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);1593315934if (LangOpts.CPlusPlus) {15935MangleNumberingContext *MCtx;15936Decl *ManglingContextDecl;15937std::tie(MCtx, ManglingContextDecl) =15938getCurrentMangleNumberContext(Block->getDeclContext());15939if (MCtx) {15940unsigned ManglingNumber = MCtx->getManglingNumber(Block);15941Block->setBlockMangling(ManglingNumber, ManglingContextDecl);15942}15943}1594415945PushBlockScope(CurScope, Block);15946CurContext->addDecl(Block);15947if (CurScope)15948PushDeclContext(CurScope, Block);15949else15950CurContext = Block;1595115952getCurBlock()->HasImplicitReturnType = true;1595315954// Enter a new evaluation context to insulate the block from any15955// cleanups from the enclosing full-expression.15956PushExpressionEvaluationContext(15957ExpressionEvaluationContext::PotentiallyEvaluated);15958}1595915960void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,15961Scope *CurScope) {15962assert(ParamInfo.getIdentifier() == nullptr &&15963"block-id should have no identifier!");15964assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);15965BlockScopeInfo *CurBlock = getCurBlock();1596615967TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);15968QualType T = Sig->getType();1596915970// FIXME: We should allow unexpanded parameter packs here, but that would,15971// in turn, make the block expression contain unexpanded parameter packs.15972if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {15973// Drop the parameters.15974FunctionProtoType::ExtProtoInfo EPI;15975EPI.HasTrailingReturn = false;15976EPI.TypeQuals.addConst();15977T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);15978Sig = Context.getTrivialTypeSourceInfo(T);15979}1598015981// GetTypeForDeclarator always produces a function type for a block15982// literal signature. Furthermore, it is always a FunctionProtoType15983// unless the function was written with a typedef.15984assert(T->isFunctionType() &&15985"GetTypeForDeclarator made a non-function block signature");1598615987// Look for an explicit signature in that function type.15988FunctionProtoTypeLoc ExplicitSignature;1598915990if ((ExplicitSignature = Sig->getTypeLoc()15991.getAsAdjusted<FunctionProtoTypeLoc>())) {1599215993// Check whether that explicit signature was synthesized by15994// GetTypeForDeclarator. If so, don't save that as part of the15995// written signature.15996if (ExplicitSignature.getLocalRangeBegin() ==15997ExplicitSignature.getLocalRangeEnd()) {15998// This would be much cheaper if we stored TypeLocs instead of15999// TypeSourceInfos.16000TypeLoc Result = ExplicitSignature.getReturnLoc();16001unsigned Size = Result.getFullDataSize();16002Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);16003Sig->getTypeLoc().initializeFullCopy(Result, Size);1600416005ExplicitSignature = FunctionProtoTypeLoc();16006}16007}1600816009CurBlock->TheDecl->setSignatureAsWritten(Sig);16010CurBlock->FunctionType = T;1601116012const auto *Fn = T->castAs<FunctionType>();16013QualType RetTy = Fn->getReturnType();16014bool isVariadic =16015(isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());1601616017CurBlock->TheDecl->setIsVariadic(isVariadic);1601816019// Context.DependentTy is used as a placeholder for a missing block16020// return type. TODO: what should we do with declarators like:16021// ^ * { ... }16022// If the answer is "apply template argument deduction"....16023if (RetTy != Context.DependentTy) {16024CurBlock->ReturnType = RetTy;16025CurBlock->TheDecl->setBlockMissingReturnType(false);16026CurBlock->HasImplicitReturnType = false;16027}1602816029// Push block parameters from the declarator if we had them.16030SmallVector<ParmVarDecl*, 8> Params;16031if (ExplicitSignature) {16032for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {16033ParmVarDecl *Param = ExplicitSignature.getParam(I);16034if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&16035!Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {16036// Diagnose this as an extension in C17 and earlier.16037if (!getLangOpts().C23)16038Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);16039}16040Params.push_back(Param);16041}1604216043// Fake up parameter variables if we have a typedef, like16044// ^ fntype { ... }16045} else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {16046for (const auto &I : Fn->param_types()) {16047ParmVarDecl *Param = BuildParmVarDeclForTypedef(16048CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);16049Params.push_back(Param);16050}16051}1605216053// Set the parameters on the block decl.16054if (!Params.empty()) {16055CurBlock->TheDecl->setParams(Params);16056CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),16057/*CheckParameterNames=*/false);16058}1605916060// Finally we can process decl attributes.16061ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);1606216063// Put the parameter variables in scope.16064for (auto *AI : CurBlock->TheDecl->parameters()) {16065AI->setOwningFunction(CurBlock->TheDecl);1606616067// If this has an identifier, add it to the scope stack.16068if (AI->getIdentifier()) {16069CheckShadow(CurBlock->TheScope, AI);1607016071PushOnScopeChains(AI, CurBlock->TheScope);16072}1607316074if (AI->isInvalidDecl())16075CurBlock->TheDecl->setInvalidDecl();16076}16077}1607816079void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {16080// Leave the expression-evaluation context.16081DiscardCleanupsInEvaluationContext();16082PopExpressionEvaluationContext();1608316084// Pop off CurBlock, handle nested blocks.16085PopDeclContext();16086PopFunctionScopeInfo();16087}1608816089ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,16090Stmt *Body, Scope *CurScope) {16091// If blocks are disabled, emit an error.16092if (!LangOpts.Blocks)16093Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;1609416095// Leave the expression-evaluation context.16096if (hasAnyUnrecoverableErrorsInThisFunction())16097DiscardCleanupsInEvaluationContext();16098assert(!Cleanup.exprNeedsCleanups() &&16099"cleanups within block not correctly bound!");16100PopExpressionEvaluationContext();1610116102BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());16103BlockDecl *BD = BSI->TheDecl;1610416105if (BSI->HasImplicitReturnType)16106deduceClosureReturnType(*BSI);1610716108QualType RetTy = Context.VoidTy;16109if (!BSI->ReturnType.isNull())16110RetTy = BSI->ReturnType;1611116112bool NoReturn = BD->hasAttr<NoReturnAttr>();16113QualType BlockTy;1611416115// If the user wrote a function type in some form, try to use that.16116if (!BSI->FunctionType.isNull()) {16117const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();1611816119FunctionType::ExtInfo Ext = FTy->getExtInfo();16120if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);1612116122// Turn protoless block types into nullary block types.16123if (isa<FunctionNoProtoType>(FTy)) {16124FunctionProtoType::ExtProtoInfo EPI;16125EPI.ExtInfo = Ext;16126BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);1612716128// Otherwise, if we don't need to change anything about the function type,16129// preserve its sugar structure.16130} else if (FTy->getReturnType() == RetTy &&16131(!NoReturn || FTy->getNoReturnAttr())) {16132BlockTy = BSI->FunctionType;1613316134// Otherwise, make the minimal modifications to the function type.16135} else {16136const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);16137FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();16138EPI.TypeQuals = Qualifiers();16139EPI.ExtInfo = Ext;16140BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);16141}1614216143// If we don't have a function type, just build one from nothing.16144} else {16145FunctionProtoType::ExtProtoInfo EPI;16146EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);16147BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);16148}1614916150DiagnoseUnusedParameters(BD->parameters());16151BlockTy = Context.getBlockPointerType(BlockTy);1615216153// If needed, diagnose invalid gotos and switches in the block.16154if (getCurFunction()->NeedsScopeChecking() &&16155!PP.isCodeCompletionEnabled())16156DiagnoseInvalidJumps(cast<CompoundStmt>(Body));1615716158BD->setBody(cast<CompoundStmt>(Body));1615916160if (Body && getCurFunction()->HasPotentialAvailabilityViolations)16161DiagnoseUnguardedAvailabilityViolations(BD);1616216163// Try to apply the named return value optimization. We have to check again16164// if we can do this, though, because blocks keep return statements around16165// to deduce an implicit return type.16166if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&16167!BD->isDependentContext())16168computeNRVO(Body, BSI);1616916170if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||16171RetTy.hasNonTrivialToPrimitiveCopyCUnion())16172checkNonTrivialCUnion(RetTy, BD->getCaretLocation(), NTCUC_FunctionReturn,16173NTCUK_Destruct|NTCUK_Copy);1617416175PopDeclContext();1617616177// Set the captured variables on the block.16178SmallVector<BlockDecl::Capture, 4> Captures;16179for (Capture &Cap : BSI->Captures) {16180if (Cap.isInvalid() || Cap.isThisCapture())16181continue;16182// Cap.getVariable() is always a VarDecl because16183// blocks cannot capture structured bindings or other ValueDecl kinds.16184auto *Var = cast<VarDecl>(Cap.getVariable());16185Expr *CopyExpr = nullptr;16186if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {16187if (const RecordType *Record =16188Cap.getCaptureType()->getAs<RecordType>()) {16189// The capture logic needs the destructor, so make sure we mark it.16190// Usually this is unnecessary because most local variables have16191// their destructors marked at declaration time, but parameters are16192// an exception because it's technically only the call site that16193// actually requires the destructor.16194if (isa<ParmVarDecl>(Var))16195FinalizeVarWithDestructor(Var, Record);1619616197// Enter a separate potentially-evaluated context while building block16198// initializers to isolate their cleanups from those of the block16199// itself.16200// FIXME: Is this appropriate even when the block itself occurs in an16201// unevaluated operand?16202EnterExpressionEvaluationContext EvalContext(16203*this, ExpressionEvaluationContext::PotentiallyEvaluated);1620416205SourceLocation Loc = Cap.getLocation();1620616207ExprResult Result = BuildDeclarationNameExpr(16208CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);1620916210// According to the blocks spec, the capture of a variable from16211// the stack requires a const copy constructor. This is not true16212// of the copy/move done to move a __block variable to the heap.16213if (!Result.isInvalid() &&16214!Result.get()->getType().isConstQualified()) {16215Result = ImpCastExprToType(Result.get(),16216Result.get()->getType().withConst(),16217CK_NoOp, VK_LValue);16218}1621916220if (!Result.isInvalid()) {16221Result = PerformCopyInitialization(16222InitializedEntity::InitializeBlock(Var->getLocation(),16223Cap.getCaptureType()),16224Loc, Result.get());16225}1622616227// Build a full-expression copy expression if initialization16228// succeeded and used a non-trivial constructor. Recover from16229// errors by pretending that the copy isn't necessary.16230if (!Result.isInvalid() &&16231!cast<CXXConstructExpr>(Result.get())->getConstructor()16232->isTrivial()) {16233Result = MaybeCreateExprWithCleanups(Result);16234CopyExpr = Result.get();16235}16236}16237}1623816239BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),16240CopyExpr);16241Captures.push_back(NewCap);16242}16243BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);1624416245// Pop the block scope now but keep it alive to the end of this function.16246AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();16247PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);1624816249BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);1625016251// If the block isn't obviously global, i.e. it captures anything at16252// all, then we need to do a few things in the surrounding context:16253if (Result->getBlockDecl()->hasCaptures()) {16254// First, this expression has a new cleanup object.16255ExprCleanupObjects.push_back(Result->getBlockDecl());16256Cleanup.setExprNeedsCleanups(true);1625716258// It also gets a branch-protected scope if any of the captured16259// variables needs destruction.16260for (const auto &CI : Result->getBlockDecl()->captures()) {16261const VarDecl *var = CI.getVariable();16262if (var->getType().isDestructedType() != QualType::DK_none) {16263setFunctionHasBranchProtectedScope();16264break;16265}16266}16267}1626816269if (getCurFunction())16270getCurFunction()->addBlock(BD);1627116272if (BD->isInvalidDecl())16273return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),16274{Result}, Result->getType());16275return Result;16276}1627716278ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,16279SourceLocation RPLoc) {16280TypeSourceInfo *TInfo;16281GetTypeFromParser(Ty, &TInfo);16282return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);16283}1628416285ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,16286Expr *E, TypeSourceInfo *TInfo,16287SourceLocation RPLoc) {16288Expr *OrigExpr = E;16289bool IsMS = false;1629016291// CUDA device code does not support varargs.16292if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {16293if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {16294CUDAFunctionTarget T = CUDA().IdentifyTarget(F);16295if (T == CUDAFunctionTarget::Global || T == CUDAFunctionTarget::Device ||16296T == CUDAFunctionTarget::HostDevice)16297return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));16298}16299}1630016301// NVPTX does not support va_arg expression.16302if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&16303Context.getTargetInfo().getTriple().isNVPTX())16304targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);1630516306// It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()16307// as Microsoft ABI on an actual Microsoft platform, where16308// __builtin_ms_va_list and __builtin_va_list are the same.)16309if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&16310Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {16311QualType MSVaListType = Context.getBuiltinMSVaListType();16312if (Context.hasSameType(MSVaListType, E->getType())) {16313if (CheckForModifiableLvalue(E, BuiltinLoc, *this))16314return ExprError();16315IsMS = true;16316}16317}1631816319// Get the va_list type16320QualType VaListType = Context.getBuiltinVaListType();16321if (!IsMS) {16322if (VaListType->isArrayType()) {16323// Deal with implicit array decay; for example, on x86-64,16324// va_list is an array, but it's supposed to decay to16325// a pointer for va_arg.16326VaListType = Context.getArrayDecayedType(VaListType);16327// Make sure the input expression also decays appropriately.16328ExprResult Result = UsualUnaryConversions(E);16329if (Result.isInvalid())16330return ExprError();16331E = Result.get();16332} else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {16333// If va_list is a record type and we are compiling in C++ mode,16334// check the argument using reference binding.16335InitializedEntity Entity = InitializedEntity::InitializeParameter(16336Context, Context.getLValueReferenceType(VaListType), false);16337ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);16338if (Init.isInvalid())16339return ExprError();16340E = Init.getAs<Expr>();16341} else {16342// Otherwise, the va_list argument must be an l-value because16343// it is modified by va_arg.16344if (!E->isTypeDependent() &&16345CheckForModifiableLvalue(E, BuiltinLoc, *this))16346return ExprError();16347}16348}1634916350if (!IsMS && !E->isTypeDependent() &&16351!Context.hasSameType(VaListType, E->getType()))16352return ExprError(16353Diag(E->getBeginLoc(),16354diag::err_first_argument_to_va_arg_not_of_type_va_list)16355<< OrigExpr->getType() << E->getSourceRange());1635616357if (!TInfo->getType()->isDependentType()) {16358if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),16359diag::err_second_parameter_to_va_arg_incomplete,16360TInfo->getTypeLoc()))16361return ExprError();1636216363if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),16364TInfo->getType(),16365diag::err_second_parameter_to_va_arg_abstract,16366TInfo->getTypeLoc()))16367return ExprError();1636816369if (!TInfo->getType().isPODType(Context)) {16370Diag(TInfo->getTypeLoc().getBeginLoc(),16371TInfo->getType()->isObjCLifetimeType()16372? diag::warn_second_parameter_to_va_arg_ownership_qualified16373: diag::warn_second_parameter_to_va_arg_not_pod)16374<< TInfo->getType()16375<< TInfo->getTypeLoc().getSourceRange();16376}1637716378// Check for va_arg where arguments of the given type will be promoted16379// (i.e. this va_arg is guaranteed to have undefined behavior).16380QualType PromoteType;16381if (Context.isPromotableIntegerType(TInfo->getType())) {16382PromoteType = Context.getPromotedIntegerType(TInfo->getType());16383// [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,16384// and C23 7.16.1.1p2 says, in part:16385// If type is not compatible with the type of the actual next argument16386// (as promoted according to the default argument promotions), the16387// behavior is undefined, except for the following cases:16388// - both types are pointers to qualified or unqualified versions of16389// compatible types;16390// - one type is compatible with a signed integer type, the other16391// type is compatible with the corresponding unsigned integer type,16392// and the value is representable in both types;16393// - one type is pointer to qualified or unqualified void and the16394// other is a pointer to a qualified or unqualified character type;16395// - or, the type of the next argument is nullptr_t and type is a16396// pointer type that has the same representation and alignment16397// requirements as a pointer to a character type.16398// Given that type compatibility is the primary requirement (ignoring16399// qualifications), you would think we could call typesAreCompatible()16400// directly to test this. However, in C++, that checks for *same type*,16401// which causes false positives when passing an enumeration type to16402// va_arg. Instead, get the underlying type of the enumeration and pass16403// that.16404QualType UnderlyingType = TInfo->getType();16405if (const auto *ET = UnderlyingType->getAs<EnumType>())16406UnderlyingType = ET->getDecl()->getIntegerType();16407if (Context.typesAreCompatible(PromoteType, UnderlyingType,16408/*CompareUnqualified*/ true))16409PromoteType = QualType();1641016411// If the types are still not compatible, we need to test whether the16412// promoted type and the underlying type are the same except for16413// signedness. Ask the AST for the correctly corresponding type and see16414// if that's compatible.16415if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&16416PromoteType->isUnsignedIntegerType() !=16417UnderlyingType->isUnsignedIntegerType()) {16418UnderlyingType =16419UnderlyingType->isUnsignedIntegerType()16420? Context.getCorrespondingSignedType(UnderlyingType)16421: Context.getCorrespondingUnsignedType(UnderlyingType);16422if (Context.typesAreCompatible(PromoteType, UnderlyingType,16423/*CompareUnqualified*/ true))16424PromoteType = QualType();16425}16426}16427if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))16428PromoteType = Context.DoubleTy;16429if (!PromoteType.isNull())16430DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,16431PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)16432<< TInfo->getType()16433<< PromoteType16434<< TInfo->getTypeLoc().getSourceRange());16435}1643616437QualType T = TInfo->getType().getNonLValueExprType(Context);16438return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);16439}1644016441ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {16442// The type of __null will be int or long, depending on the size of16443// pointers on the target.16444QualType Ty;16445unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);16446if (pw == Context.getTargetInfo().getIntWidth())16447Ty = Context.IntTy;16448else if (pw == Context.getTargetInfo().getLongWidth())16449Ty = Context.LongTy;16450else if (pw == Context.getTargetInfo().getLongLongWidth())16451Ty = Context.LongLongTy;16452else {16453llvm_unreachable("I don't know size of pointer!");16454}1645516456return new (Context) GNUNullExpr(Ty, TokenLoc);16457}1645816459static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {16460CXXRecordDecl *ImplDecl = nullptr;1646116462// Fetch the std::source_location::__impl decl.16463if (NamespaceDecl *Std = S.getStdNamespace()) {16464LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),16465Loc, Sema::LookupOrdinaryName);16466if (S.LookupQualifiedName(ResultSL, Std)) {16467if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {16468LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),16469Loc, Sema::LookupOrdinaryName);16470if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&16471S.LookupQualifiedName(ResultImpl, SLDecl)) {16472ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();16473}16474}16475}16476}1647716478if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {16479S.Diag(Loc, diag::err_std_source_location_impl_not_found);16480return nullptr;16481}1648216483// Verify that __impl is a trivial struct type, with no base classes, and with16484// only the four expected fields.16485if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||16486ImplDecl->getNumBases() != 0) {16487S.Diag(Loc, diag::err_std_source_location_impl_malformed);16488return nullptr;16489}1649016491unsigned Count = 0;16492for (FieldDecl *F : ImplDecl->fields()) {16493StringRef Name = F->getName();1649416495if (Name == "_M_file_name") {16496if (F->getType() !=16497S.Context.getPointerType(S.Context.CharTy.withConst()))16498break;16499Count++;16500} else if (Name == "_M_function_name") {16501if (F->getType() !=16502S.Context.getPointerType(S.Context.CharTy.withConst()))16503break;16504Count++;16505} else if (Name == "_M_line") {16506if (!F->getType()->isIntegerType())16507break;16508Count++;16509} else if (Name == "_M_column") {16510if (!F->getType()->isIntegerType())16511break;16512Count++;16513} else {16514Count = 100; // invalid16515break;16516}16517}16518if (Count != 4) {16519S.Diag(Loc, diag::err_std_source_location_impl_malformed);16520return nullptr;16521}1652216523return ImplDecl;16524}1652516526ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,16527SourceLocation BuiltinLoc,16528SourceLocation RPLoc) {16529QualType ResultTy;16530switch (Kind) {16531case SourceLocIdentKind::File:16532case SourceLocIdentKind::FileName:16533case SourceLocIdentKind::Function:16534case SourceLocIdentKind::FuncSig: {16535QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);16536ResultTy =16537Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());16538break;16539}16540case SourceLocIdentKind::Line:16541case SourceLocIdentKind::Column:16542ResultTy = Context.UnsignedIntTy;16543break;16544case SourceLocIdentKind::SourceLocStruct:16545if (!StdSourceLocationImplDecl) {16546StdSourceLocationImplDecl =16547LookupStdSourceLocationImpl(*this, BuiltinLoc);16548if (!StdSourceLocationImplDecl)16549return ExprError();16550}16551ResultTy = Context.getPointerType(16552Context.getRecordType(StdSourceLocationImplDecl).withConst());16553break;16554}1655516556return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);16557}1655816559ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,16560SourceLocation BuiltinLoc,16561SourceLocation RPLoc,16562DeclContext *ParentContext) {16563return new (Context)16564SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);16565}1656616567ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,16568StringLiteral *BinaryData) {16569EmbedDataStorage *Data = new (Context) EmbedDataStorage;16570Data->BinaryData = BinaryData;16571return new (Context)16572EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,16573Data->getDataElementCount());16574}1657516576static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,16577const Expr *SrcExpr) {16578if (!DstType->isFunctionPointerType() ||16579!SrcExpr->getType()->isFunctionType())16580return false;1658116582auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());16583if (!DRE)16584return false;1658516586auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());16587if (!FD)16588return false;1658916590return !S.checkAddressOfFunctionIsAvailable(FD,16591/*Complain=*/true,16592SrcExpr->getBeginLoc());16593}1659416595bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,16596SourceLocation Loc,16597QualType DstType, QualType SrcType,16598Expr *SrcExpr, AssignmentAction Action,16599bool *Complained) {16600if (Complained)16601*Complained = false;1660216603// Decode the result (notice that AST's are still created for extensions).16604bool CheckInferredResultType = false;16605bool isInvalid = false;16606unsigned DiagKind = 0;16607ConversionFixItGenerator ConvHints;16608bool MayHaveConvFixit = false;16609bool MayHaveFunctionDiff = false;16610const ObjCInterfaceDecl *IFace = nullptr;16611const ObjCProtocolDecl *PDecl = nullptr;1661216613switch (ConvTy) {16614case Compatible:16615DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);16616return false;1661716618case PointerToInt:16619if (getLangOpts().CPlusPlus) {16620DiagKind = diag::err_typecheck_convert_pointer_int;16621isInvalid = true;16622} else {16623DiagKind = diag::ext_typecheck_convert_pointer_int;16624}16625ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);16626MayHaveConvFixit = true;16627break;16628case IntToPointer:16629if (getLangOpts().CPlusPlus) {16630DiagKind = diag::err_typecheck_convert_int_pointer;16631isInvalid = true;16632} else {16633DiagKind = diag::ext_typecheck_convert_int_pointer;16634}16635ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);16636MayHaveConvFixit = true;16637break;16638case IncompatibleFunctionPointerStrict:16639DiagKind =16640diag::warn_typecheck_convert_incompatible_function_pointer_strict;16641ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);16642MayHaveConvFixit = true;16643break;16644case IncompatibleFunctionPointer:16645if (getLangOpts().CPlusPlus) {16646DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;16647isInvalid = true;16648} else {16649DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;16650}16651ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);16652MayHaveConvFixit = true;16653break;16654case IncompatiblePointer:16655if (Action == AA_Passing_CFAudited) {16656DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;16657} else if (getLangOpts().CPlusPlus) {16658DiagKind = diag::err_typecheck_convert_incompatible_pointer;16659isInvalid = true;16660} else {16661DiagKind = diag::ext_typecheck_convert_incompatible_pointer;16662}16663CheckInferredResultType = DstType->isObjCObjectPointerType() &&16664SrcType->isObjCObjectPointerType();16665if (CheckInferredResultType) {16666SrcType = SrcType.getUnqualifiedType();16667DstType = DstType.getUnqualifiedType();16668} else {16669ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);16670}16671MayHaveConvFixit = true;16672break;16673case IncompatiblePointerSign:16674if (getLangOpts().CPlusPlus) {16675DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;16676isInvalid = true;16677} else {16678DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;16679}16680break;16681case FunctionVoidPointer:16682if (getLangOpts().CPlusPlus) {16683DiagKind = diag::err_typecheck_convert_pointer_void_func;16684isInvalid = true;16685} else {16686DiagKind = diag::ext_typecheck_convert_pointer_void_func;16687}16688break;16689case IncompatiblePointerDiscardsQualifiers: {16690// Perform array-to-pointer decay if necessary.16691if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);1669216693isInvalid = true;1669416695Qualifiers lhq = SrcType->getPointeeType().getQualifiers();16696Qualifiers rhq = DstType->getPointeeType().getQualifiers();16697if (lhq.getAddressSpace() != rhq.getAddressSpace()) {16698DiagKind = diag::err_typecheck_incompatible_address_space;16699break;16700} else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {16701DiagKind = diag::err_typecheck_incompatible_ownership;16702break;16703}1670416705llvm_unreachable("unknown error case for discarding qualifiers!");16706// fallthrough16707}16708case CompatiblePointerDiscardsQualifiers:16709// If the qualifiers lost were because we were applying the16710// (deprecated) C++ conversion from a string literal to a char*16711// (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:16712// Ideally, this check would be performed in16713// checkPointerTypesForAssignment. However, that would require a16714// bit of refactoring (so that the second argument is an16715// expression, rather than a type), which should be done as part16716// of a larger effort to fix checkPointerTypesForAssignment for16717// C++ semantics.16718if (getLangOpts().CPlusPlus &&16719IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))16720return false;16721if (getLangOpts().CPlusPlus) {16722DiagKind = diag::err_typecheck_convert_discards_qualifiers;16723isInvalid = true;16724} else {16725DiagKind = diag::ext_typecheck_convert_discards_qualifiers;16726}1672716728break;16729case IncompatibleNestedPointerQualifiers:16730if (getLangOpts().CPlusPlus) {16731isInvalid = true;16732DiagKind = diag::err_nested_pointer_qualifier_mismatch;16733} else {16734DiagKind = diag::ext_nested_pointer_qualifier_mismatch;16735}16736break;16737case IncompatibleNestedPointerAddressSpaceMismatch:16738DiagKind = diag::err_typecheck_incompatible_nested_address_space;16739isInvalid = true;16740break;16741case IntToBlockPointer:16742DiagKind = diag::err_int_to_block_pointer;16743isInvalid = true;16744break;16745case IncompatibleBlockPointer:16746DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;16747isInvalid = true;16748break;16749case IncompatibleObjCQualifiedId: {16750if (SrcType->isObjCQualifiedIdType()) {16751const ObjCObjectPointerType *srcOPT =16752SrcType->castAs<ObjCObjectPointerType>();16753for (auto *srcProto : srcOPT->quals()) {16754PDecl = srcProto;16755break;16756}16757if (const ObjCInterfaceType *IFaceT =16758DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())16759IFace = IFaceT->getDecl();16760}16761else if (DstType->isObjCQualifiedIdType()) {16762const ObjCObjectPointerType *dstOPT =16763DstType->castAs<ObjCObjectPointerType>();16764for (auto *dstProto : dstOPT->quals()) {16765PDecl = dstProto;16766break;16767}16768if (const ObjCInterfaceType *IFaceT =16769SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())16770IFace = IFaceT->getDecl();16771}16772if (getLangOpts().CPlusPlus) {16773DiagKind = diag::err_incompatible_qualified_id;16774isInvalid = true;16775} else {16776DiagKind = diag::warn_incompatible_qualified_id;16777}16778break;16779}16780case IncompatibleVectors:16781if (getLangOpts().CPlusPlus) {16782DiagKind = diag::err_incompatible_vectors;16783isInvalid = true;16784} else {16785DiagKind = diag::warn_incompatible_vectors;16786}16787break;16788case IncompatibleObjCWeakRef:16789DiagKind = diag::err_arc_weak_unavailable_assign;16790isInvalid = true;16791break;16792case Incompatible:16793if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {16794if (Complained)16795*Complained = true;16796return true;16797}1679816799DiagKind = diag::err_typecheck_convert_incompatible;16800ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);16801MayHaveConvFixit = true;16802isInvalid = true;16803MayHaveFunctionDiff = true;16804break;16805}1680616807QualType FirstType, SecondType;16808switch (Action) {16809case AA_Assigning:16810case AA_Initializing:16811// The destination type comes first.16812FirstType = DstType;16813SecondType = SrcType;16814break;1681516816case AA_Returning:16817case AA_Passing:16818case AA_Passing_CFAudited:16819case AA_Converting:16820case AA_Sending:16821case AA_Casting:16822// The source type comes first.16823FirstType = SrcType;16824SecondType = DstType;16825break;16826}1682716828PartialDiagnostic FDiag = PDiag(DiagKind);16829AssignmentAction ActionForDiag = Action;16830if (Action == AA_Passing_CFAudited)16831ActionForDiag = AA_Passing;1683216833FDiag << FirstType << SecondType << ActionForDiag16834<< SrcExpr->getSourceRange();1683516836if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||16837DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {16838auto isPlainChar = [](const clang::Type *Type) {16839return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||16840Type->isSpecificBuiltinType(BuiltinType::Char_U);16841};16842FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||16843isPlainChar(SecondType->getPointeeOrArrayElementType()));16844}1684516846// If we can fix the conversion, suggest the FixIts.16847if (!ConvHints.isNull()) {16848for (FixItHint &H : ConvHints.Hints)16849FDiag << H;16850}1685116852if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }1685316854if (MayHaveFunctionDiff)16855HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);1685616857Diag(Loc, FDiag);16858if ((DiagKind == diag::warn_incompatible_qualified_id ||16859DiagKind == diag::err_incompatible_qualified_id) &&16860PDecl && IFace && !IFace->hasDefinition())16861Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)16862<< IFace << PDecl;1686316864if (SecondType == Context.OverloadTy)16865NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,16866FirstType, /*TakingAddress=*/true);1686716868if (CheckInferredResultType)16869ObjC().EmitRelatedResultTypeNote(SrcExpr);1687016871if (Action == AA_Returning && ConvTy == IncompatiblePointer)16872ObjC().EmitRelatedResultTypeNoteForReturn(DstType);1687316874if (Complained)16875*Complained = true;16876return isInvalid;16877}1687816879ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,16880llvm::APSInt *Result,16881AllowFoldKind CanFold) {16882class SimpleICEDiagnoser : public VerifyICEDiagnoser {16883public:16884SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,16885QualType T) override {16886return S.Diag(Loc, diag::err_ice_not_integral)16887<< T << S.LangOpts.CPlusPlus;16888}16889SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {16890return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;16891}16892} Diagnoser;1689316894return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);16895}1689616897ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,16898llvm::APSInt *Result,16899unsigned DiagID,16900AllowFoldKind CanFold) {16901class IDDiagnoser : public VerifyICEDiagnoser {16902unsigned DiagID;1690316904public:16905IDDiagnoser(unsigned DiagID)16906: VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }1690716908SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {16909return S.Diag(Loc, DiagID);16910}16911} Diagnoser(DiagID);1691216913return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);16914}1691516916Sema::SemaDiagnosticBuilder16917Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,16918QualType T) {16919return diagnoseNotICE(S, Loc);16920}1692116922Sema::SemaDiagnosticBuilder16923Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {16924return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;16925}1692616927ExprResult16928Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,16929VerifyICEDiagnoser &Diagnoser,16930AllowFoldKind CanFold) {16931SourceLocation DiagLoc = E->getBeginLoc();1693216933if (getLangOpts().CPlusPlus11) {16934// C++11 [expr.const]p5:16935// If an expression of literal class type is used in a context where an16936// integral constant expression is required, then that class type shall16937// have a single non-explicit conversion function to an integral or16938// unscoped enumeration type16939ExprResult Converted;16940class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {16941VerifyICEDiagnoser &BaseDiagnoser;16942public:16943CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)16944: ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,16945BaseDiagnoser.Suppress, true),16946BaseDiagnoser(BaseDiagnoser) {}1694716948SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,16949QualType T) override {16950return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);16951}1695216953SemaDiagnosticBuilder diagnoseIncomplete(16954Sema &S, SourceLocation Loc, QualType T) override {16955return S.Diag(Loc, diag::err_ice_incomplete_type) << T;16956}1695716958SemaDiagnosticBuilder diagnoseExplicitConv(16959Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {16960return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;16961}1696216963SemaDiagnosticBuilder noteExplicitConv(16964Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {16965return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)16966<< ConvTy->isEnumeralType() << ConvTy;16967}1696816969SemaDiagnosticBuilder diagnoseAmbiguous(16970Sema &S, SourceLocation Loc, QualType T) override {16971return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;16972}1697316974SemaDiagnosticBuilder noteAmbiguous(16975Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {16976return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)16977<< ConvTy->isEnumeralType() << ConvTy;16978}1697916980SemaDiagnosticBuilder diagnoseConversion(16981Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {16982llvm_unreachable("conversion functions are permitted");16983}16984} ConvertDiagnoser(Diagnoser);1698516986Converted = PerformContextualImplicitConversion(DiagLoc, E,16987ConvertDiagnoser);16988if (Converted.isInvalid())16989return Converted;16990E = Converted.get();16991// The 'explicit' case causes us to get a RecoveryExpr. Give up here so we16992// don't try to evaluate it later. We also don't want to return the16993// RecoveryExpr here, as it results in this call succeeding, thus callers of16994// this function will attempt to use 'Value'.16995if (isa<RecoveryExpr>(E))16996return ExprError();16997if (!E->getType()->isIntegralOrUnscopedEnumerationType())16998return ExprError();16999} else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {17000// An ICE must be of integral or unscoped enumeration type.17001if (!Diagnoser.Suppress)17002Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())17003<< E->getSourceRange();17004return ExprError();17005}1700617007ExprResult RValueExpr = DefaultLvalueConversion(E);17008if (RValueExpr.isInvalid())17009return ExprError();1701017011E = RValueExpr.get();1701217013// Circumvent ICE checking in C++11 to avoid evaluating the expression twice17014// in the non-ICE case.17015if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {17016SmallVector<PartialDiagnosticAt, 8> Notes;17017if (Result)17018*Result = E->EvaluateKnownConstIntCheckOverflow(Context, &Notes);17019if (!isa<ConstantExpr>(E))17020E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))17021: ConstantExpr::Create(Context, E);1702217023if (Notes.empty())17024return E;1702517026// If our only note is the usual "invalid subexpression" note, just point17027// the caret at its location rather than producing an essentially17028// redundant note.17029if (Notes.size() == 1 && Notes[0].second.getDiagID() ==17030diag::note_invalid_subexpr_in_const_expr) {17031DiagLoc = Notes[0].first;17032Notes.clear();17033}1703417035if (getLangOpts().CPlusPlus) {17036if (!Diagnoser.Suppress) {17037Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();17038for (const PartialDiagnosticAt &Note : Notes)17039Diag(Note.first, Note.second);17040}17041return ExprError();17042}1704317044Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();17045for (const PartialDiagnosticAt &Note : Notes)17046Diag(Note.first, Note.second);1704717048return E;17049}1705017051Expr::EvalResult EvalResult;17052SmallVector<PartialDiagnosticAt, 8> Notes;17053EvalResult.Diag = &Notes;1705417055// Try to evaluate the expression, and produce diagnostics explaining why it's17056// not a constant expression as a side-effect.17057bool Folded =17058E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&17059EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&17060(!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);1706117062if (!isa<ConstantExpr>(E))17063E = ConstantExpr::Create(Context, E, EvalResult.Val);1706417065// In C++11, we can rely on diagnostics being produced for any expression17066// which is not a constant expression. If no diagnostics were produced, then17067// this is a constant expression.17068if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {17069if (Result)17070*Result = EvalResult.Val.getInt();17071return E;17072}1707317074// If our only note is the usual "invalid subexpression" note, just point17075// the caret at its location rather than producing an essentially17076// redundant note.17077if (Notes.size() == 1 && Notes[0].second.getDiagID() ==17078diag::note_invalid_subexpr_in_const_expr) {17079DiagLoc = Notes[0].first;17080Notes.clear();17081}1708217083if (!Folded || !CanFold) {17084if (!Diagnoser.Suppress) {17085Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();17086for (const PartialDiagnosticAt &Note : Notes)17087Diag(Note.first, Note.second);17088}1708917090return ExprError();17091}1709217093Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();17094for (const PartialDiagnosticAt &Note : Notes)17095Diag(Note.first, Note.second);1709617097if (Result)17098*Result = EvalResult.Val.getInt();17099return E;17100}1710117102namespace {17103// Handle the case where we conclude a expression which we speculatively17104// considered to be unevaluated is actually evaluated.17105class TransformToPE : public TreeTransform<TransformToPE> {17106typedef TreeTransform<TransformToPE> BaseTransform;1710717108public:17109TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }1711017111// Make sure we redo semantic analysis17112bool AlwaysRebuild() { return true; }17113bool ReplacingOriginal() { return true; }1711417115// We need to special-case DeclRefExprs referring to FieldDecls which17116// are not part of a member pointer formation; normal TreeTransforming17117// doesn't catch this case because of the way we represent them in the AST.17118// FIXME: This is a bit ugly; is it really the best way to handle this17119// case?17120//17121// Error on DeclRefExprs referring to FieldDecls.17122ExprResult TransformDeclRefExpr(DeclRefExpr *E) {17123if (isa<FieldDecl>(E->getDecl()) &&17124!SemaRef.isUnevaluatedContext())17125return SemaRef.Diag(E->getLocation(),17126diag::err_invalid_non_static_member_use)17127<< E->getDecl() << E->getSourceRange();1712817129return BaseTransform::TransformDeclRefExpr(E);17130}1713117132// Exception: filter out member pointer formation17133ExprResult TransformUnaryOperator(UnaryOperator *E) {17134if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())17135return E;1713617137return BaseTransform::TransformUnaryOperator(E);17138}1713917140// The body of a lambda-expression is in a separate expression evaluation17141// context so never needs to be transformed.17142// FIXME: Ideally we wouldn't transform the closure type either, and would17143// just recreate the capture expressions and lambda expression.17144StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {17145return SkipLambdaBody(E, Body);17146}17147};17148}1714917150ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {17151assert(isUnevaluatedContext() &&17152"Should only transform unevaluated expressions");17153ExprEvalContexts.back().Context =17154ExprEvalContexts[ExprEvalContexts.size()-2].Context;17155if (isUnevaluatedContext())17156return E;17157return TransformToPE(*this).TransformExpr(E);17158}1715917160TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {17161assert(isUnevaluatedContext() &&17162"Should only transform unevaluated expressions");17163ExprEvalContexts.back().Context = parentEvaluationContext().Context;17164if (isUnevaluatedContext())17165return TInfo;17166return TransformToPE(*this).TransformType(TInfo);17167}1716817169void17170Sema::PushExpressionEvaluationContext(17171ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,17172ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {17173ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,17174LambdaContextDecl, ExprContext);1717517176// Discarded statements and immediate contexts nested in other17177// discarded statements or immediate context are themselves17178// a discarded statement or an immediate context, respectively.17179ExprEvalContexts.back().InDiscardedStatement =17180parentEvaluationContext().isDiscardedStatementContext();1718117182// C++23 [expr.const]/p1517183// An expression or conversion is in an immediate function context if [...]17184// it is a subexpression of a manifestly constant-evaluated expression or17185// conversion.17186const auto &Prev = parentEvaluationContext();17187ExprEvalContexts.back().InImmediateFunctionContext =17188Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();1718917190ExprEvalContexts.back().InImmediateEscalatingFunctionContext =17191Prev.InImmediateEscalatingFunctionContext;1719217193Cleanup.reset();17194if (!MaybeODRUseExprs.empty())17195std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);17196}1719717198void17199Sema::PushExpressionEvaluationContext(17200ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,17201ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {17202Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;17203PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);17204}1720517206namespace {1720717208const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {17209PossibleDeref = PossibleDeref->IgnoreParenImpCasts();17210if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {17211if (E->getOpcode() == UO_Deref)17212return CheckPossibleDeref(S, E->getSubExpr());17213} else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {17214return CheckPossibleDeref(S, E->getBase());17215} else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {17216return CheckPossibleDeref(S, E->getBase());17217} else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {17218QualType Inner;17219QualType Ty = E->getType();17220if (const auto *Ptr = Ty->getAs<PointerType>())17221Inner = Ptr->getPointeeType();17222else if (const auto *Arr = S.Context.getAsArrayType(Ty))17223Inner = Arr->getElementType();17224else17225return nullptr;1722617227if (Inner->hasAttr(attr::NoDeref))17228return E;17229}17230return nullptr;17231}1723217233} // namespace1723417235void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {17236for (const Expr *E : Rec.PossibleDerefs) {17237const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);17238if (DeclRef) {17239const ValueDecl *Decl = DeclRef->getDecl();17240Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)17241<< Decl->getName() << E->getSourceRange();17242Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();17243} else {17244Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)17245<< E->getSourceRange();17246}17247}17248Rec.PossibleDerefs.clear();17249}1725017251void Sema::CheckUnusedVolatileAssignment(Expr *E) {17252if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)17253return;1725417255// Note: ignoring parens here is not justified by the standard rules, but17256// ignoring parentheses seems like a more reasonable approach, and this only17257// drives a deprecation warning so doesn't affect conformance.17258if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {17259if (BO->getOpcode() == BO_Assign) {17260auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;17261llvm::erase(LHSs, BO->getLHS());17262}17263}17264}1726517266void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {17267assert(getLangOpts().CPlusPlus20 &&17268ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&17269"Cannot mark an immediate escalating expression outside of an "17270"immediate escalating context");17271if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());17272Call && Call->getCallee()) {17273if (auto *DeclRef =17274dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))17275DeclRef->setIsImmediateEscalating(true);17276} else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {17277Ctr->setIsImmediateEscalating(true);17278} else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {17279DeclRef->setIsImmediateEscalating(true);17280} else {17281assert(false && "expected an immediately escalating expression");17282}17283if (FunctionScopeInfo *FI = getCurFunction())17284FI->FoundImmediateEscalatingExpression = true;17285}1728617287ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {17288if (isUnevaluatedContext() || !E.isUsable() || !Decl ||17289!Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||17290isCheckingDefaultArgumentOrInitializer() ||17291RebuildingImmediateInvocation || isImmediateFunctionContext())17292return E;1729317294/// Opportunistically remove the callee from ReferencesToConsteval if we can.17295/// It's OK if this fails; we'll also remove this in17296/// HandleImmediateInvocations, but catching it here allows us to avoid17297/// walking the AST looking for it in simple cases.17298if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))17299if (auto *DeclRef =17300dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))17301ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);1730217303// C++23 [expr.const]/p1617304// An expression or conversion is immediate-escalating if it is not initially17305// in an immediate function context and it is [...] an immediate invocation17306// that is not a constant expression and is not a subexpression of an17307// immediate invocation.17308APValue Cached;17309auto CheckConstantExpressionAndKeepResult = [&]() {17310llvm::SmallVector<PartialDiagnosticAt, 8> Notes;17311Expr::EvalResult Eval;17312Eval.Diag = &Notes;17313bool Res = E.get()->EvaluateAsConstantExpr(17314Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);17315if (Res && Notes.empty()) {17316Cached = std::move(Eval.Val);17317return true;17318}17319return false;17320};1732117322if (!E.get()->isValueDependent() &&17323ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&17324!CheckConstantExpressionAndKeepResult()) {17325MarkExpressionAsImmediateEscalating(E.get());17326return E;17327}1732817329if (Cleanup.exprNeedsCleanups()) {17330// Since an immediate invocation is a full expression itself - it requires17331// an additional ExprWithCleanups node, but it can participate to a bigger17332// full expression which actually requires cleanups to be run after so17333// create ExprWithCleanups without using MaybeCreateExprWithCleanups as it17334// may discard cleanups for outer expression too early.1733517336// Note that ExprWithCleanups created here must always have empty cleanup17337// objects:17338// - compound literals do not create cleanup objects in C++ and immediate17339// invocations are C++-only.17340// - blocks are not allowed inside constant expressions and compiler will17341// issue an error if they appear there.17342//17343// Hence, in correct code any cleanup objects created inside current17344// evaluation context must be outside the immediate invocation.17345E = ExprWithCleanups::Create(getASTContext(), E.get(),17346Cleanup.cleanupsHaveSideEffects(), {});17347}1734817349ConstantExpr *Res = ConstantExpr::Create(17350getASTContext(), E.get(),17351ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),17352getASTContext()),17353/*IsImmediateInvocation*/ true);17354if (Cached.hasValue())17355Res->MoveIntoResult(Cached, getASTContext());17356/// Value-dependent constant expressions should not be immediately17357/// evaluated until they are instantiated.17358if (!Res->isValueDependent())17359ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);17360return Res;17361}1736217363static void EvaluateAndDiagnoseImmediateInvocation(17364Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {17365llvm::SmallVector<PartialDiagnosticAt, 8> Notes;17366Expr::EvalResult Eval;17367Eval.Diag = &Notes;17368ConstantExpr *CE = Candidate.getPointer();17369bool Result = CE->EvaluateAsConstantExpr(17370Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);17371if (!Result || !Notes.empty()) {17372SemaRef.FailedImmediateInvocations.insert(CE);17373Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();17374if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))17375InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();17376FunctionDecl *FD = nullptr;17377if (auto *Call = dyn_cast<CallExpr>(InnerExpr))17378FD = cast<FunctionDecl>(Call->getCalleeDecl());17379else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))17380FD = Call->getConstructor();17381else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))17382FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());1738317384assert(FD && FD->isImmediateFunction() &&17385"could not find an immediate function in this expression");17386if (FD->isInvalidDecl())17387return;17388SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)17389<< FD << FD->isConsteval();17390if (auto Context =17391SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {17392SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)17393<< Context->Decl;17394SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);17395}17396if (!FD->isConsteval())17397SemaRef.DiagnoseImmediateEscalatingReason(FD);17398for (auto &Note : Notes)17399SemaRef.Diag(Note.first, Note.second);17400return;17401}17402CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());17403}1740417405static void RemoveNestedImmediateInvocation(17406Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,17407SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {17408struct ComplexRemove : TreeTransform<ComplexRemove> {17409using Base = TreeTransform<ComplexRemove>;17410llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;17411SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;17412SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator17413CurrentII;17414ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,17415SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,17416SmallVector<Sema::ImmediateInvocationCandidate,174174>::reverse_iterator Current)17418: Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}17419void RemoveImmediateInvocation(ConstantExpr* E) {17420auto It = std::find_if(CurrentII, IISet.rend(),17421[E](Sema::ImmediateInvocationCandidate Elem) {17422return Elem.getPointer() == E;17423});17424// It is possible that some subexpression of the current immediate17425// invocation was handled from another expression evaluation context. Do17426// not handle the current immediate invocation if some of its17427// subexpressions failed before.17428if (It == IISet.rend()) {17429if (SemaRef.FailedImmediateInvocations.contains(E))17430CurrentII->setInt(1);17431} else {17432It->setInt(1); // Mark as deleted17433}17434}17435ExprResult TransformConstantExpr(ConstantExpr *E) {17436if (!E->isImmediateInvocation())17437return Base::TransformConstantExpr(E);17438RemoveImmediateInvocation(E);17439return Base::TransformExpr(E->getSubExpr());17440}17441/// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so17442/// we need to remove its DeclRefExpr from the DRSet.17443ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {17444DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));17445return Base::TransformCXXOperatorCallExpr(E);17446}17447/// Base::TransformUserDefinedLiteral doesn't preserve the17448/// UserDefinedLiteral node.17449ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }17450/// Base::TransformInitializer skips ConstantExpr so we need to visit them17451/// here.17452ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {17453if (!Init)17454return Init;17455/// ConstantExpr are the first layer of implicit node to be removed so if17456/// Init isn't a ConstantExpr, no ConstantExpr will be skipped.17457if (auto *CE = dyn_cast<ConstantExpr>(Init))17458if (CE->isImmediateInvocation())17459RemoveImmediateInvocation(CE);17460return Base::TransformInitializer(Init, NotCopyInit);17461}17462ExprResult TransformDeclRefExpr(DeclRefExpr *E) {17463DRSet.erase(E);17464return E;17465}17466ExprResult TransformLambdaExpr(LambdaExpr *E) {17467// Do not rebuild lambdas to avoid creating a new type.17468// Lambdas have already been processed inside their eval context.17469return E;17470}17471bool AlwaysRebuild() { return false; }17472bool ReplacingOriginal() { return true; }17473bool AllowSkippingCXXConstructExpr() {17474bool Res = AllowSkippingFirstCXXConstructExpr;17475AllowSkippingFirstCXXConstructExpr = true;17476return Res;17477}17478bool AllowSkippingFirstCXXConstructExpr = true;17479} Transformer(SemaRef, Rec.ReferenceToConsteval,17480Rec.ImmediateInvocationCandidates, It);1748117482/// CXXConstructExpr with a single argument are getting skipped by17483/// TreeTransform in some situtation because they could be implicit. This17484/// can only occur for the top-level CXXConstructExpr because it is used17485/// nowhere in the expression being transformed therefore will not be rebuilt.17486/// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from17487/// skipping the first CXXConstructExpr.17488if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))17489Transformer.AllowSkippingFirstCXXConstructExpr = false;1749017491ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());17492// The result may not be usable in case of previous compilation errors.17493// In this case evaluation of the expression may result in crash so just17494// don't do anything further with the result.17495if (Res.isUsable()) {17496Res = SemaRef.MaybeCreateExprWithCleanups(Res);17497It->getPointer()->setSubExpr(Res.get());17498}17499}1750017501static void17502HandleImmediateInvocations(Sema &SemaRef,17503Sema::ExpressionEvaluationContextRecord &Rec) {17504if ((Rec.ImmediateInvocationCandidates.size() == 0 &&17505Rec.ReferenceToConsteval.size() == 0) ||17506Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)17507return;1750817509/// When we have more than 1 ImmediateInvocationCandidates or previously17510/// failed immediate invocations, we need to check for nested17511/// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.17512/// Otherwise we only need to remove ReferenceToConsteval in the immediate17513/// invocation.17514if (Rec.ImmediateInvocationCandidates.size() > 1 ||17515!SemaRef.FailedImmediateInvocations.empty()) {1751617517/// Prevent sema calls during the tree transform from adding pointers that17518/// are already in the sets.17519llvm::SaveAndRestore DisableIITracking(17520SemaRef.RebuildingImmediateInvocation, true);1752117522/// Prevent diagnostic during tree transfrom as they are duplicates17523Sema::TentativeAnalysisScope DisableDiag(SemaRef);1752417525for (auto It = Rec.ImmediateInvocationCandidates.rbegin();17526It != Rec.ImmediateInvocationCandidates.rend(); It++)17527if (!It->getInt())17528RemoveNestedImmediateInvocation(SemaRef, Rec, It);17529} else if (Rec.ImmediateInvocationCandidates.size() == 1 &&17530Rec.ReferenceToConsteval.size()) {17531struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {17532llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;17533SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}17534bool VisitDeclRefExpr(DeclRefExpr *E) {17535DRSet.erase(E);17536return DRSet.size();17537}17538} Visitor(Rec.ReferenceToConsteval);17539Visitor.TraverseStmt(17540Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());17541}17542for (auto CE : Rec.ImmediateInvocationCandidates)17543if (!CE.getInt())17544EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);17545for (auto *DR : Rec.ReferenceToConsteval) {17546// If the expression is immediate escalating, it is not an error;17547// The outer context itself becomes immediate and further errors,17548// if any, will be handled by DiagnoseImmediateEscalatingReason.17549if (DR->isImmediateEscalating())17550continue;17551auto *FD = cast<FunctionDecl>(DR->getDecl());17552const NamedDecl *ND = FD;17553if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);17554MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))17555ND = MD->getParent();1755617557// C++23 [expr.const]/p1617558// An expression or conversion is immediate-escalating if it is not17559// initially in an immediate function context and it is [...] a17560// potentially-evaluated id-expression that denotes an immediate function17561// that is not a subexpression of an immediate invocation.17562bool ImmediateEscalating = false;17563bool IsPotentiallyEvaluated =17564Rec.Context ==17565Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||17566Rec.Context ==17567Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;17568if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)17569ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;1757017571if (!Rec.InImmediateEscalatingFunctionContext ||17572(SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {17573SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)17574<< ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();17575SemaRef.Diag(ND->getLocation(), diag::note_declared_at);17576if (auto Context =17577SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {17578SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)17579<< Context->Decl;17580SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);17581}17582if (FD->isImmediateEscalating() && !FD->isConsteval())17583SemaRef.DiagnoseImmediateEscalatingReason(FD);1758417585} else {17586SemaRef.MarkExpressionAsImmediateEscalating(DR);17587}17588}17589}1759017591void Sema::PopExpressionEvaluationContext() {17592ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();17593unsigned NumTypos = Rec.NumTypos;1759417595if (!Rec.Lambdas.empty()) {17596using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;17597if (!getLangOpts().CPlusPlus20 &&17598(Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||17599Rec.isUnevaluated() ||17600(Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {17601unsigned D;17602if (Rec.isUnevaluated()) {17603// C++11 [expr.prim.lambda]p2:17604// A lambda-expression shall not appear in an unevaluated operand17605// (Clause 5).17606D = diag::err_lambda_unevaluated_operand;17607} else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {17608// C++1y [expr.const]p2:17609// A conditional-expression e is a core constant expression unless the17610// evaluation of e, following the rules of the abstract machine, would17611// evaluate [...] a lambda-expression.17612D = diag::err_lambda_in_constant_expression;17613} else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {17614// C++17 [expr.prim.lamda]p2:17615// A lambda-expression shall not appear [...] in a template-argument.17616D = diag::err_lambda_in_invalid_context;17617} else17618llvm_unreachable("Couldn't infer lambda error message.");1761917620for (const auto *L : Rec.Lambdas)17621Diag(L->getBeginLoc(), D);17622}17623}1762417625// Append the collected materialized temporaries into previous context before17626// exit if the previous also is a lifetime extending context.17627auto &PrevRecord = parentEvaluationContext();17628if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&17629PrevRecord.InLifetimeExtendingContext &&17630!Rec.ForRangeLifetimeExtendTemps.empty()) {17631PrevRecord.ForRangeLifetimeExtendTemps.append(17632Rec.ForRangeLifetimeExtendTemps);17633}1763417635WarnOnPendingNoDerefs(Rec);17636HandleImmediateInvocations(*this, Rec);1763717638// Warn on any volatile-qualified simple-assignments that are not discarded-17639// value expressions nor unevaluated operands (those cases get removed from17640// this list by CheckUnusedVolatileAssignment).17641for (auto *BO : Rec.VolatileAssignmentLHSs)17642Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)17643<< BO->getType();1764417645// When are coming out of an unevaluated context, clear out any17646// temporaries that we may have created as part of the evaluation of17647// the expression in that context: they aren't relevant because they17648// will never be constructed.17649if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {17650ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,17651ExprCleanupObjects.end());17652Cleanup = Rec.ParentCleanup;17653CleanupVarDeclMarking();17654std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);17655// Otherwise, merge the contexts together.17656} else {17657Cleanup.mergeFrom(Rec.ParentCleanup);17658MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),17659Rec.SavedMaybeODRUseExprs.end());17660}1766117662// Pop the current expression evaluation context off the stack.17663ExprEvalContexts.pop_back();1766417665// The global expression evaluation context record is never popped.17666ExprEvalContexts.back().NumTypos += NumTypos;17667}1766817669void Sema::DiscardCleanupsInEvaluationContext() {17670ExprCleanupObjects.erase(17671ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,17672ExprCleanupObjects.end());17673Cleanup.reset();17674MaybeODRUseExprs.clear();17675}1767617677ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {17678ExprResult Result = CheckPlaceholderExpr(E);17679if (Result.isInvalid())17680return ExprError();17681E = Result.get();17682if (!E->getType()->isVariablyModifiedType())17683return E;17684return TransformToPotentiallyEvaluated(E);17685}1768617687/// Are we in a context that is potentially constant evaluated per C++2017688/// [expr.const]p12?17689static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {17690/// C++2a [expr.const]p12:17691// An expression or conversion is potentially constant evaluated if it is17692switch (SemaRef.ExprEvalContexts.back().Context) {17693case Sema::ExpressionEvaluationContext::ConstantEvaluated:17694case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:1769517696// -- a manifestly constant-evaluated expression,17697case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:17698case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:17699case Sema::ExpressionEvaluationContext::DiscardedStatement:17700// -- a potentially-evaluated expression,17701case Sema::ExpressionEvaluationContext::UnevaluatedList:17702// -- an immediate subexpression of a braced-init-list,1770317704// -- [FIXME] an expression of the form & cast-expression that occurs17705// within a templated entity17706// -- a subexpression of one of the above that is not a subexpression of17707// a nested unevaluated operand.17708return true;1770917710case Sema::ExpressionEvaluationContext::Unevaluated:17711case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:17712// Expressions in this context are never evaluated.17713return false;17714}17715llvm_unreachable("Invalid context");17716}1771717718/// Return true if this function has a calling convention that requires mangling17719/// in the size of the parameter pack.17720static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {17721// These manglings don't do anything on non-Windows or non-x86 platforms, so17722// we don't need parameter type sizes.17723const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();17724if (!TT.isOSWindows() || !TT.isX86())17725return false;1772617727// If this is C++ and this isn't an extern "C" function, parameters do not17728// need to be complete. In this case, C++ mangling will apply, which doesn't17729// use the size of the parameters.17730if (S.getLangOpts().CPlusPlus && !FD->isExternC())17731return false;1773217733// Stdcall, fastcall, and vectorcall need this special treatment.17734CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();17735switch (CC) {17736case CC_X86StdCall:17737case CC_X86FastCall:17738case CC_X86VectorCall:17739return true;17740default:17741break;17742}17743return false;17744}1774517746/// Require that all of the parameter types of function be complete. Normally,17747/// parameter types are only required to be complete when a function is called17748/// or defined, but to mangle functions with certain calling conventions, the17749/// mangler needs to know the size of the parameter list. In this situation,17750/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles17751/// the function as _foo@0, i.e. zero bytes of parameters, which will usually17752/// result in a linker error. Clang doesn't implement this behavior, and instead17753/// attempts to error at compile time.17754static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,17755SourceLocation Loc) {17756class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {17757FunctionDecl *FD;17758ParmVarDecl *Param;1775917760public:17761ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)17762: FD(FD), Param(Param) {}1776317764void diagnose(Sema &S, SourceLocation Loc, QualType T) override {17765CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();17766StringRef CCName;17767switch (CC) {17768case CC_X86StdCall:17769CCName = "stdcall";17770break;17771case CC_X86FastCall:17772CCName = "fastcall";17773break;17774case CC_X86VectorCall:17775CCName = "vectorcall";17776break;17777default:17778llvm_unreachable("CC does not need mangling");17779}1778017781S.Diag(Loc, diag::err_cconv_incomplete_param_type)17782<< Param->getDeclName() << FD->getDeclName() << CCName;17783}17784};1778517786for (ParmVarDecl *Param : FD->parameters()) {17787ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);17788S.RequireCompleteType(Loc, Param->getType(), Diagnoser);17789}17790}1779117792namespace {17793enum class OdrUseContext {17794/// Declarations in this context are not odr-used.17795None,17796/// Declarations in this context are formally odr-used, but this is a17797/// dependent context.17798Dependent,17799/// Declarations in this context are odr-used but not actually used (yet).17800FormallyOdrUsed,17801/// Declarations in this context are used.17802Used17803};17804}1780517806/// Are we within a context in which references to resolved functions or to17807/// variables result in odr-use?17808static OdrUseContext isOdrUseContext(Sema &SemaRef) {17809OdrUseContext Result;1781017811switch (SemaRef.ExprEvalContexts.back().Context) {17812case Sema::ExpressionEvaluationContext::Unevaluated:17813case Sema::ExpressionEvaluationContext::UnevaluatedList:17814case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:17815return OdrUseContext::None;1781617817case Sema::ExpressionEvaluationContext::ConstantEvaluated:17818case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:17819case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:17820Result = OdrUseContext::Used;17821break;1782217823case Sema::ExpressionEvaluationContext::DiscardedStatement:17824Result = OdrUseContext::FormallyOdrUsed;17825break;1782617827case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:17828// A default argument formally results in odr-use, but doesn't actually17829// result in a use in any real sense until it itself is used.17830Result = OdrUseContext::FormallyOdrUsed;17831break;17832}1783317834if (SemaRef.CurContext->isDependentContext())17835return OdrUseContext::Dependent;1783617837return Result;17838}1783917840static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {17841if (!Func->isConstexpr())17842return false;1784317844if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())17845return true;17846auto *CCD = dyn_cast<CXXConstructorDecl>(Func);17847return CCD && CCD->getInheritedConstructor();17848}1784917850void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,17851bool MightBeOdrUse) {17852assert(Func && "No function?");1785317854Func->setReferenced();1785517856// Recursive functions aren't really used until they're used from some other17857// context.17858bool IsRecursiveCall = CurContext == Func;1785917860// C++11 [basic.def.odr]p3:17861// A function whose name appears as a potentially-evaluated expression is17862// odr-used if it is the unique lookup result or the selected member of a17863// set of overloaded functions [...].17864//17865// We (incorrectly) mark overload resolution as an unevaluated context, so we17866// can just check that here.17867OdrUseContext OdrUse =17868MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;17869if (IsRecursiveCall && OdrUse == OdrUseContext::Used)17870OdrUse = OdrUseContext::FormallyOdrUsed;1787117872// Trivial default constructors and destructors are never actually used.17873// FIXME: What about other special members?17874if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&17875OdrUse == OdrUseContext::Used) {17876if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))17877if (Constructor->isDefaultConstructor())17878OdrUse = OdrUseContext::FormallyOdrUsed;17879if (isa<CXXDestructorDecl>(Func))17880OdrUse = OdrUseContext::FormallyOdrUsed;17881}1788217883// C++20 [expr.const]p12:17884// A function [...] is needed for constant evaluation if it is [...] a17885// constexpr function that is named by an expression that is potentially17886// constant evaluated17887bool NeededForConstantEvaluation =17888isPotentiallyConstantEvaluatedContext(*this) &&17889isImplicitlyDefinableConstexprFunction(Func);1789017891// Determine whether we require a function definition to exist, per17892// C++11 [temp.inst]p3:17893// Unless a function template specialization has been explicitly17894// instantiated or explicitly specialized, the function template17895// specialization is implicitly instantiated when the specialization is17896// referenced in a context that requires a function definition to exist.17897// C++20 [temp.inst]p7:17898// The existence of a definition of a [...] function is considered to17899// affect the semantics of the program if the [...] function is needed for17900// constant evaluation by an expression17901// C++20 [basic.def.odr]p10:17902// Every program shall contain exactly one definition of every non-inline17903// function or variable that is odr-used in that program outside of a17904// discarded statement17905// C++20 [special]p1:17906// The implementation will implicitly define [defaulted special members]17907// if they are odr-used or needed for constant evaluation.17908//17909// Note that we skip the implicit instantiation of templates that are only17910// used in unused default arguments or by recursive calls to themselves.17911// This is formally non-conforming, but seems reasonable in practice.17912bool NeedDefinition =17913!IsRecursiveCall &&17914(OdrUse == OdrUseContext::Used ||17915(NeededForConstantEvaluation && !Func->isPureVirtual()));1791617917// C++14 [temp.expl.spec]p6:17918// If a template [...] is explicitly specialized then that specialization17919// shall be declared before the first use of that specialization that would17920// cause an implicit instantiation to take place, in every translation unit17921// in which such a use occurs17922if (NeedDefinition &&17923(Func->getTemplateSpecializationKind() != TSK_Undeclared ||17924Func->getMemberSpecializationInfo()))17925checkSpecializationReachability(Loc, Func);1792617927if (getLangOpts().CUDA)17928CUDA().CheckCall(Loc, Func);1792917930// If we need a definition, try to create one.17931if (NeedDefinition && !Func->getBody()) {17932runWithSufficientStackSpace(Loc, [&] {17933if (CXXConstructorDecl *Constructor =17934dyn_cast<CXXConstructorDecl>(Func)) {17935Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());17936if (Constructor->isDefaulted() && !Constructor->isDeleted()) {17937if (Constructor->isDefaultConstructor()) {17938if (Constructor->isTrivial() &&17939!Constructor->hasAttr<DLLExportAttr>())17940return;17941DefineImplicitDefaultConstructor(Loc, Constructor);17942} else if (Constructor->isCopyConstructor()) {17943DefineImplicitCopyConstructor(Loc, Constructor);17944} else if (Constructor->isMoveConstructor()) {17945DefineImplicitMoveConstructor(Loc, Constructor);17946}17947} else if (Constructor->getInheritedConstructor()) {17948DefineInheritingConstructor(Loc, Constructor);17949}17950} else if (CXXDestructorDecl *Destructor =17951dyn_cast<CXXDestructorDecl>(Func)) {17952Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());17953if (Destructor->isDefaulted() && !Destructor->isDeleted()) {17954if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())17955return;17956DefineImplicitDestructor(Loc, Destructor);17957}17958if (Destructor->isVirtual() && getLangOpts().AppleKext)17959MarkVTableUsed(Loc, Destructor->getParent());17960} else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {17961if (MethodDecl->isOverloadedOperator() &&17962MethodDecl->getOverloadedOperator() == OO_Equal) {17963MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());17964if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {17965if (MethodDecl->isCopyAssignmentOperator())17966DefineImplicitCopyAssignment(Loc, MethodDecl);17967else if (MethodDecl->isMoveAssignmentOperator())17968DefineImplicitMoveAssignment(Loc, MethodDecl);17969}17970} else if (isa<CXXConversionDecl>(MethodDecl) &&17971MethodDecl->getParent()->isLambda()) {17972CXXConversionDecl *Conversion =17973cast<CXXConversionDecl>(MethodDecl->getFirstDecl());17974if (Conversion->isLambdaToBlockPointerConversion())17975DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);17976else17977DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);17978} else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)17979MarkVTableUsed(Loc, MethodDecl->getParent());17980}1798117982if (Func->isDefaulted() && !Func->isDeleted()) {17983DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);17984if (DCK != DefaultedComparisonKind::None)17985DefineDefaultedComparison(Loc, Func, DCK);17986}1798717988// Implicit instantiation of function templates and member functions of17989// class templates.17990if (Func->isImplicitlyInstantiable()) {17991TemplateSpecializationKind TSK =17992Func->getTemplateSpecializationKindForInstantiation();17993SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();17994bool FirstInstantiation = PointOfInstantiation.isInvalid();17995if (FirstInstantiation) {17996PointOfInstantiation = Loc;17997if (auto *MSI = Func->getMemberSpecializationInfo())17998MSI->setPointOfInstantiation(Loc);17999// FIXME: Notify listener.18000else18001Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);18002} else if (TSK != TSK_ImplicitInstantiation) {18003// Use the point of use as the point of instantiation, instead of the18004// point of explicit instantiation (which we track as the actual point18005// of instantiation). This gives better backtraces in diagnostics.18006PointOfInstantiation = Loc;18007}1800818009if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||18010Func->isConstexpr()) {18011if (isa<CXXRecordDecl>(Func->getDeclContext()) &&18012cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&18013CodeSynthesisContexts.size())18014PendingLocalImplicitInstantiations.push_back(18015std::make_pair(Func, PointOfInstantiation));18016else if (Func->isConstexpr())18017// Do not defer instantiations of constexpr functions, to avoid the18018// expression evaluator needing to call back into Sema if it sees a18019// call to such a function.18020InstantiateFunctionDefinition(PointOfInstantiation, Func);18021else {18022Func->setInstantiationIsPending(true);18023PendingInstantiations.push_back(18024std::make_pair(Func, PointOfInstantiation));18025// Notify the consumer that a function was implicitly instantiated.18026Consumer.HandleCXXImplicitFunctionInstantiation(Func);18027}18028}18029} else {18030// Walk redefinitions, as some of them may be instantiable.18031for (auto *i : Func->redecls()) {18032if (!i->isUsed(false) && i->isImplicitlyInstantiable())18033MarkFunctionReferenced(Loc, i, MightBeOdrUse);18034}18035}18036});18037}1803818039// If a constructor was defined in the context of a default parameter18040// or of another default member initializer (ie a PotentiallyEvaluatedIfUsed18041// context), its initializers may not be referenced yet.18042if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {18043EnterExpressionEvaluationContext EvalContext(18044*this,18045Constructor->isImmediateFunction()18046? ExpressionEvaluationContext::ImmediateFunctionContext18047: ExpressionEvaluationContext::PotentiallyEvaluated,18048Constructor);18049for (CXXCtorInitializer *Init : Constructor->inits()) {18050if (Init->isInClassMemberInitializer())18051runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {18052MarkDeclarationsReferencedInExpr(Init->getInit());18053});18054}18055}1805618057// C++14 [except.spec]p17:18058// An exception-specification is considered to be needed when:18059// - the function is odr-used or, if it appears in an unevaluated operand,18060// would be odr-used if the expression were potentially-evaluated;18061//18062// Note, we do this even if MightBeOdrUse is false. That indicates that the18063// function is a pure virtual function we're calling, and in that case the18064// function was selected by overload resolution and we need to resolve its18065// exception specification for a different reason.18066const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();18067if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))18068ResolveExceptionSpec(Loc, FPT);1806918070// A callee could be called by a host function then by a device function.18071// If we only try recording once, we will miss recording the use on device18072// side. Therefore keep trying until it is recorded.18073if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&18074!getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))18075CUDA().RecordImplicitHostDeviceFuncUsedByDevice(Func);1807618077// If this is the first "real" use, act on that.18078if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {18079// Keep track of used but undefined functions.18080if (!Func->isDefined()) {18081if (mightHaveNonExternalLinkage(Func))18082UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));18083else if (Func->getMostRecentDecl()->isInlined() &&18084!LangOpts.GNUInline &&18085!Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())18086UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));18087else if (isExternalWithNoLinkageType(Func))18088UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));18089}1809018091// Some x86 Windows calling conventions mangle the size of the parameter18092// pack into the name. Computing the size of the parameters requires the18093// parameter types to be complete. Check that now.18094if (funcHasParameterSizeMangling(*this, Func))18095CheckCompleteParameterTypesForMangler(*this, Func, Loc);1809618097// In the MS C++ ABI, the compiler emits destructor variants where they are18098// used. If the destructor is used here but defined elsewhere, mark the18099// virtual base destructors referenced. If those virtual base destructors18100// are inline, this will ensure they are defined when emitting the complete18101// destructor variant. This checking may be redundant if the destructor is18102// provided later in this TU.18103if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {18104if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {18105CXXRecordDecl *Parent = Dtor->getParent();18106if (Parent->getNumVBases() > 0 && !Dtor->getBody())18107CheckCompleteDestructorVariant(Loc, Dtor);18108}18109}1811018111Func->markUsed(Context);18112}18113}1811418115/// Directly mark a variable odr-used. Given a choice, prefer to use18116/// MarkVariableReferenced since it does additional checks and then18117/// calls MarkVarDeclODRUsed.18118/// If the variable must be captured:18119/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext18120/// - else capture it in the DeclContext that maps to the18121/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.18122static void18123MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,18124const unsigned *const FunctionScopeIndexToStopAt = nullptr) {18125// Keep track of used but undefined variables.18126// FIXME: We shouldn't suppress this warning for static data members.18127VarDecl *Var = V->getPotentiallyDecomposedVarDecl();18128assert(Var && "expected a capturable variable");1812918130if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&18131(!Var->isExternallyVisible() || Var->isInline() ||18132SemaRef.isExternalWithNoLinkageType(Var)) &&18133!(Var->isStaticDataMember() && Var->hasInit())) {18134SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];18135if (old.isInvalid())18136old = Loc;18137}18138QualType CaptureType, DeclRefType;18139if (SemaRef.LangOpts.OpenMP)18140SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);18141SemaRef.tryCaptureVariable(V, Loc, Sema::TryCapture_Implicit,18142/*EllipsisLoc*/ SourceLocation(),18143/*BuildAndDiagnose*/ true, CaptureType,18144DeclRefType, FunctionScopeIndexToStopAt);1814518146if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {18147auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);18148auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);18149auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);18150if (VarTarget == SemaCUDA::CVT_Host &&18151(UserTarget == CUDAFunctionTarget::Device ||18152UserTarget == CUDAFunctionTarget::HostDevice ||18153UserTarget == CUDAFunctionTarget::Global)) {18154// Diagnose ODR-use of host global variables in device functions.18155// Reference of device global variables in host functions is allowed18156// through shadow variables therefore it is not diagnosed.18157if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {18158SemaRef.targetDiag(Loc, diag::err_ref_bad_target)18159<< /*host*/ 2 << /*variable*/ 1 << Var18160<< llvm::to_underlying(UserTarget);18161SemaRef.targetDiag(Var->getLocation(),18162Var->getType().isConstQualified()18163? diag::note_cuda_const_var_unpromoted18164: diag::note_cuda_host_var);18165}18166} else if (VarTarget == SemaCUDA::CVT_Device &&18167!Var->hasAttr<CUDASharedAttr>() &&18168(UserTarget == CUDAFunctionTarget::Host ||18169UserTarget == CUDAFunctionTarget::HostDevice)) {18170// Record a CUDA/HIP device side variable if it is ODR-used18171// by host code. This is done conservatively, when the variable is18172// referenced in any of the following contexts:18173// - a non-function context18174// - a host function18175// - a host device function18176// This makes the ODR-use of the device side variable by host code to18177// be visible in the device compilation for the compiler to be able to18178// emit template variables instantiated by host code only and to18179// externalize the static device side variable ODR-used by host code.18180if (!Var->hasExternalStorage())18181SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);18182else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&18183(!FD || (!FD->getDescribedFunctionTemplate() &&18184SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==18185GVA_StrongExternal)))18186SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);18187}18188}1818918190V->markUsed(SemaRef.Context);18191}1819218193void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,18194SourceLocation Loc,18195unsigned CapturingScopeIndex) {18196MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);18197}1819818199void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,18200ValueDecl *var) {18201DeclContext *VarDC = var->getDeclContext();1820218203// If the parameter still belongs to the translation unit, then18204// we're actually just using one parameter in the declaration of18205// the next.18206if (isa<ParmVarDecl>(var) &&18207isa<TranslationUnitDecl>(VarDC))18208return;1820918210// For C code, don't diagnose about capture if we're not actually in code18211// right now; it's impossible to write a non-constant expression outside of18212// function context, so we'll get other (more useful) diagnostics later.18213//18214// For C++, things get a bit more nasty... it would be nice to suppress this18215// diagnostic for certain cases like using a local variable in an array bound18216// for a member of a local class, but the correct predicate is not obvious.18217if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())18218return;1821918220unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;18221unsigned ContextKind = 3; // unknown18222if (isa<CXXMethodDecl>(VarDC) &&18223cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {18224ContextKind = 2;18225} else if (isa<FunctionDecl>(VarDC)) {18226ContextKind = 0;18227} else if (isa<BlockDecl>(VarDC)) {18228ContextKind = 1;18229}1823018231S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)18232<< var << ValueKind << ContextKind << VarDC;18233S.Diag(var->getLocation(), diag::note_entity_declared_at)18234<< var;1823518236// FIXME: Add additional diagnostic info about class etc. which prevents18237// capture.18238}1823918240static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,18241ValueDecl *Var,18242bool &SubCapturesAreNested,18243QualType &CaptureType,18244QualType &DeclRefType) {18245// Check whether we've already captured it.18246if (CSI->CaptureMap.count(Var)) {18247// If we found a capture, any subcaptures are nested.18248SubCapturesAreNested = true;1824918250// Retrieve the capture type for this variable.18251CaptureType = CSI->getCapture(Var).getCaptureType();1825218253// Compute the type of an expression that refers to this variable.18254DeclRefType = CaptureType.getNonReferenceType();1825518256// Similarly to mutable captures in lambda, all the OpenMP captures by copy18257// are mutable in the sense that user can change their value - they are18258// private instances of the captured declarations.18259const Capture &Cap = CSI->getCapture(Var);18260if (Cap.isCopyCapture() &&18261!(isa<LambdaScopeInfo>(CSI) &&18262!cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&18263!(isa<CapturedRegionScopeInfo>(CSI) &&18264cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))18265DeclRefType.addConst();18266return true;18267}18268return false;18269}1827018271// Only block literals, captured statements, and lambda expressions can18272// capture; other scopes don't work.18273static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,18274ValueDecl *Var,18275SourceLocation Loc,18276const bool Diagnose,18277Sema &S) {18278if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))18279return getLambdaAwareParentOfDeclContext(DC);1828018281VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();18282if (Underlying) {18283if (Underlying->hasLocalStorage() && Diagnose)18284diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);18285}18286return nullptr;18287}1828818289// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture18290// certain types of variables (unnamed, variably modified types etc.)18291// so check for eligibility.18292static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,18293SourceLocation Loc, const bool Diagnose,18294Sema &S) {1829518296assert((isa<VarDecl, BindingDecl>(Var)) &&18297"Only variables and structured bindings can be captured");1829818299bool IsBlock = isa<BlockScopeInfo>(CSI);18300bool IsLambda = isa<LambdaScopeInfo>(CSI);1830118302// Lambdas are not allowed to capture unnamed variables18303// (e.g. anonymous unions).18304// FIXME: The C++11 rule don't actually state this explicitly, but I'm18305// assuming that's the intent.18306if (IsLambda && !Var->getDeclName()) {18307if (Diagnose) {18308S.Diag(Loc, diag::err_lambda_capture_anonymous_var);18309S.Diag(Var->getLocation(), diag::note_declared_at);18310}18311return false;18312}1831318314// Prohibit variably-modified types in blocks; they're difficult to deal with.18315if (Var->getType()->isVariablyModifiedType() && IsBlock) {18316if (Diagnose) {18317S.Diag(Loc, diag::err_ref_vm_type);18318S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;18319}18320return false;18321}18322// Prohibit structs with flexible array members too.18323// We cannot capture what is in the tail end of the struct.18324if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {18325if (VTTy->getDecl()->hasFlexibleArrayMember()) {18326if (Diagnose) {18327if (IsBlock)18328S.Diag(Loc, diag::err_ref_flexarray_type);18329else18330S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;18331S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;18332}18333return false;18334}18335}18336const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();18337// Lambdas and captured statements are not allowed to capture __block18338// variables; they don't support the expected semantics.18339if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {18340if (Diagnose) {18341S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;18342S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;18343}18344return false;18345}18346// OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks18347if (S.getLangOpts().OpenCL && IsBlock &&18348Var->getType()->isBlockPointerType()) {18349if (Diagnose)18350S.Diag(Loc, diag::err_opencl_block_ref_block);18351return false;18352}1835318354if (isa<BindingDecl>(Var)) {18355if (!IsLambda || !S.getLangOpts().CPlusPlus) {18356if (Diagnose)18357diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);18358return false;18359} else if (Diagnose && S.getLangOpts().CPlusPlus) {18360S.Diag(Loc, S.LangOpts.CPlusPlus2018361? diag::warn_cxx17_compat_capture_binding18362: diag::ext_capture_binding)18363<< Var;18364S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;18365}18366}1836718368return true;18369}1837018371// Returns true if the capture by block was successful.18372static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,18373SourceLocation Loc, const bool BuildAndDiagnose,18374QualType &CaptureType, QualType &DeclRefType,18375const bool Nested, Sema &S, bool Invalid) {18376bool ByRef = false;1837718378// Blocks are not allowed to capture arrays, excepting OpenCL.18379// OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference18380// (decayed to pointers).18381if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {18382if (BuildAndDiagnose) {18383S.Diag(Loc, diag::err_ref_array_type);18384S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;18385Invalid = true;18386} else {18387return false;18388}18389}1839018391// Forbid the block-capture of autoreleasing variables.18392if (!Invalid &&18393CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {18394if (BuildAndDiagnose) {18395S.Diag(Loc, diag::err_arc_autoreleasing_capture)18396<< /*block*/ 0;18397S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;18398Invalid = true;18399} else {18400return false;18401}18402}1840318404// Warn about implicitly autoreleasing indirect parameters captured by blocks.18405if (const auto *PT = CaptureType->getAs<PointerType>()) {18406QualType PointeeTy = PT->getPointeeType();1840718408if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&18409PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&18410!S.Context.hasDirectOwnershipQualifier(PointeeTy)) {18411if (BuildAndDiagnose) {18412SourceLocation VarLoc = Var->getLocation();18413S.Diag(Loc, diag::warn_block_capture_autoreleasing);18414S.Diag(VarLoc, diag::note_declare_parameter_strong);18415}18416}18417}1841818419const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();18420if (HasBlocksAttr || CaptureType->isReferenceType() ||18421(S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {18422// Block capture by reference does not change the capture or18423// declaration reference types.18424ByRef = true;18425} else {18426// Block capture by copy introduces 'const'.18427CaptureType = CaptureType.getNonReferenceType().withConst();18428DeclRefType = CaptureType;18429}1843018431// Actually capture the variable.18432if (BuildAndDiagnose)18433BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),18434CaptureType, Invalid);1843518436return !Invalid;18437}1843818439/// Capture the given variable in the captured region.18440static bool captureInCapturedRegion(18441CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,18442const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,18443const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,18444bool IsTopScope, Sema &S, bool Invalid) {18445// By default, capture variables by reference.18446bool ByRef = true;18447if (IsTopScope && Kind != Sema::TryCapture_Implicit) {18448ByRef = (Kind == Sema::TryCapture_ExplicitByRef);18449} else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {18450// Using an LValue reference type is consistent with Lambdas (see below).18451if (S.OpenMP().isOpenMPCapturedDecl(Var)) {18452bool HasConst = DeclRefType.isConstQualified();18453DeclRefType = DeclRefType.getUnqualifiedType();18454// Don't lose diagnostics about assignments to const.18455if (HasConst)18456DeclRefType.addConst();18457}18458// Do not capture firstprivates in tasks.18459if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,18460RSI->OpenMPCaptureLevel) != OMPC_unknown)18461return true;18462ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,18463RSI->OpenMPCaptureLevel);18464}1846518466if (ByRef)18467CaptureType = S.Context.getLValueReferenceType(DeclRefType);18468else18469CaptureType = DeclRefType;1847018471// Actually capture the variable.18472if (BuildAndDiagnose)18473RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,18474Loc, SourceLocation(), CaptureType, Invalid);1847518476return !Invalid;18477}1847818479/// Capture the given variable in the lambda.18480static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,18481SourceLocation Loc, const bool BuildAndDiagnose,18482QualType &CaptureType, QualType &DeclRefType,18483const bool RefersToCapturedVariable,18484const Sema::TryCaptureKind Kind,18485SourceLocation EllipsisLoc, const bool IsTopScope,18486Sema &S, bool Invalid) {18487// Determine whether we are capturing by reference or by value.18488bool ByRef = false;18489if (IsTopScope && Kind != Sema::TryCapture_Implicit) {18490ByRef = (Kind == Sema::TryCapture_ExplicitByRef);18491} else {18492ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);18493}1849418495if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&18496CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {18497S.Diag(Loc, diag::err_wasm_ca_reference) << 0;18498Invalid = true;18499}1850018501// Compute the type of the field that will capture this variable.18502if (ByRef) {18503// C++11 [expr.prim.lambda]p15:18504// An entity is captured by reference if it is implicitly or18505// explicitly captured but not captured by copy. It is18506// unspecified whether additional unnamed non-static data18507// members are declared in the closure type for entities18508// captured by reference.18509//18510// FIXME: It is not clear whether we want to build an lvalue reference18511// to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears18512// to do the former, while EDG does the latter. Core issue 1249 will18513// clarify, but for now we follow GCC because it's a more permissive and18514// easily defensible position.18515CaptureType = S.Context.getLValueReferenceType(DeclRefType);18516} else {18517// C++11 [expr.prim.lambda]p14:18518// For each entity captured by copy, an unnamed non-static18519// data member is declared in the closure type. The18520// declaration order of these members is unspecified. The type18521// of such a data member is the type of the corresponding18522// captured entity if the entity is not a reference to an18523// object, or the referenced type otherwise. [Note: If the18524// captured entity is a reference to a function, the18525// corresponding data member is also a reference to a18526// function. - end note ]18527if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){18528if (!RefType->getPointeeType()->isFunctionType())18529CaptureType = RefType->getPointeeType();18530}1853118532// Forbid the lambda copy-capture of autoreleasing variables.18533if (!Invalid &&18534CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {18535if (BuildAndDiagnose) {18536S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;18537S.Diag(Var->getLocation(), diag::note_previous_decl)18538<< Var->getDeclName();18539Invalid = true;18540} else {18541return false;18542}18543}1854418545// Make sure that by-copy captures are of a complete and non-abstract type.18546if (!Invalid && BuildAndDiagnose) {18547if (!CaptureType->isDependentType() &&18548S.RequireCompleteSizedType(18549Loc, CaptureType,18550diag::err_capture_of_incomplete_or_sizeless_type,18551Var->getDeclName()))18552Invalid = true;18553else if (S.RequireNonAbstractType(Loc, CaptureType,18554diag::err_capture_of_abstract_type))18555Invalid = true;18556}18557}1855818559// Compute the type of a reference to this captured variable.18560if (ByRef)18561DeclRefType = CaptureType.getNonReferenceType();18562else {18563// C++ [expr.prim.lambda]p5:18564// The closure type for a lambda-expression has a public inline18565// function call operator [...]. This function call operator is18566// declared const (9.3.1) if and only if the lambda-expression's18567// parameter-declaration-clause is not followed by mutable.18568DeclRefType = CaptureType.getNonReferenceType();18569bool Const = LSI->lambdaCaptureShouldBeConst();18570if (Const && !CaptureType->isReferenceType())18571DeclRefType.addConst();18572}1857318574// Add the capture.18575if (BuildAndDiagnose)18576LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,18577Loc, EllipsisLoc, CaptureType, Invalid);1857818579return !Invalid;18580}1858118582static bool canCaptureVariableByCopy(ValueDecl *Var,18583const ASTContext &Context) {18584// Offer a Copy fix even if the type is dependent.18585if (Var->getType()->isDependentType())18586return true;18587QualType T = Var->getType().getNonReferenceType();18588if (T.isTriviallyCopyableType(Context))18589return true;18590if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {1859118592if (!(RD = RD->getDefinition()))18593return false;18594if (RD->hasSimpleCopyConstructor())18595return true;18596if (RD->hasUserDeclaredCopyConstructor())18597for (CXXConstructorDecl *Ctor : RD->ctors())18598if (Ctor->isCopyConstructor())18599return !Ctor->isDeleted();18600}18601return false;18602}1860318604/// Create up to 4 fix-its for explicit reference and value capture of \p Var or18605/// default capture. Fixes may be omitted if they aren't allowed by the18606/// standard, for example we can't emit a default copy capture fix-it if we18607/// already explicitly copy capture capture another variable.18608static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,18609ValueDecl *Var) {18610assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);18611// Don't offer Capture by copy of default capture by copy fixes if Var is18612// known not to be copy constructible.18613bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());1861418615SmallString<32> FixBuffer;18616StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";18617if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {18618SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();18619if (ShouldOfferCopyFix) {18620// Offer fixes to insert an explicit capture for the variable.18621// [] -> [VarName]18622// [OtherCapture] -> [OtherCapture, VarName]18623FixBuffer.assign({Separator, Var->getName()});18624Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)18625<< Var << /*value*/ 018626<< FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);18627}18628// As above but capture by reference.18629FixBuffer.assign({Separator, "&", Var->getName()});18630Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)18631<< Var << /*reference*/ 118632<< FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);18633}1863418635// Only try to offer default capture if there are no captures excluding this18636// and init captures.18637// [this]: OK.18638// [X = Y]: OK.18639// [&A, &B]: Don't offer.18640// [A, B]: Don't offer.18641if (llvm::any_of(LSI->Captures, [](Capture &C) {18642return !C.isThisCapture() && !C.isInitCapture();18643}))18644return;1864518646// The default capture specifiers, '=' or '&', must appear first in the18647// capture body.18648SourceLocation DefaultInsertLoc =18649LSI->IntroducerRange.getBegin().getLocWithOffset(1);1865018651if (ShouldOfferCopyFix) {18652bool CanDefaultCopyCapture = true;18653// [=, *this] OK since c++1718654// [=, this] OK since c++2018655if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)18656CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus1718657? LSI->getCXXThisCapture().isCopyCapture()18658: false;18659// We can't use default capture by copy if any captures already specified18660// capture by copy.18661if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {18662return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();18663})) {18664FixBuffer.assign({"=", Separator});18665Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)18666<< /*value*/ 018667<< FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);18668}18669}1867018671// We can't use default capture by reference if any captures already specified18672// capture by reference.18673if (llvm::none_of(LSI->Captures, [](Capture &C) {18674return !C.isInitCapture() && C.isReferenceCapture() &&18675!C.isThisCapture();18676})) {18677FixBuffer.assign({"&", Separator});18678Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)18679<< /*reference*/ 118680<< FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);18681}18682}1868318684bool Sema::tryCaptureVariable(18685ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,18686SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,18687QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {18688// An init-capture is notionally from the context surrounding its18689// declaration, but its parent DC is the lambda class.18690DeclContext *VarDC = Var->getDeclContext();18691DeclContext *DC = CurContext;1869218693// Skip past RequiresExprBodys because they don't constitute function scopes.18694while (DC->isRequiresExprBody())18695DC = DC->getParent();1869618697// tryCaptureVariable is called every time a DeclRef is formed,18698// it can therefore have non-negigible impact on performances.18699// For local variables and when there is no capturing scope,18700// we can bailout early.18701if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))18702return true;1870318704// Exception: Function parameters are not tied to the function's DeclContext18705// until we enter the function definition. Capturing them anyway would result18706// in an out-of-bounds error while traversing DC and its parents.18707if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())18708return true;1870918710const auto *VD = dyn_cast<VarDecl>(Var);18711if (VD) {18712if (VD->isInitCapture())18713VarDC = VarDC->getParent();18714} else {18715VD = Var->getPotentiallyDecomposedVarDecl();18716}18717assert(VD && "Cannot capture a null variable");1871818719const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt18720? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;18721// We need to sync up the Declaration Context with the18722// FunctionScopeIndexToStopAt18723if (FunctionScopeIndexToStopAt) {18724unsigned FSIndex = FunctionScopes.size() - 1;18725while (FSIndex != MaxFunctionScopesIndex) {18726DC = getLambdaAwareParentOfDeclContext(DC);18727--FSIndex;18728}18729}1873018731// Capture global variables if it is required to use private copy of this18732// variable.18733bool IsGlobal = !VD->hasLocalStorage();18734if (IsGlobal && !(LangOpts.OpenMP &&18735OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,18736MaxFunctionScopesIndex)))18737return true;1873818739if (isa<VarDecl>(Var))18740Var = cast<VarDecl>(Var->getCanonicalDecl());1874118742// Walk up the stack to determine whether we can capture the variable,18743// performing the "simple" checks that don't depend on type. We stop when18744// we've either hit the declared scope of the variable or find an existing18745// capture of that variable. We start from the innermost capturing-entity18746// (the DC) and ensure that all intervening capturing-entities18747// (blocks/lambdas etc.) between the innermost capturer and the variable`s18748// declcontext can either capture the variable or have already captured18749// the variable.18750CaptureType = Var->getType();18751DeclRefType = CaptureType.getNonReferenceType();18752bool Nested = false;18753bool Explicit = (Kind != TryCapture_Implicit);18754unsigned FunctionScopesIndex = MaxFunctionScopesIndex;18755do {1875618757LambdaScopeInfo *LSI = nullptr;18758if (!FunctionScopes.empty())18759LSI = dyn_cast_or_null<LambdaScopeInfo>(18760FunctionScopes[FunctionScopesIndex]);1876118762bool IsInScopeDeclarationContext =18763!LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;1876418765if (LSI && !LSI->AfterParameterList) {18766// This allows capturing parameters from a default value which does not18767// seems correct18768if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())18769return true;18770}18771// If the variable is declared in the current context, there is no need to18772// capture it.18773if (IsInScopeDeclarationContext &&18774FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)18775return true;1877618777// Only block literals, captured statements, and lambda expressions can18778// capture; other scopes don't work.18779DeclContext *ParentDC =18780!IsInScopeDeclarationContext18781? DC->getParent()18782: getParentOfCapturingContextOrNull(DC, Var, ExprLoc,18783BuildAndDiagnose, *this);18784// We need to check for the parent *first* because, if we *have*18785// private-captured a global variable, we need to recursively capture it in18786// intermediate blocks, lambdas, etc.18787if (!ParentDC) {18788if (IsGlobal) {18789FunctionScopesIndex = MaxFunctionScopesIndex - 1;18790break;18791}18792return true;18793}1879418795FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];18796CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);1879718798// Check whether we've already captured it.18799if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,18800DeclRefType)) {18801CSI->getCapture(Var).markUsed(BuildAndDiagnose);18802break;18803}1880418805// When evaluating some attributes (like enable_if) we might refer to a18806// function parameter appertaining to the same declaration as that18807// attribute.18808if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);18809Parm && Parm->getDeclContext() == DC)18810return true;1881118812// If we are instantiating a generic lambda call operator body,18813// we do not want to capture new variables. What was captured18814// during either a lambdas transformation or initial parsing18815// should be used.18816if (isGenericLambdaCallOperatorSpecialization(DC)) {18817if (BuildAndDiagnose) {18818LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);18819if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {18820Diag(ExprLoc, diag::err_lambda_impcap) << Var;18821Diag(Var->getLocation(), diag::note_previous_decl) << Var;18822Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);18823buildLambdaCaptureFixit(*this, LSI, Var);18824} else18825diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);18826}18827return true;18828}1882918830// Try to capture variable-length arrays types.18831if (Var->getType()->isVariablyModifiedType()) {18832// We're going to walk down into the type and look for VLA18833// expressions.18834QualType QTy = Var->getType();18835if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))18836QTy = PVD->getOriginalType();18837captureVariablyModifiedType(Context, QTy, CSI);18838}1883918840if (getLangOpts().OpenMP) {18841if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {18842// OpenMP private variables should not be captured in outer scope, so18843// just break here. Similarly, global variables that are captured in a18844// target region should not be captured outside the scope of the region.18845if (RSI->CapRegionKind == CR_OpenMP) {18846// FIXME: We should support capturing structured bindings in OpenMP.18847if (isa<BindingDecl>(Var)) {18848if (BuildAndDiagnose) {18849Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;18850Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;18851}18852return true;18853}18854OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(18855Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);18856// If the variable is private (i.e. not captured) and has variably18857// modified type, we still need to capture the type for correct18858// codegen in all regions, associated with the construct. Currently,18859// it is captured in the innermost captured region only.18860if (IsOpenMPPrivateDecl != OMPC_unknown &&18861Var->getType()->isVariablyModifiedType()) {18862QualType QTy = Var->getType();18863if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))18864QTy = PVD->getOriginalType();18865for (int I = 1,18866E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);18867I < E; ++I) {18868auto *OuterRSI = cast<CapturedRegionScopeInfo>(18869FunctionScopes[FunctionScopesIndex - I]);18870assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&18871"Wrong number of captured regions associated with the "18872"OpenMP construct.");18873captureVariablyModifiedType(Context, QTy, OuterRSI);18874}18875}18876bool IsTargetCap =18877IsOpenMPPrivateDecl != OMPC_private &&18878OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,18879RSI->OpenMPCaptureLevel);18880// Do not capture global if it is not privatized in outer regions.18881bool IsGlobalCap =18882IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(18883Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);1888418885// When we detect target captures we are looking from inside the18886// target region, therefore we need to propagate the capture from the18887// enclosing region. Therefore, the capture is not initially nested.18888if (IsTargetCap)18889OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,18890RSI->OpenMPLevel);1889118892if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||18893(IsGlobal && !IsGlobalCap)) {18894Nested = !IsTargetCap;18895bool HasConst = DeclRefType.isConstQualified();18896DeclRefType = DeclRefType.getUnqualifiedType();18897// Don't lose diagnostics about assignments to const.18898if (HasConst)18899DeclRefType.addConst();18900CaptureType = Context.getLValueReferenceType(DeclRefType);18901break;18902}18903}18904}18905}18906if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {18907// No capture-default, and this is not an explicit capture18908// so cannot capture this variable.18909if (BuildAndDiagnose) {18910Diag(ExprLoc, diag::err_lambda_impcap) << Var;18911Diag(Var->getLocation(), diag::note_previous_decl) << Var;18912auto *LSI = cast<LambdaScopeInfo>(CSI);18913if (LSI->Lambda) {18914Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);18915buildLambdaCaptureFixit(*this, LSI, Var);18916}18917// FIXME: If we error out because an outer lambda can not implicitly18918// capture a variable that an inner lambda explicitly captures, we18919// should have the inner lambda do the explicit capture - because18920// it makes for cleaner diagnostics later. This would purely be done18921// so that the diagnostic does not misleadingly claim that a variable18922// can not be captured by a lambda implicitly even though it is captured18923// explicitly. Suggestion:18924// - create const bool VariableCaptureWasInitiallyExplicit = Explicit18925// at the function head18926// - cache the StartingDeclContext - this must be a lambda18927// - captureInLambda in the innermost lambda the variable.18928}18929return true;18930}18931Explicit = false;18932FunctionScopesIndex--;18933if (IsInScopeDeclarationContext)18934DC = ParentDC;18935} while (!VarDC->Equals(DC));1893618937// Walk back down the scope stack, (e.g. from outer lambda to inner lambda)18938// computing the type of the capture at each step, checking type-specific18939// requirements, and adding captures if requested.18940// If the variable had already been captured previously, we start capturing18941// at the lambda nested within that one.18942bool Invalid = false;18943for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;18944++I) {18945CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);1894618947// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture18948// certain types of variables (unnamed, variably modified types etc.)18949// so check for eligibility.18950if (!Invalid)18951Invalid =18952!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);1895318954// After encountering an error, if we're actually supposed to capture, keep18955// capturing in nested contexts to suppress any follow-on diagnostics.18956if (Invalid && !BuildAndDiagnose)18957return true;1895818959if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {18960Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,18961DeclRefType, Nested, *this, Invalid);18962Nested = true;18963} else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {18964Invalid = !captureInCapturedRegion(18965RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,18966Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);18967Nested = true;18968} else {18969LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);18970Invalid =18971!captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,18972DeclRefType, Nested, Kind, EllipsisLoc,18973/*IsTopScope*/ I == N - 1, *this, Invalid);18974Nested = true;18975}1897618977if (Invalid && !BuildAndDiagnose)18978return true;18979}18980return Invalid;18981}1898218983bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,18984TryCaptureKind Kind, SourceLocation EllipsisLoc) {18985QualType CaptureType;18986QualType DeclRefType;18987return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,18988/*BuildAndDiagnose=*/true, CaptureType,18989DeclRefType, nullptr);18990}1899118992bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {18993QualType CaptureType;18994QualType DeclRefType;18995return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),18996/*BuildAndDiagnose=*/false, CaptureType,18997DeclRefType, nullptr);18998}1899919000QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {19001QualType CaptureType;19002QualType DeclRefType;1900319004// Determine whether we can capture this variable.19005if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),19006/*BuildAndDiagnose=*/false, CaptureType,19007DeclRefType, nullptr))19008return QualType();1900919010return DeclRefType;19011}1901219013namespace {19014// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.19015// The produced TemplateArgumentListInfo* points to data stored within this19016// object, so should only be used in contexts where the pointer will not be19017// used after the CopiedTemplateArgs object is destroyed.19018class CopiedTemplateArgs {19019bool HasArgs;19020TemplateArgumentListInfo TemplateArgStorage;19021public:19022template<typename RefExpr>19023CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {19024if (HasArgs)19025E->copyTemplateArgumentsInto(TemplateArgStorage);19026}19027operator TemplateArgumentListInfo*()19028#ifdef __has_cpp_attribute19029#if __has_cpp_attribute(clang::lifetimebound)19030[[clang::lifetimebound]]19031#endif19032#endif19033{19034return HasArgs ? &TemplateArgStorage : nullptr;19035}19036};19037}1903819039/// Walk the set of potential results of an expression and mark them all as19040/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.19041///19042/// \return A new expression if we found any potential results, ExprEmpty() if19043/// not, and ExprError() if we diagnosed an error.19044static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,19045NonOdrUseReason NOUR) {19046// Per C++11 [basic.def.odr], a variable is odr-used "unless it is19047// an object that satisfies the requirements for appearing in a19048// constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)19049// is immediately applied." This function handles the lvalue-to-rvalue19050// conversion part.19051//19052// If we encounter a node that claims to be an odr-use but shouldn't be, we19053// transform it into the relevant kind of non-odr-use node and rebuild the19054// tree of nodes leading to it.19055//19056// This is a mini-TreeTransform that only transforms a restricted subset of19057// nodes (and only certain operands of them).1905819059// Rebuild a subexpression.19060auto Rebuild = [&](Expr *Sub) {19061return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);19062};1906319064// Check whether a potential result satisfies the requirements of NOUR.19065auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {19066// Any entity other than a VarDecl is always odr-used whenever it's named19067// in a potentially-evaluated expression.19068auto *VD = dyn_cast<VarDecl>(D);19069if (!VD)19070return true;1907119072// C++2a [basic.def.odr]p4:19073// A variable x whose name appears as a potentially-evalauted expression19074// e is odr-used by e unless19075// -- x is a reference that is usable in constant expressions, or19076// -- x is a variable of non-reference type that is usable in constant19077// expressions and has no mutable subobjects, and e is an element of19078// the set of potential results of an expression of19079// non-volatile-qualified non-class type to which the lvalue-to-rvalue19080// conversion is applied, or19081// -- x is a variable of non-reference type, and e is an element of the19082// set of potential results of a discarded-value expression to which19083// the lvalue-to-rvalue conversion is not applied19084//19085// We check the first bullet and the "potentially-evaluated" condition in19086// BuildDeclRefExpr. We check the type requirements in the second bullet19087// in CheckLValueToRValueConversionOperand below.19088switch (NOUR) {19089case NOUR_None:19090case NOUR_Unevaluated:19091llvm_unreachable("unexpected non-odr-use-reason");1909219093case NOUR_Constant:19094// Constant references were handled when they were built.19095if (VD->getType()->isReferenceType())19096return true;19097if (auto *RD = VD->getType()->getAsCXXRecordDecl())19098if (RD->hasMutableFields())19099return true;19100if (!VD->isUsableInConstantExpressions(S.Context))19101return true;19102break;1910319104case NOUR_Discarded:19105if (VD->getType()->isReferenceType())19106return true;19107break;19108}19109return false;19110};1911119112// Mark that this expression does not constitute an odr-use.19113auto MarkNotOdrUsed = [&] {19114S.MaybeODRUseExprs.remove(E);19115if (LambdaScopeInfo *LSI = S.getCurLambda())19116LSI->markVariableExprAsNonODRUsed(E);19117};1911819119// C++2a [basic.def.odr]p2:19120// The set of potential results of an expression e is defined as follows:19121switch (E->getStmtClass()) {19122// -- If e is an id-expression, ...19123case Expr::DeclRefExprClass: {19124auto *DRE = cast<DeclRefExpr>(E);19125if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))19126break;1912719128// Rebuild as a non-odr-use DeclRefExpr.19129MarkNotOdrUsed();19130return DeclRefExpr::Create(19131S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),19132DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),19133DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),19134DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);19135}1913619137case Expr::FunctionParmPackExprClass: {19138auto *FPPE = cast<FunctionParmPackExpr>(E);19139// If any of the declarations in the pack is odr-used, then the expression19140// as a whole constitutes an odr-use.19141for (VarDecl *D : *FPPE)19142if (IsPotentialResultOdrUsed(D))19143return ExprEmpty();1914419145// FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,19146// nothing cares about whether we marked this as an odr-use, but it might19147// be useful for non-compiler tools.19148MarkNotOdrUsed();19149break;19150}1915119152// -- If e is a subscripting operation with an array operand...19153case Expr::ArraySubscriptExprClass: {19154auto *ASE = cast<ArraySubscriptExpr>(E);19155Expr *OldBase = ASE->getBase()->IgnoreImplicit();19156if (!OldBase->getType()->isArrayType())19157break;19158ExprResult Base = Rebuild(OldBase);19159if (!Base.isUsable())19160return Base;19161Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();19162Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();19163SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.19164return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,19165ASE->getRBracketLoc());19166}1916719168case Expr::MemberExprClass: {19169auto *ME = cast<MemberExpr>(E);19170// -- If e is a class member access expression [...] naming a non-static19171// data member...19172if (isa<FieldDecl>(ME->getMemberDecl())) {19173ExprResult Base = Rebuild(ME->getBase());19174if (!Base.isUsable())19175return Base;19176return MemberExpr::Create(19177S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),19178ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),19179ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),19180CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),19181ME->getObjectKind(), ME->isNonOdrUse());19182}1918319184if (ME->getMemberDecl()->isCXXInstanceMember())19185break;1918619187// -- If e is a class member access expression naming a static data member,19188// ...19189if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))19190break;1919119192// Rebuild as a non-odr-use MemberExpr.19193MarkNotOdrUsed();19194return MemberExpr::Create(19195S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),19196ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),19197ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),19198ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);19199}1920019201case Expr::BinaryOperatorClass: {19202auto *BO = cast<BinaryOperator>(E);19203Expr *LHS = BO->getLHS();19204Expr *RHS = BO->getRHS();19205// -- If e is a pointer-to-member expression of the form e1 .* e2 ...19206if (BO->getOpcode() == BO_PtrMemD) {19207ExprResult Sub = Rebuild(LHS);19208if (!Sub.isUsable())19209return Sub;19210BO->setLHS(Sub.get());19211// -- If e is a comma expression, ...19212} else if (BO->getOpcode() == BO_Comma) {19213ExprResult Sub = Rebuild(RHS);19214if (!Sub.isUsable())19215return Sub;19216BO->setRHS(Sub.get());19217} else {19218break;19219}19220return ExprResult(BO);19221}1922219223// -- If e has the form (e1)...19224case Expr::ParenExprClass: {19225auto *PE = cast<ParenExpr>(E);19226ExprResult Sub = Rebuild(PE->getSubExpr());19227if (!Sub.isUsable())19228return Sub;19229return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());19230}1923119232// -- If e is a glvalue conditional expression, ...19233// We don't apply this to a binary conditional operator. FIXME: Should we?19234case Expr::ConditionalOperatorClass: {19235auto *CO = cast<ConditionalOperator>(E);19236ExprResult LHS = Rebuild(CO->getLHS());19237if (LHS.isInvalid())19238return ExprError();19239ExprResult RHS = Rebuild(CO->getRHS());19240if (RHS.isInvalid())19241return ExprError();19242if (!LHS.isUsable() && !RHS.isUsable())19243return ExprEmpty();19244if (!LHS.isUsable())19245LHS = CO->getLHS();19246if (!RHS.isUsable())19247RHS = CO->getRHS();19248return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),19249CO->getCond(), LHS.get(), RHS.get());19250}1925119252// [Clang extension]19253// -- If e has the form __extension__ e1...19254case Expr::UnaryOperatorClass: {19255auto *UO = cast<UnaryOperator>(E);19256if (UO->getOpcode() != UO_Extension)19257break;19258ExprResult Sub = Rebuild(UO->getSubExpr());19259if (!Sub.isUsable())19260return Sub;19261return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,19262Sub.get());19263}1926419265// [Clang extension]19266// -- If e has the form _Generic(...), the set of potential results is the19267// union of the sets of potential results of the associated expressions.19268case Expr::GenericSelectionExprClass: {19269auto *GSE = cast<GenericSelectionExpr>(E);1927019271SmallVector<Expr *, 4> AssocExprs;19272bool AnyChanged = false;19273for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {19274ExprResult AssocExpr = Rebuild(OrigAssocExpr);19275if (AssocExpr.isInvalid())19276return ExprError();19277if (AssocExpr.isUsable()) {19278AssocExprs.push_back(AssocExpr.get());19279AnyChanged = true;19280} else {19281AssocExprs.push_back(OrigAssocExpr);19282}19283}1928419285void *ExOrTy = nullptr;19286bool IsExpr = GSE->isExprPredicate();19287if (IsExpr)19288ExOrTy = GSE->getControllingExpr();19289else19290ExOrTy = GSE->getControllingType();19291return AnyChanged ? S.CreateGenericSelectionExpr(19292GSE->getGenericLoc(), GSE->getDefaultLoc(),19293GSE->getRParenLoc(), IsExpr, ExOrTy,19294GSE->getAssocTypeSourceInfos(), AssocExprs)19295: ExprEmpty();19296}1929719298// [Clang extension]19299// -- If e has the form __builtin_choose_expr(...), the set of potential19300// results is the union of the sets of potential results of the19301// second and third subexpressions.19302case Expr::ChooseExprClass: {19303auto *CE = cast<ChooseExpr>(E);1930419305ExprResult LHS = Rebuild(CE->getLHS());19306if (LHS.isInvalid())19307return ExprError();1930819309ExprResult RHS = Rebuild(CE->getLHS());19310if (RHS.isInvalid())19311return ExprError();1931219313if (!LHS.get() && !RHS.get())19314return ExprEmpty();19315if (!LHS.isUsable())19316LHS = CE->getLHS();19317if (!RHS.isUsable())19318RHS = CE->getRHS();1931919320return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),19321RHS.get(), CE->getRParenLoc());19322}1932319324// Step through non-syntactic nodes.19325case Expr::ConstantExprClass: {19326auto *CE = cast<ConstantExpr>(E);19327ExprResult Sub = Rebuild(CE->getSubExpr());19328if (!Sub.isUsable())19329return Sub;19330return ConstantExpr::Create(S.Context, Sub.get());19331}1933219333// We could mostly rely on the recursive rebuilding to rebuild implicit19334// casts, but not at the top level, so rebuild them here.19335case Expr::ImplicitCastExprClass: {19336auto *ICE = cast<ImplicitCastExpr>(E);19337// Only step through the narrow set of cast kinds we expect to encounter.19338// Anything else suggests we've left the region in which potential results19339// can be found.19340switch (ICE->getCastKind()) {19341case CK_NoOp:19342case CK_DerivedToBase:19343case CK_UncheckedDerivedToBase: {19344ExprResult Sub = Rebuild(ICE->getSubExpr());19345if (!Sub.isUsable())19346return Sub;19347CXXCastPath Path(ICE->path());19348return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),19349ICE->getValueKind(), &Path);19350}1935119352default:19353break;19354}19355break;19356}1935719358default:19359break;19360}1936119362// Can't traverse through this node. Nothing to do.19363return ExprEmpty();19364}1936519366ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {19367// Check whether the operand is or contains an object of non-trivial C union19368// type.19369if (E->getType().isVolatileQualified() &&19370(E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||19371E->getType().hasNonTrivialToPrimitiveCopyCUnion()))19372checkNonTrivialCUnion(E->getType(), E->getExprLoc(),19373Sema::NTCUC_LValueToRValueVolatile,19374NTCUK_Destruct|NTCUK_Copy);1937519376// C++2a [basic.def.odr]p4:19377// [...] an expression of non-volatile-qualified non-class type to which19378// the lvalue-to-rvalue conversion is applied [...]19379if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())19380return E;1938119382ExprResult Result =19383rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);19384if (Result.isInvalid())19385return ExprError();19386return Result.get() ? Result : E;19387}1938819389ExprResult Sema::ActOnConstantExpression(ExprResult Res) {19390Res = CorrectDelayedTyposInExpr(Res);1939119392if (!Res.isUsable())19393return Res;1939419395// If a constant-expression is a reference to a variable where we delay19396// deciding whether it is an odr-use, just assume we will apply the19397// lvalue-to-rvalue conversion. In the one case where this doesn't happen19398// (a non-type template argument), we have special handling anyway.19399return CheckLValueToRValueConversionOperand(Res.get());19400}1940119402void Sema::CleanupVarDeclMarking() {19403// Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive19404// call.19405MaybeODRUseExprSet LocalMaybeODRUseExprs;19406std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);1940719408for (Expr *E : LocalMaybeODRUseExprs) {19409if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {19410MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),19411DRE->getLocation(), *this);19412} else if (auto *ME = dyn_cast<MemberExpr>(E)) {19413MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),19414*this);19415} else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {19416for (VarDecl *VD : *FP)19417MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);19418} else {19419llvm_unreachable("Unexpected expression");19420}19421}1942219423assert(MaybeODRUseExprs.empty() &&19424"MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");19425}1942619427static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,19428ValueDecl *Var, Expr *E) {19429VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();19430if (!VD)19431return;1943219433const bool RefersToEnclosingScope =19434(SemaRef.CurContext != VD->getDeclContext() &&19435VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());19436if (RefersToEnclosingScope) {19437LambdaScopeInfo *const LSI =19438SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);19439if (LSI && (!LSI->CallOperator ||19440!LSI->CallOperator->Encloses(Var->getDeclContext()))) {19441// If a variable could potentially be odr-used, defer marking it so19442// until we finish analyzing the full expression for any19443// lvalue-to-rvalue19444// or discarded value conversions that would obviate odr-use.19445// Add it to the list of potential captures that will be analyzed19446// later (ActOnFinishFullExpr) for eventual capture and odr-use marking19447// unless the variable is a reference that was initialized by a constant19448// expression (this will never need to be captured or odr-used).19449//19450// FIXME: We can simplify this a lot after implementing P0588R1.19451assert(E && "Capture variable should be used in an expression.");19452if (!Var->getType()->isReferenceType() ||19453!VD->isUsableInConstantExpressions(SemaRef.Context))19454LSI->addPotentialCapture(E->IgnoreParens());19455}19456}19457}1945819459static void DoMarkVarDeclReferenced(19460Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,19461llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {19462assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||19463isa<FunctionParmPackExpr>(E)) &&19464"Invalid Expr argument to DoMarkVarDeclReferenced");19465Var->setReferenced();1946619467if (Var->isInvalidDecl())19468return;1946919470auto *MSI = Var->getMemberSpecializationInfo();19471TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()19472: Var->getTemplateSpecializationKind();1947319474OdrUseContext OdrUse = isOdrUseContext(SemaRef);19475bool UsableInConstantExpr =19476Var->mightBeUsableInConstantExpressions(SemaRef.Context);1947719478if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {19479RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;19480}1948119482// C++20 [expr.const]p12:19483// A variable [...] is needed for constant evaluation if it is [...] a19484// variable whose name appears as a potentially constant evaluated19485// expression that is either a contexpr variable or is of non-volatile19486// const-qualified integral type or of reference type19487bool NeededForConstantEvaluation =19488isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;1948919490bool NeedDefinition =19491OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;1949219493assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&19494"Can't instantiate a partial template specialization.");1949519496// If this might be a member specialization of a static data member, check19497// the specialization is visible. We already did the checks for variable19498// template specializations when we created them.19499if (NeedDefinition && TSK != TSK_Undeclared &&19500!isa<VarTemplateSpecializationDecl>(Var))19501SemaRef.checkSpecializationVisibility(Loc, Var);1950219503// Perform implicit instantiation of static data members, static data member19504// templates of class templates, and variable template specializations. Delay19505// instantiations of variable templates, except for those that could be used19506// in a constant expression.19507if (NeedDefinition && isTemplateInstantiation(TSK)) {19508// Per C++17 [temp.explicit]p10, we may instantiate despite an explicit19509// instantiation declaration if a variable is usable in a constant19510// expression (among other cases).19511bool TryInstantiating =19512TSK == TSK_ImplicitInstantiation ||19513(TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);1951419515if (TryInstantiating) {19516SourceLocation PointOfInstantiation =19517MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();19518bool FirstInstantiation = PointOfInstantiation.isInvalid();19519if (FirstInstantiation) {19520PointOfInstantiation = Loc;19521if (MSI)19522MSI->setPointOfInstantiation(PointOfInstantiation);19523// FIXME: Notify listener.19524else19525Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);19526}1952719528if (UsableInConstantExpr) {19529// Do not defer instantiations of variables that could be used in a19530// constant expression.19531SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {19532SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);19533});1953419535// Re-set the member to trigger a recomputation of the dependence bits19536// for the expression.19537if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))19538DRE->setDecl(DRE->getDecl());19539else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))19540ME->setMemberDecl(ME->getMemberDecl());19541} else if (FirstInstantiation) {19542SemaRef.PendingInstantiations19543.push_back(std::make_pair(Var, PointOfInstantiation));19544} else {19545bool Inserted = false;19546for (auto &I : SemaRef.SavedPendingInstantiations) {19547auto Iter = llvm::find_if(19548I, [Var](const Sema::PendingImplicitInstantiation &P) {19549return P.first == Var;19550});19551if (Iter != I.end()) {19552SemaRef.PendingInstantiations.push_back(*Iter);19553I.erase(Iter);19554Inserted = true;19555break;19556}19557}1955819559// FIXME: For a specialization of a variable template, we don't19560// distinguish between "declaration and type implicitly instantiated"19561// and "implicit instantiation of definition requested", so we have19562// no direct way to avoid enqueueing the pending instantiation19563// multiple times.19564if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)19565SemaRef.PendingInstantiations19566.push_back(std::make_pair(Var, PointOfInstantiation));19567}19568}19569}1957019571// C++2a [basic.def.odr]p4:19572// A variable x whose name appears as a potentially-evaluated expression e19573// is odr-used by e unless19574// -- x is a reference that is usable in constant expressions19575// -- x is a variable of non-reference type that is usable in constant19576// expressions and has no mutable subobjects [FIXME], and e is an19577// element of the set of potential results of an expression of19578// non-volatile-qualified non-class type to which the lvalue-to-rvalue19579// conversion is applied19580// -- x is a variable of non-reference type, and e is an element of the set19581// of potential results of a discarded-value expression to which the19582// lvalue-to-rvalue conversion is not applied [FIXME]19583//19584// We check the first part of the second bullet here, and19585// Sema::CheckLValueToRValueConversionOperand deals with the second part.19586// FIXME: To get the third bullet right, we need to delay this even for19587// variables that are not usable in constant expressions.1958819589// If we already know this isn't an odr-use, there's nothing more to do.19590if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))19591if (DRE->isNonOdrUse())19592return;19593if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))19594if (ME->isNonOdrUse())19595return;1959619597switch (OdrUse) {19598case OdrUseContext::None:19599// In some cases, a variable may not have been marked unevaluated, if it19600// appears in a defaukt initializer.19601assert((!E || isa<FunctionParmPackExpr>(E) ||19602SemaRef.isUnevaluatedContext()) &&19603"missing non-odr-use marking for unevaluated decl ref");19604break;1960519606case OdrUseContext::FormallyOdrUsed:19607// FIXME: Ignoring formal odr-uses results in incorrect lambda capture19608// behavior.19609break;1961019611case OdrUseContext::Used:19612// If we might later find that this expression isn't actually an odr-use,19613// delay the marking.19614if (E && Var->isUsableInConstantExpressions(SemaRef.Context))19615SemaRef.MaybeODRUseExprs.insert(E);19616else19617MarkVarDeclODRUsed(Var, Loc, SemaRef);19618break;1961919620case OdrUseContext::Dependent:19621// If this is a dependent context, we don't need to mark variables as19622// odr-used, but we may still need to track them for lambda capture.19623// FIXME: Do we also need to do this inside dependent typeid expressions19624// (which are modeled as unevaluated at this point)?19625DoMarkPotentialCapture(SemaRef, Loc, Var, E);19626break;19627}19628}1962919630static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,19631BindingDecl *BD, Expr *E) {19632BD->setReferenced();1963319634if (BD->isInvalidDecl())19635return;1963619637OdrUseContext OdrUse = isOdrUseContext(SemaRef);19638if (OdrUse == OdrUseContext::Used) {19639QualType CaptureType, DeclRefType;19640SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,19641/*EllipsisLoc*/ SourceLocation(),19642/*BuildAndDiagnose*/ true, CaptureType,19643DeclRefType,19644/*FunctionScopeIndexToStopAt*/ nullptr);19645} else if (OdrUse == OdrUseContext::Dependent) {19646DoMarkPotentialCapture(SemaRef, Loc, BD, E);19647}19648}1964919650void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {19651DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);19652}1965319654// C++ [temp.dep.expr]p3:19655// An id-expression is type-dependent if it contains:19656// - an identifier associated by name lookup with an entity captured by copy19657// in a lambda-expression that has an explicit object parameter whose type19658// is dependent ([dcl.fct]),19659static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(19660Sema &SemaRef, ValueDecl *D, Expr *E) {19661auto *ID = dyn_cast<DeclRefExpr>(E);19662if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())19663return;1966419665// If any enclosing lambda with a dependent explicit object parameter either19666// explicitly captures the variable by value, or has a capture default of '='19667// and does not capture the variable by reference, then the type of the DRE19668// is dependent on the type of that lambda's explicit object parameter.19669auto IsDependent = [&]() {19670for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {19671auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);19672if (!LSI)19673continue;1967419675if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&19676LSI->AfterParameterList)19677return false;1967819679const auto *MD = LSI->CallOperator;19680if (MD->getType().isNull())19681continue;1968219683const auto *Ty = MD->getType()->getAs<FunctionProtoType>();19684if (!Ty || !MD->isExplicitObjectMemberFunction() ||19685!Ty->getParamType(0)->isDependentType())19686continue;1968719688if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {19689if (C->isCopyCapture())19690return true;19691continue;19692}1969319694if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)19695return true;19696}19697return false;19698}();1969919700ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(19701IsDependent, SemaRef.getASTContext());19702}1970319704static void19705MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,19706bool MightBeOdrUse,19707llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {19708if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())19709SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);1971019711if (VarDecl *Var = dyn_cast<VarDecl>(D)) {19712DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);19713if (SemaRef.getLangOpts().CPlusPlus)19714FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,19715Var, E);19716return;19717}1971819719if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {19720DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);19721if (SemaRef.getLangOpts().CPlusPlus)19722FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,19723Decl, E);19724return;19725}19726SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);1972719728// If this is a call to a method via a cast, also mark the method in the19729// derived class used in case codegen can devirtualize the call.19730const MemberExpr *ME = dyn_cast<MemberExpr>(E);19731if (!ME)19732return;19733CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());19734if (!MD)19735return;19736// Only attempt to devirtualize if this is truly a virtual call.19737bool IsVirtualCall = MD->isVirtual() &&19738ME->performsVirtualDispatch(SemaRef.getLangOpts());19739if (!IsVirtualCall)19740return;1974119742// If it's possible to devirtualize the call, mark the called function19743// referenced.19744CXXMethodDecl *DM = MD->getDevirtualizedMethod(19745ME->getBase(), SemaRef.getLangOpts().AppleKext);19746if (DM)19747SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);19748}1974919750void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {19751// TODO: update this with DR# once a defect report is filed.19752// C++11 defect. The address of a pure member should not be an ODR use, even19753// if it's a qualified reference.19754bool OdrUse = true;19755if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))19756if (Method->isVirtual() &&19757!Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))19758OdrUse = false;1975919760if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {19761if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&19762!isImmediateFunctionContext() &&19763!isCheckingDefaultArgumentOrInitializer() &&19764FD->isImmediateFunction() && !RebuildingImmediateInvocation &&19765!FD->isDependentContext())19766ExprEvalContexts.back().ReferenceToConsteval.insert(E);19767}19768MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,19769RefsMinusAssignments);19770}1977119772void Sema::MarkMemberReferenced(MemberExpr *E) {19773// C++11 [basic.def.odr]p2:19774// A non-overloaded function whose name appears as a potentially-evaluated19775// expression or a member of a set of candidate functions, if selected by19776// overload resolution when referred to from a potentially-evaluated19777// expression, is odr-used, unless it is a pure virtual function and its19778// name is not explicitly qualified.19779bool MightBeOdrUse = true;19780if (E->performsVirtualDispatch(getLangOpts())) {19781if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))19782if (Method->isPureVirtual())19783MightBeOdrUse = false;19784}19785SourceLocation Loc =19786E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();19787MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,19788RefsMinusAssignments);19789}1979019791void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {19792for (VarDecl *VD : *E)19793MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,19794RefsMinusAssignments);19795}1979619797/// Perform marking for a reference to an arbitrary declaration. It19798/// marks the declaration referenced, and performs odr-use checking for19799/// functions and variables. This method should not be used when building a19800/// normal expression which refers to a variable.19801void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,19802bool MightBeOdrUse) {19803if (MightBeOdrUse) {19804if (auto *VD = dyn_cast<VarDecl>(D)) {19805MarkVariableReferenced(Loc, VD);19806return;19807}19808}19809if (auto *FD = dyn_cast<FunctionDecl>(D)) {19810MarkFunctionReferenced(Loc, FD, MightBeOdrUse);19811return;19812}19813D->setReferenced();19814}1981519816namespace {19817// Mark all of the declarations used by a type as referenced.19818// FIXME: Not fully implemented yet! We need to have a better understanding19819// of when we're entering a context we should not recurse into.19820// FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to19821// TreeTransforms rebuilding the type in a new context. Rather than19822// duplicating the TreeTransform logic, we should consider reusing it here.19823// Currently that causes problems when rebuilding LambdaExprs.19824class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {19825Sema &S;19826SourceLocation Loc;1982719828public:19829typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;1983019831MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }1983219833bool TraverseTemplateArgument(const TemplateArgument &Arg);19834};19835}1983619837bool MarkReferencedDecls::TraverseTemplateArgument(19838const TemplateArgument &Arg) {19839{19840// A non-type template argument is a constant-evaluated context.19841EnterExpressionEvaluationContext Evaluated(19842S, Sema::ExpressionEvaluationContext::ConstantEvaluated);19843if (Arg.getKind() == TemplateArgument::Declaration) {19844if (Decl *D = Arg.getAsDecl())19845S.MarkAnyDeclReferenced(Loc, D, true);19846} else if (Arg.getKind() == TemplateArgument::Expression) {19847S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);19848}19849}1985019851return Inherited::TraverseTemplateArgument(Arg);19852}1985319854void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {19855MarkReferencedDecls Marker(*this, Loc);19856Marker.TraverseType(T);19857}1985819859namespace {19860/// Helper class that marks all of the declarations referenced by19861/// potentially-evaluated subexpressions as "referenced".19862class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {19863public:19864typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;19865bool SkipLocalVariables;19866ArrayRef<const Expr *> StopAt;1986719868EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,19869ArrayRef<const Expr *> StopAt)19870: Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}1987119872void visitUsedDecl(SourceLocation Loc, Decl *D) {19873S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));19874}1987519876void Visit(Expr *E) {19877if (llvm::is_contained(StopAt, E))19878return;19879Inherited::Visit(E);19880}1988119882void VisitConstantExpr(ConstantExpr *E) {19883// Don't mark declarations within a ConstantExpression, as this expression19884// will be evaluated and folded to a value.19885}1988619887void VisitDeclRefExpr(DeclRefExpr *E) {19888// If we were asked not to visit local variables, don't.19889if (SkipLocalVariables) {19890if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))19891if (VD->hasLocalStorage())19892return;19893}1989419895// FIXME: This can trigger the instantiation of the initializer of a19896// variable, which can cause the expression to become value-dependent19897// or error-dependent. Do we need to propagate the new dependence bits?19898S.MarkDeclRefReferenced(E);19899}1990019901void VisitMemberExpr(MemberExpr *E) {19902S.MarkMemberReferenced(E);19903Visit(E->getBase());19904}19905};19906} // namespace1990719908void Sema::MarkDeclarationsReferencedInExpr(Expr *E,19909bool SkipLocalVariables,19910ArrayRef<const Expr*> StopAt) {19911EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);19912}1991319914/// Emit a diagnostic when statements are reachable.19915/// FIXME: check for reachability even in expressions for which we don't build a19916/// CFG (eg, in the initializer of a global or in a constant expression).19917/// For example,19918/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }19919bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,19920const PartialDiagnostic &PD) {19921if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {19922if (!FunctionScopes.empty())19923FunctionScopes.back()->PossiblyUnreachableDiags.push_back(19924sema::PossiblyUnreachableDiag(PD, Loc, Stmts));19925return true;19926}1992719928// The initializer of a constexpr variable or of the first declaration of a19929// static data member is not syntactically a constant evaluated constant,19930// but nonetheless is always required to be a constant expression, so we19931// can skip diagnosing.19932// FIXME: Using the mangling context here is a hack.19933if (auto *VD = dyn_cast_or_null<VarDecl>(19934ExprEvalContexts.back().ManglingContextDecl)) {19935if (VD->isConstexpr() ||19936(VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))19937return false;19938// FIXME: For any other kind of variable, we should build a CFG for its19939// initializer and check whether the context in question is reachable.19940}1994119942Diag(Loc, PD);19943return true;19944}1994519946/// Emit a diagnostic that describes an effect on the run-time behavior19947/// of the program being compiled.19948///19949/// This routine emits the given diagnostic when the code currently being19950/// type-checked is "potentially evaluated", meaning that there is a19951/// possibility that the code will actually be executable. Code in sizeof()19952/// expressions, code used only during overload resolution, etc., are not19953/// potentially evaluated. This routine will suppress such diagnostics or,19954/// in the absolutely nutty case of potentially potentially evaluated19955/// expressions (C++ typeid), queue the diagnostic to potentially emit it19956/// later.19957///19958/// This routine should be used for all diagnostics that describe the run-time19959/// behavior of a program, such as passing a non-POD value through an ellipsis.19960/// Failure to do so will likely result in spurious diagnostics or failures19961/// during overload resolution or within sizeof/alignof/typeof/typeid.19962bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,19963const PartialDiagnostic &PD) {1996419965if (ExprEvalContexts.back().isDiscardedStatementContext())19966return false;1996719968switch (ExprEvalContexts.back().Context) {19969case ExpressionEvaluationContext::Unevaluated:19970case ExpressionEvaluationContext::UnevaluatedList:19971case ExpressionEvaluationContext::UnevaluatedAbstract:19972case ExpressionEvaluationContext::DiscardedStatement:19973// The argument will never be evaluated, so don't complain.19974break;1997519976case ExpressionEvaluationContext::ConstantEvaluated:19977case ExpressionEvaluationContext::ImmediateFunctionContext:19978// Relevant diagnostics should be produced by constant evaluation.19979break;1998019981case ExpressionEvaluationContext::PotentiallyEvaluated:19982case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:19983return DiagIfReachable(Loc, Stmts, PD);19984}1998519986return false;19987}1998819989bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,19990const PartialDiagnostic &PD) {19991return DiagRuntimeBehavior(19992Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);19993}1999419995bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,19996CallExpr *CE, FunctionDecl *FD) {19997if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())19998return false;1999920000// If we're inside a decltype's expression, don't check for a valid return20001// type or construct temporaries until we know whether this is the last call.20002if (ExprEvalContexts.back().ExprContext ==20003ExpressionEvaluationContextRecord::EK_Decltype) {20004ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);20005return false;20006}2000720008class CallReturnIncompleteDiagnoser : public TypeDiagnoser {20009FunctionDecl *FD;20010CallExpr *CE;2001120012public:20013CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)20014: FD(FD), CE(CE) { }2001520016void diagnose(Sema &S, SourceLocation Loc, QualType T) override {20017if (!FD) {20018S.Diag(Loc, diag::err_call_incomplete_return)20019<< T << CE->getSourceRange();20020return;20021}2002220023S.Diag(Loc, diag::err_call_function_incomplete_return)20024<< CE->getSourceRange() << FD << T;20025S.Diag(FD->getLocation(), diag::note_entity_declared_at)20026<< FD->getDeclName();20027}20028} Diagnoser(FD, CE);2002920030if (RequireCompleteType(Loc, ReturnType, Diagnoser))20031return true;2003220033return false;20034}2003520036// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses20037// will prevent this condition from triggering, which is what we want.20038void Sema::DiagnoseAssignmentAsCondition(Expr *E) {20039SourceLocation Loc;2004020041unsigned diagnostic = diag::warn_condition_is_assignment;20042bool IsOrAssign = false;2004320044if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {20045if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)20046return;2004720048IsOrAssign = Op->getOpcode() == BO_OrAssign;2004920050// Greylist some idioms by putting them into a warning subcategory.20051if (ObjCMessageExpr *ME20052= dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {20053Selector Sel = ME->getSelector();2005420055// self = [<foo> init...]20056if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)20057diagnostic = diag::warn_condition_is_idiomatic_assignment;2005820059// <foo> = [<bar> nextObject]20060else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")20061diagnostic = diag::warn_condition_is_idiomatic_assignment;20062}2006320064Loc = Op->getOperatorLoc();20065} else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {20066if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)20067return;2006820069IsOrAssign = Op->getOperator() == OO_PipeEqual;20070Loc = Op->getOperatorLoc();20071} else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))20072return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());20073else {20074// Not an assignment.20075return;20076}2007720078Diag(Loc, diagnostic) << E->getSourceRange();2007920080SourceLocation Open = E->getBeginLoc();20081SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());20082Diag(Loc, diag::note_condition_assign_silence)20083<< FixItHint::CreateInsertion(Open, "(")20084<< FixItHint::CreateInsertion(Close, ")");2008520086if (IsOrAssign)20087Diag(Loc, diag::note_condition_or_assign_to_comparison)20088<< FixItHint::CreateReplacement(Loc, "!=");20089else20090Diag(Loc, diag::note_condition_assign_to_comparison)20091<< FixItHint::CreateReplacement(Loc, "==");20092}2009320094void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {20095// Don't warn if the parens came from a macro.20096SourceLocation parenLoc = ParenE->getBeginLoc();20097if (parenLoc.isInvalid() || parenLoc.isMacroID())20098return;20099// Don't warn for dependent expressions.20100if (ParenE->isTypeDependent())20101return;2010220103Expr *E = ParenE->IgnoreParens();2010420105if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))20106if (opE->getOpcode() == BO_EQ &&20107opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)20108== Expr::MLV_Valid) {20109SourceLocation Loc = opE->getOperatorLoc();2011020111Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();20112SourceRange ParenERange = ParenE->getSourceRange();20113Diag(Loc, diag::note_equality_comparison_silence)20114<< FixItHint::CreateRemoval(ParenERange.getBegin())20115<< FixItHint::CreateRemoval(ParenERange.getEnd());20116Diag(Loc, diag::note_equality_comparison_to_assign)20117<< FixItHint::CreateReplacement(Loc, "=");20118}20119}2012020121ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,20122bool IsConstexpr) {20123DiagnoseAssignmentAsCondition(E);20124if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))20125DiagnoseEqualityWithExtraParens(parenE);2012620127ExprResult result = CheckPlaceholderExpr(E);20128if (result.isInvalid()) return ExprError();20129E = result.get();2013020131if (!E->isTypeDependent()) {20132if (getLangOpts().CPlusPlus)20133return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p42013420135ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);20136if (ERes.isInvalid())20137return ExprError();20138E = ERes.get();2013920140QualType T = E->getType();20141if (!T->isScalarType()) { // C99 6.8.4.1p120142Diag(Loc, diag::err_typecheck_statement_requires_scalar)20143<< T << E->getSourceRange();20144return ExprError();20145}20146CheckBoolLikeConversion(E, Loc);20147}2014820149return E;20150}2015120152Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,20153Expr *SubExpr, ConditionKind CK,20154bool MissingOK) {20155// MissingOK indicates whether having no condition expression is valid20156// (for loop) or invalid (e.g. while loop).20157if (!SubExpr)20158return MissingOK ? ConditionResult() : ConditionError();2015920160ExprResult Cond;20161switch (CK) {20162case ConditionKind::Boolean:20163Cond = CheckBooleanCondition(Loc, SubExpr);20164break;2016520166case ConditionKind::ConstexprIf:20167Cond = CheckBooleanCondition(Loc, SubExpr, true);20168break;2016920170case ConditionKind::Switch:20171Cond = CheckSwitchCondition(Loc, SubExpr);20172break;20173}20174if (Cond.isInvalid()) {20175Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),20176{SubExpr}, PreferredConditionType(CK));20177if (!Cond.get())20178return ConditionError();20179}20180// FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.20181FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);20182if (!FullExpr.get())20183return ConditionError();2018420185return ConditionResult(*this, nullptr, FullExpr,20186CK == ConditionKind::ConstexprIf);20187}2018820189namespace {20190/// A visitor for rebuilding a call to an __unknown_any expression20191/// to have an appropriate type.20192struct RebuildUnknownAnyFunction20193: StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {2019420195Sema &S;2019620197RebuildUnknownAnyFunction(Sema &S) : S(S) {}2019820199ExprResult VisitStmt(Stmt *S) {20200llvm_unreachable("unexpected statement!");20201}2020220203ExprResult VisitExpr(Expr *E) {20204S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)20205<< E->getSourceRange();20206return ExprError();20207}2020820209/// Rebuild an expression which simply semantically wraps another20210/// expression which it shares the type and value kind of.20211template <class T> ExprResult rebuildSugarExpr(T *E) {20212ExprResult SubResult = Visit(E->getSubExpr());20213if (SubResult.isInvalid()) return ExprError();2021420215Expr *SubExpr = SubResult.get();20216E->setSubExpr(SubExpr);20217E->setType(SubExpr->getType());20218E->setValueKind(SubExpr->getValueKind());20219assert(E->getObjectKind() == OK_Ordinary);20220return E;20221}2022220223ExprResult VisitParenExpr(ParenExpr *E) {20224return rebuildSugarExpr(E);20225}2022620227ExprResult VisitUnaryExtension(UnaryOperator *E) {20228return rebuildSugarExpr(E);20229}2023020231ExprResult VisitUnaryAddrOf(UnaryOperator *E) {20232ExprResult SubResult = Visit(E->getSubExpr());20233if (SubResult.isInvalid()) return ExprError();2023420235Expr *SubExpr = SubResult.get();20236E->setSubExpr(SubExpr);20237E->setType(S.Context.getPointerType(SubExpr->getType()));20238assert(E->isPRValue());20239assert(E->getObjectKind() == OK_Ordinary);20240return E;20241}2024220243ExprResult resolveDecl(Expr *E, ValueDecl *VD) {20244if (!isa<FunctionDecl>(VD)) return VisitExpr(E);2024520246E->setType(VD->getType());2024720248assert(E->isPRValue());20249if (S.getLangOpts().CPlusPlus &&20250!(isa<CXXMethodDecl>(VD) &&20251cast<CXXMethodDecl>(VD)->isInstance()))20252E->setValueKind(VK_LValue);2025320254return E;20255}2025620257ExprResult VisitMemberExpr(MemberExpr *E) {20258return resolveDecl(E, E->getMemberDecl());20259}2026020261ExprResult VisitDeclRefExpr(DeclRefExpr *E) {20262return resolveDecl(E, E->getDecl());20263}20264};20265}2026620267/// Given a function expression of unknown-any type, try to rebuild it20268/// to have a function type.20269static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {20270ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);20271if (Result.isInvalid()) return ExprError();20272return S.DefaultFunctionArrayConversion(Result.get());20273}2027420275namespace {20276/// A visitor for rebuilding an expression of type __unknown_anytype20277/// into one which resolves the type directly on the referring20278/// expression. Strict preservation of the original source20279/// structure is not a goal.20280struct RebuildUnknownAnyExpr20281: StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {2028220283Sema &S;2028420285/// The current destination type.20286QualType DestType;2028720288RebuildUnknownAnyExpr(Sema &S, QualType CastType)20289: S(S), DestType(CastType) {}2029020291ExprResult VisitStmt(Stmt *S) {20292llvm_unreachable("unexpected statement!");20293}2029420295ExprResult VisitExpr(Expr *E) {20296S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)20297<< E->getSourceRange();20298return ExprError();20299}2030020301ExprResult VisitCallExpr(CallExpr *E);20302ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);2030320304/// Rebuild an expression which simply semantically wraps another20305/// expression which it shares the type and value kind of.20306template <class T> ExprResult rebuildSugarExpr(T *E) {20307ExprResult SubResult = Visit(E->getSubExpr());20308if (SubResult.isInvalid()) return ExprError();20309Expr *SubExpr = SubResult.get();20310E->setSubExpr(SubExpr);20311E->setType(SubExpr->getType());20312E->setValueKind(SubExpr->getValueKind());20313assert(E->getObjectKind() == OK_Ordinary);20314return E;20315}2031620317ExprResult VisitParenExpr(ParenExpr *E) {20318return rebuildSugarExpr(E);20319}2032020321ExprResult VisitUnaryExtension(UnaryOperator *E) {20322return rebuildSugarExpr(E);20323}2032420325ExprResult VisitUnaryAddrOf(UnaryOperator *E) {20326const PointerType *Ptr = DestType->getAs<PointerType>();20327if (!Ptr) {20328S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)20329<< E->getSourceRange();20330return ExprError();20331}2033220333if (isa<CallExpr>(E->getSubExpr())) {20334S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)20335<< E->getSourceRange();20336return ExprError();20337}2033820339assert(E->isPRValue());20340assert(E->getObjectKind() == OK_Ordinary);20341E->setType(DestType);2034220343// Build the sub-expression as if it were an object of the pointee type.20344DestType = Ptr->getPointeeType();20345ExprResult SubResult = Visit(E->getSubExpr());20346if (SubResult.isInvalid()) return ExprError();20347E->setSubExpr(SubResult.get());20348return E;20349}2035020351ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);2035220353ExprResult resolveDecl(Expr *E, ValueDecl *VD);2035420355ExprResult VisitMemberExpr(MemberExpr *E) {20356return resolveDecl(E, E->getMemberDecl());20357}2035820359ExprResult VisitDeclRefExpr(DeclRefExpr *E) {20360return resolveDecl(E, E->getDecl());20361}20362};20363}2036420365/// Rebuilds a call expression which yielded __unknown_anytype.20366ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {20367Expr *CalleeExpr = E->getCallee();2036820369enum FnKind {20370FK_MemberFunction,20371FK_FunctionPointer,20372FK_BlockPointer20373};2037420375FnKind Kind;20376QualType CalleeType = CalleeExpr->getType();20377if (CalleeType == S.Context.BoundMemberTy) {20378assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));20379Kind = FK_MemberFunction;20380CalleeType = Expr::findBoundMemberType(CalleeExpr);20381} else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {20382CalleeType = Ptr->getPointeeType();20383Kind = FK_FunctionPointer;20384} else {20385CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();20386Kind = FK_BlockPointer;20387}20388const FunctionType *FnType = CalleeType->castAs<FunctionType>();2038920390// Verify that this is a legal result type of a function.20391if (DestType->isArrayType() || DestType->isFunctionType()) {20392unsigned diagID = diag::err_func_returning_array_function;20393if (Kind == FK_BlockPointer)20394diagID = diag::err_block_returning_array_function;2039520396S.Diag(E->getExprLoc(), diagID)20397<< DestType->isFunctionType() << DestType;20398return ExprError();20399}2040020401// Otherwise, go ahead and set DestType as the call's result.20402E->setType(DestType.getNonLValueExprType(S.Context));20403E->setValueKind(Expr::getValueKindForType(DestType));20404assert(E->getObjectKind() == OK_Ordinary);2040520406// Rebuild the function type, replacing the result type with DestType.20407const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);20408if (Proto) {20409// __unknown_anytype(...) is a special case used by the debugger when20410// it has no idea what a function's signature is.20411//20412// We want to build this call essentially under the K&R20413// unprototyped rules, but making a FunctionNoProtoType in C++20414// would foul up all sorts of assumptions. However, we cannot20415// simply pass all arguments as variadic arguments, nor can we20416// portably just call the function under a non-variadic type; see20417// the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.20418// However, it turns out that in practice it is generally safe to20419// call a function declared as "A foo(B,C,D);" under the prototype20420// "A foo(B,C,D,...);". The only known exception is with the20421// Windows ABI, where any variadic function is implicitly cdecl20422// regardless of its normal CC. Therefore we change the parameter20423// types to match the types of the arguments.20424//20425// This is a hack, but it is far superior to moving the20426// corresponding target-specific code from IR-gen to Sema/AST.2042720428ArrayRef<QualType> ParamTypes = Proto->getParamTypes();20429SmallVector<QualType, 8> ArgTypes;20430if (ParamTypes.empty() && Proto->isVariadic()) { // the special case20431ArgTypes.reserve(E->getNumArgs());20432for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {20433ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));20434}20435ParamTypes = ArgTypes;20436}20437DestType = S.Context.getFunctionType(DestType, ParamTypes,20438Proto->getExtProtoInfo());20439} else {20440DestType = S.Context.getFunctionNoProtoType(DestType,20441FnType->getExtInfo());20442}2044320444// Rebuild the appropriate pointer-to-function type.20445switch (Kind) {20446case FK_MemberFunction:20447// Nothing to do.20448break;2044920450case FK_FunctionPointer:20451DestType = S.Context.getPointerType(DestType);20452break;2045320454case FK_BlockPointer:20455DestType = S.Context.getBlockPointerType(DestType);20456break;20457}2045820459// Finally, we can recurse.20460ExprResult CalleeResult = Visit(CalleeExpr);20461if (!CalleeResult.isUsable()) return ExprError();20462E->setCallee(CalleeResult.get());2046320464// Bind a temporary if necessary.20465return S.MaybeBindToTemporary(E);20466}2046720468ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {20469// Verify that this is a legal result type of a call.20470if (DestType->isArrayType() || DestType->isFunctionType()) {20471S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)20472<< DestType->isFunctionType() << DestType;20473return ExprError();20474}2047520476// Rewrite the method result type if available.20477if (ObjCMethodDecl *Method = E->getMethodDecl()) {20478assert(Method->getReturnType() == S.Context.UnknownAnyTy);20479Method->setReturnType(DestType);20480}2048120482// Change the type of the message.20483E->setType(DestType.getNonReferenceType());20484E->setValueKind(Expr::getValueKindForType(DestType));2048520486return S.MaybeBindToTemporary(E);20487}2048820489ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {20490// The only case we should ever see here is a function-to-pointer decay.20491if (E->getCastKind() == CK_FunctionToPointerDecay) {20492assert(E->isPRValue());20493assert(E->getObjectKind() == OK_Ordinary);2049420495E->setType(DestType);2049620497// Rebuild the sub-expression as the pointee (function) type.20498DestType = DestType->castAs<PointerType>()->getPointeeType();2049920500ExprResult Result = Visit(E->getSubExpr());20501if (!Result.isUsable()) return ExprError();2050220503E->setSubExpr(Result.get());20504return E;20505} else if (E->getCastKind() == CK_LValueToRValue) {20506assert(E->isPRValue());20507assert(E->getObjectKind() == OK_Ordinary);2050820509assert(isa<BlockPointerType>(E->getType()));2051020511E->setType(DestType);2051220513// The sub-expression has to be a lvalue reference, so rebuild it as such.20514DestType = S.Context.getLValueReferenceType(DestType);2051520516ExprResult Result = Visit(E->getSubExpr());20517if (!Result.isUsable()) return ExprError();2051820519E->setSubExpr(Result.get());20520return E;20521} else {20522llvm_unreachable("Unhandled cast type!");20523}20524}2052520526ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {20527ExprValueKind ValueKind = VK_LValue;20528QualType Type = DestType;2052920530// We know how to make this work for certain kinds of decls:2053120532// - functions20533if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {20534if (const PointerType *Ptr = Type->getAs<PointerType>()) {20535DestType = Ptr->getPointeeType();20536ExprResult Result = resolveDecl(E, VD);20537if (Result.isInvalid()) return ExprError();20538return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,20539VK_PRValue);20540}2054120542if (!Type->isFunctionType()) {20543S.Diag(E->getExprLoc(), diag::err_unknown_any_function)20544<< VD << E->getSourceRange();20545return ExprError();20546}20547if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {20548// We must match the FunctionDecl's type to the hack introduced in20549// RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown20550// type. See the lengthy commentary in that routine.20551QualType FDT = FD->getType();20552const FunctionType *FnType = FDT->castAs<FunctionType>();20553const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);20554DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);20555if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {20556SourceLocation Loc = FD->getLocation();20557FunctionDecl *NewFD = FunctionDecl::Create(20558S.Context, FD->getDeclContext(), Loc, Loc,20559FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),20560SC_None, S.getCurFPFeatures().isFPConstrained(),20561false /*isInlineSpecified*/, FD->hasPrototype(),20562/*ConstexprKind*/ ConstexprSpecKind::Unspecified);2056320564if (FD->getQualifier())20565NewFD->setQualifierInfo(FD->getQualifierLoc());2056620567SmallVector<ParmVarDecl*, 16> Params;20568for (const auto &AI : FT->param_types()) {20569ParmVarDecl *Param =20570S.BuildParmVarDeclForTypedef(FD, Loc, AI);20571Param->setScopeInfo(0, Params.size());20572Params.push_back(Param);20573}20574NewFD->setParams(Params);20575DRE->setDecl(NewFD);20576VD = DRE->getDecl();20577}20578}2057920580if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))20581if (MD->isInstance()) {20582ValueKind = VK_PRValue;20583Type = S.Context.BoundMemberTy;20584}2058520586// Function references aren't l-values in C.20587if (!S.getLangOpts().CPlusPlus)20588ValueKind = VK_PRValue;2058920590// - variables20591} else if (isa<VarDecl>(VD)) {20592if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {20593Type = RefTy->getPointeeType();20594} else if (Type->isFunctionType()) {20595S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)20596<< VD << E->getSourceRange();20597return ExprError();20598}2059920600// - nothing else20601} else {20602S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)20603<< VD << E->getSourceRange();20604return ExprError();20605}2060620607// Modifying the declaration like this is friendly to IR-gen but20608// also really dangerous.20609VD->setType(DestType);20610E->setType(Type);20611E->setValueKind(ValueKind);20612return E;20613}2061420615ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,20616Expr *CastExpr, CastKind &CastKind,20617ExprValueKind &VK, CXXCastPath &Path) {20618// The type we're casting to must be either void or complete.20619if (!CastType->isVoidType() &&20620RequireCompleteType(TypeRange.getBegin(), CastType,20621diag::err_typecheck_cast_to_incomplete))20622return ExprError();2062320624// Rewrite the casted expression from scratch.20625ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);20626if (!result.isUsable()) return ExprError();2062720628CastExpr = result.get();20629VK = CastExpr->getValueKind();20630CastKind = CK_NoOp;2063120632return CastExpr;20633}2063420635ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {20636return RebuildUnknownAnyExpr(*this, ToType).Visit(E);20637}2063820639ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,20640Expr *arg, QualType ¶mType) {20641// If the syntactic form of the argument is not an explicit cast of20642// any sort, just do default argument promotion.20643ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());20644if (!castArg) {20645ExprResult result = DefaultArgumentPromotion(arg);20646if (result.isInvalid()) return ExprError();20647paramType = result.get()->getType();20648return result;20649}2065020651// Otherwise, use the type that was written in the explicit cast.20652assert(!arg->hasPlaceholderType());20653paramType = castArg->getTypeAsWritten();2065420655// Copy-initialize a parameter of that type.20656InitializedEntity entity =20657InitializedEntity::InitializeParameter(Context, paramType,20658/*consumed*/ false);20659return PerformCopyInitialization(entity, callLoc, arg);20660}2066120662static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {20663Expr *orig = E;20664unsigned diagID = diag::err_uncasted_use_of_unknown_any;20665while (true) {20666E = E->IgnoreParenImpCasts();20667if (CallExpr *call = dyn_cast<CallExpr>(E)) {20668E = call->getCallee();20669diagID = diag::err_uncasted_call_of_unknown_any;20670} else {20671break;20672}20673}2067420675SourceLocation loc;20676NamedDecl *d;20677if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {20678loc = ref->getLocation();20679d = ref->getDecl();20680} else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {20681loc = mem->getMemberLoc();20682d = mem->getMemberDecl();20683} else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {20684diagID = diag::err_uncasted_call_of_unknown_any;20685loc = msg->getSelectorStartLoc();20686d = msg->getMethodDecl();20687if (!d) {20688S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)20689<< static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()20690<< orig->getSourceRange();20691return ExprError();20692}20693} else {20694S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)20695<< E->getSourceRange();20696return ExprError();20697}2069820699S.Diag(loc, diagID) << d << orig->getSourceRange();2070020701// Never recoverable.20702return ExprError();20703}2070420705ExprResult Sema::CheckPlaceholderExpr(Expr *E) {20706if (!Context.isDependenceAllowed()) {20707// C cannot handle TypoExpr nodes on either side of a binop because it20708// doesn't handle dependent types properly, so make sure any TypoExprs have20709// been dealt with before checking the operands.20710ExprResult Result = CorrectDelayedTyposInExpr(E);20711if (!Result.isUsable()) return ExprError();20712E = Result.get();20713}2071420715const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();20716if (!placeholderType) return E;2071720718switch (placeholderType->getKind()) {20719case BuiltinType::UnresolvedTemplate: {20720auto *ULE = cast<UnresolvedLookupExpr>(E);20721const DeclarationNameInfo &NameInfo = ULE->getNameInfo();20722// There's only one FoundDecl for UnresolvedTemplate type. See20723// BuildTemplateIdExpr.20724NamedDecl *Temp = *ULE->decls_begin();20725const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);2072620727if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())20728Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)20729<< Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()20730<< Loc.getSourceRange() << IsTypeAliasTemplateDecl;20731else20732Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)20733<< "" << NameInfo.getName().getAsString() << ULE->getSourceRange()20734<< IsTypeAliasTemplateDecl;20735Diag(Temp->getLocation(), diag::note_referenced_type_template)20736<< IsTypeAliasTemplateDecl;2073720738return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});20739}2074020741// Overloaded expressions.20742case BuiltinType::Overload: {20743// Try to resolve a single function template specialization.20744// This is obligatory.20745ExprResult Result = E;20746if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))20747return Result;2074820749// No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization20750// leaves Result unchanged on failure.20751Result = E;20752if (resolveAndFixAddressOfSingleOverloadCandidate(Result))20753return Result;2075420755// If that failed, try to recover with a call.20756tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),20757/*complain*/ true);20758return Result;20759}2076020761// Bound member functions.20762case BuiltinType::BoundMember: {20763ExprResult result = E;20764const Expr *BME = E->IgnoreParens();20765PartialDiagnostic PD = PDiag(diag::err_bound_member_function);20766// Try to give a nicer diagnostic if it is a bound member that we recognize.20767if (isa<CXXPseudoDestructorExpr>(BME)) {20768PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;20769} else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {20770if (ME->getMemberNameInfo().getName().getNameKind() ==20771DeclarationName::CXXDestructorName)20772PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;20773}20774tryToRecoverWithCall(result, PD,20775/*complain*/ true);20776return result;20777}2077820779// ARC unbridged casts.20780case BuiltinType::ARCUnbridgedCast: {20781Expr *realCast = ObjC().stripARCUnbridgedCast(E);20782ObjC().diagnoseARCUnbridgedCast(realCast);20783return realCast;20784}2078520786// Expressions of unknown type.20787case BuiltinType::UnknownAny:20788return diagnoseUnknownAnyExpr(*this, E);2078920790// Pseudo-objects.20791case BuiltinType::PseudoObject:20792return PseudoObject().checkRValue(E);2079320794case BuiltinType::BuiltinFn: {20795// Accept __noop without parens by implicitly converting it to a call expr.20796auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());20797if (DRE) {20798auto *FD = cast<FunctionDecl>(DRE->getDecl());20799unsigned BuiltinID = FD->getBuiltinID();20800if (BuiltinID == Builtin::BI__noop) {20801E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),20802CK_BuiltinFnToFnPtr)20803.get();20804return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,20805VK_PRValue, SourceLocation(),20806FPOptionsOverride());20807}2080820809if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {20810// Any use of these other than a direct call is ill-formed as of C++20,20811// because they are not addressable functions. In earlier language20812// modes, warn and force an instantiation of the real body.20813Diag(E->getBeginLoc(),20814getLangOpts().CPlusPlus2020815? diag::err_use_of_unaddressable_function20816: diag::warn_cxx20_compat_use_of_unaddressable_function);20817if (FD->isImplicitlyInstantiable()) {20818// Require a definition here because a normal attempt at20819// instantiation for a builtin will be ignored, and we won't try20820// again later. We assume that the definition of the template20821// precedes this use.20822InstantiateFunctionDefinition(E->getBeginLoc(), FD,20823/*Recursive=*/false,20824/*DefinitionRequired=*/true,20825/*AtEndOfTU=*/false);20826}20827// Produce a properly-typed reference to the function.20828CXXScopeSpec SS;20829SS.Adopt(DRE->getQualifierLoc());20830TemplateArgumentListInfo TemplateArgs;20831DRE->copyTemplateArgumentsInto(TemplateArgs);20832return BuildDeclRefExpr(20833FD, FD->getType(), VK_LValue, DRE->getNameInfo(),20834DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),20835DRE->getTemplateKeywordLoc(),20836DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);20837}20838}2083920840Diag(E->getBeginLoc(), diag::err_builtin_fn_use);20841return ExprError();20842}2084320844case BuiltinType::IncompleteMatrixIdx:20845Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())20846->getRowIdx()20847->getBeginLoc(),20848diag::err_matrix_incomplete_index);20849return ExprError();2085020851// Expressions of unknown type.20852case BuiltinType::ArraySection:20853Diag(E->getBeginLoc(), diag::err_array_section_use)20854<< cast<ArraySectionExpr>(E)->isOMPArraySection();20855return ExprError();2085620857// Expressions of unknown type.20858case BuiltinType::OMPArrayShaping:20859return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));2086020861case BuiltinType::OMPIterator:20862return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));2086320864// Everything else should be impossible.20865#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \20866case BuiltinType::Id:20867#include "clang/Basic/OpenCLImageTypes.def"20868#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \20869case BuiltinType::Id:20870#include "clang/Basic/OpenCLExtensionTypes.def"20871#define SVE_TYPE(Name, Id, SingletonId) \20872case BuiltinType::Id:20873#include "clang/Basic/AArch64SVEACLETypes.def"20874#define PPC_VECTOR_TYPE(Name, Id, Size) \20875case BuiltinType::Id:20876#include "clang/Basic/PPCTypes.def"20877#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:20878#include "clang/Basic/RISCVVTypes.def"20879#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:20880#include "clang/Basic/WebAssemblyReferenceTypes.def"20881#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:20882#include "clang/Basic/AMDGPUTypes.def"20883#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:20884#define PLACEHOLDER_TYPE(Id, SingletonId)20885#include "clang/AST/BuiltinTypes.def"20886break;20887}2088820889llvm_unreachable("invalid placeholder type!");20890}2089120892bool Sema::CheckCaseExpression(Expr *E) {20893if (E->isTypeDependent())20894return true;20895if (E->isValueDependent() || E->isIntegerConstantExpr(Context))20896return E->getType()->isIntegralOrEnumerationType();20897return false;20898}2089920900ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,20901ArrayRef<Expr *> SubExprs, QualType T) {20902if (!Context.getLangOpts().RecoveryAST)20903return ExprError();2090420905if (isSFINAEContext())20906return ExprError();2090720908if (T.isNull() || T->isUndeducedType() ||20909!Context.getLangOpts().RecoveryASTType)20910// We don't know the concrete type, fallback to dependent type.20911T = Context.DependentTy;2091220913return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);20914}209152091620917