brintos

brintos / llvm-project-archived public Read only

0
0
Text · 851.3 KiB · cfabd1b Raw
21606 lines · cpp
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9//  This file implements semantic analysis for expressions.10//11//===----------------------------------------------------------------------===//12 13#include "CheckExprLifetime.h"14#include "TreeTransform.h"15#include "UsedDeclVisitor.h"16#include "clang/AST/ASTConsumer.h"17#include "clang/AST/ASTContext.h"18#include "clang/AST/ASTDiagnostic.h"19#include "clang/AST/ASTLambda.h"20#include "clang/AST/ASTMutationListener.h"21#include "clang/AST/Attrs.inc"22#include "clang/AST/CXXInheritance.h"23#include "clang/AST/Decl.h"24#include "clang/AST/DeclObjC.h"25#include "clang/AST/DeclTemplate.h"26#include "clang/AST/DynamicRecursiveASTVisitor.h"27#include "clang/AST/EvaluatedExprVisitor.h"28#include "clang/AST/Expr.h"29#include "clang/AST/ExprCXX.h"30#include "clang/AST/ExprObjC.h"31#include "clang/AST/MangleNumberingContext.h"32#include "clang/AST/OperationKinds.h"33#include "clang/AST/Type.h"34#include "clang/AST/TypeLoc.h"35#include "clang/Basic/Builtins.h"36#include "clang/Basic/DiagnosticSema.h"37#include "clang/Basic/PartialDiagnostic.h"38#include "clang/Basic/SourceManager.h"39#include "clang/Basic/Specifiers.h"40#include "clang/Basic/TargetInfo.h"41#include "clang/Basic/TypeTraits.h"42#include "clang/Lex/LiteralSupport.h"43#include "clang/Lex/Preprocessor.h"44#include "clang/Sema/AnalysisBasedWarnings.h"45#include "clang/Sema/DeclSpec.h"46#include "clang/Sema/DelayedDiagnostic.h"47#include "clang/Sema/Designator.h"48#include "clang/Sema/EnterExpressionEvaluationContext.h"49#include "clang/Sema/Initialization.h"50#include "clang/Sema/Lookup.h"51#include "clang/Sema/Overload.h"52#include "clang/Sema/ParsedTemplate.h"53#include "clang/Sema/Scope.h"54#include "clang/Sema/ScopeInfo.h"55#include "clang/Sema/SemaARM.h"56#include "clang/Sema/SemaCUDA.h"57#include "clang/Sema/SemaFixItUtils.h"58#include "clang/Sema/SemaHLSL.h"59#include "clang/Sema/SemaObjC.h"60#include "clang/Sema/SemaOpenMP.h"61#include "clang/Sema/SemaPseudoObject.h"62#include "clang/Sema/Template.h"63#include "llvm/ADT/STLExtras.h"64#include "llvm/ADT/StringExtras.h"65#include "llvm/Support/ConvertUTF.h"66#include "llvm/Support/SaveAndRestore.h"67#include "llvm/Support/TimeProfiler.h"68#include "llvm/Support/TypeSize.h"69#include <limits>70#include <optional>71 72using namespace clang;73using namespace sema;74 75bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {76  // See if this is an auto-typed variable whose initializer we are parsing.77  if (ParsingInitForAutoVars.count(D))78    return false;79 80  // See if this is a deleted function.81  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {82    if (FD->isDeleted())83      return false;84 85    // If the function has a deduced return type, and we can't deduce it,86    // then we can't use it either.87    if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&88        DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))89      return false;90 91    // See if this is an aligned allocation/deallocation function that is92    // unavailable.93    if (TreatUnavailableAsInvalid &&94        isUnavailableAlignedAllocationFunction(*FD))95      return false;96  }97 98  // See if this function is unavailable.99  if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&100      cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)101    return false;102 103  if (isa<UnresolvedUsingIfExistsDecl>(D))104    return false;105 106  return true;107}108 109static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {110  // Warn if this is used but marked unused.111  if (const auto *A = D->getAttr<UnusedAttr>()) {112    // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))113    // should diagnose them.114    if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&115        A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {116      const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());117      if (DC && !DC->hasAttr<UnusedAttr>())118        S.Diag(Loc, diag::warn_used_but_marked_unused) << D;119    }120  }121}122 123void Sema::NoteDeletedFunction(FunctionDecl *Decl) {124  assert(Decl && Decl->isDeleted());125 126  if (Decl->isDefaulted()) {127    // If the method was explicitly defaulted, point at that declaration.128    if (!Decl->isImplicit())129      Diag(Decl->getLocation(), diag::note_implicitly_deleted);130 131    // Try to diagnose why this special member function was implicitly132    // deleted. This might fail, if that reason no longer applies.133    DiagnoseDeletedDefaultedFunction(Decl);134    return;135  }136 137  auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);138  if (Ctor && Ctor->isInheritingConstructor())139    return NoteDeletedInheritingConstructor(Ctor);140 141  Diag(Decl->getLocation(), diag::note_availability_specified_here)142    << Decl << 1;143}144 145/// Determine whether a FunctionDecl was ever declared with an146/// explicit storage class.147static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {148  for (auto *I : D->redecls()) {149    if (I->getStorageClass() != SC_None)150      return true;151  }152  return false;153}154 155/// Check whether we're in an extern inline function and referring to a156/// variable or function with internal linkage (C11 6.7.4p3).157///158/// This is only a warning because we used to silently accept this code, but159/// in many cases it will not behave correctly. This is not enabled in C++ mode160/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)161/// and so while there may still be user mistakes, most of the time we can't162/// prove that there are errors.163static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,164                                                      const NamedDecl *D,165                                                      SourceLocation Loc) {166  // This is disabled under C++; there are too many ways for this to fire in167  // contexts where the warning is a false positive, or where it is technically168  // correct but benign.169  //170  // WG14 N3622 which removed the constraint entirely in C2y. It is left171  // enabled in earlier language modes because this is a constraint in those172  // language modes. But in C2y mode, we still want to issue the "incompatible173  // with previous standards" diagnostic, too.174  if (S.getLangOpts().CPlusPlus)175    return;176 177  // Check if this is an inlined function or method.178  FunctionDecl *Current = S.getCurFunctionDecl();179  if (!Current)180    return;181  if (!Current->isInlined())182    return;183  if (!Current->isExternallyVisible())184    return;185 186  // Check if the decl has internal linkage.187  if (D->getFormalLinkage() != Linkage::Internal)188    return;189 190  // Downgrade from ExtWarn to Extension if191  //  (1) the supposedly external inline function is in the main file,192  //      and probably won't be included anywhere else.193  //  (2) the thing we're referencing is a pure function.194  //  (3) the thing we're referencing is another inline function.195  // This last can give us false negatives, but it's better than warning on196  // wrappers for simple C library functions.197  const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);198  unsigned DiagID;199  if (S.getLangOpts().C2y)200    DiagID = diag::warn_c2y_compat_internal_in_extern_inline;201  else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||202           S.getSourceManager().isInMainFile(Loc))203    DiagID = diag::ext_internal_in_extern_inline_quiet;204  else205    DiagID = diag::ext_internal_in_extern_inline;206 207  S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;208  S.MaybeSuggestAddingStaticToDecl(Current);209  S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)210      << D;211}212 213void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {214  const FunctionDecl *First = Cur->getFirstDecl();215 216  // Suggest "static" on the function, if possible.217  if (!hasAnyExplicitStorageClass(First)) {218    SourceLocation DeclBegin = First->getSourceRange().getBegin();219    Diag(DeclBegin, diag::note_convert_inline_to_static)220      << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");221  }222}223 224bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,225                             const ObjCInterfaceDecl *UnknownObjCClass,226                             bool ObjCPropertyAccess,227                             bool AvoidPartialAvailabilityChecks,228                             ObjCInterfaceDecl *ClassReceiver,229                             bool SkipTrailingRequiresClause) {230  SourceLocation Loc = Locs.front();231  if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {232    // If there were any diagnostics suppressed by template argument deduction,233    // emit them now.234    auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());235    if (Pos != SuppressedDiagnostics.end()) {236      for (const auto &[DiagLoc, PD] : Pos->second) {237        DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));238        PD.Emit(Builder);239      }240      // Clear out the list of suppressed diagnostics, so that we don't emit241      // them again for this specialization. However, we don't obsolete this242      // entry from the table, because we want to avoid ever emitting these243      // diagnostics again.244      Pos->second.clear();245    }246 247    // C++ [basic.start.main]p3:248    //   The function 'main' shall not be used within a program.249    if (cast<FunctionDecl>(D)->isMain())250      Diag(Loc, diag::ext_main_used);251 252    diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);253  }254 255  // See if this is an auto-typed variable whose initializer we are parsing.256  if (ParsingInitForAutoVars.count(D)) {257    if (isa<BindingDecl>(D)) {258      Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)259        << D->getDeclName();260    } else {261      Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)262          << diag::ParsingInitFor::Var << D->getDeclName()263          << cast<VarDecl>(D)->getType();264    }265    return true;266  }267 268  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {269    // See if this is a deleted function.270    if (FD->isDeleted()) {271      auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);272      if (Ctor && Ctor->isInheritingConstructor())273        Diag(Loc, diag::err_deleted_inherited_ctor_use)274            << Ctor->getParent()275            << Ctor->getInheritedConstructor().getConstructor()->getParent();276      else {277        StringLiteral *Msg = FD->getDeletedMessage();278        Diag(Loc, diag::err_deleted_function_use)279            << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());280      }281      NoteDeletedFunction(FD);282      return true;283    }284 285    // [expr.prim.id]p4286    //   A program that refers explicitly or implicitly to a function with a287    //   trailing requires-clause whose constraint-expression is not satisfied,288    //   other than to declare it, is ill-formed. [...]289    //290    // See if this is a function with constraints that need to be satisfied.291    // Check this before deducing the return type, as it might instantiate the292    // definition.293    if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {294      ConstraintSatisfaction Satisfaction;295      if (CheckFunctionConstraints(FD, Satisfaction, Loc,296                                   /*ForOverloadResolution*/ true))297        // A diagnostic will have already been generated (non-constant298        // constraint expression, for example)299        return true;300      if (!Satisfaction.IsSatisfied) {301        Diag(Loc,302             diag::err_reference_to_function_with_unsatisfied_constraints)303            << D;304        DiagnoseUnsatisfiedConstraint(Satisfaction);305        return true;306      }307    }308 309    // If the function has a deduced return type, and we can't deduce it,310    // then we can't use it either.311    if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&312        DeduceReturnType(FD, Loc))313      return true;314 315    if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))316      return true;317 318  }319 320  if (auto *Concept = dyn_cast<ConceptDecl>(D);321      Concept && CheckConceptUseInDefinition(Concept, Loc))322    return true;323 324  if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {325    // Lambdas are only default-constructible or assignable in C++2a onwards.326    if (MD->getParent()->isLambda() &&327        ((isa<CXXConstructorDecl>(MD) &&328          cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||329         MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {330      Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)331        << !isa<CXXConstructorDecl>(MD);332    }333  }334 335  auto getReferencedObjCProp = [](const NamedDecl *D) ->336                                      const ObjCPropertyDecl * {337    if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))338      return MD->findPropertyDecl();339    return nullptr;340  };341  if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {342    if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))343      return true;344  } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {345      return true;346  }347 348  // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions349  // Only the variables omp_in and omp_out are allowed in the combiner.350  // Only the variables omp_priv and omp_orig are allowed in the351  // initializer-clause.352  auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);353  if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&354      isa<VarDecl>(D)) {355    Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)356        << getCurFunction()->HasOMPDeclareReductionCombiner;357    Diag(D->getLocation(), diag::note_entity_declared_at) << D;358    return true;359  }360 361  // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions362  //  List-items in map clauses on this construct may only refer to the declared363  //  variable var and entities that could be referenced by a procedure defined364  //  at the same location.365  // [OpenMP 5.2] Also allow iterator declared variables.366  if (LangOpts.OpenMP && isa<VarDecl>(D) &&367      !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {368    Diag(Loc, diag::err_omp_declare_mapper_wrong_var)369        << OpenMP().getOpenMPDeclareMapperVarName();370    Diag(D->getLocation(), diag::note_entity_declared_at) << D;371    return true;372  }373 374  if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {375    Diag(Loc, diag::err_use_of_empty_using_if_exists);376    Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);377    return true;378  }379 380  DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,381                             AvoidPartialAvailabilityChecks, ClassReceiver);382 383  DiagnoseUnusedOfDecl(*this, D, Loc);384 385  diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);386 387  if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {388    if (getLangOpts().getFPEvalMethod() !=389            LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&390        PP.getLastFPEvalPragmaLocation().isValid() &&391        PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())392      Diag(D->getLocation(),393           diag::err_type_available_only_in_default_eval_method)394          << D->getName();395  }396 397  if (auto *VD = dyn_cast<ValueDecl>(D))398    checkTypeSupport(VD->getType(), Loc, VD);399 400  if (LangOpts.SYCLIsDevice ||401      (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {402    if (!Context.getTargetInfo().isTLSSupported())403      if (const auto *VD = dyn_cast<VarDecl>(D))404        if (VD->getTLSKind() != VarDecl::TLS_None)405          targetDiag(*Locs.begin(), diag::err_thread_unsupported);406  }407 408  return false;409}410 411void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,412                                 ArrayRef<Expr *> Args) {413  const SentinelAttr *Attr = D->getAttr<SentinelAttr>();414  if (!Attr)415    return;416 417  // The number of formal parameters of the declaration.418  unsigned NumFormalParams;419 420  // The kind of declaration.  This is also an index into a %select in421  // the diagnostic.422  enum { CK_Function, CK_Method, CK_Block } CalleeKind;423 424  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {425    NumFormalParams = MD->param_size();426    CalleeKind = CK_Method;427  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {428    NumFormalParams = FD->param_size();429    CalleeKind = CK_Function;430  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {431    QualType Ty = VD->getType();432    const FunctionType *Fn = nullptr;433    if (const auto *PtrTy = Ty->getAs<PointerType>()) {434      Fn = PtrTy->getPointeeType()->getAs<FunctionType>();435      if (!Fn)436        return;437      CalleeKind = CK_Function;438    } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {439      Fn = PtrTy->getPointeeType()->castAs<FunctionType>();440      CalleeKind = CK_Block;441    } else {442      return;443    }444 445    if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))446      NumFormalParams = proto->getNumParams();447    else448      NumFormalParams = 0;449  } else {450    return;451  }452 453  // "NullPos" is the number of formal parameters at the end which454  // effectively count as part of the variadic arguments.  This is455  // useful if you would prefer to not have *any* formal parameters,456  // but the language forces you to have at least one.457  unsigned NullPos = Attr->getNullPos();458  assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");459  NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);460 461  // The number of arguments which should follow the sentinel.462  unsigned NumArgsAfterSentinel = Attr->getSentinel();463 464  // If there aren't enough arguments for all the formal parameters,465  // the sentinel, and the args after the sentinel, complain.466  if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {467    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();468    Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);469    return;470  }471 472  // Otherwise, find the sentinel expression.473  const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];474  if (!SentinelExpr)475    return;476  if (SentinelExpr->isValueDependent())477    return;478  if (Context.isSentinelNullExpr(SentinelExpr))479    return;480 481  // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',482  // or 'NULL' if those are actually defined in the context.  Only use483  // 'nil' for ObjC methods, where it's much more likely that the484  // variadic arguments form a list of object pointers.485  SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());486  std::string NullValue;487  if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))488    NullValue = "nil";489  else if (getLangOpts().CPlusPlus11)490    NullValue = "nullptr";491  else if (PP.isMacroDefined("NULL"))492    NullValue = "NULL";493  else494    NullValue = "(void*) 0";495 496  if (MissingNilLoc.isInvalid())497    Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);498  else499    Diag(MissingNilLoc, diag::warn_missing_sentinel)500        << int(CalleeKind)501        << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);502  Diag(D->getLocation(), diag::note_sentinel_here)503      << int(CalleeKind) << Attr->getRange();504}505 506SourceRange Sema::getExprRange(Expr *E) const {507  return E ? E->getSourceRange() : SourceRange();508}509 510//===----------------------------------------------------------------------===//511//  Standard Promotions and Conversions512//===----------------------------------------------------------------------===//513 514/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).515ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {516  // Handle any placeholder expressions which made it here.517  if (E->hasPlaceholderType()) {518    ExprResult result = CheckPlaceholderExpr(E);519    if (result.isInvalid()) return ExprError();520    E = result.get();521  }522 523  QualType Ty = E->getType();524  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");525 526  if (Ty->isFunctionType()) {527    if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))528      if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))529        if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))530          return ExprError();531 532    E = ImpCastExprToType(E, Context.getPointerType(Ty),533                          CK_FunctionToPointerDecay).get();534  } else if (Ty->isArrayType()) {535    // In C90 mode, arrays only promote to pointers if the array expression is536    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has537    // type 'array of type' is converted to an expression that has type 'pointer538    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression539    // that has type 'array of type' ...".  The relevant change is "an lvalue"540    // (C90) to "an expression" (C99).541    //542    // C++ 4.2p1:543    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of544    // T" can be converted to an rvalue of type "pointer to T".545    //546    if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {547      ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),548                                         CK_ArrayToPointerDecay);549      if (Res.isInvalid())550        return ExprError();551      E = Res.get();552    }553  }554  return E;555}556 557static void CheckForNullPointerDereference(Sema &S, Expr *E) {558  // Check to see if we are dereferencing a null pointer.  If so,559  // and if not volatile-qualified, this is undefined behavior that the560  // optimizer will delete, so warn about it.  People sometimes try to use this561  // to get a deterministic trap and are surprised by clang's behavior.  This562  // only handles the pattern "*null", which is a very syntactic check.563  const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());564  if (UO && UO->getOpcode() == UO_Deref &&565      UO->getSubExpr()->getType()->isPointerType()) {566    const LangAS AS =567        UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();568    if ((!isTargetAddressSpace(AS) ||569         (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&570        UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(571            S.Context, Expr::NPC_ValueDependentIsNotNull) &&572        !UO->getType().isVolatileQualified()) {573      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,574                            S.PDiag(diag::warn_indirection_through_null)575                                << UO->getSubExpr()->getSourceRange());576      S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,577                            S.PDiag(diag::note_indirection_through_null));578    }579  }580}581 582static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,583                                    SourceLocation AssignLoc,584                                    const Expr* RHS) {585  const ObjCIvarDecl *IV = OIRE->getDecl();586  if (!IV)587    return;588 589  DeclarationName MemberName = IV->getDeclName();590  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();591  if (!Member || !Member->isStr("isa"))592    return;593 594  const Expr *Base = OIRE->getBase();595  QualType BaseType = Base->getType();596  if (OIRE->isArrow())597    BaseType = BaseType->getPointeeType();598  if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())599    if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {600      ObjCInterfaceDecl *ClassDeclared = nullptr;601      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);602      if (!ClassDeclared->getSuperClass()603          && (*ClassDeclared->ivar_begin()) == IV) {604        if (RHS) {605          NamedDecl *ObjectSetClass =606            S.LookupSingleName(S.TUScope,607                               &S.Context.Idents.get("object_setClass"),608                               SourceLocation(), S.LookupOrdinaryName);609          if (ObjectSetClass) {610            SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());611            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)612                << FixItHint::CreateInsertion(OIRE->getBeginLoc(),613                                              "object_setClass(")614                << FixItHint::CreateReplacement(615                       SourceRange(OIRE->getOpLoc(), AssignLoc), ",")616                << FixItHint::CreateInsertion(RHSLocEnd, ")");617          }618          else619            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);620        } else {621          NamedDecl *ObjectGetClass =622            S.LookupSingleName(S.TUScope,623                               &S.Context.Idents.get("object_getClass"),624                               SourceLocation(), S.LookupOrdinaryName);625          if (ObjectGetClass)626            S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)627                << FixItHint::CreateInsertion(OIRE->getBeginLoc(),628                                              "object_getClass(")629                << FixItHint::CreateReplacement(630                       SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");631          else632            S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);633        }634        S.Diag(IV->getLocation(), diag::note_ivar_decl);635      }636    }637}638 639ExprResult Sema::DefaultLvalueConversion(Expr *E) {640  // Handle any placeholder expressions which made it here.641  if (E->hasPlaceholderType()) {642    ExprResult result = CheckPlaceholderExpr(E);643    if (result.isInvalid()) return ExprError();644    E = result.get();645  }646 647  // C++ [conv.lval]p1:648  //   A glvalue of a non-function, non-array type T can be649  //   converted to a prvalue.650  if (!E->isGLValue()) return E;651 652  QualType T = E->getType();653  assert(!T.isNull() && "r-value conversion on typeless expression?");654 655  // lvalue-to-rvalue conversion cannot be applied to types that decay to656  // pointers (i.e. function or array types).657  if (T->canDecayToPointerType())658    return E;659 660  // We don't want to throw lvalue-to-rvalue casts on top of661  // expressions of certain types in C++.662  if (getLangOpts().CPlusPlus) {663    if (T == Context.OverloadTy || T->isRecordType() ||664        (T->isDependentType() && !T->isAnyPointerType() &&665         !T->isMemberPointerType()))666      return E;667  }668 669  // The C standard is actually really unclear on this point, and670  // DR106 tells us what the result should be but not why.  It's671  // generally best to say that void types just doesn't undergo672  // lvalue-to-rvalue at all.  Note that expressions of unqualified673  // 'void' type are never l-values, but qualified void can be.674  if (T->isVoidType())675    return E;676 677  // OpenCL usually rejects direct accesses to values of 'half' type.678  if (getLangOpts().OpenCL &&679      !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&680      T->isHalfType()) {681    Diag(E->getExprLoc(), diag::err_opencl_half_load_store)682      << 0 << T;683    return ExprError();684  }685 686  CheckForNullPointerDereference(*this, E);687  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {688    NamedDecl *ObjectGetClass = LookupSingleName(TUScope,689                                     &Context.Idents.get("object_getClass"),690                                     SourceLocation(), LookupOrdinaryName);691    if (ObjectGetClass)692      Diag(E->getExprLoc(), diag::warn_objc_isa_use)693          << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")694          << FixItHint::CreateReplacement(695                 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");696    else697      Diag(E->getExprLoc(), diag::warn_objc_isa_use);698  }699  else if (const ObjCIvarRefExpr *OIRE =700            dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))701    DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);702 703  // C++ [conv.lval]p1:704  //   [...] If T is a non-class type, the type of the prvalue is the705  //   cv-unqualified version of T. Otherwise, the type of the706  //   rvalue is T.707  //708  // C99 6.3.2.1p2:709  //   If the lvalue has qualified type, the value has the unqualified710  //   version of the type of the lvalue; otherwise, the value has the711  //   type of the lvalue.712  if (T.hasQualifiers())713    T = T.getUnqualifiedType();714 715  // Under the MS ABI, lock down the inheritance model now.716  if (T->isMemberPointerType() &&717      Context.getTargetInfo().getCXXABI().isMicrosoft())718    (void)isCompleteType(E->getExprLoc(), T);719 720  ExprResult Res = CheckLValueToRValueConversionOperand(E);721  if (Res.isInvalid())722    return Res;723  E = Res.get();724 725  // Loading a __weak object implicitly retains the value, so we need a cleanup to726  // balance that.727  if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)728    Cleanup.setExprNeedsCleanups(true);729 730  if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)731    Cleanup.setExprNeedsCleanups(true);732 733  if (!BoundsSafetyCheckUseOfCountAttrPtr(Res.get()))734    return ExprError();735 736  // C++ [conv.lval]p3:737  //   If T is cv std::nullptr_t, the result is a null pointer constant.738  CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;739  Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,740                                 CurFPFeatureOverrides());741 742  // C11 6.3.2.1p2:743  //   ... if the lvalue has atomic type, the value has the non-atomic version744  //   of the type of the lvalue ...745  if (const AtomicType *Atomic = T->getAs<AtomicType>()) {746    T = Atomic->getValueType().getUnqualifiedType();747    Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),748                                   nullptr, VK_PRValue, FPOptionsOverride());749  }750 751  return Res;752}753 754ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {755  ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);756  if (Res.isInvalid())757    return ExprError();758  Res = DefaultLvalueConversion(Res.get());759  if (Res.isInvalid())760    return ExprError();761  return Res;762}763 764ExprResult Sema::CallExprUnaryConversions(Expr *E) {765  QualType Ty = E->getType();766  ExprResult Res = E;767  // Only do implicit cast for a function type, but not for a pointer768  // to function type.769  if (Ty->isFunctionType()) {770    Res = ImpCastExprToType(E, Context.getPointerType(Ty),771                            CK_FunctionToPointerDecay);772    if (Res.isInvalid())773      return ExprError();774  }775  Res = DefaultLvalueConversion(Res.get());776  if (Res.isInvalid())777    return ExprError();778  return Res.get();779}780 781/// UsualUnaryFPConversions - Promotes floating-point types according to the782/// current language semantics.783ExprResult Sema::UsualUnaryFPConversions(Expr *E) {784  QualType Ty = E->getType();785  assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");786 787  LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();788  if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&789      (getLangOpts().getFPEvalMethod() !=790           LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||791       PP.getLastFPEvalPragmaLocation().isValid())) {792    switch (EvalMethod) {793    default:794      llvm_unreachable("Unrecognized float evaluation method");795      break;796    case LangOptions::FEM_UnsetOnCommandLine:797      llvm_unreachable("Float evaluation method should be set by now");798      break;799    case LangOptions::FEM_Double:800      if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)801        // Widen the expression to double.802        return Ty->isComplexType()803                   ? ImpCastExprToType(E,804                                       Context.getComplexType(Context.DoubleTy),805                                       CK_FloatingComplexCast)806                   : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);807      break;808    case LangOptions::FEM_Extended:809      if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)810        // Widen the expression to long double.811        return Ty->isComplexType()812                   ? ImpCastExprToType(813                         E, Context.getComplexType(Context.LongDoubleTy),814                         CK_FloatingComplexCast)815                   : ImpCastExprToType(E, Context.LongDoubleTy,816                                       CK_FloatingCast);817      break;818    }819  }820 821  // Half FP have to be promoted to float unless it is natively supported822  if (Ty->isHalfType() && !getLangOpts().NativeHalfType)823    return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);824 825  return E;826}827 828/// UsualUnaryConversions - Performs various conversions that are common to most829/// operators (C99 6.3). The conversions of array and function types are830/// sometimes suppressed. For example, the array->pointer conversion doesn't831/// apply if the array is an argument to the sizeof or address (&) operators.832/// In these instances, this routine should *not* be called.833ExprResult Sema::UsualUnaryConversions(Expr *E) {834  // First, convert to an r-value.835  ExprResult Res = DefaultFunctionArrayLvalueConversion(E);836  if (Res.isInvalid())837    return ExprError();838 839  // Promote floating-point types.840  Res = UsualUnaryFPConversions(Res.get());841  if (Res.isInvalid())842    return ExprError();843  E = Res.get();844 845  QualType Ty = E->getType();846  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");847 848  // Try to perform integral promotions if the object has a theoretically849  // promotable type.850  if (Ty->isIntegralOrUnscopedEnumerationType()) {851    // C99 6.3.1.1p2:852    //853    //   The following may be used in an expression wherever an int or854    //   unsigned int may be used:855    //     - an object or expression with an integer type whose integer856    //       conversion rank is less than or equal to the rank of int857    //       and unsigned int.858    //     - A bit-field of type _Bool, int, signed int, or unsigned int.859    //860    //   If an int can represent all values of the original type, the861    //   value is converted to an int; otherwise, it is converted to an862    //   unsigned int. These are called the integer promotions. All863    //   other types are unchanged by the integer promotions.864 865    QualType PTy = Context.isPromotableBitField(E);866    if (!PTy.isNull()) {867      E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();868      return E;869    }870    if (Context.isPromotableIntegerType(Ty)) {871      QualType PT = Context.getPromotedIntegerType(Ty);872      E = ImpCastExprToType(E, PT, CK_IntegralCast).get();873      return E;874    }875  }876  return E;877}878 879/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that880/// do not have a prototype. Arguments that have type float or __fp16881/// are promoted to double. All other argument types are converted by882/// UsualUnaryConversions().883ExprResult Sema::DefaultArgumentPromotion(Expr *E) {884  QualType Ty = E->getType();885  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");886 887  ExprResult Res = UsualUnaryConversions(E);888  if (Res.isInvalid())889    return ExprError();890  E = Res.get();891 892  // If this is a 'float'  or '__fp16' (CVR qualified or typedef)893  // promote to double.894  // Note that default argument promotion applies only to float (and895  // half/fp16); it does not apply to _Float16.896  const BuiltinType *BTy = Ty->getAs<BuiltinType>();897  if (BTy && (BTy->getKind() == BuiltinType::Half ||898              BTy->getKind() == BuiltinType::Float)) {899    if (getLangOpts().OpenCL &&900        !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {901      if (BTy->getKind() == BuiltinType::Half) {902        E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();903      }904    } else {905      E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();906    }907  }908  if (BTy &&909      getLangOpts().getExtendIntArgs() ==910          LangOptions::ExtendArgsKind::ExtendTo64 &&911      Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&912      Context.getTypeSizeInChars(BTy) <913          Context.getTypeSizeInChars(Context.LongLongTy)) {914    E = (Ty->isUnsignedIntegerType())915            ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)916                  .get()917            : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();918    assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&919           "Unexpected typesize for LongLongTy");920  }921 922  // C++ performs lvalue-to-rvalue conversion as a default argument923  // promotion, even on class types, but note:924  //   C++11 [conv.lval]p2:925  //     When an lvalue-to-rvalue conversion occurs in an unevaluated926  //     operand or a subexpression thereof the value contained in the927  //     referenced object is not accessed. Otherwise, if the glvalue928  //     has a class type, the conversion copy-initializes a temporary929  //     of type T from the glvalue and the result of the conversion930  //     is a prvalue for the temporary.931  // FIXME: add some way to gate this entire thing for correctness in932  // potentially potentially evaluated contexts.933  if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {934    ExprResult Temp = PerformCopyInitialization(935                       InitializedEntity::InitializeTemporary(E->getType()),936                                                E->getExprLoc(), E);937    if (Temp.isInvalid())938      return ExprError();939    E = Temp.get();940  }941 942  // C++ [expr.call]p7, per CWG722:943  //   An argument that has (possibly cv-qualified) type std::nullptr_t is944  //   converted to void* ([conv.ptr]).945  // (This does not apply to C23 nullptr)946  if (getLangOpts().CPlusPlus && E->getType()->isNullPtrType())947    E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();948 949  return E;950}951 952VarArgKind Sema::isValidVarArgType(const QualType &Ty) {953  if (Ty->isIncompleteType()) {954    // C++11 [expr.call]p7:955    //   After these conversions, if the argument does not have arithmetic,956    //   enumeration, pointer, pointer to member, or class type, the program957    //   is ill-formed.958    //959    // Since we've already performed null pointer conversion, array-to-pointer960    // decay and function-to-pointer decay, the only such type in C++ is cv961    // void. This also handles initializer lists as variadic arguments.962    if (Ty->isVoidType())963      return VarArgKind::Invalid;964 965    if (Ty->isObjCObjectType())966      return VarArgKind::Invalid;967    return VarArgKind::Valid;968  }969 970  if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)971    return VarArgKind::Invalid;972 973  if (Context.getTargetInfo().getTriple().isWasm() &&974      Ty.isWebAssemblyReferenceType()) {975    return VarArgKind::Invalid;976  }977 978  if (Ty.isCXX98PODType(Context))979    return VarArgKind::Valid;980 981  // C++11 [expr.call]p7:982  //   Passing a potentially-evaluated argument of class type (Clause 9)983  //   having a non-trivial copy constructor, a non-trivial move constructor,984  //   or a non-trivial destructor, with no corresponding parameter,985  //   is conditionally-supported with implementation-defined semantics.986  if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())987    if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())988      if (!Record->hasNonTrivialCopyConstructor() &&989          !Record->hasNonTrivialMoveConstructor() &&990          !Record->hasNonTrivialDestructor())991        return VarArgKind::ValidInCXX11;992 993  if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())994    return VarArgKind::Valid;995 996  if (Ty->isObjCObjectType())997    return VarArgKind::Invalid;998 999  if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())1000    return VarArgKind::Valid;1001 1002  if (getLangOpts().MSVCCompat)1003    return VarArgKind::MSVCUndefined;1004 1005  if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())1006    return VarArgKind::Valid;1007 1008  // FIXME: In C++11, these cases are conditionally-supported, meaning we're1009  // permitted to reject them. We should consider doing so.1010  return VarArgKind::Undefined;1011}1012 1013void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {1014  // Don't allow one to pass an Objective-C interface to a vararg.1015  const QualType &Ty = E->getType();1016  VarArgKind VAK = isValidVarArgType(Ty);1017 1018  // Complain about passing non-POD types through varargs.1019  switch (VAK) {1020  case VarArgKind::ValidInCXX11:1021    DiagRuntimeBehavior(1022        E->getBeginLoc(), nullptr,1023        PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);1024    [[fallthrough]];1025  case VarArgKind::Valid:1026    if (Ty->isRecordType()) {1027      // This is unlikely to be what the user intended. If the class has a1028      // 'c_str' member function, the user probably meant to call that.1029      DiagRuntimeBehavior(E->getBeginLoc(), nullptr,1030                          PDiag(diag::warn_pass_class_arg_to_vararg)1031                              << Ty << CT << hasCStrMethod(E) << ".c_str()");1032    }1033    break;1034 1035  case VarArgKind::Undefined:1036  case VarArgKind::MSVCUndefined:1037    DiagRuntimeBehavior(E->getBeginLoc(), nullptr,1038                        PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)1039                            << getLangOpts().CPlusPlus11 << Ty << CT);1040    break;1041 1042  case VarArgKind::Invalid:1043    if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)1044      Diag(E->getBeginLoc(),1045           diag::err_cannot_pass_non_trivial_c_struct_to_vararg)1046          << Ty << CT;1047    else if (Ty->isObjCObjectType())1048      DiagRuntimeBehavior(E->getBeginLoc(), nullptr,1049                          PDiag(diag::err_cannot_pass_objc_interface_to_vararg)1050                              << Ty << CT);1051    else1052      Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)1053          << isa<InitListExpr>(E) << Ty << CT;1054    break;1055  }1056}1057 1058ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,1059                                                  FunctionDecl *FDecl) {1060  if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {1061    // Strip the unbridged-cast placeholder expression off, if applicable.1062    if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&1063        (CT == VariadicCallType::Method ||1064         (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {1065      E = ObjC().stripARCUnbridgedCast(E);1066 1067      // Otherwise, do normal placeholder checking.1068    } else {1069      ExprResult ExprRes = CheckPlaceholderExpr(E);1070      if (ExprRes.isInvalid())1071        return ExprError();1072      E = ExprRes.get();1073    }1074  }1075 1076  ExprResult ExprRes = DefaultArgumentPromotion(E);1077  if (ExprRes.isInvalid())1078    return ExprError();1079 1080  // Copy blocks to the heap.1081  if (ExprRes.get()->getType()->isBlockPointerType())1082    maybeExtendBlockObject(ExprRes);1083 1084  E = ExprRes.get();1085 1086  // Diagnostics regarding non-POD argument types are1087  // emitted along with format string checking in Sema::CheckFunctionCall().1088  if (isValidVarArgType(E->getType()) == VarArgKind::Undefined) {1089    // Turn this into a trap.1090    CXXScopeSpec SS;1091    SourceLocation TemplateKWLoc;1092    UnqualifiedId Name;1093    Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),1094                       E->getBeginLoc());1095    ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,1096                                          /*HasTrailingLParen=*/true,1097                                          /*IsAddressOfOperand=*/false);1098    if (TrapFn.isInvalid())1099      return ExprError();1100 1101    ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},1102                                    E->getEndLoc());1103    if (Call.isInvalid())1104      return ExprError();1105 1106    ExprResult Comma =1107        ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);1108    if (Comma.isInvalid())1109      return ExprError();1110    return Comma.get();1111  }1112 1113  if (!getLangOpts().CPlusPlus &&1114      RequireCompleteType(E->getExprLoc(), E->getType(),1115                          diag::err_call_incomplete_argument))1116    return ExprError();1117 1118  return E;1119}1120 1121/// Convert complex integers to complex floats and real integers to1122/// real floats as required for complex arithmetic. Helper function of1123/// UsualArithmeticConversions()1124///1125/// \return false if the integer expression is an integer type and is1126/// successfully converted to the (complex) float type.1127static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,1128                                                  ExprResult &ComplexExpr,1129                                                  QualType IntTy,1130                                                  QualType ComplexTy,1131                                                  bool SkipCast) {1132  if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;1133  if (SkipCast) return false;1134  if (IntTy->isIntegerType()) {1135    QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();1136    IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);1137  } else {1138    assert(IntTy->isComplexIntegerType());1139    IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,1140                                  CK_IntegralComplexToFloatingComplex);1141  }1142  return false;1143}1144 1145// This handles complex/complex, complex/float, or float/complex.1146// When both operands are complex, the shorter operand is converted to the1147// type of the longer, and that is the type of the result. This corresponds1148// to what is done when combining two real floating-point operands.1149// The fun begins when size promotion occur across type domains.1150// From H&S 6.3.4: When one operand is complex and the other is a real1151// floating-point type, the less precise type is converted, within it's1152// real or complex domain, to the precision of the other type. For example,1153// when combining a "long double" with a "double _Complex", the1154// "double _Complex" is promoted to "long double _Complex".1155static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,1156                                             QualType ShorterType,1157                                             QualType LongerType,1158                                             bool PromotePrecision) {1159  bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());1160  QualType Result =1161      LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);1162 1163  if (PromotePrecision) {1164    if (isa<ComplexType>(ShorterType.getCanonicalType())) {1165      Shorter =1166          S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);1167    } else {1168      if (LongerIsComplex)1169        LongerType = LongerType->castAs<ComplexType>()->getElementType();1170      Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);1171    }1172  }1173  return Result;1174}1175 1176/// Handle arithmetic conversion with complex types.  Helper function of1177/// UsualArithmeticConversions()1178static QualType handleComplexConversion(Sema &S, ExprResult &LHS,1179                                        ExprResult &RHS, QualType LHSType,1180                                        QualType RHSType, bool IsCompAssign) {1181  // Handle (complex) integer types.1182  if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,1183                                             /*SkipCast=*/false))1184    return LHSType;1185  if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,1186                                             /*SkipCast=*/IsCompAssign))1187    return RHSType;1188 1189  // Compute the rank of the two types, regardless of whether they are complex.1190  int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);1191  if (Order < 0)1192    // Promote the precision of the LHS if not an assignment.1193    return handleComplexFloatConversion(S, LHS, LHSType, RHSType,1194                                        /*PromotePrecision=*/!IsCompAssign);1195  // Promote the precision of the RHS unless it is already the same as the LHS.1196  return handleComplexFloatConversion(S, RHS, RHSType, LHSType,1197                                      /*PromotePrecision=*/Order > 0);1198}1199 1200/// Handle arithmetic conversion from integer to float.  Helper function1201/// of UsualArithmeticConversions()1202static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,1203                                           ExprResult &IntExpr,1204                                           QualType FloatTy, QualType IntTy,1205                                           bool ConvertFloat, bool ConvertInt) {1206  if (IntTy->isIntegerType()) {1207    if (ConvertInt)1208      // Convert intExpr to the lhs floating point type.1209      IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,1210                                    CK_IntegralToFloating);1211    return FloatTy;1212  }1213 1214  // Convert both sides to the appropriate complex float.1215  assert(IntTy->isComplexIntegerType());1216  QualType result = S.Context.getComplexType(FloatTy);1217 1218  // _Complex int -> _Complex float1219  if (ConvertInt)1220    IntExpr = S.ImpCastExprToType(IntExpr.get(), result,1221                                  CK_IntegralComplexToFloatingComplex);1222 1223  // float -> _Complex float1224  if (ConvertFloat)1225    FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,1226                                    CK_FloatingRealToComplex);1227 1228  return result;1229}1230 1231/// Handle arithmethic conversion with floating point types.  Helper1232/// function of UsualArithmeticConversions()1233static QualType handleFloatConversion(Sema &S, ExprResult &LHS,1234                                      ExprResult &RHS, QualType LHSType,1235                                      QualType RHSType, bool IsCompAssign) {1236  bool LHSFloat = LHSType->isRealFloatingType();1237  bool RHSFloat = RHSType->isRealFloatingType();1238 1239  // N1169 4.1.4: If one of the operands has a floating type and the other1240  //              operand has a fixed-point type, the fixed-point operand1241  //              is converted to the floating type [...]1242  if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {1243    if (LHSFloat)1244      RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);1245    else if (!IsCompAssign)1246      LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);1247    return LHSFloat ? LHSType : RHSType;1248  }1249 1250  // If we have two real floating types, convert the smaller operand1251  // to the bigger result.1252  if (LHSFloat && RHSFloat) {1253    int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);1254    if (order > 0) {1255      RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);1256      return LHSType;1257    }1258 1259    assert(order < 0 && "illegal float comparison");1260    if (!IsCompAssign)1261      LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);1262    return RHSType;1263  }1264 1265  if (LHSFloat) {1266    // Half FP has to be promoted to float unless it is natively supported1267    if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)1268      LHSType = S.Context.FloatTy;1269 1270    return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,1271                                      /*ConvertFloat=*/!IsCompAssign,1272                                      /*ConvertInt=*/ true);1273  }1274  assert(RHSFloat);1275  return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,1276                                    /*ConvertFloat=*/ true,1277                                    /*ConvertInt=*/!IsCompAssign);1278}1279 1280/// Diagnose attempts to convert between __float128, __ibm128 and1281/// long double if there is no support for such conversion.1282/// Helper function of UsualArithmeticConversions().1283static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,1284                                      QualType RHSType) {1285  // No issue if either is not a floating point type.1286  if (!LHSType->isFloatingType() || !RHSType->isFloatingType())1287    return false;1288 1289  // No issue if both have the same 128-bit float semantics.1290  auto *LHSComplex = LHSType->getAs<ComplexType>();1291  auto *RHSComplex = RHSType->getAs<ComplexType>();1292 1293  QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;1294  QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;1295 1296  const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);1297  const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);1298 1299  if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||1300       &RHSSem != &llvm::APFloat::IEEEquad()) &&1301      (&LHSSem != &llvm::APFloat::IEEEquad() ||1302       &RHSSem != &llvm::APFloat::PPCDoubleDouble()))1303    return false;1304 1305  return true;1306}1307 1308typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);1309 1310namespace {1311/// These helper callbacks are placed in an anonymous namespace to1312/// permit their use as function template parameters.1313ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {1314  return S.ImpCastExprToType(op, toType, CK_IntegralCast);1315}1316 1317ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {1318  return S.ImpCastExprToType(op, S.Context.getComplexType(toType),1319                             CK_IntegralComplexCast);1320}1321}1322 1323/// Handle integer arithmetic conversions.  Helper function of1324/// UsualArithmeticConversions()1325template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>1326static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,1327                                        ExprResult &RHS, QualType LHSType,1328                                        QualType RHSType, bool IsCompAssign) {1329  // The rules for this case are in C99 6.3.1.81330  int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);1331  bool LHSSigned = LHSType->hasSignedIntegerRepresentation();1332  bool RHSSigned = RHSType->hasSignedIntegerRepresentation();1333  if (LHSSigned == RHSSigned) {1334    // Same signedness; use the higher-ranked type1335    if (order >= 0) {1336      RHS = (*doRHSCast)(S, RHS.get(), LHSType);1337      return LHSType;1338    } else if (!IsCompAssign)1339      LHS = (*doLHSCast)(S, LHS.get(), RHSType);1340    return RHSType;1341  } else if (order != (LHSSigned ? 1 : -1)) {1342    // The unsigned type has greater than or equal rank to the1343    // signed type, so use the unsigned type1344    if (RHSSigned) {1345      RHS = (*doRHSCast)(S, RHS.get(), LHSType);1346      return LHSType;1347    } else if (!IsCompAssign)1348      LHS = (*doLHSCast)(S, LHS.get(), RHSType);1349    return RHSType;1350  } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {1351    // The two types are different widths; if we are here, that1352    // means the signed type is larger than the unsigned type, so1353    // use the signed type.1354    if (LHSSigned) {1355      RHS = (*doRHSCast)(S, RHS.get(), LHSType);1356      return LHSType;1357    } else if (!IsCompAssign)1358      LHS = (*doLHSCast)(S, LHS.get(), RHSType);1359    return RHSType;1360  } else {1361    // The signed type is higher-ranked than the unsigned type,1362    // but isn't actually any bigger (like unsigned int and long1363    // on most 32-bit systems).  Use the unsigned type corresponding1364    // to the signed type.1365    QualType result =1366      S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);1367    RHS = (*doRHSCast)(S, RHS.get(), result);1368    if (!IsCompAssign)1369      LHS = (*doLHSCast)(S, LHS.get(), result);1370    return result;1371  }1372}1373 1374/// Handle conversions with GCC complex int extension.  Helper function1375/// of UsualArithmeticConversions()1376static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,1377                                           ExprResult &RHS, QualType LHSType,1378                                           QualType RHSType,1379                                           bool IsCompAssign) {1380  const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();1381  const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();1382 1383  if (LHSComplexInt && RHSComplexInt) {1384    QualType LHSEltType = LHSComplexInt->getElementType();1385    QualType RHSEltType = RHSComplexInt->getElementType();1386    QualType ScalarType =1387      handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>1388        (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);1389 1390    return S.Context.getComplexType(ScalarType);1391  }1392 1393  if (LHSComplexInt) {1394    QualType LHSEltType = LHSComplexInt->getElementType();1395    QualType ScalarType =1396      handleIntegerConversion<doComplexIntegralCast, doIntegralCast>1397        (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);1398    QualType ComplexType = S.Context.getComplexType(ScalarType);1399    RHS = S.ImpCastExprToType(RHS.get(), ComplexType,1400                              CK_IntegralRealToComplex);1401 1402    return ComplexType;1403  }1404 1405  assert(RHSComplexInt);1406 1407  QualType RHSEltType = RHSComplexInt->getElementType();1408  QualType ScalarType =1409    handleIntegerConversion<doIntegralCast, doComplexIntegralCast>1410      (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);1411  QualType ComplexType = S.Context.getComplexType(ScalarType);1412 1413  if (!IsCompAssign)1414    LHS = S.ImpCastExprToType(LHS.get(), ComplexType,1415                              CK_IntegralRealToComplex);1416  return ComplexType;1417}1418 1419/// Return the rank of a given fixed point or integer type. The value itself1420/// doesn't matter, but the values must be increasing with proper increasing1421/// rank as described in N1169 4.1.1.1422static unsigned GetFixedPointRank(QualType Ty) {1423  const auto *BTy = Ty->getAs<BuiltinType>();1424  assert(BTy && "Expected a builtin type.");1425 1426  switch (BTy->getKind()) {1427  case BuiltinType::ShortFract:1428  case BuiltinType::UShortFract:1429  case BuiltinType::SatShortFract:1430  case BuiltinType::SatUShortFract:1431    return 1;1432  case BuiltinType::Fract:1433  case BuiltinType::UFract:1434  case BuiltinType::SatFract:1435  case BuiltinType::SatUFract:1436    return 2;1437  case BuiltinType::LongFract:1438  case BuiltinType::ULongFract:1439  case BuiltinType::SatLongFract:1440  case BuiltinType::SatULongFract:1441    return 3;1442  case BuiltinType::ShortAccum:1443  case BuiltinType::UShortAccum:1444  case BuiltinType::SatShortAccum:1445  case BuiltinType::SatUShortAccum:1446    return 4;1447  case BuiltinType::Accum:1448  case BuiltinType::UAccum:1449  case BuiltinType::SatAccum:1450  case BuiltinType::SatUAccum:1451    return 5;1452  case BuiltinType::LongAccum:1453  case BuiltinType::ULongAccum:1454  case BuiltinType::SatLongAccum:1455  case BuiltinType::SatULongAccum:1456    return 6;1457  default:1458    if (BTy->isInteger())1459      return 0;1460    llvm_unreachable("Unexpected fixed point or integer type");1461  }1462}1463 1464/// handleFixedPointConversion - Fixed point operations between fixed1465/// point types and integers or other fixed point types do not fall under1466/// usual arithmetic conversion since these conversions could result in loss1467/// of precsision (N1169 4.1.4). These operations should be calculated with1468/// the full precision of their result type (N1169 4.1.6.2.1).1469static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,1470                                           QualType RHSTy) {1471  assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&1472         "Expected at least one of the operands to be a fixed point type");1473  assert((LHSTy->isFixedPointOrIntegerType() ||1474          RHSTy->isFixedPointOrIntegerType()) &&1475         "Special fixed point arithmetic operation conversions are only "1476         "applied to ints or other fixed point types");1477 1478  // If one operand has signed fixed-point type and the other operand has1479  // unsigned fixed-point type, then the unsigned fixed-point operand is1480  // converted to its corresponding signed fixed-point type and the resulting1481  // type is the type of the converted operand.1482  if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())1483    LHSTy = S.Context.getCorrespondingSignedFixedPointType(LHSTy);1484  else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())1485    RHSTy = S.Context.getCorrespondingSignedFixedPointType(RHSTy);1486 1487  // The result type is the type with the highest rank, whereby a fixed-point1488  // conversion rank is always greater than an integer conversion rank; if the1489  // type of either of the operands is a saturating fixedpoint type, the result1490  // type shall be the saturating fixed-point type corresponding to the type1491  // with the highest rank; the resulting value is converted (taking into1492  // account rounding and overflow) to the precision of the resulting type.1493  // Same ranks between signed and unsigned types are resolved earlier, so both1494  // types are either signed or both unsigned at this point.1495  unsigned LHSTyRank = GetFixedPointRank(LHSTy);1496  unsigned RHSTyRank = GetFixedPointRank(RHSTy);1497 1498  QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;1499 1500  if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())1501    ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);1502 1503  return ResultTy;1504}1505 1506/// Check that the usual arithmetic conversions can be performed on this pair of1507/// expressions that might be of enumeration type.1508void Sema::checkEnumArithmeticConversions(Expr *LHS, Expr *RHS,1509                                          SourceLocation Loc,1510                                          ArithConvKind ACK) {1511  // C++2a [expr.arith.conv]p1:1512  //   If one operand is of enumeration type and the other operand is of a1513  //   different enumeration type or a floating-point type, this behavior is1514  //   deprecated ([depr.arith.conv.enum]).1515  //1516  // Warn on this in all language modes. Produce a deprecation warning in C++20.1517  // Eventually we will presumably reject these cases (in C++23 onwards?).1518  QualType L = LHS->getEnumCoercedType(Context),1519           R = RHS->getEnumCoercedType(Context);1520  bool LEnum = L->isUnscopedEnumerationType(),1521       REnum = R->isUnscopedEnumerationType();1522  bool IsCompAssign = ACK == ArithConvKind::CompAssign;1523  if ((!IsCompAssign && LEnum && R->isFloatingType()) ||1524      (REnum && L->isFloatingType())) {1525    Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx261526              : getLangOpts().CPlusPlus201527                  ? diag::warn_arith_conv_enum_float_cxx201528                  : diag::warn_arith_conv_enum_float)1529        << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum1530        << L << R;1531  } else if (!IsCompAssign && LEnum && REnum &&1532             !Context.hasSameUnqualifiedType(L, R)) {1533    unsigned DiagID;1534    // In C++ 26, usual arithmetic conversions between 2 different enum types1535    // are ill-formed.1536    if (getLangOpts().CPlusPlus26)1537      DiagID = diag::warn_conv_mixed_enum_types_cxx26;1538    else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||1539             !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {1540      // If either enumeration type is unnamed, it's less likely that the1541      // user cares about this, but this situation is still deprecated in1542      // C++2a. Use a different warning group.1543      DiagID = getLangOpts().CPlusPlus201544                   ? diag::warn_arith_conv_mixed_anon_enum_types_cxx201545                   : diag::warn_arith_conv_mixed_anon_enum_types;1546    } else if (ACK == ArithConvKind::Conditional) {1547      // Conditional expressions are separated out because they have1548      // historically had a different warning flag.1549      DiagID = getLangOpts().CPlusPlus201550                   ? diag::warn_conditional_mixed_enum_types_cxx201551                   : diag::warn_conditional_mixed_enum_types;1552    } else if (ACK == ArithConvKind::Comparison) {1553      // Comparison expressions are separated out because they have1554      // historically had a different warning flag.1555      DiagID = getLangOpts().CPlusPlus201556                   ? diag::warn_comparison_mixed_enum_types_cxx201557                   : diag::warn_comparison_mixed_enum_types;1558    } else {1559      DiagID = getLangOpts().CPlusPlus201560                   ? diag::warn_arith_conv_mixed_enum_types_cxx201561                   : diag::warn_arith_conv_mixed_enum_types;1562    }1563    Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()1564                      << (int)ACK << L << R;1565  }1566}1567 1568static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS,1569                                              Expr *RHS, SourceLocation Loc,1570                                              ArithConvKind ACK) {1571  QualType LHSType = LHS->getType().getUnqualifiedType();1572  QualType RHSType = RHS->getType().getUnqualifiedType();1573 1574  if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||1575      !RHSType->isUnicodeCharacterType())1576    return;1577 1578  if (ACK == ArithConvKind::Comparison) {1579    if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))1580      return;1581 1582    auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {1583      if (T->isChar8Type())1584        return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());1585      if (T->isChar16Type())1586        return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());1587      assert(T->isChar32Type());1588      return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());1589    };1590 1591    Expr::EvalResult LHSRes, RHSRes;1592    bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),1593                                         Expr::SE_AllowSideEffects,1594                                         SemaRef.isConstantEvaluatedContext());1595    bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),1596                                        Expr::SE_AllowSideEffects,1597                                        SemaRef.isConstantEvaluatedContext());1598 1599    // Don't warn if the one known value is a representable1600    // in the type of both expressions.1601    if (LHSSuccess != RHSuccess) {1602      Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;1603      if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&1604          IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))1605        return;1606    }1607 1608    if (!LHSSuccess || !RHSuccess) {1609      SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)1610          << LHS->getSourceRange() << RHS->getSourceRange() << LHSType1611          << RHSType;1612      return;1613    }1614 1615    llvm::APSInt LHSValue(32);1616    LHSValue = LHSRes.Val.getInt();1617    llvm::APSInt RHSValue(32);1618    RHSValue = RHSRes.Val.getInt();1619 1620    bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);1621    bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);1622    if (LHSSafe && RHSSafe)1623      return;1624 1625    SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)1626        << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType1627        << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)1628        << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);1629    return;1630  }1631 1632  if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))1633    return;1634 1635  SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)1636      << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType1637      << RHSType;1638}1639 1640/// UsualArithmeticConversions - Performs various conversions that are common to1641/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this1642/// routine returns the first non-arithmetic type found. The client is1643/// responsible for emitting appropriate error diagnostics.1644QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,1645                                          SourceLocation Loc,1646                                          ArithConvKind ACK) {1647 1648  checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);1649 1650  CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);1651 1652  if (ACK != ArithConvKind::CompAssign) {1653    LHS = UsualUnaryConversions(LHS.get());1654    if (LHS.isInvalid())1655      return QualType();1656  }1657 1658  RHS = UsualUnaryConversions(RHS.get());1659  if (RHS.isInvalid())1660    return QualType();1661 1662  // For conversion purposes, we ignore any qualifiers.1663  // For example, "const float" and "float" are equivalent.1664  QualType LHSType = LHS.get()->getType().getUnqualifiedType();1665  QualType RHSType = RHS.get()->getType().getUnqualifiedType();1666 1667  // For conversion purposes, we ignore any atomic qualifier on the LHS.1668  if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())1669    LHSType = AtomicLHS->getValueType();1670 1671  // If both types are identical, no conversion is needed.1672  if (Context.hasSameType(LHSType, RHSType))1673    return Context.getCommonSugaredType(LHSType, RHSType);1674 1675  // If either side is a non-arithmetic type (e.g. a pointer), we are done.1676  // The caller can deal with this (e.g. pointer + int).1677  if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())1678    return QualType();1679 1680  // Apply unary and bitfield promotions to the LHS's type.1681  QualType LHSUnpromotedType = LHSType;1682  if (Context.isPromotableIntegerType(LHSType))1683    LHSType = Context.getPromotedIntegerType(LHSType);1684  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());1685  if (!LHSBitfieldPromoteTy.isNull())1686    LHSType = LHSBitfieldPromoteTy;1687  if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)1688    LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);1689 1690  // If both types are identical, no conversion is needed.1691  if (Context.hasSameType(LHSType, RHSType))1692    return Context.getCommonSugaredType(LHSType, RHSType);1693 1694  // At this point, we have two different arithmetic types.1695 1696  // Diagnose attempts to convert between __ibm128, __float128 and long double1697  // where such conversions currently can't be handled.1698  if (unsupportedTypeConversion(*this, LHSType, RHSType))1699    return QualType();1700 1701  // Handle complex types first (C99 6.3.1.8p1).1702  if (LHSType->isComplexType() || RHSType->isComplexType())1703    return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,1704                                   ACK == ArithConvKind::CompAssign);1705 1706  // Now handle "real" floating types (i.e. float, double, long double).1707  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())1708    return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,1709                                 ACK == ArithConvKind::CompAssign);1710 1711  // Handle GCC complex int extension.1712  if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())1713    return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,1714                                      ACK == ArithConvKind::CompAssign);1715 1716  if (LHSType->isFixedPointType() || RHSType->isFixedPointType())1717    return handleFixedPointConversion(*this, LHSType, RHSType);1718 1719  // Finally, we have two differing integer types.1720  return handleIntegerConversion<doIntegralCast, doIntegralCast>(1721      *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);1722}1723 1724//===----------------------------------------------------------------------===//1725//  Semantic Analysis for various Expression Types1726//===----------------------------------------------------------------------===//1727 1728 1729ExprResult Sema::ActOnGenericSelectionExpr(1730    SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,1731    bool PredicateIsExpr, void *ControllingExprOrType,1732    ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {1733  unsigned NumAssocs = ArgTypes.size();1734  assert(NumAssocs == ArgExprs.size());1735 1736  TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];1737  for (unsigned i = 0; i < NumAssocs; ++i) {1738    if (ArgTypes[i])1739      (void) GetTypeFromParser(ArgTypes[i], &Types[i]);1740    else1741      Types[i] = nullptr;1742  }1743 1744  // If we have a controlling type, we need to convert it from a parsed type1745  // into a semantic type and then pass that along.1746  if (!PredicateIsExpr) {1747    TypeSourceInfo *ControllingType;1748    (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),1749                            &ControllingType);1750    assert(ControllingType && "couldn't get the type out of the parser");1751    ControllingExprOrType = ControllingType;1752  }1753 1754  ExprResult ER = CreateGenericSelectionExpr(1755      KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,1756      llvm::ArrayRef(Types, NumAssocs), ArgExprs);1757  delete [] Types;1758  return ER;1759}1760 1761ExprResult Sema::CreateGenericSelectionExpr(1762    SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,1763    bool PredicateIsExpr, void *ControllingExprOrType,1764    ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {1765  unsigned NumAssocs = Types.size();1766  assert(NumAssocs == Exprs.size());1767  assert(ControllingExprOrType &&1768         "Must have either a controlling expression or a controlling type");1769 1770  Expr *ControllingExpr = nullptr;1771  TypeSourceInfo *ControllingType = nullptr;1772  if (PredicateIsExpr) {1773    // Decay and strip qualifiers for the controlling expression type, and1774    // handle placeholder type replacement. See committee discussion from WG141775    // DR423.1776    EnterExpressionEvaluationContext Unevaluated(1777        *this, Sema::ExpressionEvaluationContext::Unevaluated);1778    ExprResult R = DefaultFunctionArrayLvalueConversion(1779        reinterpret_cast<Expr *>(ControllingExprOrType));1780    if (R.isInvalid())1781      return ExprError();1782    ControllingExpr = R.get();1783  } else {1784    // The extension form uses the type directly rather than converting it.1785    ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);1786    if (!ControllingType)1787      return ExprError();1788  }1789 1790  bool TypeErrorFound = false,1791       IsResultDependent = ControllingExpr1792                               ? ControllingExpr->isTypeDependent()1793                               : ControllingType->getType()->isDependentType(),1794       ContainsUnexpandedParameterPack =1795           ControllingExpr1796               ? ControllingExpr->containsUnexpandedParameterPack()1797               : ControllingType->getType()->containsUnexpandedParameterPack();1798 1799  // The controlling expression is an unevaluated operand, so side effects are1800  // likely unintended.1801  if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&1802      ControllingExpr->HasSideEffects(Context, false))1803    Diag(ControllingExpr->getExprLoc(),1804         diag::warn_side_effects_unevaluated_context);1805 1806  for (unsigned i = 0; i < NumAssocs; ++i) {1807    if (Exprs[i]->containsUnexpandedParameterPack())1808      ContainsUnexpandedParameterPack = true;1809 1810    if (Types[i]) {1811      if (Types[i]->getType()->containsUnexpandedParameterPack())1812        ContainsUnexpandedParameterPack = true;1813 1814      if (Types[i]->getType()->isDependentType()) {1815        IsResultDependent = true;1816      } else {1817        // We relax the restriction on use of incomplete types and non-object1818        // types with the type-based extension of _Generic. Allowing incomplete1819        // objects means those can be used as "tags" for a type-safe way to map1820        // to a value. Similarly, matching on function types rather than1821        // function pointer types can be useful. However, the restriction on VM1822        // types makes sense to retain as there are open questions about how1823        // the selection can be made at compile time.1824        //1825        // C11 6.5.1.1p2 "The type name in a generic association shall specify a1826        // complete object type other than a variably modified type."1827        // C2y removed the requirement that an expression form must1828        // use a complete type, though it's still as-if the type has undergone1829        // lvalue conversion. We support this as an extension in C23 and1830        // earlier because GCC does so.1831        unsigned D = 0;1832        if (ControllingExpr && Types[i]->getType()->isIncompleteType())1833          D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete1834                           : diag::ext_assoc_type_incomplete;1835        else if (ControllingExpr && !Types[i]->getType()->isObjectType())1836          D = diag::err_assoc_type_nonobject;1837        else if (Types[i]->getType()->isVariablyModifiedType())1838          D = diag::err_assoc_type_variably_modified;1839        else if (ControllingExpr) {1840          // Because the controlling expression undergoes lvalue conversion,1841          // array conversion, and function conversion, an association which is1842          // of array type, function type, or is qualified can never be1843          // reached. We will warn about this so users are less surprised by1844          // the unreachable association. However, we don't have to handle1845          // function types; that's not an object type, so it's handled above.1846          //1847          // The logic is somewhat different for C++ because C++ has different1848          // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,1849          // If T is a non-class type, the type of the prvalue is the cv-1850          // unqualified version of T. Otherwise, the type of the prvalue is T.1851          // The result of these rules is that all qualified types in an1852          // association in C are unreachable, and in C++, only qualified non-1853          // class types are unreachable.1854          //1855          // NB: this does not apply when the first operand is a type rather1856          // than an expression, because the type form does not undergo1857          // conversion.1858          unsigned Reason = 0;1859          QualType QT = Types[i]->getType();1860          if (QT->isArrayType())1861            Reason = 1;1862          else if (QT.hasQualifiers() &&1863                   (!LangOpts.CPlusPlus || !QT->isRecordType()))1864            Reason = 2;1865 1866          if (Reason)1867            Diag(Types[i]->getTypeLoc().getBeginLoc(),1868                 diag::warn_unreachable_association)1869                << QT << (Reason - 1);1870        }1871 1872        if (D != 0) {1873          Diag(Types[i]->getTypeLoc().getBeginLoc(), D)1874              << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();1875          if (getDiagnostics().getDiagnosticLevel(1876                  D, Types[i]->getTypeLoc().getBeginLoc()) >=1877              DiagnosticsEngine::Error)1878            TypeErrorFound = true;1879        }1880 1881        // C11 6.5.1.1p2 "No two generic associations in the same generic1882        // selection shall specify compatible types."1883        for (unsigned j = i+1; j < NumAssocs; ++j)1884          if (Types[j] && !Types[j]->getType()->isDependentType() &&1885              Context.typesAreCompatible(Types[i]->getType(),1886                                         Types[j]->getType())) {1887            Diag(Types[j]->getTypeLoc().getBeginLoc(),1888                 diag::err_assoc_compatible_types)1889              << Types[j]->getTypeLoc().getSourceRange()1890              << Types[j]->getType()1891              << Types[i]->getType();1892            Diag(Types[i]->getTypeLoc().getBeginLoc(),1893                 diag::note_compat_assoc)1894              << Types[i]->getTypeLoc().getSourceRange()1895              << Types[i]->getType();1896            TypeErrorFound = true;1897          }1898      }1899    }1900  }1901  if (TypeErrorFound)1902    return ExprError();1903 1904  // If we determined that the generic selection is result-dependent, don't1905  // try to compute the result expression.1906  if (IsResultDependent) {1907    if (ControllingExpr)1908      return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,1909                                          Types, Exprs, DefaultLoc, RParenLoc,1910                                          ContainsUnexpandedParameterPack);1911    return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,1912                                        Exprs, DefaultLoc, RParenLoc,1913                                        ContainsUnexpandedParameterPack);1914  }1915 1916  SmallVector<unsigned, 1> CompatIndices;1917  unsigned DefaultIndex = std::numeric_limits<unsigned>::max();1918  // Look at the canonical type of the controlling expression in case it was a1919  // deduced type like __auto_type. However, when issuing diagnostics, use the1920  // type the user wrote in source rather than the canonical one.1921  for (unsigned i = 0; i < NumAssocs; ++i) {1922    if (!Types[i])1923      DefaultIndex = i;1924    else if (ControllingExpr &&1925             Context.typesAreCompatible(1926                 ControllingExpr->getType().getCanonicalType(),1927                 Types[i]->getType()))1928      CompatIndices.push_back(i);1929    else if (ControllingType &&1930             Context.typesAreCompatible(1931                 ControllingType->getType().getCanonicalType(),1932                 Types[i]->getType()))1933      CompatIndices.push_back(i);1934  }1935 1936  auto GetControllingRangeAndType = [](Expr *ControllingExpr,1937                                       TypeSourceInfo *ControllingType) {1938    // We strip parens here because the controlling expression is typically1939    // parenthesized in macro definitions.1940    if (ControllingExpr)1941      ControllingExpr = ControllingExpr->IgnoreParens();1942 1943    SourceRange SR = ControllingExpr1944                         ? ControllingExpr->getSourceRange()1945                         : ControllingType->getTypeLoc().getSourceRange();1946    QualType QT = ControllingExpr ? ControllingExpr->getType()1947                                  : ControllingType->getType();1948 1949    return std::make_pair(SR, QT);1950  };1951 1952  // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have1953  // type compatible with at most one of the types named in its generic1954  // association list."1955  if (CompatIndices.size() > 1) {1956    auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);1957    SourceRange SR = P.first;1958    Diag(SR.getBegin(), diag::err_generic_sel_multi_match)1959        << SR << P.second << (unsigned)CompatIndices.size();1960    for (unsigned I : CompatIndices) {1961      Diag(Types[I]->getTypeLoc().getBeginLoc(),1962           diag::note_compat_assoc)1963        << Types[I]->getTypeLoc().getSourceRange()1964        << Types[I]->getType();1965    }1966    return ExprError();1967  }1968 1969  // C11 6.5.1.1p2 "If a generic selection has no default generic association,1970  // its controlling expression shall have type compatible with exactly one of1971  // the types named in its generic association list."1972  if (DefaultIndex == std::numeric_limits<unsigned>::max() &&1973      CompatIndices.size() == 0) {1974    auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);1975    SourceRange SR = P.first;1976    Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;1977    return ExprError();1978  }1979 1980  // C11 6.5.1.1p3 "If a generic selection has a generic association with a1981  // type name that is compatible with the type of the controlling expression,1982  // then the result expression of the generic selection is the expression1983  // in that generic association. Otherwise, the result expression of the1984  // generic selection is the expression in the default generic association."1985  unsigned ResultIndex =1986    CompatIndices.size() ? CompatIndices[0] : DefaultIndex;1987 1988  if (ControllingExpr) {1989    return GenericSelectionExpr::Create(1990        Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,1991        ContainsUnexpandedParameterPack, ResultIndex);1992  }1993  return GenericSelectionExpr::Create(1994      Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,1995      ContainsUnexpandedParameterPack, ResultIndex);1996}1997 1998static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {1999  switch (Kind) {2000  default:2001    llvm_unreachable("unexpected TokenKind");2002  case tok::kw___func__:2003    return PredefinedIdentKind::Func; // [C99 6.4.2.2]2004  case tok::kw___FUNCTION__:2005    return PredefinedIdentKind::Function;2006  case tok::kw___FUNCDNAME__:2007    return PredefinedIdentKind::FuncDName; // [MS]2008  case tok::kw___FUNCSIG__:2009    return PredefinedIdentKind::FuncSig; // [MS]2010  case tok::kw_L__FUNCTION__:2011    return PredefinedIdentKind::LFunction; // [MS]2012  case tok::kw_L__FUNCSIG__:2013    return PredefinedIdentKind::LFuncSig; // [MS]2014  case tok::kw___PRETTY_FUNCTION__:2015    return PredefinedIdentKind::PrettyFunction; // [GNU]2016  }2017}2018 2019/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used2020/// to determine the value of a PredefinedExpr. This can be either a2021/// block, lambda, captured statement, function, otherwise a nullptr.2022static Decl *getPredefinedExprDecl(DeclContext *DC) {2023  while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))2024    DC = DC->getParent();2025  return cast_or_null<Decl>(DC);2026}2027 2028/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the2029/// location of the token and the offset of the ud-suffix within it.2030static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,2031                                     unsigned Offset) {2032  return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),2033                                        S.getLangOpts());2034}2035 2036/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up2037/// the corresponding cooked (non-raw) literal operator, and build a call to it.2038static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,2039                                                 IdentifierInfo *UDSuffix,2040                                                 SourceLocation UDSuffixLoc,2041                                                 ArrayRef<Expr*> Args,2042                                                 SourceLocation LitEndLoc) {2043  assert(Args.size() <= 2 && "too many arguments for literal operator");2044 2045  QualType ArgTy[2];2046  for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {2047    ArgTy[ArgIdx] = Args[ArgIdx]->getType();2048    if (ArgTy[ArgIdx]->isArrayType())2049      ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);2050  }2051 2052  DeclarationName OpName =2053    S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);2054  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);2055  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);2056 2057  LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);2058  if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),2059                              /*AllowRaw*/ false, /*AllowTemplate*/ false,2060                              /*AllowStringTemplatePack*/ false,2061                              /*DiagnoseMissing*/ true) == Sema::LOLR_Error)2062    return ExprError();2063 2064  return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);2065}2066 2067ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {2068  // StringToks needs backing storage as it doesn't hold array elements itself2069  std::vector<Token> ExpandedToks;2070  if (getLangOpts().MicrosoftExt)2071    StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);2072 2073  StringLiteralParser Literal(StringToks, PP,2074                              StringLiteralEvalMethod::Unevaluated);2075  if (Literal.hadError)2076    return ExprError();2077 2078  SmallVector<SourceLocation, 4> StringTokLocs;2079  for (const Token &Tok : StringToks)2080    StringTokLocs.push_back(Tok.getLocation());2081 2082  StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),2083                                             StringLiteralKind::Unevaluated,2084                                             false, {}, StringTokLocs);2085 2086  if (!Literal.getUDSuffix().empty()) {2087    SourceLocation UDSuffixLoc =2088        getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],2089                       Literal.getUDSuffixOffset());2090    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));2091  }2092 2093  return Lit;2094}2095 2096std::vector<Token>2097Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {2098  // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function2099  // local macros that expand to string literals that may be concatenated.2100  // These macros are expanded here (in Sema), because StringLiteralParser2101  // (in Lex) doesn't know the enclosing function (because it hasn't been2102  // parsed yet).2103  assert(getLangOpts().MicrosoftExt);2104 2105  // Note: Although function local macros are defined only inside functions,2106  // we ensure a valid `CurrentDecl` even outside of a function. This allows2107  // expansion of macros into empty string literals without additional checks.2108  Decl *CurrentDecl = getPredefinedExprDecl(CurContext);2109  if (!CurrentDecl)2110    CurrentDecl = Context.getTranslationUnitDecl();2111 2112  std::vector<Token> ExpandedToks;2113  ExpandedToks.reserve(Toks.size());2114  for (const Token &Tok : Toks) {2115    if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {2116      assert(tok::isStringLiteral(Tok.getKind()));2117      ExpandedToks.emplace_back(Tok);2118      continue;2119    }2120    if (isa<TranslationUnitDecl>(CurrentDecl))2121      Diag(Tok.getLocation(), diag::ext_predef_outside_function);2122    // Stringify predefined expression2123    Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)2124        << Tok.getKind();2125    SmallString<64> Str;2126    llvm::raw_svector_ostream OS(Str);2127    Token &Exp = ExpandedToks.emplace_back();2128    Exp.startToken();2129    if (Tok.getKind() == tok::kw_L__FUNCTION__ ||2130        Tok.getKind() == tok::kw_L__FUNCSIG__) {2131      OS << 'L';2132      Exp.setKind(tok::wide_string_literal);2133    } else {2134      Exp.setKind(tok::string_literal);2135    }2136    OS << '"'2137       << Lexer::Stringify(PredefinedExpr::ComputeName(2138              getPredefinedExprKind(Tok.getKind()), CurrentDecl))2139       << '"';2140    PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());2141  }2142  return ExpandedToks;2143}2144 2145ExprResult2146Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {2147  assert(!StringToks.empty() && "Must have at least one string!");2148 2149  // StringToks needs backing storage as it doesn't hold array elements itself2150  std::vector<Token> ExpandedToks;2151  if (getLangOpts().MicrosoftExt)2152    StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);2153 2154  StringLiteralParser Literal(StringToks, PP);2155  if (Literal.hadError)2156    return ExprError();2157 2158  SmallVector<SourceLocation, 4> StringTokLocs;2159  for (const Token &Tok : StringToks)2160    StringTokLocs.push_back(Tok.getLocation());2161 2162  QualType CharTy = Context.CharTy;2163  StringLiteralKind Kind = StringLiteralKind::Ordinary;2164  if (Literal.isWide()) {2165    CharTy = Context.getWideCharType();2166    Kind = StringLiteralKind::Wide;2167  } else if (Literal.isUTF8()) {2168    if (getLangOpts().Char8)2169      CharTy = Context.Char8Ty;2170    else if (getLangOpts().C23)2171      CharTy = Context.UnsignedCharTy;2172    Kind = StringLiteralKind::UTF8;2173  } else if (Literal.isUTF16()) {2174    CharTy = Context.Char16Ty;2175    Kind = StringLiteralKind::UTF16;2176  } else if (Literal.isUTF32()) {2177    CharTy = Context.Char32Ty;2178    Kind = StringLiteralKind::UTF32;2179  } else if (Literal.isPascal()) {2180    CharTy = Context.UnsignedCharTy;2181  }2182 2183  // Warn on u8 string literals before C++20 and C23, whose type2184  // was an array of char before but becomes an array of char8_t.2185  // In C++20, it cannot be used where a pointer to char is expected.2186  // In C23, it might have an unexpected value if char was signed.2187  if (Kind == StringLiteralKind::UTF8 &&2188      (getLangOpts().CPlusPlus2189           ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char82190           : !getLangOpts().C23)) {2191    Diag(StringTokLocs.front(), getLangOpts().CPlusPlus2192                                    ? diag::warn_cxx20_compat_utf8_string2193                                    : diag::warn_c23_compat_utf8_string);2194 2195    // Create removals for all 'u8' prefixes in the string literal(s). This2196    // ensures C++20/C23 compatibility (but may change the program behavior when2197    // built by non-Clang compilers for which the execution character set is2198    // not always UTF-8).2199    auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);2200    SourceLocation RemovalDiagLoc;2201    for (const Token &Tok : StringToks) {2202      if (Tok.getKind() == tok::utf8_string_literal) {2203        if (RemovalDiagLoc.isInvalid())2204          RemovalDiagLoc = Tok.getLocation();2205        RemovalDiag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(2206            Tok.getLocation(),2207            Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,2208                                           getSourceManager(), getLangOpts())));2209      }2210    }2211    Diag(RemovalDiagLoc, RemovalDiag);2212  }2213 2214  QualType StrTy =2215      Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());2216 2217  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!2218  StringLiteral *Lit = StringLiteral::Create(2219      Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);2220  if (Literal.getUDSuffix().empty())2221    return Lit;2222 2223  // We're building a user-defined literal.2224  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());2225  SourceLocation UDSuffixLoc =2226    getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],2227                   Literal.getUDSuffixOffset());2228 2229  // Make sure we're allowed user-defined literals here.2230  if (!UDLScope)2231    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));2232 2233  // C++11 [lex.ext]p5: The literal L is treated as a call of the form2234  //   operator "" X (str, len)2235  QualType SizeType = Context.getSizeType();2236 2237  DeclarationName OpName =2238    Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);2239  DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);2240  OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);2241 2242  QualType ArgTy[] = {2243    Context.getArrayDecayedType(StrTy), SizeType2244  };2245 2246  LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);2247  switch (LookupLiteralOperator(UDLScope, R, ArgTy,2248                                /*AllowRaw*/ false, /*AllowTemplate*/ true,2249                                /*AllowStringTemplatePack*/ true,2250                                /*DiagnoseMissing*/ true, Lit)) {2251 2252  case LOLR_Cooked: {2253    llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());2254    IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,2255                                                    StringTokLocs[0]);2256    Expr *Args[] = { Lit, LenArg };2257 2258    return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());2259  }2260 2261  case LOLR_Template: {2262    TemplateArgumentListInfo ExplicitArgs;2263    TemplateArgument Arg(Lit, /*IsCanonical=*/false);2264    TemplateArgumentLocInfo ArgInfo(Lit);2265    ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));2266    return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),2267                                    &ExplicitArgs);2268  }2269 2270  case LOLR_StringTemplatePack: {2271    TemplateArgumentListInfo ExplicitArgs;2272 2273    unsigned CharBits = Context.getIntWidth(CharTy);2274    bool CharIsUnsigned = CharTy->isUnsignedIntegerType();2275    llvm::APSInt Value(CharBits, CharIsUnsigned);2276 2277    TemplateArgument TypeArg(CharTy);2278    TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));2279    ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));2280 2281    for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {2282      Value = Lit->getCodeUnit(I);2283      TemplateArgument Arg(Context, Value, CharTy);2284      TemplateArgumentLocInfo ArgInfo;2285      ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));2286    }2287    return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),2288                                    &ExplicitArgs);2289  }2290  case LOLR_Raw:2291  case LOLR_ErrorNoDiagnostic:2292    llvm_unreachable("unexpected literal operator lookup result");2293  case LOLR_Error:2294    return ExprError();2295  }2296  llvm_unreachable("unexpected literal operator lookup result");2297}2298 2299DeclRefExpr *2300Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,2301                       SourceLocation Loc,2302                       const CXXScopeSpec *SS) {2303  DeclarationNameInfo NameInfo(D->getDeclName(), Loc);2304  return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);2305}2306 2307DeclRefExpr *2308Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,2309                       const DeclarationNameInfo &NameInfo,2310                       const CXXScopeSpec *SS, NamedDecl *FoundD,2311                       SourceLocation TemplateKWLoc,2312                       const TemplateArgumentListInfo *TemplateArgs) {2313  NestedNameSpecifierLoc NNS =2314      SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();2315  return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,2316                          TemplateArgs);2317}2318 2319// CUDA/HIP: Check whether a captured reference variable is referencing a2320// host variable in a device or host device lambda.2321static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,2322                                                            VarDecl *VD) {2323  if (!S.getLangOpts().CUDA || !VD->hasInit())2324    return false;2325  assert(VD->getType()->isReferenceType());2326 2327  // Check whether the reference variable is referencing a host variable.2328  auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());2329  if (!DRE)2330    return false;2331  auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());2332  if (!Referee || !Referee->hasGlobalStorage() ||2333      Referee->hasAttr<CUDADeviceAttr>())2334    return false;2335 2336  // Check whether the current function is a device or host device lambda.2337  // Check whether the reference variable is a capture by getDeclContext()2338  // since refersToEnclosingVariableOrCapture() is not ready at this point.2339  auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);2340  if (MD && MD->getParent()->isLambda() &&2341      MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&2342      VD->getDeclContext() != MD)2343    return true;2344 2345  return false;2346}2347 2348NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {2349  // A declaration named in an unevaluated operand never constitutes an odr-use.2350  if (isUnevaluatedContext())2351    return NOUR_Unevaluated;2352 2353  // C++2a [basic.def.odr]p4:2354  //   A variable x whose name appears as a potentially-evaluated expression e2355  //   is odr-used by e unless [...] x is a reference that is usable in2356  //   constant expressions.2357  // CUDA/HIP:2358  //   If a reference variable referencing a host variable is captured in a2359  //   device or host device lambda, the value of the referee must be copied2360  //   to the capture and the reference variable must be treated as odr-use2361  //   since the value of the referee is not known at compile time and must2362  //   be loaded from the captured.2363  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {2364    if (VD->getType()->isReferenceType() &&2365        !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&2366        !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD) &&2367        VD->isUsableInConstantExpressions(Context))2368      return NOUR_Constant;2369  }2370 2371  // All remaining non-variable cases constitute an odr-use. For variables, we2372  // need to wait and see how the expression is used.2373  return NOUR_None;2374}2375 2376DeclRefExpr *2377Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,2378                       const DeclarationNameInfo &NameInfo,2379                       NestedNameSpecifierLoc NNS, NamedDecl *FoundD,2380                       SourceLocation TemplateKWLoc,2381                       const TemplateArgumentListInfo *TemplateArgs) {2382  bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&2383                                  NeedToCaptureVariable(D, NameInfo.getLoc());2384 2385  DeclRefExpr *E = DeclRefExpr::Create(2386      Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,2387      VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));2388  MarkDeclRefReferenced(E);2389 2390  // C++ [except.spec]p17:2391  //   An exception-specification is considered to be needed when:2392  //   - in an expression, the function is the unique lookup result or2393  //     the selected member of a set of overloaded functions.2394  //2395  // We delay doing this until after we've built the function reference and2396  // marked it as used so that:2397  //  a) if the function is defaulted, we get errors from defining it before /2398  //     instead of errors from computing its exception specification, and2399  //  b) if the function is a defaulted comparison, we can use the body we2400  //     build when defining it as input to the exception specification2401  //     computation rather than computing a new body.2402  if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {2403    if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {2404      if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))2405        E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));2406    }2407  }2408 2409  if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&2410      Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&2411      !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))2412    getCurFunction()->recordUseOfWeak(E);2413 2414  const auto *FD = dyn_cast<FieldDecl>(D);2415  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))2416    FD = IFD->getAnonField();2417  if (FD) {2418    UnusedPrivateFields.remove(FD);2419    // Just in case we're building an illegal pointer-to-member.2420    if (FD->isBitField())2421      E->setObjectKind(OK_BitField);2422  }2423 2424  // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier2425  // designates a bit-field.2426  if (const auto *BD = dyn_cast<BindingDecl>(D))2427    if (const auto *BE = BD->getBinding())2428      E->setObjectKind(BE->getObjectKind());2429 2430  return E;2431}2432 2433void2434Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,2435                             TemplateArgumentListInfo &Buffer,2436                             DeclarationNameInfo &NameInfo,2437                             const TemplateArgumentListInfo *&TemplateArgs) {2438  if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {2439    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);2440    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);2441 2442    ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),2443                                       Id.TemplateId->NumArgs);2444    translateTemplateArguments(TemplateArgsPtr, Buffer);2445 2446    TemplateName TName = Id.TemplateId->Template.get();2447    SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;2448    NameInfo = Context.getNameForTemplate(TName, TNameLoc);2449    TemplateArgs = &Buffer;2450  } else {2451    NameInfo = GetNameFromUnqualifiedId(Id);2452    TemplateArgs = nullptr;2453  }2454}2455 2456bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {2457  // During a default argument instantiation the CurContext points2458  // to a CXXMethodDecl; but we can't apply a this-> fixit inside a2459  // function parameter list, hence add an explicit check.2460  bool isDefaultArgument =2461      !CodeSynthesisContexts.empty() &&2462      CodeSynthesisContexts.back().Kind ==2463          CodeSynthesisContext::DefaultFunctionArgumentInstantiation;2464  const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);2465  bool isInstance = CurMethod && CurMethod->isInstance() &&2466                    R.getNamingClass() == CurMethod->getParent() &&2467                    !isDefaultArgument;2468 2469  // There are two ways we can find a class-scope declaration during template2470  // instantiation that we did not find in the template definition: if it is a2471  // member of a dependent base class, or if it is declared after the point of2472  // use in the same class. Distinguish these by comparing the class in which2473  // the member was found to the naming class of the lookup.2474  unsigned DiagID = diag::err_found_in_dependent_base;2475  unsigned NoteID = diag::note_member_declared_at;2476  if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {2477    DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class2478                                      : diag::err_found_later_in_class;2479  } else if (getLangOpts().MSVCCompat) {2480    DiagID = diag::ext_found_in_dependent_base;2481    NoteID = diag::note_dependent_member_use;2482  }2483 2484  if (isInstance) {2485    // Give a code modification hint to insert 'this->'.2486    Diag(R.getNameLoc(), DiagID)2487        << R.getLookupName()2488        << FixItHint::CreateInsertion(R.getNameLoc(), "this->");2489    CheckCXXThisCapture(R.getNameLoc());2490  } else {2491    // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming2492    // they're not shadowed).2493    Diag(R.getNameLoc(), DiagID) << R.getLookupName();2494  }2495 2496  for (const NamedDecl *D : R)2497    Diag(D->getLocation(), NoteID);2498 2499  // Return true if we are inside a default argument instantiation2500  // and the found name refers to an instance member function, otherwise2501  // the caller will try to create an implicit member call and this is wrong2502  // for default arguments.2503  //2504  // FIXME: Is this special case necessary? We could allow the caller to2505  // diagnose this.2506  if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {2507    Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;2508    return true;2509  }2510 2511  // Tell the callee to try to recover.2512  return false;2513}2514 2515bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,2516                               CorrectionCandidateCallback &CCC,2517                               TemplateArgumentListInfo *ExplicitTemplateArgs,2518                               ArrayRef<Expr *> Args, DeclContext *LookupCtx) {2519  DeclarationName Name = R.getLookupName();2520  SourceRange NameRange = R.getLookupNameInfo().getSourceRange();2521 2522  unsigned diagnostic = diag::err_undeclared_var_use;2523  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;2524  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||2525      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||2526      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {2527    diagnostic = diag::err_undeclared_use;2528    diagnostic_suggest = diag::err_undeclared_use_suggest;2529  }2530 2531  // If the original lookup was an unqualified lookup, fake an2532  // unqualified lookup.  This is useful when (for example) the2533  // original lookup would not have found something because it was a2534  // dependent name.2535  DeclContext *DC =2536      LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);2537  while (DC) {2538    if (isa<CXXRecordDecl>(DC)) {2539      if (ExplicitTemplateArgs) {2540        if (LookupTemplateName(2541                R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),2542                /*EnteringContext*/ false, TemplateNameIsRequired,2543                /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))2544          return true;2545      } else {2546        LookupQualifiedName(R, DC);2547      }2548 2549      if (!R.empty()) {2550        // Don't give errors about ambiguities in this lookup.2551        R.suppressDiagnostics();2552 2553        // If there's a best viable function among the results, only mention2554        // that one in the notes.2555        OverloadCandidateSet Candidates(R.getNameLoc(),2556                                        OverloadCandidateSet::CSK_Normal);2557        AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);2558        OverloadCandidateSet::iterator Best;2559        if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==2560            OR_Success) {2561          R.clear();2562          R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());2563          R.resolveKind();2564        }2565 2566        return DiagnoseDependentMemberLookup(R);2567      }2568 2569      R.clear();2570    }2571 2572    DC = DC->getLookupParent();2573  }2574 2575  // We didn't find anything, so try to correct for a typo.2576  TypoCorrection Corrected;2577  if (S && (Corrected =2578                CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,2579                            CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {2580    std::string CorrectedStr(Corrected.getAsString(getLangOpts()));2581    bool DroppedSpecifier =2582        Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;2583    R.setLookupName(Corrected.getCorrection());2584 2585    bool AcceptableWithRecovery = false;2586    bool AcceptableWithoutRecovery = false;2587    NamedDecl *ND = Corrected.getFoundDecl();2588    if (ND) {2589      if (Corrected.isOverloaded()) {2590        OverloadCandidateSet OCS(R.getNameLoc(),2591                                 OverloadCandidateSet::CSK_Normal);2592        OverloadCandidateSet::iterator Best;2593        for (NamedDecl *CD : Corrected) {2594          if (FunctionTemplateDecl *FTD =2595                   dyn_cast<FunctionTemplateDecl>(CD))2596            AddTemplateOverloadCandidate(2597                FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,2598                Args, OCS);2599          else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))2600            if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)2601              AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),2602                                   Args, OCS);2603        }2604        switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {2605        case OR_Success:2606          ND = Best->FoundDecl;2607          Corrected.setCorrectionDecl(ND);2608          break;2609        default:2610          // FIXME: Arbitrarily pick the first declaration for the note.2611          Corrected.setCorrectionDecl(ND);2612          break;2613        }2614      }2615      R.addDecl(ND);2616      if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {2617        CXXRecordDecl *Record =2618            Corrected.getCorrectionSpecifier().getAsRecordDecl();2619        if (!Record)2620          Record = cast<CXXRecordDecl>(2621              ND->getDeclContext()->getRedeclContext());2622        R.setNamingClass(Record);2623      }2624 2625      auto *UnderlyingND = ND->getUnderlyingDecl();2626      AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||2627                               isa<FunctionTemplateDecl>(UnderlyingND);2628      // FIXME: If we ended up with a typo for a type name or2629      // Objective-C class name, we're in trouble because the parser2630      // is in the wrong place to recover. Suggest the typo2631      // correction, but don't make it a fix-it since we're not going2632      // to recover well anyway.2633      AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||2634                                  getAsTypeTemplateDecl(UnderlyingND) ||2635                                  isa<ObjCInterfaceDecl>(UnderlyingND);2636    } else {2637      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it2638      // because we aren't able to recover.2639      AcceptableWithoutRecovery = true;2640    }2641 2642    if (AcceptableWithRecovery || AcceptableWithoutRecovery) {2643      unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()2644                            ? diag::note_implicit_param_decl2645                            : diag::note_previous_decl;2646      if (SS.isEmpty())2647        diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,2648                     PDiag(NoteID), AcceptableWithRecovery);2649      else2650        diagnoseTypo(Corrected,2651                     PDiag(diag::err_no_member_suggest)2652                         << Name << computeDeclContext(SS, false)2653                         << DroppedSpecifier << NameRange,2654                     PDiag(NoteID), AcceptableWithRecovery);2655 2656      // Tell the callee whether to try to recover.2657      return !AcceptableWithRecovery;2658    }2659  }2660  R.clear();2661 2662  // Emit a special diagnostic for failed member lookups.2663  // FIXME: computing the declaration context might fail here (?)2664  if (!SS.isEmpty()) {2665    Diag(R.getNameLoc(), diag::err_no_member)2666        << Name << computeDeclContext(SS, false) << NameRange;2667    return true;2668  }2669 2670  // Give up, we can't recover.2671  Diag(R.getNameLoc(), diagnostic) << Name << NameRange;2672  return true;2673}2674 2675/// In Microsoft mode, if we are inside a template class whose parent class has2676/// dependent base classes, and we can't resolve an unqualified identifier, then2677/// assume the identifier is a member of a dependent base class.  We can only2678/// recover successfully in static methods, instance methods, and other contexts2679/// where 'this' is available.  This doesn't precisely match MSVC's2680/// instantiation model, but it's close enough.2681static Expr *2682recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,2683                               DeclarationNameInfo &NameInfo,2684                               SourceLocation TemplateKWLoc,2685                               const TemplateArgumentListInfo *TemplateArgs) {2686  // Only try to recover from lookup into dependent bases in static methods or2687  // contexts where 'this' is available.2688  QualType ThisType = S.getCurrentThisType();2689  const CXXRecordDecl *RD = nullptr;2690  if (!ThisType.isNull())2691    RD = ThisType->getPointeeType()->getAsCXXRecordDecl();2692  else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))2693    RD = MD->getParent();2694  if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())2695    return nullptr;2696 2697  // Diagnose this as unqualified lookup into a dependent base class.  If 'this'2698  // is available, suggest inserting 'this->' as a fixit.2699  SourceLocation Loc = NameInfo.getLoc();2700  auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);2701  DB << NameInfo.getName() << RD;2702 2703  if (!ThisType.isNull()) {2704    DB << FixItHint::CreateInsertion(Loc, "this->");2705    return CXXDependentScopeMemberExpr::Create(2706        Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,2707        /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,2708        /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);2709  }2710 2711  // Synthesize a fake NNS that points to the derived class.  This will2712  // perform name lookup during template instantiation.2713  CXXScopeSpec SS;2714  NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());2715  SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));2716  return DependentScopeDeclRefExpr::Create(2717      Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,2718      TemplateArgs);2719}2720 2721ExprResult2722Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,2723                        SourceLocation TemplateKWLoc, UnqualifiedId &Id,2724                        bool HasTrailingLParen, bool IsAddressOfOperand,2725                        CorrectionCandidateCallback *CCC,2726                        bool IsInlineAsmIdentifier, Token *KeywordReplacement) {2727  assert(!(IsAddressOfOperand && HasTrailingLParen) &&2728         "cannot be direct & operand and have a trailing lparen");2729  if (SS.isInvalid())2730    return ExprError();2731 2732  TemplateArgumentListInfo TemplateArgsBuffer;2733 2734  // Decompose the UnqualifiedId into the following data.2735  DeclarationNameInfo NameInfo;2736  const TemplateArgumentListInfo *TemplateArgs;2737  DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);2738 2739  DeclarationName Name = NameInfo.getName();2740  IdentifierInfo *II = Name.getAsIdentifierInfo();2741  SourceLocation NameLoc = NameInfo.getLoc();2742 2743  if (II && II->isEditorPlaceholder()) {2744    // FIXME: When typed placeholders are supported we can create a typed2745    // placeholder expression node.2746    return ExprError();2747  }2748 2749  // This specially handles arguments of attributes appertains to a type of C2750  // struct field such that the name lookup within a struct finds the member2751  // name, which is not the case for other contexts in C.2752  if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {2753    // See if this is reference to a field of struct.2754    LookupResult R(*this, NameInfo, LookupMemberName);2755    // LookupName handles a name lookup from within anonymous struct.2756    if (LookupName(R, S)) {2757      if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {2758        QualType type = VD->getType().getNonReferenceType();2759        // This will eventually be translated into MemberExpr upon2760        // the use of instantiated struct fields.2761        return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);2762      }2763    }2764  }2765 2766  // Perform the required lookup.2767  LookupResult R(*this, NameInfo,2768                 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)2769                     ? LookupObjCImplicitSelfParam2770                     : LookupOrdinaryName);2771  if (TemplateKWLoc.isValid() || TemplateArgs) {2772    // Lookup the template name again to correctly establish the context in2773    // which it was found. This is really unfortunate as we already did the2774    // lookup to determine that it was a template name in the first place. If2775    // this becomes a performance hit, we can work harder to preserve those2776    // results until we get here but it's likely not worth it.2777    AssumedTemplateKind AssumedTemplate;2778    if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),2779                           /*EnteringContext=*/false, TemplateKWLoc,2780                           &AssumedTemplate))2781      return ExprError();2782 2783    if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())2784      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,2785                                        IsAddressOfOperand, TemplateArgs);2786  } else {2787    bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();2788    LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),2789                     /*AllowBuiltinCreation=*/!IvarLookupFollowUp);2790 2791    // If the result might be in a dependent base class, this is a dependent2792    // id-expression.2793    if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())2794      return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,2795                                        IsAddressOfOperand, TemplateArgs);2796 2797    // If this reference is in an Objective-C method, then we need to do2798    // some special Objective-C lookup, too.2799    if (IvarLookupFollowUp) {2800      ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));2801      if (E.isInvalid())2802        return ExprError();2803 2804      if (Expr *Ex = E.getAs<Expr>())2805        return Ex;2806    }2807  }2808 2809  if (R.isAmbiguous())2810    return ExprError();2811 2812  // This could be an implicitly declared function reference if the language2813  // mode allows it as a feature.2814  if (R.empty() && HasTrailingLParen && II &&2815      getLangOpts().implicitFunctionsAllowed()) {2816    NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);2817    if (D) R.addDecl(D);2818  }2819 2820  // Determine whether this name might be a candidate for2821  // argument-dependent lookup.2822  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);2823 2824  if (R.empty() && !ADL) {2825    if (SS.isEmpty() && getLangOpts().MSVCCompat) {2826      if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,2827                                                   TemplateKWLoc, TemplateArgs))2828        return E;2829    }2830 2831    // Don't diagnose an empty lookup for inline assembly.2832    if (IsInlineAsmIdentifier)2833      return ExprError();2834 2835    // If this name wasn't predeclared and if this is not a function2836    // call, diagnose the problem.2837    DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());2838    DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;2839    assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&2840           "Typo correction callback misconfigured");2841    if (CCC) {2842      // Make sure the callback knows what the typo being diagnosed is.2843      CCC->setTypoName(II);2844      if (SS.isValid())2845        CCC->setTypoNNS(SS.getScopeRep());2846    }2847    // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for2848    // a template name, but we happen to have always already looked up the name2849    // before we get here if it must be a template name.2850    if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,2851                            {}, nullptr))2852      return ExprError();2853 2854    assert(!R.empty() &&2855           "DiagnoseEmptyLookup returned false but added no results");2856 2857    // If we found an Objective-C instance variable, let2858    // LookupInObjCMethod build the appropriate expression to2859    // reference the ivar.2860    if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {2861      R.clear();2862      ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));2863      // In a hopelessly buggy code, Objective-C instance variable2864      // lookup fails and no expression will be built to reference it.2865      if (!E.isInvalid() && !E.get())2866        return ExprError();2867      return E;2868    }2869  }2870 2871  // This is guaranteed from this point on.2872  assert(!R.empty() || ADL);2873 2874  // Check whether this might be a C++ implicit instance member access.2875  // C++ [class.mfct.non-static]p3:2876  //   When an id-expression that is not part of a class member access2877  //   syntax and not used to form a pointer to member is used in the2878  //   body of a non-static member function of class X, if name lookup2879  //   resolves the name in the id-expression to a non-static non-type2880  //   member of some class C, the id-expression is transformed into a2881  //   class member access expression using (*this) as the2882  //   postfix-expression to the left of the . operator.2883  //2884  // But we don't actually need to do this for '&' operands if R2885  // resolved to a function or overloaded function set, because the2886  // expression is ill-formed if it actually works out to be a2887  // non-static member function:2888  //2889  // C++ [expr.ref]p4:2890  //   Otherwise, if E1.E2 refers to a non-static member function. . .2891  //   [t]he expression can be used only as the left-hand operand of a2892  //   member function call.2893  //2894  // There are other safeguards against such uses, but it's important2895  // to get this right here so that we don't end up making a2896  // spuriously dependent expression if we're inside a dependent2897  // instance method.2898  if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))2899    return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,2900                                           S);2901 2902  if (TemplateArgs || TemplateKWLoc.isValid()) {2903 2904    // In C++1y, if this is a variable template id, then check it2905    // in BuildTemplateIdExpr().2906    // The single lookup result must be a variable template declaration.2907    if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&2908        (Id.TemplateId->Kind == TNK_Var_template ||2909         Id.TemplateId->Kind == TNK_Concept_template)) {2910      assert(R.getAsSingle<TemplateDecl>() &&2911             "There should only be one declaration found.");2912    }2913 2914    return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);2915  }2916 2917  return BuildDeclarationNameExpr(SS, R, ADL);2918}2919 2920ExprResult Sema::BuildQualifiedDeclarationNameExpr(2921    CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,2922    bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {2923  LookupResult R(*this, NameInfo, LookupOrdinaryName);2924  LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());2925 2926  if (R.isAmbiguous())2927    return ExprError();2928 2929  if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())2930    return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),2931                                     NameInfo, /*TemplateArgs=*/nullptr);2932 2933  if (R.empty()) {2934    // Don't diagnose problems with invalid record decl, the secondary no_member2935    // diagnostic during template instantiation is likely bogus, e.g. if a class2936    // is invalid because it's derived from an invalid base class, then missing2937    // members were likely supposed to be inherited.2938    DeclContext *DC = computeDeclContext(SS);2939    if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))2940      if (CD->isInvalidDecl())2941        return ExprError();2942    Diag(NameInfo.getLoc(), diag::err_no_member)2943      << NameInfo.getName() << DC << SS.getRange();2944    return ExprError();2945  }2946 2947  if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {2948    QualType ET;2949    TypeLocBuilder TLB;2950    if (auto *TagD = dyn_cast<TagDecl>(TD)) {2951      ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,2952                                      SS.getScopeRep(), TagD,2953                                      /*OwnsTag=*/false);2954      auto TL = TLB.push<TagTypeLoc>(ET);2955      TL.setElaboratedKeywordLoc(SourceLocation());2956      TL.setQualifierLoc(SS.getWithLocInContext(Context));2957      TL.setNameLoc(NameInfo.getLoc());2958    } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {2959      ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,2960                                          SS.getScopeRep(), TypedefD);2961      TLB.push<TypedefTypeLoc>(ET).set(2962          /*ElaboratedKeywordLoc=*/SourceLocation(),2963          SS.getWithLocInContext(Context), NameInfo.getLoc());2964    } else {2965      // FIXME: What else can appear here?2966      ET = SemaRef.Context.getTypeDeclType(TD);2967      TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());2968      assert(SS.isEmpty());2969    }2970 2971    // Diagnose a missing typename if this resolved unambiguously to a type in2972    // a dependent context.  If we can recover with a type, downgrade this to2973    // a warning in Microsoft compatibility mode.2974    unsigned DiagID = diag::err_typename_missing;2975    if (RecoveryTSI && getLangOpts().MSVCCompat)2976      DiagID = diag::ext_typename_missing;2977    SourceLocation Loc = SS.getBeginLoc();2978    auto D = Diag(Loc, DiagID);2979    D << ET << SourceRange(Loc, NameInfo.getEndLoc());2980 2981    // Don't recover if the caller isn't expecting us to or if we're in a SFINAE2982    // context.2983    if (!RecoveryTSI)2984      return ExprError();2985 2986    // Only issue the fixit if we're prepared to recover.2987    D << FixItHint::CreateInsertion(Loc, "typename ");2988 2989    // Recover by pretending this was an elaborated type.2990    *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);2991 2992    return ExprEmpty();2993  }2994 2995  // If necessary, build an implicit class member access.2996  if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))2997    return BuildPossibleImplicitMemberExpr(SS,2998                                           /*TemplateKWLoc=*/SourceLocation(),2999                                           R, /*TemplateArgs=*/nullptr,3000                                           /*S=*/nullptr);3001 3002  return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);3003}3004 3005ExprResult Sema::PerformObjectMemberConversion(Expr *From,3006                                               NestedNameSpecifier Qualifier,3007                                               NamedDecl *FoundDecl,3008                                               NamedDecl *Member) {3009  const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());3010  if (!RD)3011    return From;3012 3013  QualType DestRecordType;3014  QualType DestType;3015  QualType FromRecordType;3016  QualType FromType = From->getType();3017  bool PointerConversions = false;3018  if (isa<FieldDecl>(Member)) {3019    DestRecordType = Context.getCanonicalTagType(RD);3020    auto FromPtrType = FromType->getAs<PointerType>();3021    DestRecordType = Context.getAddrSpaceQualType(3022        DestRecordType, FromPtrType3023                            ? FromType->getPointeeType().getAddressSpace()3024                            : FromType.getAddressSpace());3025 3026    if (FromPtrType) {3027      DestType = Context.getPointerType(DestRecordType);3028      FromRecordType = FromPtrType->getPointeeType();3029      PointerConversions = true;3030    } else {3031      DestType = DestRecordType;3032      FromRecordType = FromType;3033    }3034  } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {3035    if (!Method->isImplicitObjectMemberFunction())3036      return From;3037 3038    DestType = Method->getThisType().getNonReferenceType();3039    DestRecordType = Method->getFunctionObjectParameterType();3040 3041    if (FromType->getAs<PointerType>()) {3042      FromRecordType = FromType->getPointeeType();3043      PointerConversions = true;3044    } else {3045      FromRecordType = FromType;3046      DestType = DestRecordType;3047    }3048 3049    LangAS FromAS = FromRecordType.getAddressSpace();3050    LangAS DestAS = DestRecordType.getAddressSpace();3051    if (FromAS != DestAS) {3052      QualType FromRecordTypeWithoutAS =3053          Context.removeAddrSpaceQualType(FromRecordType);3054      QualType FromTypeWithDestAS =3055          Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);3056      if (PointerConversions)3057        FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);3058      From = ImpCastExprToType(From, FromTypeWithDestAS,3059                               CK_AddressSpaceConversion, From->getValueKind())3060                 .get();3061    }3062  } else {3063    // No conversion necessary.3064    return From;3065  }3066 3067  if (DestType->isDependentType() || FromType->isDependentType())3068    return From;3069 3070  // If the unqualified types are the same, no conversion is necessary.3071  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))3072    return From;3073 3074  SourceRange FromRange = From->getSourceRange();3075  SourceLocation FromLoc = FromRange.getBegin();3076 3077  ExprValueKind VK = From->getValueKind();3078 3079  // C++ [class.member.lookup]p8:3080  //   [...] Ambiguities can often be resolved by qualifying a name with its3081  //   class name.3082  //3083  // If the member was a qualified name and the qualified referred to a3084  // specific base subobject type, we'll cast to that intermediate type3085  // first and then to the object in which the member is declared. That allows3086  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:3087  //3088  //   class Base { public: int x; };3089  //   class Derived1 : public Base { };3090  //   class Derived2 : public Base { };3091  //   class VeryDerived : public Derived1, public Derived2 { void f(); };3092  //3093  //   void VeryDerived::f() {3094  //     x = 17; // error: ambiguous base subobjects3095  //     Derived1::x = 17; // okay, pick the Base subobject of Derived13096  //   }3097  if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {3098    QualType QType = QualType(Qualifier.getAsType(), 0);3099    assert(QType->isRecordType() && "lookup done with non-record type");3100 3101    QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);3102 3103    // In C++98, the qualifier type doesn't actually have to be a base3104    // type of the object type, in which case we just ignore it.3105    // Otherwise build the appropriate casts.3106    if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {3107      CXXCastPath BasePath;3108      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,3109                                       FromLoc, FromRange, &BasePath))3110        return ExprError();3111 3112      if (PointerConversions)3113        QType = Context.getPointerType(QType);3114      From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,3115                               VK, &BasePath).get();3116 3117      FromType = QType;3118      FromRecordType = QRecordType;3119 3120      // If the qualifier type was the same as the destination type,3121      // we're done.3122      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))3123        return From;3124    }3125  }3126 3127  CXXCastPath BasePath;3128  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,3129                                   FromLoc, FromRange, &BasePath,3130                                   /*IgnoreAccess=*/true))3131    return ExprError();3132 3133  // Propagate qualifiers to base subobjects as per:3134  // C++ [basic.type.qualifier]p1.2:3135  //   A volatile object is [...] a subobject of a volatile object.3136  Qualifiers FromTypeQuals = FromType.getQualifiers();3137  FromTypeQuals.setAddressSpace(DestType.getAddressSpace());3138  DestType = Context.getQualifiedType(DestType, FromTypeQuals);3139 3140  return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,3141                           &BasePath);3142}3143 3144bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,3145                                      const LookupResult &R,3146                                      bool HasTrailingLParen) {3147  // Only when used directly as the postfix-expression of a call.3148  if (!HasTrailingLParen)3149    return false;3150 3151  // Never if a scope specifier was provided.3152  if (SS.isNotEmpty())3153    return false;3154 3155  // Only in C++ or ObjC++.3156  if (!getLangOpts().CPlusPlus)3157    return false;3158 3159  // Turn off ADL when we find certain kinds of declarations during3160  // normal lookup:3161  for (const NamedDecl *D : R) {3162    // C++0x [basic.lookup.argdep]p3:3163    //     -- a declaration of a class member3164    // Since using decls preserve this property, we check this on the3165    // original decl.3166    if (D->isCXXClassMember())3167      return false;3168 3169    // C++0x [basic.lookup.argdep]p3:3170    //     -- a block-scope function declaration that is not a3171    //        using-declaration3172    // NOTE: we also trigger this for function templates (in fact, we3173    // don't check the decl type at all, since all other decl types3174    // turn off ADL anyway).3175    if (isa<UsingShadowDecl>(D))3176      D = cast<UsingShadowDecl>(D)->getTargetDecl();3177    else if (D->getLexicalDeclContext()->isFunctionOrMethod())3178      return false;3179 3180    // C++0x [basic.lookup.argdep]p3:3181    //     -- a declaration that is neither a function or a function3182    //        template3183    // And also for builtin functions.3184    if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {3185      // But also builtin functions.3186      if (FDecl->getBuiltinID() && FDecl->isImplicit())3187        return false;3188    } else if (!isa<FunctionTemplateDecl>(D))3189      return false;3190  }3191 3192  return true;3193}3194 3195 3196/// Diagnoses obvious problems with the use of the given declaration3197/// as an expression.  This is only actually called for lookups that3198/// were not overloaded, and it doesn't promise that the declaration3199/// will in fact be used.3200static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,3201                            bool AcceptInvalid) {3202  if (D->isInvalidDecl() && !AcceptInvalid)3203    return true;3204 3205  if (isa<TypedefNameDecl>(D)) {3206    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();3207    return true;3208  }3209 3210  if (isa<ObjCInterfaceDecl>(D)) {3211    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();3212    return true;3213  }3214 3215  if (isa<NamespaceDecl>(D)) {3216    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();3217    return true;3218  }3219 3220  return false;3221}3222 3223// Certain multiversion types should be treated as overloaded even when there is3224// only one result.3225static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {3226  assert(R.isSingleResult() && "Expected only a single result");3227  const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());3228  return FD &&3229         (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());3230}3231 3232ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,3233                                          LookupResult &R, bool NeedsADL,3234                                          bool AcceptInvalidDecl) {3235  // If this is a single, fully-resolved result and we don't need ADL,3236  // just build an ordinary singleton decl ref.3237  if (!NeedsADL && R.isSingleResult() &&3238      !R.getAsSingle<FunctionTemplateDecl>() &&3239      !ShouldLookupResultBeMultiVersionOverload(R))3240    return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),3241                                    R.getRepresentativeDecl(), nullptr,3242                                    AcceptInvalidDecl);3243 3244  // We only need to check the declaration if there's exactly one3245  // result, because in the overloaded case the results can only be3246  // functions and function templates.3247  if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&3248      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),3249                      AcceptInvalidDecl))3250    return ExprError();3251 3252  // Otherwise, just build an unresolved lookup expression.  Suppress3253  // any lookup-related diagnostics; we'll hash these out later, when3254  // we've picked a target.3255  R.suppressDiagnostics();3256 3257  UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(3258      Context, R.getNamingClass(), SS.getWithLocInContext(Context),3259      R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),3260      /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);3261 3262  return ULE;3263}3264 3265ExprResult Sema::BuildDeclarationNameExpr(3266    const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,3267    NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,3268    bool AcceptInvalidDecl) {3269  assert(D && "Cannot refer to a NULL declaration");3270  assert(!isa<FunctionTemplateDecl>(D) &&3271         "Cannot refer unambiguously to a function template");3272 3273  SourceLocation Loc = NameInfo.getLoc();3274  if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {3275    // Recovery from invalid cases (e.g. D is an invalid Decl).3276    // We use the dependent type for the RecoveryExpr to prevent bogus follow-up3277    // diagnostics, as invalid decls use int as a fallback type.3278    return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});3279  }3280 3281  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {3282    // Specifically diagnose references to class templates that are missing3283    // a template argument list.3284    diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);3285    return ExprError();3286  }3287 3288  // Make sure that we're referring to a value.3289  if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {3290    Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();3291    Diag(D->getLocation(), diag::note_declared_at);3292    return ExprError();3293  }3294 3295  // Check whether this declaration can be used. Note that we suppress3296  // this check when we're going to perform argument-dependent lookup3297  // on this function name, because this might not be the function3298  // that overload resolution actually selects.3299  if (DiagnoseUseOfDecl(D, Loc))3300    return ExprError();3301 3302  auto *VD = cast<ValueDecl>(D);3303 3304  // Only create DeclRefExpr's for valid Decl's.3305  if (VD->isInvalidDecl() && !AcceptInvalidDecl)3306    return ExprError();3307 3308  // Handle members of anonymous structs and unions.  If we got here,3309  // and the reference is to a class member indirect field, then this3310  // must be the subject of a pointer-to-member expression.3311  if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);3312      IndirectField && !IndirectField->isCXXClassMember())3313    return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),3314                                                    IndirectField);3315 3316  QualType type = VD->getType();3317  if (type.isNull())3318    return ExprError();3319  ExprValueKind valueKind = VK_PRValue;3320 3321  // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of3322  // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,3323  // is expanded by some outer '...' in the context of the use.3324  type = type.getNonPackExpansionType();3325 3326  switch (D->getKind()) {3327    // Ignore all the non-ValueDecl kinds.3328#define ABSTRACT_DECL(kind)3329#define VALUE(type, base)3330#define DECL(type, base) case Decl::type:3331#include "clang/AST/DeclNodes.inc"3332    llvm_unreachable("invalid value decl kind");3333 3334  // These shouldn't make it here.3335  case Decl::ObjCAtDefsField:3336    llvm_unreachable("forming non-member reference to ivar?");3337 3338  // Enum constants are always r-values and never references.3339  // Unresolved using declarations are dependent.3340  case Decl::EnumConstant:3341  case Decl::UnresolvedUsingValue:3342  case Decl::OMPDeclareReduction:3343  case Decl::OMPDeclareMapper:3344    valueKind = VK_PRValue;3345    break;3346 3347  // Fields and indirect fields that got here must be for3348  // pointer-to-member expressions; we just call them l-values for3349  // internal consistency, because this subexpression doesn't really3350  // exist in the high-level semantics.3351  case Decl::Field:3352  case Decl::IndirectField:3353  case Decl::ObjCIvar:3354    assert((getLangOpts().CPlusPlus || isAttrContext()) &&3355           "building reference to field in C?");3356 3357    // These can't have reference type in well-formed programs, but3358    // for internal consistency we do this anyway.3359    type = type.getNonReferenceType();3360    valueKind = VK_LValue;3361    break;3362 3363  // Non-type template parameters are either l-values or r-values3364  // depending on the type.3365  case Decl::NonTypeTemplateParm: {3366    if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {3367      type = reftype->getPointeeType();3368      valueKind = VK_LValue; // even if the parameter is an r-value reference3369      break;3370    }3371 3372    // [expr.prim.id.unqual]p2:3373    //   If the entity is a template parameter object for a template3374    //   parameter of type T, the type of the expression is const T.3375    //   [...] The expression is an lvalue if the entity is a [...] template3376    //   parameter object.3377    if (type->isRecordType()) {3378      type = type.getUnqualifiedType().withConst();3379      valueKind = VK_LValue;3380      break;3381    }3382 3383    // For non-references, we need to strip qualifiers just in case3384    // the template parameter was declared as 'const int' or whatever.3385    valueKind = VK_PRValue;3386    type = type.getUnqualifiedType();3387    break;3388  }3389 3390  case Decl::Var:3391  case Decl::VarTemplateSpecialization:3392  case Decl::VarTemplatePartialSpecialization:3393  case Decl::Decomposition:3394  case Decl::Binding:3395  case Decl::OMPCapturedExpr:3396    // In C, "extern void blah;" is valid and is an r-value.3397    if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&3398        type->isVoidType()) {3399      valueKind = VK_PRValue;3400      break;3401    }3402    [[fallthrough]];3403 3404  case Decl::ImplicitParam:3405  case Decl::ParmVar: {3406    // These are always l-values.3407    valueKind = VK_LValue;3408    type = type.getNonReferenceType();3409 3410    // FIXME: Does the addition of const really only apply in3411    // potentially-evaluated contexts? Since the variable isn't actually3412    // captured in an unevaluated context, it seems that the answer is no.3413    if (!isUnevaluatedContext()) {3414      QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);3415      if (!CapturedType.isNull())3416        type = CapturedType;3417    }3418    break;3419  }3420 3421  case Decl::Function: {3422    if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {3423      if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {3424        type = Context.BuiltinFnTy;3425        valueKind = VK_PRValue;3426        break;3427      }3428    }3429 3430    const FunctionType *fty = type->castAs<FunctionType>();3431 3432    // If we're referring to a function with an __unknown_anytype3433    // result type, make the entire expression __unknown_anytype.3434    if (fty->getReturnType() == Context.UnknownAnyTy) {3435      type = Context.UnknownAnyTy;3436      valueKind = VK_PRValue;3437      break;3438    }3439 3440    // Functions are l-values in C++.3441    if (getLangOpts().CPlusPlus) {3442      valueKind = VK_LValue;3443      break;3444    }3445 3446    // C99 DR 316 says that, if a function type comes from a3447    // function definition (without a prototype), that type is only3448    // used for checking compatibility. Therefore, when referencing3449    // the function, we pretend that we don't have the full function3450    // type.3451    if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))3452      type = Context.getFunctionNoProtoType(fty->getReturnType(),3453                                            fty->getExtInfo());3454 3455    // Functions are r-values in C.3456    valueKind = VK_PRValue;3457    break;3458  }3459 3460  case Decl::CXXDeductionGuide:3461    llvm_unreachable("building reference to deduction guide");3462 3463  case Decl::MSProperty:3464  case Decl::MSGuid:3465  case Decl::TemplateParamObject:3466    // FIXME: Should MSGuidDecl and template parameter objects be subject to3467    // capture in OpenMP, or duplicated between host and device?3468    valueKind = VK_LValue;3469    break;3470 3471  case Decl::UnnamedGlobalConstant:3472    valueKind = VK_LValue;3473    break;3474 3475  case Decl::CXXMethod:3476    // If we're referring to a method with an __unknown_anytype3477    // result type, make the entire expression __unknown_anytype.3478    // This should only be possible with a type written directly.3479    if (const FunctionProtoType *proto =3480            dyn_cast<FunctionProtoType>(VD->getType()))3481      if (proto->getReturnType() == Context.UnknownAnyTy) {3482        type = Context.UnknownAnyTy;3483        valueKind = VK_PRValue;3484        break;3485      }3486 3487    // C++ methods are l-values if static, r-values if non-static.3488    if (cast<CXXMethodDecl>(VD)->isStatic()) {3489      valueKind = VK_LValue;3490      break;3491    }3492    [[fallthrough]];3493 3494  case Decl::CXXConversion:3495  case Decl::CXXDestructor:3496  case Decl::CXXConstructor:3497    valueKind = VK_PRValue;3498    break;3499  }3500 3501  auto *E =3502      BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,3503                       /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);3504  // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We3505  // wrap a DeclRefExpr referring to an invalid decl with a dependent-type3506  // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus3507  // diagnostics).3508  if (VD->isInvalidDecl() && E)3509    return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});3510  return E;3511}3512 3513static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,3514                                    SmallString<32> &Target) {3515  Target.resize(CharByteWidth * (Source.size() + 1));3516  char *ResultPtr = &Target[0];3517  const llvm::UTF8 *ErrorPtr;3518  bool success =3519      llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);3520  (void)success;3521  assert(success);3522  Target.resize(ResultPtr - &Target[0]);3523}3524 3525ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,3526                                     PredefinedIdentKind IK) {3527  Decl *currentDecl = getPredefinedExprDecl(CurContext);3528  if (!currentDecl) {3529    Diag(Loc, diag::ext_predef_outside_function);3530    currentDecl = Context.getTranslationUnitDecl();3531  }3532 3533  QualType ResTy;3534  StringLiteral *SL = nullptr;3535  if (cast<DeclContext>(currentDecl)->isDependentContext())3536    ResTy = Context.DependentTy;3537  else {3538    // Pre-defined identifiers are of type char[x], where x is the length of3539    // the string.3540    bool ForceElaboratedPrinting =3541        IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;3542    auto Str =3543        PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);3544    unsigned Length = Str.length();3545 3546    llvm::APInt LengthI(32, Length + 1);3547    if (IK == PredefinedIdentKind::LFunction ||3548        IK == PredefinedIdentKind::LFuncSig) {3549      ResTy =3550          Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());3551      SmallString<32> RawChars;3552      ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),3553                              Str, RawChars);3554      ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,3555                                           ArraySizeModifier::Normal,3556                                           /*IndexTypeQuals*/ 0);3557      SL = StringLiteral::Create(Context, RawChars, StringLiteralKind::Wide,3558                                 /*Pascal*/ false, ResTy, Loc);3559    } else {3560      ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());3561      ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,3562                                           ArraySizeModifier::Normal,3563                                           /*IndexTypeQuals*/ 0);3564      SL = StringLiteral::Create(Context, Str, StringLiteralKind::Ordinary,3565                                 /*Pascal*/ false, ResTy, Loc);3566    }3567  }3568 3569  return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,3570                                SL);3571}3572 3573ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {3574  return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));3575}3576 3577ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {3578  SmallString<16> CharBuffer;3579  bool Invalid = false;3580  StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);3581  if (Invalid)3582    return ExprError();3583 3584  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),3585                            PP, Tok.getKind());3586  if (Literal.hadError())3587    return ExprError();3588 3589  QualType Ty;3590  if (Literal.isWide())3591    Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.3592  else if (Literal.isUTF8() && getLangOpts().C23)3593    Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C233594  else if (Literal.isUTF8() && getLangOpts().Char8)3595    Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.3596  else if (Literal.isUTF16())3597    Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.3598  else if (Literal.isUTF32())3599    Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.3600  else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())3601    Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.3602  else3603    Ty = Context.CharTy; // 'x' -> char in C++;3604                         // u8'x' -> char in C11-C17 and in C++ without char8_t.3605 3606  CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;3607  if (Literal.isWide())3608    Kind = CharacterLiteralKind::Wide;3609  else if (Literal.isUTF16())3610    Kind = CharacterLiteralKind::UTF16;3611  else if (Literal.isUTF32())3612    Kind = CharacterLiteralKind::UTF32;3613  else if (Literal.isUTF8())3614    Kind = CharacterLiteralKind::UTF8;3615 3616  Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,3617                                             Tok.getLocation());3618 3619  if (Literal.getUDSuffix().empty())3620    return Lit;3621 3622  // We're building a user-defined literal.3623  IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());3624  SourceLocation UDSuffixLoc =3625    getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());3626 3627  // Make sure we're allowed user-defined literals here.3628  if (!UDLScope)3629    return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));3630 3631  // C++11 [lex.ext]p6: The literal L is treated as a call of the form3632  //   operator "" X (ch)3633  return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,3634                                        Lit, Tok.getLocation());3635}3636 3637ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, int64_t Val) {3638  unsigned IntSize = Context.getTargetInfo().getIntWidth();3639  return IntegerLiteral::Create(Context,3640                                llvm::APInt(IntSize, Val, /*isSigned=*/true),3641                                Context.IntTy, Loc);3642}3643 3644static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,3645                                  QualType Ty, SourceLocation Loc) {3646  const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);3647 3648  using llvm::APFloat;3649  APFloat Val(Format);3650 3651  llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();3652  if (RM == llvm::RoundingMode::Dynamic)3653    RM = llvm::RoundingMode::NearestTiesToEven;3654  APFloat::opStatus result = Literal.GetFloatValue(Val, RM);3655 3656  // Overflow is always an error, but underflow is only an error if3657  // we underflowed to zero (APFloat reports denormals as underflow).3658  if ((result & APFloat::opOverflow) ||3659      ((result & APFloat::opUnderflow) && Val.isZero())) {3660    unsigned diagnostic;3661    SmallString<20> buffer;3662    if (result & APFloat::opOverflow) {3663      diagnostic = diag::warn_float_overflow;3664      APFloat::getLargest(Format).toString(buffer);3665    } else {3666      diagnostic = diag::warn_float_underflow;3667      APFloat::getSmallest(Format).toString(buffer);3668    }3669 3670    S.Diag(Loc, diagnostic) << Ty << buffer.str();3671  }3672 3673  bool isExact = (result == APFloat::opOK);3674  return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);3675}3676 3677bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {3678  assert(E && "Invalid expression");3679 3680  if (E->isValueDependent())3681    return false;3682 3683  QualType QT = E->getType();3684  if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {3685    Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;3686    return true;3687  }3688 3689  llvm::APSInt ValueAPS;3690  ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);3691 3692  if (R.isInvalid())3693    return true;3694 3695  // GCC allows the value of unroll count to be 0.3696  // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says3697  // "The values of 0 and 1 block any unrolling of the loop."3698  // The values doesn't have to be strictly positive in '#pragma GCC unroll' and3699  // '#pragma unroll' cases.3700  bool ValueIsPositive =3701      AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();3702  if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {3703    Diag(E->getExprLoc(), diag::err_requires_positive_value)3704        << toString(ValueAPS, 10) << ValueIsPositive;3705    return true;3706  }3707 3708  return false;3709}3710 3711ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {3712  // Fast path for a single digit (which is quite common).  A single digit3713  // cannot have a trigraph, escaped newline, radix prefix, or suffix.3714  if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {3715    const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);3716    return ActOnIntegerConstant(Tok.getLocation(), Val);3717  }3718 3719  SmallString<128> SpellingBuffer;3720  // NumericLiteralParser wants to overread by one character.  Add padding to3721  // the buffer in case the token is copied to the buffer.  If getSpelling()3722  // returns a StringRef to the memory buffer, it should have a null char at3723  // the EOF, so it is also safe.3724  SpellingBuffer.resize(Tok.getLength() + 1);3725 3726  // Get the spelling of the token, which eliminates trigraphs, etc.3727  bool Invalid = false;3728  StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);3729  if (Invalid)3730    return ExprError();3731 3732  NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),3733                               PP.getSourceManager(), PP.getLangOpts(),3734                               PP.getTargetInfo(), PP.getDiagnostics());3735  if (Literal.hadError)3736    return ExprError();3737 3738  if (Literal.hasUDSuffix()) {3739    // We're building a user-defined literal.3740    const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());3741    SourceLocation UDSuffixLoc =3742      getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());3743 3744    // Make sure we're allowed user-defined literals here.3745    if (!UDLScope)3746      return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));3747 3748    QualType CookedTy;3749    if (Literal.isFloatingLiteral()) {3750      // C++11 [lex.ext]p4: If S contains a literal operator with parameter type3751      // long double, the literal is treated as a call of the form3752      //   operator "" X (f L)3753      CookedTy = Context.LongDoubleTy;3754    } else {3755      // C++11 [lex.ext]p3: If S contains a literal operator with parameter type3756      // unsigned long long, the literal is treated as a call of the form3757      //   operator "" X (n ULL)3758      CookedTy = Context.UnsignedLongLongTy;3759    }3760 3761    DeclarationName OpName =3762      Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);3763    DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);3764    OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);3765 3766    SourceLocation TokLoc = Tok.getLocation();3767 3768    // Perform literal operator lookup to determine if we're building a raw3769    // literal or a cooked one.3770    LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);3771    switch (LookupLiteralOperator(UDLScope, R, CookedTy,3772                                  /*AllowRaw*/ true, /*AllowTemplate*/ true,3773                                  /*AllowStringTemplatePack*/ false,3774                                  /*DiagnoseMissing*/ !Literal.isImaginary)) {3775    case LOLR_ErrorNoDiagnostic:3776      // Lookup failure for imaginary constants isn't fatal, there's still the3777      // GNU extension producing _Complex types.3778      break;3779    case LOLR_Error:3780      return ExprError();3781    case LOLR_Cooked: {3782      Expr *Lit;3783      if (Literal.isFloatingLiteral()) {3784        Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());3785      } else {3786        llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);3787        if (Literal.GetIntegerValue(ResultVal))3788          Diag(Tok.getLocation(), diag::err_integer_literal_too_large)3789              << /* Unsigned */ 1;3790        Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,3791                                     Tok.getLocation());3792      }3793      return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);3794    }3795 3796    case LOLR_Raw: {3797      // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the3798      // literal is treated as a call of the form3799      //   operator "" X ("n")3800      unsigned Length = Literal.getUDSuffixOffset();3801      QualType StrTy = Context.getConstantArrayType(3802          Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),3803          llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);3804      Expr *Lit =3805          StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),3806                                StringLiteralKind::Ordinary,3807                                /*Pascal*/ false, StrTy, TokLoc);3808      return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);3809    }3810 3811    case LOLR_Template: {3812      // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator3813      // template), L is treated as a call fo the form3814      //   operator "" X <'c1', 'c2', ... 'ck'>()3815      // where n is the source character sequence c1 c2 ... ck.3816      TemplateArgumentListInfo ExplicitArgs;3817      unsigned CharBits = Context.getIntWidth(Context.CharTy);3818      bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();3819      llvm::APSInt Value(CharBits, CharIsUnsigned);3820      for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {3821        Value = TokSpelling[I];3822        TemplateArgument Arg(Context, Value, Context.CharTy);3823        TemplateArgumentLocInfo ArgInfo;3824        ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));3825      }3826      return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);3827    }3828    case LOLR_StringTemplatePack:3829      llvm_unreachable("unexpected literal operator lookup result");3830    }3831  }3832 3833  Expr *Res;3834 3835  if (Literal.isFixedPointLiteral()) {3836    QualType Ty;3837 3838    if (Literal.isAccum) {3839      if (Literal.isHalf) {3840        Ty = Context.ShortAccumTy;3841      } else if (Literal.isLong) {3842        Ty = Context.LongAccumTy;3843      } else {3844        Ty = Context.AccumTy;3845      }3846    } else if (Literal.isFract) {3847      if (Literal.isHalf) {3848        Ty = Context.ShortFractTy;3849      } else if (Literal.isLong) {3850        Ty = Context.LongFractTy;3851      } else {3852        Ty = Context.FractTy;3853      }3854    }3855 3856    if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);3857 3858    bool isSigned = !Literal.isUnsigned;3859    unsigned scale = Context.getFixedPointScale(Ty);3860    unsigned bit_width = Context.getTypeInfo(Ty).Width;3861 3862    llvm::APInt Val(bit_width, 0, isSigned);3863    bool Overflowed = Literal.GetFixedPointValue(Val, scale);3864    bool ValIsZero = Val.isZero() && !Overflowed;3865 3866    auto MaxVal = Context.getFixedPointMax(Ty).getValue();3867    if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)3868      // Clause 6.4.4 - The value of a constant shall be in the range of3869      // representable values for its type, with exception for constants of a3870      // fract type with a value of exactly 1; such a constant shall denote3871      // the maximal value for the type.3872      --Val;3873    else if (Val.ugt(MaxVal) || Overflowed)3874      Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);3875 3876    Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,3877                                              Tok.getLocation(), scale);3878  } else if (Literal.isFloatingLiteral()) {3879    QualType Ty;3880    if (Literal.isHalf){3881      if (getLangOpts().HLSL ||3882          getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))3883        Ty = Context.HalfTy;3884      else {3885        Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);3886        return ExprError();3887      }3888    } else if (Literal.isFloat)3889      Ty = Context.FloatTy;3890    else if (Literal.isLong)3891      Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;3892    else if (Literal.isFloat16)3893      Ty = Context.Float16Ty;3894    else if (Literal.isFloat128)3895      Ty = Context.Float128Ty;3896    else if (getLangOpts().HLSL)3897      Ty = Context.FloatTy;3898    else3899      Ty = Context.DoubleTy;3900 3901    Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());3902 3903    if (Ty == Context.DoubleTy) {3904      if (getLangOpts().SinglePrecisionConstants) {3905        if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {3906          Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();3907        }3908      } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(3909                                             "cl_khr_fp64", getLangOpts())) {3910        // Impose single-precision float type when cl_khr_fp64 is not enabled.3911        Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)3912            << (getLangOpts().getOpenCLCompatibleVersion() >= 300);3913        Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();3914      }3915    }3916  } else if (!Literal.isIntegerLiteral()) {3917    return ExprError();3918  } else {3919    QualType Ty;3920 3921    // 'z/uz' literals are a C++23 feature.3922    if (Literal.isSizeT)3923      Diag(Tok.getLocation(), getLangOpts().CPlusPlus3924                                  ? getLangOpts().CPlusPlus233925                                        ? diag::warn_cxx20_compat_size_t_suffix3926                                        : diag::ext_cxx23_size_t_suffix3927                                  : diag::err_cxx23_size_t_suffix);3928 3929    // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,3930    // but we do not currently support the suffix in C++ mode because it's not3931    // entirely clear whether WG21 will prefer this suffix to return a library3932    // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'3933    // literals are a C++ extension.3934    if (Literal.isBitInt)3935      PP.Diag(Tok.getLocation(),3936              getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix3937              : getLangOpts().C23     ? diag::warn_c23_compat_bitint_suffix3938                                      : diag::ext_c23_bitint_suffix);3939 3940    // Get the value in the widest-possible width. What is "widest" depends on3941    // whether the literal is a bit-precise integer or not. For a bit-precise3942    // integer type, try to scan the source to determine how many bits are3943    // needed to represent the value. This may seem a bit expensive, but trying3944    // to get the integer value from an overly-wide APInt is *extremely*3945    // expensive, so the naive approach of assuming3946    // llvm::IntegerType::MAX_INT_BITS is a big performance hit.3947    unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();3948    if (Literal.isBitInt)3949      BitsNeeded = llvm::APInt::getSufficientBitsNeeded(3950          Literal.getLiteralDigits(), Literal.getRadix());3951    if (Literal.MicrosoftInteger) {3952      if (Literal.MicrosoftInteger == 128 &&3953          !Context.getTargetInfo().hasInt128Type())3954        PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)3955            << Literal.isUnsigned;3956      BitsNeeded = Literal.MicrosoftInteger;3957    }3958 3959    llvm::APInt ResultVal(BitsNeeded, 0);3960 3961    if (Literal.GetIntegerValue(ResultVal)) {3962      // If this value didn't fit into uintmax_t, error and force to ull.3963      Diag(Tok.getLocation(), diag::err_integer_literal_too_large)3964          << /* Unsigned */ 1;3965      Ty = Context.UnsignedLongLongTy;3966      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&3967             "long long is not intmax_t?");3968    } else {3969      // If this value fits into a ULL, try to figure out what else it fits into3970      // according to the rules of C99 6.4.4.1p5.3971 3972      // Octal, Hexadecimal, and integers with a U suffix are allowed to3973      // be an unsigned int.3974      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;3975 3976      // HLSL doesn't really have `long` or `long long`. We support the `ll`3977      // suffix for portability of code with C++, but both `l` and `ll` are3978      // 64-bit integer types, and we want the type of `1l` and `1ll` to be the3979      // same.3980      if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {3981        Literal.isLong = true;3982        Literal.isLongLong = false;3983      }3984 3985      // Check from smallest to largest, picking the smallest type we can.3986      unsigned Width = 0;3987 3988      // Microsoft specific integer suffixes are explicitly sized.3989      if (Literal.MicrosoftInteger) {3990        if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {3991          Width = 8;3992          Ty = Context.CharTy;3993        } else {3994          Width = Literal.MicrosoftInteger;3995          Ty = Context.getIntTypeForBitwidth(Width,3996                                             /*Signed=*/!Literal.isUnsigned);3997        }3998      }3999 4000      // Bit-precise integer literals are automagically-sized based on the4001      // width required by the literal.4002      if (Literal.isBitInt) {4003        // The signed version has one more bit for the sign value. There are no4004        // zero-width bit-precise integers, even if the literal value is 0.4005        Width = std::max(ResultVal.getActiveBits(), 1u) +4006                (Literal.isUnsigned ? 0u : 1u);4007 4008        // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,4009        // and reset the type to the largest supported width.4010        unsigned int MaxBitIntWidth =4011            Context.getTargetInfo().getMaxBitIntWidth();4012        if (Width > MaxBitIntWidth) {4013          Diag(Tok.getLocation(), diag::err_integer_literal_too_large)4014              << Literal.isUnsigned;4015          Width = MaxBitIntWidth;4016        }4017 4018        // Reset the result value to the smaller APInt and select the correct4019        // type to be used. Note, we zext even for signed values because the4020        // literal itself is always an unsigned value (a preceeding - is a4021        // unary operator, not part of the literal).4022        ResultVal = ResultVal.zextOrTrunc(Width);4023        Ty = Context.getBitIntType(Literal.isUnsigned, Width);4024      }4025 4026      // Check C++23 size_t literals.4027      if (Literal.isSizeT) {4028        assert(!Literal.MicrosoftInteger &&4029               "size_t literals can't be Microsoft literals");4030        unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(4031            Context.getTargetInfo().getSizeType());4032 4033        // Does it fit in size_t?4034        if (ResultVal.isIntN(SizeTSize)) {4035          // Does it fit in ssize_t?4036          if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)4037            Ty = Context.getSignedSizeType();4038          else if (AllowUnsigned)4039            Ty = Context.getSizeType();4040          Width = SizeTSize;4041        }4042      }4043 4044      if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&4045          !Literal.isSizeT) {4046        // Are int/unsigned possibilities?4047        unsigned IntSize = Context.getTargetInfo().getIntWidth();4048 4049        // Does it fit in a unsigned int?4050        if (ResultVal.isIntN(IntSize)) {4051          // Does it fit in a signed int?4052          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)4053            Ty = Context.IntTy;4054          else if (AllowUnsigned)4055            Ty = Context.UnsignedIntTy;4056          Width = IntSize;4057        }4058      }4059 4060      // Are long/unsigned long possibilities?4061      if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {4062        unsigned LongSize = Context.getTargetInfo().getLongWidth();4063 4064        // Does it fit in a unsigned long?4065        if (ResultVal.isIntN(LongSize)) {4066          // Does it fit in a signed long?4067          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)4068            Ty = Context.LongTy;4069          else if (AllowUnsigned)4070            Ty = Context.UnsignedLongTy;4071          // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p24072          // is compatible.4073          else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {4074            const unsigned LongLongSize =4075                Context.getTargetInfo().getLongLongWidth();4076            Diag(Tok.getLocation(),4077                 getLangOpts().CPlusPlus4078                     ? Literal.isLong4079                           ? diag::warn_old_implicitly_unsigned_long_cxx4080                           : /*C++98 UB*/ diag::4081                                 ext_old_implicitly_unsigned_long_cxx4082                     : diag::warn_old_implicitly_unsigned_long)4083                << (LongLongSize > LongSize ? /*will have type 'long long'*/ 04084                                            : /*will be ill-formed*/ 1);4085            Ty = Context.UnsignedLongTy;4086          }4087          Width = LongSize;4088        }4089      }4090 4091      // Check long long if needed.4092      if (Ty.isNull() && !Literal.isSizeT) {4093        unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();4094 4095        // Does it fit in a unsigned long long?4096        if (ResultVal.isIntN(LongLongSize)) {4097          // Does it fit in a signed long long?4098          // To be compatible with MSVC, hex integer literals ending with the4099          // LL or i64 suffix are always signed in Microsoft mode.4100          if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||4101              (getLangOpts().MSVCCompat && Literal.isLongLong)))4102            Ty = Context.LongLongTy;4103          else if (AllowUnsigned)4104            Ty = Context.UnsignedLongLongTy;4105          Width = LongLongSize;4106 4107          // 'long long' is a C99 or C++11 feature, whether the literal4108          // explicitly specified 'long long' or we needed the extra width.4109          if (getLangOpts().CPlusPlus)4110            Diag(Tok.getLocation(), getLangOpts().CPlusPlus114111                                        ? diag::warn_cxx98_compat_longlong4112                                        : diag::ext_cxx11_longlong);4113          else if (!getLangOpts().C99)4114            Diag(Tok.getLocation(), diag::ext_c99_longlong);4115        }4116      }4117 4118      // If we still couldn't decide a type, we either have 'size_t' literal4119      // that is out of range, or a decimal literal that does not fit in a4120      // signed long long and has no U suffix.4121      if (Ty.isNull()) {4122        if (Literal.isSizeT)4123          Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)4124              << Literal.isUnsigned;4125        else4126          Diag(Tok.getLocation(),4127               diag::ext_integer_literal_too_large_for_signed);4128        Ty = Context.UnsignedLongLongTy;4129        Width = Context.getTargetInfo().getLongLongWidth();4130      }4131 4132      if (ResultVal.getBitWidth() != Width)4133        ResultVal = ResultVal.trunc(Width);4134    }4135    Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());4136  }4137 4138  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.4139  if (Literal.isImaginary) {4140    Res = new (Context) ImaginaryLiteral(Res,4141                                        Context.getComplexType(Res->getType()));4142 4143    // In C++, this is a GNU extension. In C, it's a C2y extension.4144    unsigned DiagId;4145    if (getLangOpts().CPlusPlus)4146      DiagId = diag::ext_gnu_imaginary_constant;4147    else if (getLangOpts().C2y)4148      DiagId = diag::warn_c23_compat_imaginary_constant;4149    else4150      DiagId = diag::ext_c2y_imaginary_constant;4151    Diag(Tok.getLocation(), DiagId);4152  }4153  return Res;4154}4155 4156ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {4157  assert(E && "ActOnParenExpr() missing expr");4158  QualType ExprTy = E->getType();4159  if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&4160      !E->isLValue() && ExprTy->hasFloatingRepresentation())4161    return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);4162  return new (Context) ParenExpr(L, R, E);4163}4164 4165static bool CheckVecStepTraitOperandType(Sema &S, QualType T,4166                                         SourceLocation Loc,4167                                         SourceRange ArgRange) {4168  // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in4169  // scalar or vector data type argument..."4170  // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic4171  // type (C99 6.2.5p18) or void.4172  if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {4173    S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)4174      << T << ArgRange;4175    return true;4176  }4177 4178  assert((T->isVoidType() || !T->isIncompleteType()) &&4179         "Scalar types should always be complete");4180  return false;4181}4182 4183static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,4184                                                SourceLocation Loc,4185                                                SourceRange ArgRange) {4186  // builtin_vectorelements supports both fixed-sized and scalable vectors.4187  if (!T->isVectorType() && !T->isSizelessVectorType())4188    return S.Diag(Loc, diag::err_builtin_non_vector_type)4189           << ""4190           << "__builtin_vectorelements" << T << ArgRange;4191 4192  if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {4193    if (T->isSVESizelessBuiltinType()) {4194      llvm::StringMap<bool> CallerFeatureMap;4195      S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);4196      return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);4197    }4198  }4199 4200  return false;4201}4202 4203static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T,4204                                                     SourceLocation Loc,4205                                                     SourceRange ArgRange) {4206  if (S.checkPointerAuthEnabled(Loc, ArgRange))4207    return true;4208 4209  if (!T->isFunctionType() && !T->isFunctionPointerType() &&4210      !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {4211    S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;4212    return true;4213  }4214 4215  return false;4216}4217 4218static bool CheckExtensionTraitOperandType(Sema &S, QualType T,4219                                           SourceLocation Loc,4220                                           SourceRange ArgRange,4221                                           UnaryExprOrTypeTrait TraitKind) {4222  // Invalid types must be hard errors for SFINAE in C++.4223  if (S.LangOpts.CPlusPlus)4224    return true;4225 4226  // C99 6.5.3.4p1:4227  if (T->isFunctionType() &&4228      (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||4229       TraitKind == UETT_PreferredAlignOf)) {4230    // sizeof(function)/alignof(function) is allowed as an extension.4231    S.Diag(Loc, diag::ext_sizeof_alignof_function_type)4232        << getTraitSpelling(TraitKind) << ArgRange;4233    return false;4234  }4235 4236  // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where4237  // this is an error (OpenCL v1.1 s6.3.k)4238  if (T->isVoidType()) {4239    unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type4240                                        : diag::ext_sizeof_alignof_void_type;4241    S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;4242    return false;4243  }4244 4245  return true;4246}4247 4248static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,4249                                             SourceLocation Loc,4250                                             SourceRange ArgRange,4251                                             UnaryExprOrTypeTrait TraitKind) {4252  // Reject sizeof(interface) and sizeof(interface<proto>) if the4253  // runtime doesn't allow it.4254  if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {4255    S.Diag(Loc, diag::err_sizeof_nonfragile_interface)4256      << T << (TraitKind == UETT_SizeOf)4257      << ArgRange;4258    return true;4259  }4260 4261  return false;4262}4263 4264/// Check whether E is a pointer from a decayed array type (the decayed4265/// pointer type is equal to T) and emit a warning if it is.4266static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,4267                                     const Expr *E) {4268  // Don't warn if the operation changed the type.4269  if (T != E->getType())4270    return;4271 4272  // Now look for array decays.4273  const auto *ICE = dyn_cast<ImplicitCastExpr>(E);4274  if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)4275    return;4276 4277  S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()4278                                             << ICE->getType()4279                                             << ICE->getSubExpr()->getType();4280}4281 4282bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,4283                                            UnaryExprOrTypeTrait ExprKind) {4284  QualType ExprTy = E->getType();4285  assert(!ExprTy->isReferenceType());4286 4287  bool IsUnevaluatedOperand =4288      (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||4289       ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||4290       ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);4291  if (IsUnevaluatedOperand) {4292    ExprResult Result = CheckUnevaluatedOperand(E);4293    if (Result.isInvalid())4294      return true;4295    E = Result.get();4296  }4297 4298  // The operand for sizeof and alignof is in an unevaluated expression context,4299  // so side effects could result in unintended consequences.4300  // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes4301  // used to build SFINAE gadgets.4302  // FIXME: Should we consider instantiation-dependent operands to 'alignof'?4303  if (IsUnevaluatedOperand && !inTemplateInstantiation() &&4304      !E->isInstantiationDependent() &&4305      !E->getType()->isVariableArrayType() &&4306      E->HasSideEffects(Context, false))4307    Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);4308 4309  if (ExprKind == UETT_VecStep)4310    return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),4311                                        E->getSourceRange());4312 4313  if (ExprKind == UETT_VectorElements)4314    return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),4315                                               E->getSourceRange());4316 4317  // Explicitly list some types as extensions.4318  if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),4319                                      E->getSourceRange(), ExprKind))4320    return false;4321 4322  // WebAssembly tables are always illegal operands to unary expressions and4323  // type traits.4324  if (Context.getTargetInfo().getTriple().isWasm() &&4325      E->getType()->isWebAssemblyTableType()) {4326    Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)4327        << getTraitSpelling(ExprKind);4328    return true;4329  }4330 4331  // 'alignof' applied to an expression only requires the base element type of4332  // the expression to be complete. 'sizeof' requires the expression's type to4333  // be complete (and will attempt to complete it if it's an array of unknown4334  // bound).4335  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {4336    if (RequireCompleteSizedType(4337            E->getExprLoc(), Context.getBaseElementType(E->getType()),4338            diag::err_sizeof_alignof_incomplete_or_sizeless_type,4339            getTraitSpelling(ExprKind), E->getSourceRange()))4340      return true;4341  } else {4342    if (RequireCompleteSizedExprType(4343            E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,4344            getTraitSpelling(ExprKind), E->getSourceRange()))4345      return true;4346  }4347 4348  // Completing the expression's type may have changed it.4349  ExprTy = E->getType();4350  assert(!ExprTy->isReferenceType());4351 4352  if (ExprTy->isFunctionType()) {4353    Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)4354        << getTraitSpelling(ExprKind) << E->getSourceRange();4355    return true;4356  }4357 4358  if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),4359                                       E->getSourceRange(), ExprKind))4360    return true;4361 4362  if (ExprKind == UETT_CountOf) {4363    // The type has to be an array type. We already checked for incomplete4364    // types above.4365    QualType ExprType = E->IgnoreParens()->getType();4366    if (!ExprType->isArrayType()) {4367      Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;4368      return true;4369    }4370    // FIXME: warn on _Countof on an array parameter. Not warning on it4371    // currently because there are papers in WG14 about array types which do4372    // not decay that could impact this behavior, so we want to see if anything4373    // changes here before coming up with a warning group for _Countof-related4374    // diagnostics.4375  }4376 4377  if (ExprKind == UETT_SizeOf) {4378    if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {4379      if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {4380        QualType OType = PVD->getOriginalType();4381        QualType Type = PVD->getType();4382        if (Type->isPointerType() && OType->isArrayType()) {4383          Diag(E->getExprLoc(), diag::warn_sizeof_array_param)4384            << Type << OType;4385          Diag(PVD->getLocation(), diag::note_declared_at);4386        }4387      }4388    }4389 4390    // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array4391    // decays into a pointer and returns an unintended result. This is most4392    // likely a typo for "sizeof(array) op x".4393    if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {4394      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),4395                               BO->getLHS());4396      warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),4397                               BO->getRHS());4398    }4399  }4400 4401  return false;4402}4403 4404static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {4405  // Cannot know anything else if the expression is dependent.4406  if (E->isTypeDependent())4407    return false;4408 4409  if (E->getObjectKind() == OK_BitField) {4410    S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)4411       << 1 << E->getSourceRange();4412    return true;4413  }4414 4415  ValueDecl *D = nullptr;4416  Expr *Inner = E->IgnoreParens();4417  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {4418    D = DRE->getDecl();4419  } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {4420    D = ME->getMemberDecl();4421  }4422 4423  // If it's a field, require the containing struct to have a4424  // complete definition so that we can compute the layout.4425  //4426  // This can happen in C++11 onwards, either by naming the member4427  // in a way that is not transformed into a member access expression4428  // (in an unevaluated operand, for instance), or by naming the member4429  // in a trailing-return-type.4430  //4431  // For the record, since __alignof__ on expressions is a GCC4432  // extension, GCC seems to permit this but always gives the4433  // nonsensical answer 0.4434  //4435  // We don't really need the layout here --- we could instead just4436  // directly check for all the appropriate alignment-lowing4437  // attributes --- but that would require duplicating a lot of4438  // logic that just isn't worth duplicating for such a marginal4439  // use-case.4440  if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {4441    // Fast path this check, since we at least know the record has a4442    // definition if we can find a member of it.4443    if (!FD->getParent()->isCompleteDefinition()) {4444      S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)4445        << E->getSourceRange();4446      return true;4447    }4448 4449    // Otherwise, if it's a field, and the field doesn't have4450    // reference type, then it must have a complete type (or be a4451    // flexible array member, which we explicitly want to4452    // white-list anyway), which makes the following checks trivial.4453    if (!FD->getType()->isReferenceType())4454      return false;4455  }4456 4457  return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);4458}4459 4460bool Sema::CheckVecStepExpr(Expr *E) {4461  E = E->IgnoreParens();4462 4463  // Cannot know anything else if the expression is dependent.4464  if (E->isTypeDependent())4465    return false;4466 4467  return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);4468}4469 4470static void captureVariablyModifiedType(ASTContext &Context, QualType T,4471                                        CapturingScopeInfo *CSI) {4472  assert(T->isVariablyModifiedType());4473  assert(CSI != nullptr);4474 4475  // We're going to walk down into the type and look for VLA expressions.4476  do {4477    const Type *Ty = T.getTypePtr();4478    switch (Ty->getTypeClass()) {4479#define TYPE(Class, Base)4480#define ABSTRACT_TYPE(Class, Base)4481#define NON_CANONICAL_TYPE(Class, Base)4482#define DEPENDENT_TYPE(Class, Base) case Type::Class:4483#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)4484#include "clang/AST/TypeNodes.inc"4485      T = QualType();4486      break;4487    // These types are never variably-modified.4488    case Type::Builtin:4489    case Type::Complex:4490    case Type::Vector:4491    case Type::ExtVector:4492    case Type::ConstantMatrix:4493    case Type::Record:4494    case Type::Enum:4495    case Type::TemplateSpecialization:4496    case Type::ObjCObject:4497    case Type::ObjCInterface:4498    case Type::ObjCObjectPointer:4499    case Type::ObjCTypeParam:4500    case Type::Pipe:4501    case Type::BitInt:4502    case Type::HLSLInlineSpirv:4503      llvm_unreachable("type class is never variably-modified!");4504    case Type::Adjusted:4505      T = cast<AdjustedType>(Ty)->getOriginalType();4506      break;4507    case Type::Decayed:4508      T = cast<DecayedType>(Ty)->getPointeeType();4509      break;4510    case Type::ArrayParameter:4511      T = cast<ArrayParameterType>(Ty)->getElementType();4512      break;4513    case Type::Pointer:4514      T = cast<PointerType>(Ty)->getPointeeType();4515      break;4516    case Type::BlockPointer:4517      T = cast<BlockPointerType>(Ty)->getPointeeType();4518      break;4519    case Type::LValueReference:4520    case Type::RValueReference:4521      T = cast<ReferenceType>(Ty)->getPointeeType();4522      break;4523    case Type::MemberPointer:4524      T = cast<MemberPointerType>(Ty)->getPointeeType();4525      break;4526    case Type::ConstantArray:4527    case Type::IncompleteArray:4528      // Losing element qualification here is fine.4529      T = cast<ArrayType>(Ty)->getElementType();4530      break;4531    case Type::VariableArray: {4532      // Losing element qualification here is fine.4533      const VariableArrayType *VAT = cast<VariableArrayType>(Ty);4534 4535      // Unknown size indication requires no size computation.4536      // Otherwise, evaluate and record it.4537      auto Size = VAT->getSizeExpr();4538      if (Size && !CSI->isVLATypeCaptured(VAT) &&4539          (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))4540        CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());4541 4542      T = VAT->getElementType();4543      break;4544    }4545    case Type::FunctionProto:4546    case Type::FunctionNoProto:4547      T = cast<FunctionType>(Ty)->getReturnType();4548      break;4549    case Type::Paren:4550    case Type::TypeOf:4551    case Type::UnaryTransform:4552    case Type::Attributed:4553    case Type::BTFTagAttributed:4554    case Type::HLSLAttributedResource:4555    case Type::SubstTemplateTypeParm:4556    case Type::MacroQualified:4557    case Type::CountAttributed:4558      // Keep walking after single level desugaring.4559      T = T.getSingleStepDesugaredType(Context);4560      break;4561    case Type::Typedef:4562      T = cast<TypedefType>(Ty)->desugar();4563      break;4564    case Type::Decltype:4565      T = cast<DecltypeType>(Ty)->desugar();4566      break;4567    case Type::PackIndexing:4568      T = cast<PackIndexingType>(Ty)->desugar();4569      break;4570    case Type::Using:4571      T = cast<UsingType>(Ty)->desugar();4572      break;4573    case Type::Auto:4574    case Type::DeducedTemplateSpecialization:4575      T = cast<DeducedType>(Ty)->getDeducedType();4576      break;4577    case Type::TypeOfExpr:4578      T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();4579      break;4580    case Type::Atomic:4581      T = cast<AtomicType>(Ty)->getValueType();4582      break;4583    case Type::PredefinedSugar:4584      T = cast<PredefinedSugarType>(Ty)->desugar();4585      break;4586    }4587  } while (!T.isNull() && T->isVariablyModifiedType());4588}4589 4590bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,4591                                            SourceLocation OpLoc,4592                                            SourceRange ExprRange,4593                                            UnaryExprOrTypeTrait ExprKind,4594                                            StringRef KWName) {4595  if (ExprType->isDependentType())4596    return false;4597 4598  // C++ [expr.sizeof]p2:4599  //     When applied to a reference or a reference type, the result4600  //     is the size of the referenced type.4601  // C++11 [expr.alignof]p3:4602  //     When alignof is applied to a reference type, the result4603  //     shall be the alignment of the referenced type.4604  if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())4605    ExprType = Ref->getPointeeType();4606 4607  // C11 6.5.3.4/3, C++11 [expr.alignof]p3:4608  //   When alignof or _Alignof is applied to an array type, the result4609  //   is the alignment of the element type.4610  if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||4611      ExprKind == UETT_OpenMPRequiredSimdAlign) {4612    // If the trait is 'alignof' in C before C2y, the ability to apply the4613    // trait to an incomplete array is an extension.4614    if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&4615        ExprType->isIncompleteArrayType())4616      Diag(OpLoc, getLangOpts().C2y4617                      ? diag::warn_c2y_compat_alignof_incomplete_array4618                      : diag::ext_c2y_alignof_incomplete_array);4619    ExprType = Context.getBaseElementType(ExprType);4620  }4621 4622  if (ExprKind == UETT_VecStep)4623    return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);4624 4625  if (ExprKind == UETT_VectorElements)4626    return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,4627                                               ExprRange);4628 4629  if (ExprKind == UETT_PtrAuthTypeDiscriminator)4630    return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,4631                                                    ExprRange);4632 4633  // Explicitly list some types as extensions.4634  if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,4635                                      ExprKind))4636    return false;4637 4638  if (RequireCompleteSizedType(4639          OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,4640          KWName, ExprRange))4641    return true;4642 4643  if (ExprType->isFunctionType()) {4644    Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;4645    return true;4646  }4647 4648  if (ExprKind == UETT_CountOf) {4649    // The type has to be an array type. We already checked for incomplete4650    // types above.4651    if (!ExprType->isArrayType()) {4652      Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;4653      return true;4654    }4655  }4656 4657  // WebAssembly tables are always illegal operands to unary expressions and4658  // type traits.4659  if (Context.getTargetInfo().getTriple().isWasm() &&4660      ExprType->isWebAssemblyTableType()) {4661    Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)4662        << getTraitSpelling(ExprKind);4663    return true;4664  }4665 4666  if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,4667                                       ExprKind))4668    return true;4669 4670  if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {4671    if (auto *TT = ExprType->getAs<TypedefType>()) {4672      for (auto I = FunctionScopes.rbegin(),4673                E = std::prev(FunctionScopes.rend());4674           I != E; ++I) {4675        auto *CSI = dyn_cast<CapturingScopeInfo>(*I);4676        if (CSI == nullptr)4677          break;4678        DeclContext *DC = nullptr;4679        if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))4680          DC = LSI->CallOperator;4681        else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))4682          DC = CRSI->TheCapturedDecl;4683        else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))4684          DC = BSI->TheDecl;4685        if (DC) {4686          if (DC->containsDecl(TT->getDecl()))4687            break;4688          captureVariablyModifiedType(Context, ExprType, CSI);4689        }4690      }4691    }4692  }4693 4694  return false;4695}4696 4697ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,4698                                                SourceLocation OpLoc,4699                                                UnaryExprOrTypeTrait ExprKind,4700                                                SourceRange R) {4701  if (!TInfo)4702    return ExprError();4703 4704  QualType T = TInfo->getType();4705 4706  if (!T->isDependentType() &&4707      CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,4708                                       getTraitSpelling(ExprKind)))4709    return ExprError();4710 4711  // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to4712  // properly deal with VLAs in nested calls of sizeof and typeof.4713  if (currentEvaluationContext().isUnevaluated() &&4714      currentEvaluationContext().InConditionallyConstantEvaluateContext &&4715      (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&4716      TInfo->getType()->isVariablyModifiedType())4717    TInfo = TransformToPotentiallyEvaluated(TInfo);4718 4719  // It's possible that the transformation above failed.4720  if (!TInfo)4721    return ExprError();4722 4723  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.4724  return new (Context) UnaryExprOrTypeTraitExpr(4725      ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());4726}4727 4728ExprResult4729Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,4730                                     UnaryExprOrTypeTrait ExprKind) {4731  ExprResult PE = CheckPlaceholderExpr(E);4732  if (PE.isInvalid())4733    return ExprError();4734 4735  E = PE.get();4736 4737  // Verify that the operand is valid.4738  bool isInvalid = false;4739  if (E->isTypeDependent()) {4740    // Delay type-checking for type-dependent expressions.4741  } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {4742    isInvalid = CheckAlignOfExpr(*this, E, ExprKind);4743  } else if (ExprKind == UETT_VecStep) {4744    isInvalid = CheckVecStepExpr(E);4745  } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {4746      Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);4747      isInvalid = true;4748  } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.4749    Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;4750    isInvalid = true;4751  } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||4752             ExprKind == UETT_CountOf) { // FIXME: __datasizeof?4753    isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind);4754  }4755 4756  if (isInvalid)4757    return ExprError();4758 4759  if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&4760      E->getType()->isVariableArrayType()) {4761    PE = TransformToPotentiallyEvaluated(E);4762    if (PE.isInvalid()) return ExprError();4763    E = PE.get();4764  }4765 4766  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.4767  return new (Context) UnaryExprOrTypeTraitExpr(4768      ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());4769}4770 4771ExprResult4772Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,4773                                    UnaryExprOrTypeTrait ExprKind, bool IsType,4774                                    void *TyOrEx, SourceRange ArgRange) {4775  // If error parsing type, ignore.4776  if (!TyOrEx) return ExprError();4777 4778  if (IsType) {4779    TypeSourceInfo *TInfo;4780    (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);4781    return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);4782  }4783 4784  Expr *ArgEx = (Expr *)TyOrEx;4785  ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);4786  return Result;4787}4788 4789bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,4790                                    SourceLocation OpLoc, SourceRange R) {4791  if (!TInfo)4792    return true;4793  return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,4794                                          UETT_AlignOf, KWName);4795}4796 4797bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,4798                                    SourceLocation OpLoc, SourceRange R) {4799  TypeSourceInfo *TInfo;4800  (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty.getAsOpaquePtr()),4801                          &TInfo);4802  return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);4803}4804 4805static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,4806                                     bool IsReal) {4807  if (V.get()->isTypeDependent())4808    return S.Context.DependentTy;4809 4810  // _Real and _Imag are only l-values for normal l-values.4811  if (V.get()->getObjectKind() != OK_Ordinary) {4812    V = S.DefaultLvalueConversion(V.get());4813    if (V.isInvalid())4814      return QualType();4815  }4816 4817  // These operators return the element type of a complex type.4818  if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())4819    return CT->getElementType();4820 4821  // Otherwise they pass through real integer and floating point types here.4822  if (V.get()->getType()->isArithmeticType())4823    return V.get()->getType();4824 4825  // Test for placeholders.4826  ExprResult PR = S.CheckPlaceholderExpr(V.get());4827  if (PR.isInvalid()) return QualType();4828  if (PR.get() != V.get()) {4829    V = PR;4830    return CheckRealImagOperand(S, V, Loc, IsReal);4831  }4832 4833  // Reject anything else.4834  S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()4835    << (IsReal ? "__real" : "__imag");4836  return QualType();4837}4838 4839 4840 4841ExprResult4842Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,4843                          tok::TokenKind Kind, Expr *Input) {4844  UnaryOperatorKind Opc;4845  switch (Kind) {4846  default: llvm_unreachable("Unknown unary op!");4847  case tok::plusplus:   Opc = UO_PostInc; break;4848  case tok::minusminus: Opc = UO_PostDec; break;4849  }4850 4851  // Since this might is a postfix expression, get rid of ParenListExprs.4852  ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);4853  if (Result.isInvalid()) return ExprError();4854  Input = Result.get();4855 4856  return BuildUnaryOp(S, OpLoc, Opc, Input);4857}4858 4859/// Diagnose if arithmetic on the given ObjC pointer is illegal.4860///4861/// \return true on error4862static bool checkArithmeticOnObjCPointer(Sema &S,4863                                         SourceLocation opLoc,4864                                         Expr *op) {4865  assert(op->getType()->isObjCObjectPointerType());4866  if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&4867      !S.LangOpts.ObjCSubscriptingLegacyRuntime)4868    return false;4869 4870  S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)4871    << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()4872    << op->getSourceRange();4873  return true;4874}4875 4876static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {4877  auto *BaseNoParens = Base->IgnoreParens();4878  if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))4879    return MSProp->getPropertyDecl()->getType()->isArrayType();4880  return isa<MSPropertySubscriptExpr>(BaseNoParens);4881}4882 4883// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.4884// Typically this is DependentTy, but can sometimes be more precise.4885//4886// There are cases when we could determine a non-dependent type:4887//  - LHS and RHS may have non-dependent types despite being type-dependent4888//    (e.g. unbounded array static members of the current instantiation)4889//  - one may be a dependent-sized array with known element type4890//  - one may be a dependent-typed valid index (enum in current instantiation)4891//4892// We *always* return a dependent type, in such cases it is DependentTy.4893// This avoids creating type-dependent expressions with non-dependent types.4894// FIXME: is this important to avoid? See https://reviews.llvm.org/D1072754895static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,4896                                               const ASTContext &Ctx) {4897  assert(LHS->isTypeDependent() || RHS->isTypeDependent());4898  QualType LTy = LHS->getType(), RTy = RHS->getType();4899  QualType Result = Ctx.DependentTy;4900  if (RTy->isIntegralOrUnscopedEnumerationType()) {4901    if (const PointerType *PT = LTy->getAs<PointerType>())4902      Result = PT->getPointeeType();4903    else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())4904      Result = AT->getElementType();4905  } else if (LTy->isIntegralOrUnscopedEnumerationType()) {4906    if (const PointerType *PT = RTy->getAs<PointerType>())4907      Result = PT->getPointeeType();4908    else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())4909      Result = AT->getElementType();4910  }4911  // Ensure we return a dependent type.4912  return Result->isDependentType() ? Result : Ctx.DependentTy;4913}4914 4915ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,4916                                         SourceLocation lbLoc,4917                                         MultiExprArg ArgExprs,4918                                         SourceLocation rbLoc) {4919 4920  if (base && !base->getType().isNull() &&4921      base->hasPlaceholderType(BuiltinType::ArraySection)) {4922    auto *AS = cast<ArraySectionExpr>(base);4923    if (AS->isOMPArraySection())4924      return OpenMP().ActOnOMPArraySectionExpr(4925          base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),4926          /*Length*/ nullptr,4927          /*Stride=*/nullptr, rbLoc);4928 4929    return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),4930                                           SourceLocation(), /*Length*/ nullptr,4931                                           rbLoc);4932  }4933 4934  // Since this might be a postfix expression, get rid of ParenListExprs.4935  if (isa<ParenListExpr>(base)) {4936    ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);4937    if (result.isInvalid())4938      return ExprError();4939    base = result.get();4940  }4941 4942  // Check if base and idx form a MatrixSubscriptExpr.4943  //4944  // Helper to check for comma expressions, which are not allowed as indices for4945  // matrix subscript expressions.4946  auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {4947    if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {4948      Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)4949          << SourceRange(base->getBeginLoc(), rbLoc);4950      return true;4951    }4952    return false;4953  };4954  // The matrix subscript operator ([][])is considered a single operator.4955  // Separating the index expressions by parenthesis is not allowed.4956  if (base && !base->getType().isNull() &&4957      base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&4958      !isa<MatrixSubscriptExpr>(base)) {4959    Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)4960        << SourceRange(base->getBeginLoc(), rbLoc);4961    return ExprError();4962  }4963  // If the base is a MatrixSubscriptExpr, try to create a new4964  // MatrixSubscriptExpr.4965  auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);4966  if (matSubscriptE) {4967    assert(ArgExprs.size() == 1);4968    if (CheckAndReportCommaError(ArgExprs.front()))4969      return ExprError();4970 4971    assert(matSubscriptE->isIncomplete() &&4972           "base has to be an incomplete matrix subscript");4973    return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),4974                                            matSubscriptE->getRowIdx(),4975                                            ArgExprs.front(), rbLoc);4976  }4977  if (base->getType()->isWebAssemblyTableType()) {4978    Diag(base->getExprLoc(), diag::err_wasm_table_art)4979        << SourceRange(base->getBeginLoc(), rbLoc) << 3;4980    return ExprError();4981  }4982 4983  CheckInvalidBuiltinCountedByRef(base,4984                                  BuiltinCountedByRefKind::ArraySubscript);4985 4986  // Handle any non-overload placeholder types in the base and index4987  // expressions.  We can't handle overloads here because the other4988  // operand might be an overloadable type, in which case the overload4989  // resolution for the operator overload should get the first crack4990  // at the overload.4991  bool IsMSPropertySubscript = false;4992  if (base->getType()->isNonOverloadPlaceholderType()) {4993    IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);4994    if (!IsMSPropertySubscript) {4995      ExprResult result = CheckPlaceholderExpr(base);4996      if (result.isInvalid())4997        return ExprError();4998      base = result.get();4999    }5000  }5001 5002  // If the base is a matrix type, try to create a new MatrixSubscriptExpr.5003  if (base->getType()->isMatrixType()) {5004    assert(ArgExprs.size() == 1);5005    if (CheckAndReportCommaError(ArgExprs.front()))5006      return ExprError();5007 5008    return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,5009                                            rbLoc);5010  }5011 5012  if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {5013    Expr *idx = ArgExprs[0];5014    if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||5015        (isa<CXXOperatorCallExpr>(idx) &&5016         cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {5017      Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)5018          << SourceRange(base->getBeginLoc(), rbLoc);5019    }5020  }5021 5022  if (ArgExprs.size() == 1 &&5023      ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {5024    ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);5025    if (result.isInvalid())5026      return ExprError();5027    ArgExprs[0] = result.get();5028  } else {5029    if (CheckArgsForPlaceholders(ArgExprs))5030      return ExprError();5031  }5032 5033  // Build an unanalyzed expression if either operand is type-dependent.5034  if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&5035      (base->isTypeDependent() ||5036       Expr::hasAnyTypeDependentArguments(ArgExprs)) &&5037      !isa<PackExpansionExpr>(ArgExprs[0])) {5038    return new (Context) ArraySubscriptExpr(5039        base, ArgExprs.front(),5040        getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),5041        VK_LValue, OK_Ordinary, rbLoc);5042  }5043 5044  // MSDN, property (C++)5045  // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx5046  // This attribute can also be used in the declaration of an empty array in a5047  // class or structure definition. For example:5048  // __declspec(property(get=GetX, put=PutX)) int x[];5049  // The above statement indicates that x[] can be used with one or more array5050  // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),5051  // and p->x[a][b] = i will be turned into p->PutX(a, b, i);5052  if (IsMSPropertySubscript) {5053    assert(ArgExprs.size() == 1);5054    // Build MS property subscript expression if base is MS property reference5055    // or MS property subscript.5056    return new (Context)5057        MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,5058                                VK_LValue, OK_Ordinary, rbLoc);5059  }5060 5061  // Use C++ overloaded-operator rules if either operand has record5062  // type.  The spec says to do this if either type is *overloadable*,5063  // but enum types can't declare subscript operators or conversion5064  // operators, so there's nothing interesting for overload resolution5065  // to do if there aren't any record types involved.5066  //5067  // ObjC pointers have their own subscripting logic that is not tied5068  // to overload resolution and so should not take this path.5069  if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&5070      ((base->getType()->isRecordType() ||5071        (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||5072         ArgExprs[0]->getType()->isRecordType())))) {5073    return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);5074  }5075 5076  ExprResult Res =5077      CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);5078 5079  if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))5080    CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));5081 5082  return Res;5083}5084 5085ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {5086  InitializedEntity Entity = InitializedEntity::InitializeTemporary(Ty);5087  InitializationKind Kind =5088      InitializationKind::CreateCopy(E->getBeginLoc(), SourceLocation());5089  InitializationSequence InitSeq(*this, Entity, Kind, E);5090  return InitSeq.Perform(*this, Entity, Kind, E);5091}5092 5093ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,5094                                                  Expr *ColumnIdx,5095                                                  SourceLocation RBLoc) {5096  ExprResult BaseR = CheckPlaceholderExpr(Base);5097  if (BaseR.isInvalid())5098    return BaseR;5099  Base = BaseR.get();5100 5101  ExprResult RowR = CheckPlaceholderExpr(RowIdx);5102  if (RowR.isInvalid())5103    return RowR;5104  RowIdx = RowR.get();5105 5106  if (!ColumnIdx)5107    return new (Context) MatrixSubscriptExpr(5108        Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);5109 5110  // Build an unanalyzed expression if any of the operands is type-dependent.5111  if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||5112      ColumnIdx->isTypeDependent())5113    return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,5114                                             Context.DependentTy, RBLoc);5115 5116  ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);5117  if (ColumnR.isInvalid())5118    return ColumnR;5119  ColumnIdx = ColumnR.get();5120 5121  // Check that IndexExpr is an integer expression. If it is a constant5122  // expression, check that it is less than Dim (= the number of elements in the5123  // corresponding dimension).5124  auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,5125                          bool IsColumnIdx) -> Expr * {5126    if (!IndexExpr->getType()->isIntegerType() &&5127        !IndexExpr->isTypeDependent()) {5128      Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)5129          << IsColumnIdx;5130      return nullptr;5131    }5132 5133    if (std::optional<llvm::APSInt> Idx =5134            IndexExpr->getIntegerConstantExpr(Context)) {5135      if ((*Idx < 0 || *Idx >= Dim)) {5136        Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)5137            << IsColumnIdx << Dim;5138        return nullptr;5139      }5140    }5141 5142    ExprResult ConvExpr = IndexExpr;5143    assert(!ConvExpr.isInvalid() &&5144           "should be able to convert any integer type to size type");5145    return ConvExpr.get();5146  };5147 5148  auto *MTy = Base->getType()->getAs<ConstantMatrixType>();5149  RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);5150  ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);5151  if (!RowIdx || !ColumnIdx)5152    return ExprError();5153 5154  return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,5155                                           MTy->getElementType(), RBLoc);5156}5157 5158void Sema::CheckAddressOfNoDeref(const Expr *E) {5159  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();5160  const Expr *StrippedExpr = E->IgnoreParenImpCasts();5161 5162  // For expressions like `&(*s).b`, the base is recorded and what should be5163  // checked.5164  const MemberExpr *Member = nullptr;5165  while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())5166    StrippedExpr = Member->getBase()->IgnoreParenImpCasts();5167 5168  LastRecord.PossibleDerefs.erase(StrippedExpr);5169}5170 5171void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {5172  if (isUnevaluatedContext())5173    return;5174 5175  QualType ResultTy = E->getType();5176  ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();5177 5178  // Bail if the element is an array since it is not memory access.5179  if (isa<ArrayType>(ResultTy))5180    return;5181 5182  if (ResultTy->hasAttr(attr::NoDeref)) {5183    LastRecord.PossibleDerefs.insert(E);5184    return;5185  }5186 5187  // Check if the base type is a pointer to a member access of a struct5188  // marked with noderef.5189  const Expr *Base = E->getBase();5190  QualType BaseTy = Base->getType();5191  if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))5192    // Not a pointer access5193    return;5194 5195  const MemberExpr *Member = nullptr;5196  while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&5197         Member->isArrow())5198    Base = Member->getBase();5199 5200  if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {5201    if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))5202      LastRecord.PossibleDerefs.insert(E);5203  }5204}5205 5206ExprResult5207Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,5208                                      Expr *Idx, SourceLocation RLoc) {5209  Expr *LHSExp = Base;5210  Expr *RHSExp = Idx;5211 5212  ExprValueKind VK = VK_LValue;5213  ExprObjectKind OK = OK_Ordinary;5214 5215  // Per C++ core issue 1213, the result is an xvalue if either operand is5216  // a non-lvalue array, and an lvalue otherwise.5217  if (getLangOpts().CPlusPlus11) {5218    for (auto *Op : {LHSExp, RHSExp}) {5219      Op = Op->IgnoreImplicit();5220      if (Op->getType()->isArrayType() && !Op->isLValue())5221        VK = VK_XValue;5222    }5223  }5224 5225  // Perform default conversions.5226  if (!LHSExp->getType()->isSubscriptableVectorType()) {5227    ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);5228    if (Result.isInvalid())5229      return ExprError();5230    LHSExp = Result.get();5231  }5232  ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);5233  if (Result.isInvalid())5234    return ExprError();5235  RHSExp = Result.get();5236 5237  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();5238 5239  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent5240  // to the expression *((e1)+(e2)). This means the array "Base" may actually be5241  // in the subscript position. As a result, we need to derive the array base5242  // and index from the expression types.5243  Expr *BaseExpr, *IndexExpr;5244  QualType ResultType;5245  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {5246    BaseExpr = LHSExp;5247    IndexExpr = RHSExp;5248    ResultType =5249        getDependentArraySubscriptType(LHSExp, RHSExp, getASTContext());5250  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {5251    BaseExpr = LHSExp;5252    IndexExpr = RHSExp;5253    ResultType = PTy->getPointeeType();5254  } else if (const ObjCObjectPointerType *PTy =5255               LHSTy->getAs<ObjCObjectPointerType>()) {5256    BaseExpr = LHSExp;5257    IndexExpr = RHSExp;5258 5259    // Use custom logic if this should be the pseudo-object subscript5260    // expression.5261    if (!LangOpts.isSubscriptPointerArithmetic())5262      return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,5263                                                 nullptr, nullptr);5264 5265    ResultType = PTy->getPointeeType();5266  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {5267     // Handle the uncommon case of "123[Ptr]".5268    BaseExpr = RHSExp;5269    IndexExpr = LHSExp;5270    ResultType = PTy->getPointeeType();5271  } else if (const ObjCObjectPointerType *PTy =5272               RHSTy->getAs<ObjCObjectPointerType>()) {5273     // Handle the uncommon case of "123[Ptr]".5274    BaseExpr = RHSExp;5275    IndexExpr = LHSExp;5276    ResultType = PTy->getPointeeType();5277    if (!LangOpts.isSubscriptPointerArithmetic()) {5278      Diag(LLoc, diag::err_subscript_nonfragile_interface)5279        << ResultType << BaseExpr->getSourceRange();5280      return ExprError();5281    }5282  } else if (LHSTy->isSubscriptableVectorType()) {5283    if (LHSTy->isBuiltinType() &&5284        LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {5285      const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();5286      if (BTy->isSVEBool())5287        return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)5288                         << LHSExp->getSourceRange()5289                         << RHSExp->getSourceRange());5290      ResultType = BTy->getSveEltType(Context);5291    } else {5292      const VectorType *VTy = LHSTy->getAs<VectorType>();5293      ResultType = VTy->getElementType();5294    }5295    BaseExpr = LHSExp; // vectors: V[123]5296    IndexExpr = RHSExp;5297    // We apply C++ DR1213 to vector subscripting too.5298    if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {5299      ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);5300      if (Materialized.isInvalid())5301        return ExprError();5302      LHSExp = Materialized.get();5303    }5304    VK = LHSExp->getValueKind();5305    if (VK != VK_PRValue)5306      OK = OK_VectorComponent;5307 5308    QualType BaseType = BaseExpr->getType();5309    Qualifiers BaseQuals = BaseType.getQualifiers();5310    Qualifiers MemberQuals = ResultType.getQualifiers();5311    Qualifiers Combined = BaseQuals + MemberQuals;5312    if (Combined != MemberQuals)5313      ResultType = Context.getQualifiedType(ResultType, Combined);5314  } else if (LHSTy->isArrayType()) {5315    // If we see an array that wasn't promoted by5316    // DefaultFunctionArrayLvalueConversion, it must be an array that5317    // wasn't promoted because of the C90 rule that doesn't5318    // allow promoting non-lvalue arrays.  Warn, then5319    // force the promotion here.5320    Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)5321        << LHSExp->getSourceRange();5322    LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),5323                               CK_ArrayToPointerDecay).get();5324    LHSTy = LHSExp->getType();5325 5326    BaseExpr = LHSExp;5327    IndexExpr = RHSExp;5328    ResultType = LHSTy->castAs<PointerType>()->getPointeeType();5329  } else if (RHSTy->isArrayType()) {5330    // Same as previous, except for 123[f().a] case5331    Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)5332        << RHSExp->getSourceRange();5333    RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),5334                               CK_ArrayToPointerDecay).get();5335    RHSTy = RHSExp->getType();5336 5337    BaseExpr = RHSExp;5338    IndexExpr = LHSExp;5339    ResultType = RHSTy->castAs<PointerType>()->getPointeeType();5340  } else {5341    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)5342       << LHSExp->getSourceRange() << RHSExp->getSourceRange());5343  }5344  // C99 6.5.2.1p15345  if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())5346    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)5347                     << IndexExpr->getSourceRange());5348 5349  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||5350       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&5351      !IndexExpr->isTypeDependent()) {5352    std::optional<llvm::APSInt> IntegerContantExpr =5353        IndexExpr->getIntegerConstantExpr(getASTContext());5354    if (!IntegerContantExpr.has_value() ||5355        IntegerContantExpr.value().isNegative())5356      Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();5357  }5358 5359  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,5360  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object5361  // type. Note that Functions are not objects, and that (in C99 parlance)5362  // incomplete types are not object types.5363  if (ResultType->isFunctionType()) {5364    Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)5365        << ResultType << BaseExpr->getSourceRange();5366    return ExprError();5367  }5368 5369  if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {5370    // GNU extension: subscripting on pointer to void5371    Diag(LLoc, diag::ext_gnu_subscript_void_type)5372      << BaseExpr->getSourceRange();5373 5374    // C forbids expressions of unqualified void type from being l-values.5375    // See IsCForbiddenLValueType.5376    if (!ResultType.hasQualifiers())5377      VK = VK_PRValue;5378  } else if (!ResultType->isDependentType() &&5379             !ResultType.isWebAssemblyReferenceType() &&5380             RequireCompleteSizedType(5381                 LLoc, ResultType,5382                 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))5383    return ExprError();5384 5385  assert(VK == VK_PRValue || LangOpts.CPlusPlus ||5386         !ResultType.isCForbiddenLValueType());5387 5388  if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&5389      FunctionScopes.size() > 1) {5390    if (auto *TT =5391            LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {5392      for (auto I = FunctionScopes.rbegin(),5393                E = std::prev(FunctionScopes.rend());5394           I != E; ++I) {5395        auto *CSI = dyn_cast<CapturingScopeInfo>(*I);5396        if (CSI == nullptr)5397          break;5398        DeclContext *DC = nullptr;5399        if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))5400          DC = LSI->CallOperator;5401        else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))5402          DC = CRSI->TheCapturedDecl;5403        else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))5404          DC = BSI->TheDecl;5405        if (DC) {5406          if (DC->containsDecl(TT->getDecl()))5407            break;5408          captureVariablyModifiedType(5409              Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);5410        }5411      }5412    }5413  }5414 5415  return new (Context)5416      ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);5417}5418 5419bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,5420                                  ParmVarDecl *Param, Expr *RewrittenInit,5421                                  bool SkipImmediateInvocations) {5422  if (Param->hasUnparsedDefaultArg()) {5423    assert(!RewrittenInit && "Should not have a rewritten init expression yet");5424    // If we've already cleared out the location for the default argument,5425    // that means we're parsing it right now.5426    if (!UnparsedDefaultArgLocs.count(Param)) {5427      Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;5428      Diag(CallLoc, diag::note_recursive_default_argument_used_here);5429      Param->setInvalidDecl();5430      return true;5431    }5432 5433    Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)5434        << FD << cast<CXXRecordDecl>(FD->getDeclContext());5435    Diag(UnparsedDefaultArgLocs[Param],5436         diag::note_default_argument_declared_here);5437    return true;5438  }5439 5440  if (Param->hasUninstantiatedDefaultArg()) {5441    assert(!RewrittenInit && "Should not have a rewitten init expression yet");5442    if (InstantiateDefaultArgument(CallLoc, FD, Param))5443      return true;5444  }5445 5446  Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();5447  assert(Init && "default argument but no initializer?");5448 5449  // If the default expression creates temporaries, we need to5450  // push them to the current stack of expression temporaries so they'll5451  // be properly destroyed.5452  // FIXME: We should really be rebuilding the default argument with new5453  // bound temporaries; see the comment in PR5810.5454  // We don't need to do that with block decls, though, because5455  // blocks in default argument expression can never capture anything.5456  if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {5457    // Set the "needs cleanups" bit regardless of whether there are5458    // any explicit objects.5459    Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());5460    // Append all the objects to the cleanup list.  Right now, this5461    // should always be a no-op, because blocks in default argument5462    // expressions should never be able to capture anything.5463    assert(!InitWithCleanup->getNumObjects() &&5464           "default argument expression has capturing blocks?");5465  }5466  // C++ [expr.const]p15.1:5467  //   An expression or conversion is in an immediate function context if it is5468  //   potentially evaluated and [...] its innermost enclosing non-block scope5469  //   is a function parameter scope of an immediate function.5470  EnterExpressionEvaluationContext EvalContext(5471      *this,5472      FD->isImmediateFunction()5473          ? ExpressionEvaluationContext::ImmediateFunctionContext5474          : ExpressionEvaluationContext::PotentiallyEvaluated,5475      Param);5476  ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =5477      SkipImmediateInvocations;5478  runWithSufficientStackSpace(CallLoc, [&] {5479    MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);5480  });5481  return false;5482}5483 5484struct ImmediateCallVisitor : DynamicRecursiveASTVisitor {5485  const ASTContext &Context;5486  ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {5487    ShouldVisitImplicitCode = true;5488  }5489 5490  bool HasImmediateCalls = false;5491 5492  bool VisitCallExpr(CallExpr *E) override {5493    if (const FunctionDecl *FD = E->getDirectCallee())5494      HasImmediateCalls |= FD->isImmediateFunction();5495    return DynamicRecursiveASTVisitor::VisitStmt(E);5496  }5497 5498  bool VisitCXXConstructExpr(CXXConstructExpr *E) override {5499    if (const FunctionDecl *FD = E->getConstructor())5500      HasImmediateCalls |= FD->isImmediateFunction();5501    return DynamicRecursiveASTVisitor::VisitStmt(E);5502  }5503 5504  // SourceLocExpr are not immediate invocations5505  // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr5506  // need to be rebuilt so that they refer to the correct SourceLocation and5507  // DeclContext.5508  bool VisitSourceLocExpr(SourceLocExpr *E) override {5509    HasImmediateCalls = true;5510    return DynamicRecursiveASTVisitor::VisitStmt(E);5511  }5512 5513  // A nested lambda might have parameters with immediate invocations5514  // in their default arguments.5515  // The compound statement is not visited (as it does not constitute a5516  // subexpression).5517  // FIXME: We should consider visiting and transforming captures5518  // with init expressions.5519  bool VisitLambdaExpr(LambdaExpr *E) override {5520    return VisitCXXMethodDecl(E->getCallOperator());5521  }5522 5523  bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override {5524    return TraverseStmt(E->getExpr());5525  }5526 5527  bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override {5528    return TraverseStmt(E->getExpr());5529  }5530};5531 5532struct EnsureImmediateInvocationInDefaultArgs5533    : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {5534  EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)5535      : TreeTransform(SemaRef) {}5536 5537  bool AlwaysRebuild() { return true; }5538 5539  // Lambda can only have immediate invocations in the default5540  // args of their parameters, which is transformed upon calling the closure.5541  // The body is not a subexpression, so we have nothing to do.5542  // FIXME: Immediate calls in capture initializers should be transformed.5543  ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }5544  ExprResult TransformBlockExpr(BlockExpr *E) { return E; }5545 5546  // Make sure we don't rebuild the this pointer as it would5547  // cause it to incorrectly point it to the outermost class5548  // in the case of nested struct initialization.5549  ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }5550 5551  // Rewrite to source location to refer to the context in which they are used.5552  ExprResult TransformSourceLocExpr(SourceLocExpr *E) {5553    DeclContext *DC = E->getParentContext();5554    if (DC == SemaRef.CurContext)5555      return E;5556 5557    // FIXME: During instantiation, because the rebuild of defaults arguments5558    // is not always done in the context of the template instantiator,5559    // we run the risk of producing a dependent source location5560    // that would never be rebuilt.5561    // This usually happens during overload resolution, or in contexts5562    // where the value of the source location does not matter.5563    // However, we should find a better way to deal with source location5564    // of function templates.5565    if (!SemaRef.CurrentInstantiationScope ||5566        !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())5567      DC = SemaRef.CurContext;5568 5569    return getDerived().RebuildSourceLocExpr(5570        E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);5571  }5572};5573 5574ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,5575                                        FunctionDecl *FD, ParmVarDecl *Param,5576                                        Expr *Init) {5577  assert(Param->hasDefaultArg() && "can't build nonexistent default arg");5578 5579  bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();5580  bool NeedRebuild = needsRebuildOfDefaultArgOrInit();5581  std::optional<ExpressionEvaluationContextRecord::InitializationContext>5582      InitializationContext =5583          OutermostDeclarationWithDelayedImmediateInvocations();5584  if (!InitializationContext.has_value())5585    InitializationContext.emplace(CallLoc, Param, CurContext);5586 5587  if (!Init && !Param->hasUnparsedDefaultArg()) {5588    // Mark that we are replacing a default argument first.5589    // If we are instantiating a template we won't have to5590    // retransform immediate calls.5591    // C++ [expr.const]p15.1:5592    //   An expression or conversion is in an immediate function context if it5593    //   is potentially evaluated and [...] its innermost enclosing non-block5594    //   scope is a function parameter scope of an immediate function.5595    EnterExpressionEvaluationContext EvalContext(5596        *this,5597        FD->isImmediateFunction()5598            ? ExpressionEvaluationContext::ImmediateFunctionContext5599            : ExpressionEvaluationContext::PotentiallyEvaluated,5600        Param);5601 5602    if (Param->hasUninstantiatedDefaultArg()) {5603      if (InstantiateDefaultArgument(CallLoc, FD, Param))5604        return ExprError();5605    }5606    // CWG26315607    // An immediate invocation that is not evaluated where it appears is5608    // evaluated and checked for whether it is a constant expression at the5609    // point where the enclosing initializer is used in a function call.5610    ImmediateCallVisitor V(getASTContext());5611    if (!NestedDefaultChecking)5612      V.TraverseDecl(Param);5613 5614    // Rewrite the call argument that was created from the corresponding5615    // parameter's default argument.5616    if (V.HasImmediateCalls ||5617        (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {5618      if (V.HasImmediateCalls)5619        ExprEvalContexts.back().DelayedDefaultInitializationContext = {5620            CallLoc, Param, CurContext};5621      // Pass down lifetime extending flag, and collect temporaries in5622      // CreateMaterializeTemporaryExpr when we rewrite the call argument.5623      currentEvaluationContext().InLifetimeExtendingContext =5624          parentEvaluationContext().InLifetimeExtendingContext;5625      EnsureImmediateInvocationInDefaultArgs Immediate(*this);5626      ExprResult Res;5627      runWithSufficientStackSpace(CallLoc, [&] {5628        Res = Immediate.TransformInitializer(Param->getInit(),5629                                             /*NotCopy=*/false);5630      });5631      if (Res.isInvalid())5632        return ExprError();5633      Res = ConvertParamDefaultArgument(Param, Res.get(),5634                                        Res.get()->getBeginLoc());5635      if (Res.isInvalid())5636        return ExprError();5637      Init = Res.get();5638    }5639  }5640 5641  if (CheckCXXDefaultArgExpr(5642          CallLoc, FD, Param, Init,5643          /*SkipImmediateInvocations=*/NestedDefaultChecking))5644    return ExprError();5645 5646  return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,5647                                   Init, InitializationContext->Context);5648}5649 5650static FieldDecl *FindFieldDeclInstantiationPattern(const ASTContext &Ctx,5651                                                    FieldDecl *Field) {5652  if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))5653    return Pattern;5654  auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());5655  CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();5656  DeclContext::lookup_result Lookup =5657      ClassPattern->lookup(Field->getDeclName());5658  auto Rng = llvm::make_filter_range(5659      Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });5660  if (Rng.empty())5661    return nullptr;5662  // FIXME: this breaks clang/test/Modules/pr28812.cpp5663  // assert(std::distance(Rng.begin(), Rng.end()) <= 15664  //       && "Duplicated instantiation pattern for field decl");5665  return cast<FieldDecl>(*Rng.begin());5666}5667 5668ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {5669  assert(Field->hasInClassInitializer());5670 5671  CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());5672 5673  auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());5674 5675  std::optional<ExpressionEvaluationContextRecord::InitializationContext>5676      InitializationContext =5677          OutermostDeclarationWithDelayedImmediateInvocations();5678  if (!InitializationContext.has_value())5679    InitializationContext.emplace(Loc, Field, CurContext);5680 5681  Expr *Init = nullptr;5682 5683  bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();5684  bool NeedRebuild = needsRebuildOfDefaultArgOrInit();5685  EnterExpressionEvaluationContext EvalContext(5686      *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);5687 5688  if (!Field->getInClassInitializer()) {5689    // Maybe we haven't instantiated the in-class initializer. Go check the5690    // pattern FieldDecl to see if it has one.5691    if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {5692      FieldDecl *Pattern =5693          FindFieldDeclInstantiationPattern(getASTContext(), Field);5694      assert(Pattern && "We must have set the Pattern!");5695      if (!Pattern->hasInClassInitializer() ||5696          InstantiateInClassInitializer(Loc, Field, Pattern,5697                                        getTemplateInstantiationArgs(Field))) {5698        Field->setInvalidDecl();5699        return ExprError();5700      }5701    }5702  }5703 5704  // CWG26315705  // An immediate invocation that is not evaluated where it appears is5706  // evaluated and checked for whether it is a constant expression at the5707  // point where the enclosing initializer is used in a [...] a constructor5708  // definition, or an aggregate initialization.5709  ImmediateCallVisitor V(getASTContext());5710  if (!NestedDefaultChecking)5711    V.TraverseDecl(Field);5712 5713  // CWG18155714  // Support lifetime extension of temporary created by aggregate5715  // initialization using a default member initializer. We should rebuild5716  // the initializer in a lifetime extension context if the initializer5717  // expression is an ExprWithCleanups. Then make sure the normal lifetime5718  // extension code recurses into the default initializer and does lifetime5719  // extension when warranted.5720  bool ContainsAnyTemporaries =5721      isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());5722  if (Field->getInClassInitializer() &&5723      !Field->getInClassInitializer()->containsErrors() &&5724      (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {5725    ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,5726                                                                   CurContext};5727    ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =5728        NestedDefaultChecking;5729    // Pass down lifetime extending flag, and collect temporaries in5730    // CreateMaterializeTemporaryExpr when we rewrite the call argument.5731    currentEvaluationContext().InLifetimeExtendingContext =5732        parentEvaluationContext().InLifetimeExtendingContext;5733    EnsureImmediateInvocationInDefaultArgs Immediate(*this);5734    ExprResult Res;5735    runWithSufficientStackSpace(Loc, [&] {5736      Res = Immediate.TransformInitializer(Field->getInClassInitializer(),5737                                           /*CXXDirectInit=*/false);5738    });5739    if (!Res.isInvalid())5740      Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);5741    if (Res.isInvalid()) {5742      Field->setInvalidDecl();5743      return ExprError();5744    }5745    Init = Res.get();5746  }5747 5748  if (Field->getInClassInitializer()) {5749    Expr *E = Init ? Init : Field->getInClassInitializer();5750    if (!NestedDefaultChecking)5751      runWithSufficientStackSpace(Loc, [&] {5752        MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);5753      });5754    if (isInLifetimeExtendingContext())5755      DiscardCleanupsInEvaluationContext();5756    // C++11 [class.base.init]p7:5757    //   The initialization of each base and member constitutes a5758    //   full-expression.5759    ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);5760    if (Res.isInvalid()) {5761      Field->setInvalidDecl();5762      return ExprError();5763    }5764    Init = Res.get();5765 5766    return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,5767                                      Field, InitializationContext->Context,5768                                      Init);5769  }5770 5771  // DR1351:5772  //   If the brace-or-equal-initializer of a non-static data member5773  //   invokes a defaulted default constructor of its class or of an5774  //   enclosing class in a potentially evaluated subexpression, the5775  //   program is ill-formed.5776  //5777  // This resolution is unworkable: the exception specification of the5778  // default constructor can be needed in an unevaluated context, in5779  // particular, in the operand of a noexcept-expression, and we can be5780  // unable to compute an exception specification for an enclosed class.5781  //5782  // Any attempt to resolve the exception specification of a defaulted default5783  // constructor before the initializer is lexically complete will ultimately5784  // come here at which point we can diagnose it.5785  RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();5786  Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)5787      << OutermostClass << Field;5788  Diag(Field->getEndLoc(),5789       diag::note_default_member_initializer_not_yet_parsed);5790  // Recover by marking the field invalid, unless we're in a SFINAE context.5791  if (!isSFINAEContext())5792    Field->setInvalidDecl();5793  return ExprError();5794}5795 5796VariadicCallType Sema::getVariadicCallType(FunctionDecl *FDecl,5797                                           const FunctionProtoType *Proto,5798                                           Expr *Fn) {5799  if (Proto && Proto->isVariadic()) {5800    if (isa_and_nonnull<CXXConstructorDecl>(FDecl))5801      return VariadicCallType::Constructor;5802    else if (Fn && Fn->getType()->isBlockPointerType())5803      return VariadicCallType::Block;5804    else if (FDecl) {5805      if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))5806        if (Method->isInstance())5807          return VariadicCallType::Method;5808    } else if (Fn && Fn->getType() == Context.BoundMemberTy)5809      return VariadicCallType::Method;5810    return VariadicCallType::Function;5811  }5812  return VariadicCallType::DoesNotApply;5813}5814 5815namespace {5816class FunctionCallCCC final : public FunctionCallFilterCCC {5817public:5818  FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,5819                  unsigned NumArgs, MemberExpr *ME)5820      : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),5821        FunctionName(FuncName) {}5822 5823  bool ValidateCandidate(const TypoCorrection &candidate) override {5824    if (!candidate.getCorrectionSpecifier() ||5825        candidate.getCorrectionAsIdentifierInfo() != FunctionName) {5826      return false;5827    }5828 5829    return FunctionCallFilterCCC::ValidateCandidate(candidate);5830  }5831 5832  std::unique_ptr<CorrectionCandidateCallback> clone() override {5833    return std::make_unique<FunctionCallCCC>(*this);5834  }5835 5836private:5837  const IdentifierInfo *const FunctionName;5838};5839}5840 5841static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,5842                                               FunctionDecl *FDecl,5843                                               ArrayRef<Expr *> Args) {5844  MemberExpr *ME = dyn_cast<MemberExpr>(Fn);5845  DeclarationName FuncName = FDecl->getDeclName();5846  SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();5847 5848  FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);5849  if (TypoCorrection Corrected = S.CorrectTypo(5850          DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,5851          S.getScopeForContext(S.CurContext), nullptr, CCC,5852          CorrectTypoKind::ErrorRecovery)) {5853    if (NamedDecl *ND = Corrected.getFoundDecl()) {5854      if (Corrected.isOverloaded()) {5855        OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);5856        OverloadCandidateSet::iterator Best;5857        for (NamedDecl *CD : Corrected) {5858          if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))5859            S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,5860                                   OCS);5861        }5862        switch (OCS.BestViableFunction(S, NameLoc, Best)) {5863        case OR_Success:5864          ND = Best->FoundDecl;5865          Corrected.setCorrectionDecl(ND);5866          break;5867        default:5868          break;5869        }5870      }5871      ND = ND->getUnderlyingDecl();5872      if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))5873        return Corrected;5874    }5875  }5876  return TypoCorrection();5877}5878 5879// [C++26][[expr.unary.op]/p45880// A pointer to member is only formed when an explicit &5881// is used and its operand is a qualified-id not enclosed in parentheses.5882static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn) {5883  if (!isa<ParenExpr>(Fn))5884    return false;5885 5886  Fn = Fn->IgnoreParens();5887 5888  auto *UO = dyn_cast<UnaryOperator>(Fn);5889  if (!UO || UO->getOpcode() != clang::UO_AddrOf)5890    return false;5891  if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {5892    return DRE->hasQualifier();5893  }5894  if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))5895    return bool(OVL->getQualifier());5896  return false;5897}5898 5899bool5900Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,5901                              FunctionDecl *FDecl,5902                              const FunctionProtoType *Proto,5903                              ArrayRef<Expr *> Args,5904                              SourceLocation RParenLoc,5905                              bool IsExecConfig) {5906  // Bail out early if calling a builtin with custom typechecking.5907  if (FDecl)5908    if (unsigned ID = FDecl->getBuiltinID())5909      if (Context.BuiltinInfo.hasCustomTypechecking(ID))5910        return false;5911 5912  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by5913  // assignment, to the types of the corresponding parameter, ...5914 5915  bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);5916  bool HasExplicitObjectParameter =5917      !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();5918  unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;5919  unsigned NumParams = Proto->getNumParams();5920  bool Invalid = false;5921  unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;5922  unsigned FnKind = Fn->getType()->isBlockPointerType()5923                       ? 1 /* block */5924                       : (IsExecConfig ? 3 /* kernel function (exec config) */5925                                       : 0 /* function */);5926 5927  // If too few arguments are available (and we don't have default5928  // arguments for the remaining parameters), don't make the call.5929  if (Args.size() < NumParams) {5930    if (Args.size() < MinArgs) {5931      TypoCorrection TC;5932      if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {5933        unsigned diag_id =5934            MinArgs == NumParams && !Proto->isVariadic()5935                ? diag::err_typecheck_call_too_few_args_suggest5936                : diag::err_typecheck_call_too_few_args_at_least_suggest;5937        diagnoseTypo(5938            TC, PDiag(diag_id)5939                    << FnKind << MinArgs - ExplicitObjectParameterOffset5940                    << static_cast<unsigned>(Args.size()) -5941                           ExplicitObjectParameterOffset5942                    << HasExplicitObjectParameter << TC.getCorrectionRange());5943      } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&5944                 FDecl->getParamDecl(ExplicitObjectParameterOffset)5945                     ->getDeclName())5946        Diag(RParenLoc,5947             MinArgs == NumParams && !Proto->isVariadic()5948                 ? diag::err_typecheck_call_too_few_args_one5949                 : diag::err_typecheck_call_too_few_args_at_least_one)5950            << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)5951            << HasExplicitObjectParameter << Fn->getSourceRange();5952      else5953        Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()5954                            ? diag::err_typecheck_call_too_few_args5955                            : diag::err_typecheck_call_too_few_args_at_least)5956            << FnKind << MinArgs - ExplicitObjectParameterOffset5957            << static_cast<unsigned>(Args.size()) -5958                   ExplicitObjectParameterOffset5959            << HasExplicitObjectParameter << Fn->getSourceRange();5960 5961      // Emit the location of the prototype.5962      if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)5963        Diag(FDecl->getLocation(), diag::note_callee_decl)5964            << FDecl << FDecl->getParametersSourceRange();5965 5966      return true;5967    }5968    // We reserve space for the default arguments when we create5969    // the call expression, before calling ConvertArgumentsForCall.5970    assert((Call->getNumArgs() == NumParams) &&5971           "We should have reserved space for the default arguments before!");5972  }5973 5974  // If too many are passed and not variadic, error on the extras and drop5975  // them.5976  if (Args.size() > NumParams) {5977    if (!Proto->isVariadic()) {5978      TypoCorrection TC;5979      if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {5980        unsigned diag_id =5981            MinArgs == NumParams && !Proto->isVariadic()5982                ? diag::err_typecheck_call_too_many_args_suggest5983                : diag::err_typecheck_call_too_many_args_at_most_suggest;5984        diagnoseTypo(5985            TC, PDiag(diag_id)5986                    << FnKind << NumParams - ExplicitObjectParameterOffset5987                    << static_cast<unsigned>(Args.size()) -5988                           ExplicitObjectParameterOffset5989                    << HasExplicitObjectParameter << TC.getCorrectionRange());5990      } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&5991                 FDecl->getParamDecl(ExplicitObjectParameterOffset)5992                     ->getDeclName())5993        Diag(Args[NumParams]->getBeginLoc(),5994             MinArgs == NumParams5995                 ? diag::err_typecheck_call_too_many_args_one5996                 : diag::err_typecheck_call_too_many_args_at_most_one)5997            << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)5998            << static_cast<unsigned>(Args.size()) -5999                   ExplicitObjectParameterOffset6000            << HasExplicitObjectParameter << Fn->getSourceRange()6001            << SourceRange(Args[NumParams]->getBeginLoc(),6002                           Args.back()->getEndLoc());6003      else6004        Diag(Args[NumParams]->getBeginLoc(),6005             MinArgs == NumParams6006                 ? diag::err_typecheck_call_too_many_args6007                 : diag::err_typecheck_call_too_many_args_at_most)6008            << FnKind << NumParams - ExplicitObjectParameterOffset6009            << static_cast<unsigned>(Args.size()) -6010                   ExplicitObjectParameterOffset6011            << HasExplicitObjectParameter << Fn->getSourceRange()6012            << SourceRange(Args[NumParams]->getBeginLoc(),6013                           Args.back()->getEndLoc());6014 6015      // Emit the location of the prototype.6016      if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)6017        Diag(FDecl->getLocation(), diag::note_callee_decl)6018            << FDecl << FDecl->getParametersSourceRange();6019 6020      // This deletes the extra arguments.6021      Call->shrinkNumArgs(NumParams);6022      return true;6023    }6024  }6025  SmallVector<Expr *, 8> AllArgs;6026  VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);6027 6028  Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,6029                                   AllArgs, CallType);6030  if (Invalid)6031    return true;6032  unsigned TotalNumArgs = AllArgs.size();6033  for (unsigned i = 0; i < TotalNumArgs; ++i)6034    Call->setArg(i, AllArgs[i]);6035 6036  Call->computeDependence();6037  return false;6038}6039 6040bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,6041                                  const FunctionProtoType *Proto,6042                                  unsigned FirstParam, ArrayRef<Expr *> Args,6043                                  SmallVectorImpl<Expr *> &AllArgs,6044                                  VariadicCallType CallType, bool AllowExplicit,6045                                  bool IsListInitialization) {6046  unsigned NumParams = Proto->getNumParams();6047  bool Invalid = false;6048  size_t ArgIx = 0;6049  // Continue to check argument types (even if we have too few/many args).6050  for (unsigned i = FirstParam; i < NumParams; i++) {6051    QualType ProtoArgType = Proto->getParamType(i);6052 6053    Expr *Arg;6054    ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;6055    if (ArgIx < Args.size()) {6056      Arg = Args[ArgIx++];6057 6058      if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,6059                              diag::err_call_incomplete_argument, Arg))6060        return true;6061 6062      // Strip the unbridged-cast placeholder expression off, if applicable.6063      bool CFAudited = false;6064      if (Arg->getType() == Context.ARCUnbridgedCastTy &&6065          FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&6066          (!Param || !Param->hasAttr<CFConsumedAttr>()))6067        Arg = ObjC().stripARCUnbridgedCast(Arg);6068      else if (getLangOpts().ObjCAutoRefCount &&6069               FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&6070               (!Param || !Param->hasAttr<CFConsumedAttr>()))6071        CFAudited = true;6072 6073      if (Proto->getExtParameterInfo(i).isNoEscape() &&6074          ProtoArgType->isBlockPointerType())6075        if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))6076          BE->getBlockDecl()->setDoesNotEscape();6077      if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||6078           Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLInOut)) {6079        ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);6080        if (ArgExpr.isInvalid())6081          return true;6082        Arg = ArgExpr.getAs<Expr>();6083      }6084 6085      InitializedEntity Entity =6086          Param ? InitializedEntity::InitializeParameter(Context, Param,6087                                                         ProtoArgType)6088                : InitializedEntity::InitializeParameter(6089                      Context, ProtoArgType, Proto->isParamConsumed(i));6090 6091      // Remember that parameter belongs to a CF audited API.6092      if (CFAudited)6093        Entity.setParameterCFAudited();6094 6095      ExprResult ArgE = PerformCopyInitialization(6096          Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);6097      if (ArgE.isInvalid())6098        return true;6099 6100      Arg = ArgE.getAs<Expr>();6101    } else {6102      assert(Param && "can't use default arguments without a known callee");6103 6104      ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);6105      if (ArgExpr.isInvalid())6106        return true;6107 6108      Arg = ArgExpr.getAs<Expr>();6109    }6110 6111    // Check for array bounds violations for each argument to the call. This6112    // check only triggers warnings when the argument isn't a more complex Expr6113    // with its own checking, such as a BinaryOperator.6114    CheckArrayAccess(Arg);6115 6116    // Check for violations of C99 static array rules (C99 6.7.5.3p7).6117    CheckStaticArrayArgument(CallLoc, Param, Arg);6118 6119    AllArgs.push_back(Arg);6120  }6121 6122  // If this is a variadic call, handle args passed through "...".6123  if (CallType != VariadicCallType::DoesNotApply) {6124    // Assume that extern "C" functions with variadic arguments that6125    // return __unknown_anytype aren't *really* variadic.6126    if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&6127        FDecl->isExternC()) {6128      for (Expr *A : Args.slice(ArgIx)) {6129        QualType paramType; // ignored6130        ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);6131        Invalid |= arg.isInvalid();6132        AllArgs.push_back(arg.get());6133      }6134 6135    // Otherwise do argument promotion, (C99 6.5.2.2p7).6136    } else {6137      for (Expr *A : Args.slice(ArgIx)) {6138        ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);6139        Invalid |= Arg.isInvalid();6140        AllArgs.push_back(Arg.get());6141      }6142    }6143 6144    // Check for array bounds violations.6145    for (Expr *A : Args.slice(ArgIx))6146      CheckArrayAccess(A);6147  }6148  return Invalid;6149}6150 6151static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {6152  TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();6153  if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())6154    TL = DTL.getOriginalLoc();6155  if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())6156    S.Diag(PVD->getLocation(), diag::note_callee_static_array)6157      << ATL.getLocalSourceRange();6158}6159 6160void6161Sema::CheckStaticArrayArgument(SourceLocation CallLoc,6162                               ParmVarDecl *Param,6163                               const Expr *ArgExpr) {6164  // Static array parameters are not supported in C++.6165  if (!Param || getLangOpts().CPlusPlus)6166    return;6167 6168  QualType OrigTy = Param->getOriginalType();6169 6170  const ArrayType *AT = Context.getAsArrayType(OrigTy);6171  if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)6172    return;6173 6174  if (ArgExpr->isNullPointerConstant(Context,6175                                     Expr::NPC_NeverValueDependent)) {6176    Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();6177    DiagnoseCalleeStaticArrayParam(*this, Param);6178    return;6179  }6180 6181  const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);6182  if (!CAT)6183    return;6184 6185  const ConstantArrayType *ArgCAT =6186    Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());6187  if (!ArgCAT)6188    return;6189 6190  if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),6191                                             ArgCAT->getElementType())) {6192    if (ArgCAT->getSize().ult(CAT->getSize())) {6193      Diag(CallLoc, diag::warn_static_array_too_small)6194          << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()6195          << (unsigned)CAT->getZExtSize() << 0;6196      DiagnoseCalleeStaticArrayParam(*this, Param);6197    }6198    return;6199  }6200 6201  std::optional<CharUnits> ArgSize =6202      getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);6203  std::optional<CharUnits> ParmSize =6204      getASTContext().getTypeSizeInCharsIfKnown(CAT);6205  if (ArgSize && ParmSize && *ArgSize < *ParmSize) {6206    Diag(CallLoc, diag::warn_static_array_too_small)6207        << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()6208        << (unsigned)ParmSize->getQuantity() << 1;6209    DiagnoseCalleeStaticArrayParam(*this, Param);6210  }6211}6212 6213/// Given a function expression of unknown-any type, try to rebuild it6214/// to have a function type.6215static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);6216 6217/// Is the given type a placeholder that we need to lower out6218/// immediately during argument processing?6219static bool isPlaceholderToRemoveAsArg(QualType type) {6220  // Placeholders are never sugared.6221  const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);6222  if (!placeholder) return false;6223 6224  switch (placeholder->getKind()) {6225  // Ignore all the non-placeholder types.6226#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \6227  case BuiltinType::Id:6228#include "clang/Basic/OpenCLImageTypes.def"6229#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \6230  case BuiltinType::Id:6231#include "clang/Basic/OpenCLExtensionTypes.def"6232  // In practice we'll never use this, since all SVE types are sugared6233  // via TypedefTypes rather than exposed directly as BuiltinTypes.6234#define SVE_TYPE(Name, Id, SingletonId) \6235  case BuiltinType::Id:6236#include "clang/Basic/AArch64ACLETypes.def"6237#define PPC_VECTOR_TYPE(Name, Id, Size) \6238  case BuiltinType::Id:6239#include "clang/Basic/PPCTypes.def"6240#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:6241#include "clang/Basic/RISCVVTypes.def"6242#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:6243#include "clang/Basic/WebAssemblyReferenceTypes.def"6244#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:6245#include "clang/Basic/AMDGPUTypes.def"6246#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:6247#include "clang/Basic/HLSLIntangibleTypes.def"6248#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)6249#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:6250#include "clang/AST/BuiltinTypes.def"6251    return false;6252 6253  case BuiltinType::UnresolvedTemplate:6254  // We cannot lower out overload sets; they might validly be resolved6255  // by the call machinery.6256  case BuiltinType::Overload:6257    return false;6258 6259  // Unbridged casts in ARC can be handled in some call positions and6260  // should be left in place.6261  case BuiltinType::ARCUnbridgedCast:6262    return false;6263 6264  // Pseudo-objects should be converted as soon as possible.6265  case BuiltinType::PseudoObject:6266    return true;6267 6268  // The debugger mode could theoretically but currently does not try6269  // to resolve unknown-typed arguments based on known parameter types.6270  case BuiltinType::UnknownAny:6271    return true;6272 6273  // These are always invalid as call arguments and should be reported.6274  case BuiltinType::BoundMember:6275  case BuiltinType::BuiltinFn:6276  case BuiltinType::IncompleteMatrixIdx:6277  case BuiltinType::ArraySection:6278  case BuiltinType::OMPArrayShaping:6279  case BuiltinType::OMPIterator:6280    return true;6281 6282  }6283  llvm_unreachable("bad builtin type kind");6284}6285 6286bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {6287  // Apply this processing to all the arguments at once instead of6288  // dying at the first failure.6289  bool hasInvalid = false;6290  for (size_t i = 0, e = args.size(); i != e; i++) {6291    if (isPlaceholderToRemoveAsArg(args[i]->getType())) {6292      ExprResult result = CheckPlaceholderExpr(args[i]);6293      if (result.isInvalid()) hasInvalid = true;6294      else args[i] = result.get();6295    }6296  }6297  return hasInvalid;6298}6299 6300/// If a builtin function has a pointer argument with no explicit address6301/// space, then it should be able to accept a pointer to any address6302/// space as input.  In order to do this, we need to replace the6303/// standard builtin declaration with one that uses the same address space6304/// as the call.6305///6306/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.6307///                  it does not contain any pointer arguments without6308///                  an address space qualifer.  Otherwise the rewritten6309///                  FunctionDecl is returned.6310/// TODO: Handle pointer return types.6311static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,6312                                                FunctionDecl *FDecl,6313                                                MultiExprArg ArgExprs) {6314 6315  QualType DeclType = FDecl->getType();6316  const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);6317 6318  if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||6319      ArgExprs.size() < FT->getNumParams())6320    return nullptr;6321 6322  bool NeedsNewDecl = false;6323  unsigned i = 0;6324  SmallVector<QualType, 8> OverloadParams;6325 6326  {6327    // The lvalue conversions in this loop are only for type resolution and6328    // don't actually occur.6329    EnterExpressionEvaluationContext Unevaluated(6330        *Sema, Sema::ExpressionEvaluationContext::Unevaluated);6331    Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);6332 6333    for (QualType ParamType : FT->param_types()) {6334 6335      // Convert array arguments to pointer to simplify type lookup.6336      ExprResult ArgRes =6337          Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);6338      if (ArgRes.isInvalid())6339        return nullptr;6340      Expr *Arg = ArgRes.get();6341      QualType ArgType = Arg->getType();6342      if (!ParamType->isPointerType() ||6343          ParamType->getPointeeType().hasAddressSpace() ||6344          !ArgType->isPointerType() ||6345          !ArgType->getPointeeType().hasAddressSpace() ||6346          isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {6347        OverloadParams.push_back(ParamType);6348        continue;6349      }6350 6351      QualType PointeeType = ParamType->getPointeeType();6352      NeedsNewDecl = true;6353      LangAS AS = ArgType->getPointeeType().getAddressSpace();6354 6355      PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);6356      OverloadParams.push_back(Context.getPointerType(PointeeType));6357    }6358  }6359 6360  if (!NeedsNewDecl)6361    return nullptr;6362 6363  FunctionProtoType::ExtProtoInfo EPI;6364  EPI.Variadic = FT->isVariadic();6365  QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),6366                                                OverloadParams, EPI);6367  DeclContext *Parent = FDecl->getParent();6368  FunctionDecl *OverloadDecl = FunctionDecl::Create(6369      Context, Parent, FDecl->getLocation(), FDecl->getLocation(),6370      FDecl->getIdentifier(), OverloadTy,6371      /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),6372      false,6373      /*hasPrototype=*/true);6374  SmallVector<ParmVarDecl*, 16> Params;6375  FT = cast<FunctionProtoType>(OverloadTy);6376  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {6377    QualType ParamType = FT->getParamType(i);6378    ParmVarDecl *Parm =6379        ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),6380                                SourceLocation(), nullptr, ParamType,6381                                /*TInfo=*/nullptr, SC_None, nullptr);6382    Parm->setScopeInfo(0, i);6383    Params.push_back(Parm);6384  }6385  OverloadDecl->setParams(Params);6386  // We cannot merge host/device attributes of redeclarations. They have to6387  // be consistent when created.6388  if (Sema->LangOpts.CUDA) {6389    if (FDecl->hasAttr<CUDAHostAttr>())6390      OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));6391    if (FDecl->hasAttr<CUDADeviceAttr>())6392      OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));6393  }6394  Sema->mergeDeclAttributes(OverloadDecl, FDecl);6395  return OverloadDecl;6396}6397 6398static void checkDirectCallValidity(Sema &S, const Expr *Fn,6399                                    FunctionDecl *Callee,6400                                    MultiExprArg ArgExprs) {6401  // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and6402  // similar attributes) really don't like it when functions are called with an6403  // invalid number of args.6404  if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),6405                         /*PartialOverloading=*/false) &&6406      !Callee->isVariadic())6407    return;6408  if (Callee->getMinRequiredArguments() > ArgExprs.size())6409    return;6410 6411  if (const EnableIfAttr *Attr =6412          S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {6413    S.Diag(Fn->getBeginLoc(),6414           isa<CXXMethodDecl>(Callee)6415               ? diag::err_ovl_no_viable_member_function_in_call6416               : diag::err_ovl_no_viable_function_in_call)6417        << Callee << Callee->getSourceRange();6418    S.Diag(Callee->getLocation(),6419           diag::note_ovl_candidate_disabled_by_function_cond_attr)6420        << Attr->getCond()->getSourceRange() << Attr->getMessage();6421    return;6422  }6423}6424 6425static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(6426    const UnresolvedMemberExpr *const UME, Sema &S) {6427 6428  const auto GetFunctionLevelDCIfCXXClass =6429      [](Sema &S) -> const CXXRecordDecl * {6430    const DeclContext *const DC = S.getFunctionLevelDeclContext();6431    if (!DC || !DC->getParent())6432      return nullptr;6433 6434    // If the call to some member function was made from within a member6435    // function body 'M' return return 'M's parent.6436    if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))6437      return MD->getParent()->getCanonicalDecl();6438    // else the call was made from within a default member initializer of a6439    // class, so return the class.6440    if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))6441      return RD->getCanonicalDecl();6442    return nullptr;6443  };6444  // If our DeclContext is neither a member function nor a class (in the6445  // case of a lambda in a default member initializer), we can't have an6446  // enclosing 'this'.6447 6448  const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);6449  if (!CurParentClass)6450    return false;6451 6452  // The naming class for implicit member functions call is the class in which6453  // name lookup starts.6454  const CXXRecordDecl *const NamingClass =6455      UME->getNamingClass()->getCanonicalDecl();6456  assert(NamingClass && "Must have naming class even for implicit access");6457 6458  // If the unresolved member functions were found in a 'naming class' that is6459  // related (either the same or derived from) to the class that contains the6460  // member function that itself contained the implicit member access.6461 6462  return CurParentClass == NamingClass ||6463         CurParentClass->isDerivedFrom(NamingClass);6464}6465 6466static void6467tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(6468    Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {6469 6470  if (!UME)6471    return;6472 6473  LambdaScopeInfo *const CurLSI = S.getCurLambda();6474  // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't6475  // already been captured, or if this is an implicit member function call (if6476  // it isn't, an attempt to capture 'this' should already have been made).6477  if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||6478      !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())6479    return;6480 6481  // Check if the naming class in which the unresolved members were found is6482  // related (same as or is a base of) to the enclosing class.6483 6484  if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))6485    return;6486 6487 6488  DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();6489  // If the enclosing function is not dependent, then this lambda is6490  // capture ready, so if we can capture this, do so.6491  if (!EnclosingFunctionCtx->isDependentContext()) {6492    // If the current lambda and all enclosing lambdas can capture 'this' -6493    // then go ahead and capture 'this' (since our unresolved overload set6494    // contains at least one non-static member function).6495    if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))6496      S.CheckCXXThisCapture(CallLoc);6497  } else if (S.CurContext->isDependentContext()) {6498    // ... since this is an implicit member reference, that might potentially6499    // involve a 'this' capture, mark 'this' for potential capture in6500    // enclosing lambdas.6501    if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)6502      CurLSI->addPotentialThisCapture(CallLoc);6503  }6504}6505 6506// Once a call is fully resolved, warn for unqualified calls to specific6507// C++ standard functions, like move and forward.6508static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,6509                                                    const CallExpr *Call) {6510  // We are only checking unary move and forward so exit early here.6511  if (Call->getNumArgs() != 1)6512    return;6513 6514  const Expr *E = Call->getCallee()->IgnoreParenImpCasts();6515  if (!E || isa<UnresolvedLookupExpr>(E))6516    return;6517  const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);6518  if (!DRE || !DRE->getLocation().isValid())6519    return;6520 6521  if (DRE->getQualifier())6522    return;6523 6524  const FunctionDecl *FD = Call->getDirectCallee();6525  if (!FD)6526    return;6527 6528  // Only warn for some functions deemed more frequent or problematic.6529  unsigned BuiltinID = FD->getBuiltinID();6530  if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)6531    return;6532 6533  S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)6534      << FD->getQualifiedNameAsString()6535      << FixItHint::CreateInsertion(DRE->getLocation(), "std::");6536}6537 6538ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,6539                               MultiExprArg ArgExprs, SourceLocation RParenLoc,6540                               Expr *ExecConfig) {6541  ExprResult Call =6542      BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,6543                    /*IsExecConfig=*/false, /*AllowRecovery=*/true);6544  if (Call.isInvalid())6545    return Call;6546 6547  // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier6548  // language modes.6549  if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);6550      ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {6551    DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)6552        << ULE->getName();6553  }6554 6555  if (LangOpts.OpenMP)6556    Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,6557                                    ExecConfig);6558  if (LangOpts.CPlusPlus) {6559    if (const auto *CE = dyn_cast<CallExpr>(Call.get()))6560      DiagnosedUnqualifiedCallsToStdFunctions(*this, CE);6561 6562    // If we previously found that the id-expression of this call refers to a6563    // consteval function but the call is dependent, we should not treat is an6564    // an invalid immediate call.6565    if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());6566        DRE && Call.get()->isValueDependent()) {6567      currentEvaluationContext().ReferenceToConsteval.erase(DRE);6568    }6569  }6570  return Call;6571}6572 6573// Any type that could be used to form a callable expression6574static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {6575  QualType T = E->getType();6576  if (T->isDependentType())6577    return true;6578 6579  if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||6580      T == Context.BuiltinFnTy || T == Context.OverloadTy ||6581      T->isFunctionType() || T->isFunctionReferenceType() ||6582      T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||6583      T->isBlockPointerType() || T->isRecordType())6584    return true;6585 6586  return isa<CallExpr, DeclRefExpr, MemberExpr, CXXPseudoDestructorExpr,6587             OverloadExpr, UnresolvedMemberExpr, UnaryOperator>(E);6588}6589 6590ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,6591                               MultiExprArg ArgExprs, SourceLocation RParenLoc,6592                               Expr *ExecConfig, bool IsExecConfig,6593                               bool AllowRecovery) {6594  // Since this might be a postfix expression, get rid of ParenListExprs.6595  ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);6596  if (Result.isInvalid()) return ExprError();6597  Fn = Result.get();6598 6599  if (CheckArgsForPlaceholders(ArgExprs))6600    return ExprError();6601 6602  // The result of __builtin_counted_by_ref cannot be used as a function6603  // argument. It allows leaking and modification of bounds safety information.6604  for (const Expr *Arg : ArgExprs)6605    if (CheckInvalidBuiltinCountedByRef(Arg,6606                                        BuiltinCountedByRefKind::FunctionArg))6607      return ExprError();6608 6609  if (getLangOpts().CPlusPlus) {6610    // If this is a pseudo-destructor expression, build the call immediately.6611    if (isa<CXXPseudoDestructorExpr>(Fn)) {6612      if (!ArgExprs.empty()) {6613        // Pseudo-destructor calls should not have any arguments.6614        Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)6615            << FixItHint::CreateRemoval(6616                   SourceRange(ArgExprs.front()->getBeginLoc(),6617                               ArgExprs.back()->getEndLoc()));6618      }6619 6620      return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,6621                              VK_PRValue, RParenLoc, CurFPFeatureOverrides());6622    }6623    if (Fn->getType() == Context.PseudoObjectTy) {6624      ExprResult result = CheckPlaceholderExpr(Fn);6625      if (result.isInvalid()) return ExprError();6626      Fn = result.get();6627    }6628 6629    // Determine whether this is a dependent call inside a C++ template,6630    // in which case we won't do any semantic analysis now.6631    if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {6632      if (ExecConfig) {6633        return CUDAKernelCallExpr::Create(Context, Fn,6634                                          cast<CallExpr>(ExecConfig), ArgExprs,6635                                          Context.DependentTy, VK_PRValue,6636                                          RParenLoc, CurFPFeatureOverrides());6637      } else {6638 6639        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(6640            *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),6641            Fn->getBeginLoc());6642 6643        // If the type of the function itself is not dependent6644        // check that it is a reasonable as a function, as type deduction6645        // later assume the CallExpr has a sensible TYPE.6646        if (!MayBeFunctionType(Context, Fn))6647          return ExprError(6648              Diag(LParenLoc, diag::err_typecheck_call_not_function)6649              << Fn->getType() << Fn->getSourceRange());6650 6651        return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,6652                                VK_PRValue, RParenLoc, CurFPFeatureOverrides());6653      }6654    }6655 6656    // Determine whether this is a call to an object (C++ [over.call.object]).6657    if (Fn->getType()->isRecordType())6658      return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,6659                                          RParenLoc);6660 6661    if (Fn->getType() == Context.UnknownAnyTy) {6662      ExprResult result = rebuildUnknownAnyFunction(*this, Fn);6663      if (result.isInvalid()) return ExprError();6664      Fn = result.get();6665    }6666 6667    if (Fn->getType() == Context.BoundMemberTy) {6668      return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,6669                                       RParenLoc, ExecConfig, IsExecConfig,6670                                       AllowRecovery);6671    }6672  }6673 6674  // Check for overloaded calls.  This can happen even in C due to extensions.6675  if (Fn->getType() == Context.OverloadTy) {6676    OverloadExpr::FindResult find = OverloadExpr::find(Fn);6677 6678    // We aren't supposed to apply this logic if there's an '&' involved.6679    if (!find.HasFormOfMemberPointer || find.IsAddressOfOperandWithParen) {6680      if (Expr::hasAnyTypeDependentArguments(ArgExprs))6681        return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,6682                                VK_PRValue, RParenLoc, CurFPFeatureOverrides());6683      OverloadExpr *ovl = find.Expression;6684      if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))6685        return BuildOverloadedCallExpr(6686            Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,6687            /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);6688      return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,6689                                       RParenLoc, ExecConfig, IsExecConfig,6690                                       AllowRecovery);6691    }6692  }6693 6694  // If we're directly calling a function, get the appropriate declaration.6695  if (Fn->getType() == Context.UnknownAnyTy) {6696    ExprResult result = rebuildUnknownAnyFunction(*this, Fn);6697    if (result.isInvalid()) return ExprError();6698    Fn = result.get();6699  }6700 6701  Expr *NakedFn = Fn->IgnoreParens();6702 6703  bool CallingNDeclIndirectly = false;6704  NamedDecl *NDecl = nullptr;6705  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {6706    if (UnOp->getOpcode() == UO_AddrOf) {6707      CallingNDeclIndirectly = true;6708      NakedFn = UnOp->getSubExpr()->IgnoreParens();6709    }6710  }6711 6712  if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {6713    NDecl = DRE->getDecl();6714 6715    FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);6716    if (FDecl && FDecl->getBuiltinID()) {6717      // Rewrite the function decl for this builtin by replacing parameters6718      // with no explicit address space with the address space of the arguments6719      // in ArgExprs.6720      if ((FDecl =6721               rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {6722        NDecl = FDecl;6723        Fn = DeclRefExpr::Create(6724            Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,6725            SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,6726            nullptr, DRE->isNonOdrUse());6727      }6728    }6729  } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))6730    NDecl = ME->getMemberDecl();6731 6732  if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {6733    if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(6734                                      FD, /*Complain=*/true, Fn->getBeginLoc()))6735      return ExprError();6736 6737    checkDirectCallValidity(*this, Fn, FD, ArgExprs);6738 6739    // If this expression is a call to a builtin function in HIP compilation,6740    // allow a pointer-type argument to default address space to be passed as a6741    // pointer-type parameter to a non-default address space. If Arg is declared6742    // in the default address space and Param is declared in a non-default6743    // address space, perform an implicit address space cast to the parameter6744    // type.6745    if (getLangOpts().HIP && FD && FD->getBuiltinID()) {6746      for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();6747          ++Idx) {6748        ParmVarDecl *Param = FD->getParamDecl(Idx);6749        if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||6750            !ArgExprs[Idx]->getType()->isPointerType())6751          continue;6752 6753        auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();6754        auto ArgTy = ArgExprs[Idx]->getType();6755        auto ArgPtTy = ArgTy->getPointeeType();6756        auto ArgAS = ArgPtTy.getAddressSpace();6757 6758        // Add address space cast if target address spaces are different6759        bool NeedImplicitASC =6760          ParamAS != LangAS::Default &&       // Pointer params in generic AS don't need special handling.6761          ( ArgAS == LangAS::Default  ||      // We do allow implicit conversion from generic AS6762                                              // or from specific AS which has target AS matching that of Param.6763          getASTContext().getTargetAddressSpace(ArgAS) == getASTContext().getTargetAddressSpace(ParamAS));6764        if (!NeedImplicitASC)6765          continue;6766 6767        // First, ensure that the Arg is an RValue.6768        if (ArgExprs[Idx]->isGLValue()) {6769          ArgExprs[Idx] = ImplicitCastExpr::Create(6770              Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],6771              nullptr, VK_PRValue, FPOptionsOverride());6772        }6773 6774        // Construct a new arg type with address space of Param6775        Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();6776        ArgPtQuals.setAddressSpace(ParamAS);6777        auto NewArgPtTy =6778            Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);6779        auto NewArgTy =6780            Context.getQualifiedType(Context.getPointerType(NewArgPtTy),6781                                     ArgTy.getQualifiers());6782 6783        // Finally perform an implicit address space cast6784        ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,6785                                          CK_AddressSpaceConversion)6786                            .get();6787      }6788    }6789  }6790 6791  if (Context.isDependenceAllowed() &&6792      (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {6793    assert(!getLangOpts().CPlusPlus);6794    assert((Fn->containsErrors() ||6795            llvm::any_of(ArgExprs,6796                         [](clang::Expr *E) { return E->containsErrors(); })) &&6797           "should only occur in error-recovery path.");6798    return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,6799                            VK_PRValue, RParenLoc, CurFPFeatureOverrides());6800  }6801  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,6802                               ExecConfig, IsExecConfig);6803}6804 6805Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,6806                                 MultiExprArg CallArgs) {6807  std::string Name = Context.BuiltinInfo.getName(Id);6808  LookupResult R(*this, &Context.Idents.get(Name), Loc,6809                 Sema::LookupOrdinaryName);6810  LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);6811 6812  auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();6813  assert(BuiltInDecl && "failed to find builtin declaration");6814 6815  ExprResult DeclRef =6816      BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);6817  assert(DeclRef.isUsable() && "Builtin reference cannot fail");6818 6819  ExprResult Call =6820      BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);6821 6822  assert(!Call.isInvalid() && "Call to builtin cannot fail!");6823  return Call.get();6824}6825 6826ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,6827                                 SourceLocation BuiltinLoc,6828                                 SourceLocation RParenLoc) {6829  QualType DstTy = GetTypeFromParser(ParsedDestTy);6830  return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);6831}6832 6833ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,6834                                 SourceLocation BuiltinLoc,6835                                 SourceLocation RParenLoc) {6836  ExprValueKind VK = VK_PRValue;6837  ExprObjectKind OK = OK_Ordinary;6838  QualType SrcTy = E->getType();6839  if (!SrcTy->isDependentType() &&6840      Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))6841    return ExprError(6842        Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)6843        << DestTy << SrcTy << E->getSourceRange());6844  return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);6845}6846 6847ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,6848                                        SourceLocation BuiltinLoc,6849                                        SourceLocation RParenLoc) {6850  TypeSourceInfo *TInfo;6851  GetTypeFromParser(ParsedDestTy, &TInfo);6852  return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);6853}6854 6855ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,6856                                       SourceLocation LParenLoc,6857                                       ArrayRef<Expr *> Args,6858                                       SourceLocation RParenLoc, Expr *Config,6859                                       bool IsExecConfig, ADLCallKind UsesADL) {6860  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);6861  unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);6862 6863  // Functions with 'interrupt' attribute cannot be called directly.6864  if (FDecl) {6865    if (FDecl->hasAttr<AnyX86InterruptAttr>()) {6866      Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);6867      return ExprError();6868    }6869    if (FDecl->hasAttr<ARMInterruptAttr>()) {6870      Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);6871      return ExprError();6872    }6873  }6874 6875  // X86 interrupt handlers may only call routines with attribute6876  // no_caller_saved_registers since there is no efficient way to6877  // save and restore the non-GPR state.6878  if (auto *Caller = getCurFunctionDecl()) {6879    if (Caller->hasAttr<AnyX86InterruptAttr>() ||6880        Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {6881      const TargetInfo &TI = Context.getTargetInfo();6882      bool HasNonGPRRegisters =6883          TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");6884      if (HasNonGPRRegisters &&6885          (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {6886        Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)6887            << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);6888        if (FDecl)6889          Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;6890      }6891    }6892  }6893 6894  // Promote the function operand.6895  // We special-case function promotion here because we only allow promoting6896  // builtin functions to function pointers in the callee of a call.6897  ExprResult Result;6898  QualType ResultTy;6899  if (BuiltinID &&6900      Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {6901    // Extract the return type from the (builtin) function pointer type.6902    // FIXME Several builtins still have setType in6903    // Sema::CheckBuiltinFunctionCall. One should review their definitions in6904    // Builtins.td to ensure they are correct before removing setType calls.6905    QualType FnPtrTy = Context.getPointerType(FDecl->getType());6906    Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();6907    ResultTy = FDecl->getCallResultType();6908  } else {6909    Result = CallExprUnaryConversions(Fn);6910    ResultTy = Context.BoolTy;6911  }6912  if (Result.isInvalid())6913    return ExprError();6914  Fn = Result.get();6915 6916  // Check for a valid function type, but only if it is not a builtin which6917  // requires custom type checking. These will be handled by6918  // CheckBuiltinFunctionCall below just after creation of the call expression.6919  const FunctionType *FuncT = nullptr;6920  if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {6921  retry:6922    if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {6923      // C99 6.5.2.2p1 - "The expression that denotes the called function shall6924      // have type pointer to function".6925      FuncT = PT->getPointeeType()->getAs<FunctionType>();6926      if (!FuncT)6927        return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)6928                         << Fn->getType() << Fn->getSourceRange());6929    } else if (const BlockPointerType *BPT =6930                   Fn->getType()->getAs<BlockPointerType>()) {6931      FuncT = BPT->getPointeeType()->castAs<FunctionType>();6932    } else {6933      // Handle calls to expressions of unknown-any type.6934      if (Fn->getType() == Context.UnknownAnyTy) {6935        ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);6936        if (rewrite.isInvalid())6937          return ExprError();6938        Fn = rewrite.get();6939        goto retry;6940      }6941 6942      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)6943                       << Fn->getType() << Fn->getSourceRange());6944    }6945  }6946 6947  // Get the number of parameters in the function prototype, if any.6948  // We will allocate space for max(Args.size(), NumParams) arguments6949  // in the call expression.6950  const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);6951  unsigned NumParams = Proto ? Proto->getNumParams() : 0;6952 6953  CallExpr *TheCall;6954  if (Config) {6955    assert(UsesADL == ADLCallKind::NotADL &&6956           "CUDAKernelCallExpr should not use ADL");6957    TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),6958                                         Args, ResultTy, VK_PRValue, RParenLoc,6959                                         CurFPFeatureOverrides(), NumParams);6960  } else {6961    TheCall =6962        CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,6963                         CurFPFeatureOverrides(), NumParams, UsesADL);6964  }6965 6966  // Bail out early if calling a builtin with custom type checking.6967  if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {6968    ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);6969    if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))6970      E = CheckForImmediateInvocation(E, FDecl);6971    return E;6972  }6973 6974  if (getLangOpts().CUDA) {6975    if (Config) {6976      // CUDA: Kernel calls must be to global functions6977      if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())6978        return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)6979            << FDecl << Fn->getSourceRange());6980 6981      // CUDA: Kernel function must have 'void' return type6982      if (!FuncT->getReturnType()->isVoidType() &&6983          !FuncT->getReturnType()->getAs<AutoType>() &&6984          !FuncT->getReturnType()->isInstantiationDependentType())6985        return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)6986            << Fn->getType() << Fn->getSourceRange());6987    } else {6988      // CUDA: Calls to global functions must be configured6989      if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())6990        return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)6991            << FDecl << Fn->getSourceRange());6992    }6993  }6994 6995  // Check for a valid return type6996  if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,6997                          FDecl))6998    return ExprError();6999 7000  // We know the result type of the call, set it.7001  TheCall->setType(FuncT->getCallResultType(Context));7002  TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));7003 7004  // WebAssembly tables can't be used as arguments.7005  if (Context.getTargetInfo().getTriple().isWasm()) {7006    for (const Expr *Arg : Args) {7007      if (Arg && Arg->getType()->isWebAssemblyTableType()) {7008        return ExprError(Diag(Arg->getExprLoc(),7009                              diag::err_wasm_table_as_function_parameter));7010      }7011    }7012  }7013 7014  if (Proto) {7015    if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,7016                                IsExecConfig))7017      return ExprError();7018  } else {7019    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");7020 7021    if (FDecl) {7022      // Check if we have too few/too many template arguments, based7023      // on our knowledge of the function definition.7024      const FunctionDecl *Def = nullptr;7025      if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {7026        Proto = Def->getType()->getAs<FunctionProtoType>();7027       if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))7028          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)7029          << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();7030      }7031 7032      // If the function we're calling isn't a function prototype, but we have7033      // a function prototype from a prior declaratiom, use that prototype.7034      if (!FDecl->hasPrototype())7035        Proto = FDecl->getType()->getAs<FunctionProtoType>();7036    }7037 7038    // If we still haven't found a prototype to use but there are arguments to7039    // the call, diagnose this as calling a function without a prototype.7040    // However, if we found a function declaration, check to see if7041    // -Wdeprecated-non-prototype was disabled where the function was declared.7042    // If so, we will silence the diagnostic here on the assumption that this7043    // interface is intentional and the user knows what they're doing. We will7044    // also silence the diagnostic if there is a function declaration but it7045    // was implicitly defined (the user already gets diagnostics about the7046    // creation of the implicit function declaration, so the additional warning7047    // is not helpful).7048    if (!Proto && !Args.empty() &&7049        (!FDecl || (!FDecl->isImplicit() &&7050                    !Diags.isIgnored(diag::warn_strict_uses_without_prototype,7051                                     FDecl->getLocation()))))7052      Diag(LParenLoc, diag::warn_strict_uses_without_prototype)7053          << (FDecl != nullptr) << FDecl;7054 7055    // Promote the arguments (C99 6.5.2.2p6).7056    for (unsigned i = 0, e = Args.size(); i != e; i++) {7057      Expr *Arg = Args[i];7058 7059      if (Proto && i < Proto->getNumParams()) {7060        InitializedEntity Entity = InitializedEntity::InitializeParameter(7061            Context, Proto->getParamType(i), Proto->isParamConsumed(i));7062        ExprResult ArgE =7063            PerformCopyInitialization(Entity, SourceLocation(), Arg);7064        if (ArgE.isInvalid())7065          return true;7066 7067        Arg = ArgE.getAs<Expr>();7068 7069      } else {7070        ExprResult ArgE = DefaultArgumentPromotion(Arg);7071 7072        if (ArgE.isInvalid())7073          return true;7074 7075        Arg = ArgE.getAs<Expr>();7076      }7077 7078      if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),7079                              diag::err_call_incomplete_argument, Arg))7080        return ExprError();7081 7082      TheCall->setArg(i, Arg);7083    }7084    TheCall->computeDependence();7085  }7086 7087  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))7088    if (Method->isImplicitObjectMemberFunction())7089      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)7090                       << Fn->getSourceRange() << 0);7091 7092  // Check for sentinels7093  if (NDecl)7094    DiagnoseSentinelCalls(NDecl, LParenLoc, Args);7095 7096  // Warn for unions passing across security boundary (CMSE).7097  if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {7098    for (unsigned i = 0, e = Args.size(); i != e; i++) {7099      if (const auto *RT =7100              dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {7101        if (RT->getDecl()->isOrContainsUnion())7102          Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)7103              << 0 << i;7104      }7105    }7106  }7107 7108  // Do special checking on direct calls to functions.7109  if (FDecl) {7110    if (CheckFunctionCall(FDecl, TheCall, Proto))7111      return ExprError();7112 7113    checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);7114 7115    if (BuiltinID)7116      return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);7117  } else if (NDecl) {7118    if (CheckPointerCall(NDecl, TheCall, Proto))7119      return ExprError();7120  } else {7121    if (CheckOtherCall(TheCall, Proto))7122      return ExprError();7123  }7124 7125  return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);7126}7127 7128ExprResult7129Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,7130                           SourceLocation RParenLoc, Expr *InitExpr) {7131  assert(Ty && "ActOnCompoundLiteral(): missing type");7132  assert(InitExpr && "ActOnCompoundLiteral(): missing expression");7133 7134  TypeSourceInfo *TInfo;7135  QualType literalType = GetTypeFromParser(Ty, &TInfo);7136  if (!TInfo)7137    TInfo = Context.getTrivialTypeSourceInfo(literalType);7138 7139  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);7140}7141 7142ExprResult7143Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,7144                               SourceLocation RParenLoc, Expr *LiteralExpr) {7145  QualType literalType = TInfo->getType();7146 7147  if (literalType->isArrayType()) {7148    if (RequireCompleteSizedType(7149            LParenLoc, Context.getBaseElementType(literalType),7150            diag::err_array_incomplete_or_sizeless_type,7151            SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))7152      return ExprError();7153    if (literalType->isVariableArrayType()) {7154      // C23 6.7.10p4: An entity of variable length array type shall not be7155      // initialized except by an empty initializer.7156      //7157      // The C extension warnings are issued from ParseBraceInitializer() and7158      // do not need to be issued here. However, we continue to issue an error7159      // in the case there are initializers or we are compiling C++. We allow7160      // use of VLAs in C++, but it's not clear we want to allow {} to zero7161      // init a VLA in C++ in all cases (such as with non-trivial constructors).7162      // FIXME: should we allow this construct in C++ when it makes sense to do7163      // so?7164      //7165      // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name7166      // shall specify an object type or an array of unknown size, but not a7167      // variable length array type. This seems odd, as it allows 'int a[size] =7168      // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard7169      // says, this is what's implemented here for C (except for the extension7170      // that permits constant foldable size arrays)7171 7172      auto diagID = LangOpts.CPlusPlus7173                        ? diag::err_variable_object_no_init7174                        : diag::err_compound_literal_with_vla_type;7175      if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,7176                                           diagID))7177        return ExprError();7178    }7179  } else if (!literalType->isDependentType() &&7180             RequireCompleteType(LParenLoc, literalType,7181               diag::err_typecheck_decl_incomplete_type,7182               SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))7183    return ExprError();7184 7185  InitializedEntity Entity7186    = InitializedEntity::InitializeCompoundLiteralInit(TInfo);7187  InitializationKind Kind7188    = InitializationKind::CreateCStyleCast(LParenLoc,7189                                           SourceRange(LParenLoc, RParenLoc),7190                                           /*InitList=*/true);7191  InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);7192  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,7193                                      &literalType);7194  if (Result.isInvalid())7195    return ExprError();7196  LiteralExpr = Result.get();7197 7198  // We treat the compound literal as being at file scope if it's not in a7199  // function or method body, or within the function's prototype scope. This7200  // means the following compound literal is not at file scope:7201  //   void func(char *para[(int [1]){ 0 }[0]);7202  const Scope *S = getCurScope();7203  bool IsFileScope = !CurContext->isFunctionOrMethod() &&7204                     !S->isInCFunctionScope() &&7205                     (!S || !S->isFunctionPrototypeScope());7206 7207  // In C, compound literals are l-values for some reason.7208  // For GCC compatibility, in C++, file-scope array compound literals with7209  // constant initializers are also l-values, and compound literals are7210  // otherwise prvalues.7211  //7212  // (GCC also treats C++ list-initialized file-scope array prvalues with7213  // constant initializers as l-values, but that's non-conforming, so we don't7214  // follow it there.)7215  //7216  // FIXME: It would be better to handle the lvalue cases as materializing and7217  // lifetime-extending a temporary object, but our materialized temporaries7218  // representation only supports lifetime extension from a variable, not "out7219  // of thin air".7220  // FIXME: For C++, we might want to instead lifetime-extend only if a pointer7221  // is bound to the result of applying array-to-pointer decay to the compound7222  // literal.7223  // FIXME: GCC supports compound literals of reference type, which should7224  // obviously have a value kind derived from the kind of reference involved.7225  ExprValueKind VK =7226      (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))7227          ? VK_PRValue7228          : VK_LValue;7229 7230  // C99 6.5.2.57231  //  "If the compound literal occurs outside the body of a function, the7232  //  initializer list shall consist of constant expressions."7233  if (IsFileScope)7234    if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))7235      for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {7236        Expr *Init = ILE->getInit(i);7237        if (!Init->isTypeDependent() && !Init->isValueDependent() &&7238            !Init->isConstantInitializer(Context, /*IsForRef=*/false)) {7239          Diag(Init->getExprLoc(), diag::err_init_element_not_constant)7240              << Init->getSourceBitField();7241          return ExprError();7242        }7243 7244        ILE->setInit(i, ConstantExpr::Create(Context, Init));7245      }7246 7247  auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,7248                                              LiteralExpr, IsFileScope);7249  if (IsFileScope) {7250    if (!LiteralExpr->isTypeDependent() &&7251        !LiteralExpr->isValueDependent() &&7252        !literalType->isDependentType()) // C99 6.5.2.5p37253      if (CheckForConstantInitializer(LiteralExpr))7254        return ExprError();7255  } else if (literalType.getAddressSpace() != LangAS::opencl_private &&7256             literalType.getAddressSpace() != LangAS::Default) {7257    // Embedded-C extensions to C99 6.5.2.5:7258    //   "If the compound literal occurs inside the body of a function, the7259    //   type name shall not be qualified by an address-space qualifier."7260    Diag(LParenLoc, diag::err_compound_literal_with_address_space)7261      << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());7262    return ExprError();7263  }7264 7265  if (!IsFileScope && !getLangOpts().CPlusPlus) {7266    // Compound literals that have automatic storage duration are destroyed at7267    // the end of the scope in C; in C++, they're just temporaries.7268 7269    // Emit diagnostics if it is or contains a C union type that is non-trivial7270    // to destruct.7271    if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())7272      checkNonTrivialCUnion(E->getType(), E->getExprLoc(),7273                            NonTrivialCUnionContext::CompoundLiteral,7274                            NTCUK_Destruct);7275 7276    // Diagnose jumps that enter or exit the lifetime of the compound literal.7277    if (literalType.isDestructedType()) {7278      Cleanup.setExprNeedsCleanups(true);7279      ExprCleanupObjects.push_back(E);7280      getCurFunction()->setHasBranchProtectedScope();7281    }7282  }7283 7284  if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||7285      E->getType().hasNonTrivialToPrimitiveCopyCUnion())7286    checkNonTrivialCUnionInInitializer(E->getInitializer(),7287                                       E->getInitializer()->getExprLoc());7288 7289  return MaybeBindToTemporary(E);7290}7291 7292ExprResult7293Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,7294                    SourceLocation RBraceLoc) {7295  // Only produce each kind of designated initialization diagnostic once.7296  SourceLocation FirstDesignator;7297  bool DiagnosedArrayDesignator = false;7298  bool DiagnosedNestedDesignator = false;7299  bool DiagnosedMixedDesignator = false;7300 7301  // Check that any designated initializers are syntactically valid in the7302  // current language mode.7303  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {7304    if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {7305      if (FirstDesignator.isInvalid())7306        FirstDesignator = DIE->getBeginLoc();7307 7308      if (!getLangOpts().CPlusPlus)7309        break;7310 7311      if (!DiagnosedNestedDesignator && DIE->size() > 1) {7312        DiagnosedNestedDesignator = true;7313        Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)7314          << DIE->getDesignatorsSourceRange();7315      }7316 7317      for (auto &Desig : DIE->designators()) {7318        if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {7319          DiagnosedArrayDesignator = true;7320          Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)7321            << Desig.getSourceRange();7322        }7323      }7324 7325      if (!DiagnosedMixedDesignator &&7326          !isa<DesignatedInitExpr>(InitArgList[0])) {7327        DiagnosedMixedDesignator = true;7328        Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)7329          << DIE->getSourceRange();7330        Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)7331          << InitArgList[0]->getSourceRange();7332      }7333    } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&7334               isa<DesignatedInitExpr>(InitArgList[0])) {7335      DiagnosedMixedDesignator = true;7336      auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);7337      Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)7338        << DIE->getSourceRange();7339      Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)7340        << InitArgList[I]->getSourceRange();7341    }7342  }7343 7344  if (FirstDesignator.isValid()) {7345    // Only diagnose designated initiaization as a C++20 extension if we didn't7346    // already diagnose use of (non-C++20) C99 designator syntax.7347    if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&7348        !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {7349      Diag(FirstDesignator, getLangOpts().CPlusPlus207350                                ? diag::warn_cxx17_compat_designated_init7351                                : diag::ext_cxx_designated_init);7352    } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {7353      Diag(FirstDesignator, diag::ext_designated_init);7354    }7355  }7356 7357  return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);7358}7359 7360ExprResult7361Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,7362                    SourceLocation RBraceLoc) {7363  // Semantic analysis for initializers is done by ActOnDeclarator() and7364  // CheckInitializer() - it requires knowledge of the object being initialized.7365 7366  // Immediately handle non-overload placeholders.  Overloads can be7367  // resolved contextually, but everything else here can't.7368  for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {7369    if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {7370      ExprResult result = CheckPlaceholderExpr(InitArgList[I]);7371 7372      // Ignore failures; dropping the entire initializer list because7373      // of one failure would be terrible for indexing/etc.7374      if (result.isInvalid()) continue;7375 7376      InitArgList[I] = result.get();7377    }7378  }7379 7380  InitListExpr *E =7381      new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);7382  E->setType(Context.VoidTy); // FIXME: just a place holder for now.7383  return E;7384}7385 7386void Sema::maybeExtendBlockObject(ExprResult &E) {7387  assert(E.get()->getType()->isBlockPointerType());7388  assert(E.get()->isPRValue());7389 7390  // Only do this in an r-value context.7391  if (!getLangOpts().ObjCAutoRefCount) return;7392 7393  E = ImplicitCastExpr::Create(7394      Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),7395      /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());7396  Cleanup.setExprNeedsCleanups(true);7397}7398 7399CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {7400  // Both Src and Dest are scalar types, i.e. arithmetic or pointer.7401  // Also, callers should have filtered out the invalid cases with7402  // pointers.  Everything else should be possible.7403 7404  QualType SrcTy = Src.get()->getType();7405  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))7406    return CK_NoOp;7407 7408  switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {7409  case Type::STK_MemberPointer:7410    llvm_unreachable("member pointer type in C");7411 7412  case Type::STK_CPointer:7413  case Type::STK_BlockPointer:7414  case Type::STK_ObjCObjectPointer:7415    switch (DestTy->getScalarTypeKind()) {7416    case Type::STK_CPointer: {7417      LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();7418      LangAS DestAS = DestTy->getPointeeType().getAddressSpace();7419      if (SrcAS != DestAS)7420        return CK_AddressSpaceConversion;7421      if (Context.hasCvrSimilarType(SrcTy, DestTy))7422        return CK_NoOp;7423      return CK_BitCast;7424    }7425    case Type::STK_BlockPointer:7426      return (SrcKind == Type::STK_BlockPointer7427                ? CK_BitCast : CK_AnyPointerToBlockPointerCast);7428    case Type::STK_ObjCObjectPointer:7429      if (SrcKind == Type::STK_ObjCObjectPointer)7430        return CK_BitCast;7431      if (SrcKind == Type::STK_CPointer)7432        return CK_CPointerToObjCPointerCast;7433      maybeExtendBlockObject(Src);7434      return CK_BlockPointerToObjCPointerCast;7435    case Type::STK_Bool:7436      return CK_PointerToBoolean;7437    case Type::STK_Integral:7438      return CK_PointerToIntegral;7439    case Type::STK_Floating:7440    case Type::STK_FloatingComplex:7441    case Type::STK_IntegralComplex:7442    case Type::STK_MemberPointer:7443    case Type::STK_FixedPoint:7444      llvm_unreachable("illegal cast from pointer");7445    }7446    llvm_unreachable("Should have returned before this");7447 7448  case Type::STK_FixedPoint:7449    switch (DestTy->getScalarTypeKind()) {7450    case Type::STK_FixedPoint:7451      return CK_FixedPointCast;7452    case Type::STK_Bool:7453      return CK_FixedPointToBoolean;7454    case Type::STK_Integral:7455      return CK_FixedPointToIntegral;7456    case Type::STK_Floating:7457      return CK_FixedPointToFloating;7458    case Type::STK_IntegralComplex:7459    case Type::STK_FloatingComplex:7460      Diag(Src.get()->getExprLoc(),7461           diag::err_unimplemented_conversion_with_fixed_point_type)7462          << DestTy;7463      return CK_IntegralCast;7464    case Type::STK_CPointer:7465    case Type::STK_ObjCObjectPointer:7466    case Type::STK_BlockPointer:7467    case Type::STK_MemberPointer:7468      llvm_unreachable("illegal cast to pointer type");7469    }7470    llvm_unreachable("Should have returned before this");7471 7472  case Type::STK_Bool: // casting from bool is like casting from an integer7473  case Type::STK_Integral:7474    switch (DestTy->getScalarTypeKind()) {7475    case Type::STK_CPointer:7476    case Type::STK_ObjCObjectPointer:7477    case Type::STK_BlockPointer:7478      if (Src.get()->isNullPointerConstant(Context,7479                                           Expr::NPC_ValueDependentIsNull))7480        return CK_NullToPointer;7481      return CK_IntegralToPointer;7482    case Type::STK_Bool:7483      return CK_IntegralToBoolean;7484    case Type::STK_Integral:7485      return CK_IntegralCast;7486    case Type::STK_Floating:7487      return CK_IntegralToFloating;7488    case Type::STK_IntegralComplex:7489      Src = ImpCastExprToType(Src.get(),7490                      DestTy->castAs<ComplexType>()->getElementType(),7491                      CK_IntegralCast);7492      return CK_IntegralRealToComplex;7493    case Type::STK_FloatingComplex:7494      Src = ImpCastExprToType(Src.get(),7495                      DestTy->castAs<ComplexType>()->getElementType(),7496                      CK_IntegralToFloating);7497      return CK_FloatingRealToComplex;7498    case Type::STK_MemberPointer:7499      llvm_unreachable("member pointer type in C");7500    case Type::STK_FixedPoint:7501      return CK_IntegralToFixedPoint;7502    }7503    llvm_unreachable("Should have returned before this");7504 7505  case Type::STK_Floating:7506    switch (DestTy->getScalarTypeKind()) {7507    case Type::STK_Floating:7508      return CK_FloatingCast;7509    case Type::STK_Bool:7510      return CK_FloatingToBoolean;7511    case Type::STK_Integral:7512      return CK_FloatingToIntegral;7513    case Type::STK_FloatingComplex:7514      Src = ImpCastExprToType(Src.get(),7515                              DestTy->castAs<ComplexType>()->getElementType(),7516                              CK_FloatingCast);7517      return CK_FloatingRealToComplex;7518    case Type::STK_IntegralComplex:7519      Src = ImpCastExprToType(Src.get(),7520                              DestTy->castAs<ComplexType>()->getElementType(),7521                              CK_FloatingToIntegral);7522      return CK_IntegralRealToComplex;7523    case Type::STK_CPointer:7524    case Type::STK_ObjCObjectPointer:7525    case Type::STK_BlockPointer:7526      llvm_unreachable("valid float->pointer cast?");7527    case Type::STK_MemberPointer:7528      llvm_unreachable("member pointer type in C");7529    case Type::STK_FixedPoint:7530      return CK_FloatingToFixedPoint;7531    }7532    llvm_unreachable("Should have returned before this");7533 7534  case Type::STK_FloatingComplex:7535    switch (DestTy->getScalarTypeKind()) {7536    case Type::STK_FloatingComplex:7537      return CK_FloatingComplexCast;7538    case Type::STK_IntegralComplex:7539      return CK_FloatingComplexToIntegralComplex;7540    case Type::STK_Floating: {7541      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();7542      if (Context.hasSameType(ET, DestTy))7543        return CK_FloatingComplexToReal;7544      Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);7545      return CK_FloatingCast;7546    }7547    case Type::STK_Bool:7548      return CK_FloatingComplexToBoolean;7549    case Type::STK_Integral:7550      Src = ImpCastExprToType(Src.get(),7551                              SrcTy->castAs<ComplexType>()->getElementType(),7552                              CK_FloatingComplexToReal);7553      return CK_FloatingToIntegral;7554    case Type::STK_CPointer:7555    case Type::STK_ObjCObjectPointer:7556    case Type::STK_BlockPointer:7557      llvm_unreachable("valid complex float->pointer cast?");7558    case Type::STK_MemberPointer:7559      llvm_unreachable("member pointer type in C");7560    case Type::STK_FixedPoint:7561      Diag(Src.get()->getExprLoc(),7562           diag::err_unimplemented_conversion_with_fixed_point_type)7563          << SrcTy;7564      return CK_IntegralCast;7565    }7566    llvm_unreachable("Should have returned before this");7567 7568  case Type::STK_IntegralComplex:7569    switch (DestTy->getScalarTypeKind()) {7570    case Type::STK_FloatingComplex:7571      return CK_IntegralComplexToFloatingComplex;7572    case Type::STK_IntegralComplex:7573      return CK_IntegralComplexCast;7574    case Type::STK_Integral: {7575      QualType ET = SrcTy->castAs<ComplexType>()->getElementType();7576      if (Context.hasSameType(ET, DestTy))7577        return CK_IntegralComplexToReal;7578      Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);7579      return CK_IntegralCast;7580    }7581    case Type::STK_Bool:7582      return CK_IntegralComplexToBoolean;7583    case Type::STK_Floating:7584      Src = ImpCastExprToType(Src.get(),7585                              SrcTy->castAs<ComplexType>()->getElementType(),7586                              CK_IntegralComplexToReal);7587      return CK_IntegralToFloating;7588    case Type::STK_CPointer:7589    case Type::STK_ObjCObjectPointer:7590    case Type::STK_BlockPointer:7591      llvm_unreachable("valid complex int->pointer cast?");7592    case Type::STK_MemberPointer:7593      llvm_unreachable("member pointer type in C");7594    case Type::STK_FixedPoint:7595      Diag(Src.get()->getExprLoc(),7596           diag::err_unimplemented_conversion_with_fixed_point_type)7597          << SrcTy;7598      return CK_IntegralCast;7599    }7600    llvm_unreachable("Should have returned before this");7601  }7602 7603  llvm_unreachable("Unhandled scalar cast");7604}7605 7606static bool breakDownVectorType(QualType type, uint64_t &len,7607                                QualType &eltType) {7608  // Vectors are simple.7609  if (const VectorType *vecType = type->getAs<VectorType>()) {7610    len = vecType->getNumElements();7611    eltType = vecType->getElementType();7612    assert(eltType->isScalarType() || eltType->isMFloat8Type());7613    return true;7614  }7615 7616  // We allow lax conversion to and from non-vector types, but only if7617  // they're real types (i.e. non-complex, non-pointer scalar types).7618  if (!type->isRealType()) return false;7619 7620  len = 1;7621  eltType = type;7622  return true;7623}7624 7625bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {7626  assert(srcTy->isVectorType() || destTy->isVectorType());7627 7628  auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {7629    if (!FirstType->isSVESizelessBuiltinType())7630      return false;7631 7632    const auto *VecTy = SecondType->getAs<VectorType>();7633    return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;7634  };7635 7636  return ValidScalableConversion(srcTy, destTy) ||7637         ValidScalableConversion(destTy, srcTy);7638}7639 7640bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {7641  if (!destTy->isMatrixType() || !srcTy->isMatrixType())7642    return false;7643 7644  const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();7645  const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();7646 7647  return matSrcType->getNumRows() == matDestType->getNumRows() &&7648         matSrcType->getNumColumns() == matDestType->getNumColumns();7649}7650 7651bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {7652  assert(DestTy->isVectorType() || SrcTy->isVectorType());7653 7654  uint64_t SrcLen, DestLen;7655  QualType SrcEltTy, DestEltTy;7656  if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))7657    return false;7658  if (!breakDownVectorType(DestTy, DestLen, DestEltTy))7659    return false;7660 7661  // ASTContext::getTypeSize will return the size rounded up to a7662  // power of 2, so instead of using that, we need to use the raw7663  // element size multiplied by the element count.7664  uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);7665  uint64_t DestEltSize = Context.getTypeSize(DestEltTy);7666 7667  return (SrcLen * SrcEltSize == DestLen * DestEltSize);7668}7669 7670bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {7671  assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&7672         "expected at least one type to be a vector here");7673 7674  bool IsSrcTyAltivec =7675      SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==7676                                 VectorKind::AltiVecVector) ||7677                                (SrcTy->castAs<VectorType>()->getVectorKind() ==7678                                 VectorKind::AltiVecBool) ||7679                                (SrcTy->castAs<VectorType>()->getVectorKind() ==7680                                 VectorKind::AltiVecPixel));7681 7682  bool IsDestTyAltivec = DestTy->isVectorType() &&7683                         ((DestTy->castAs<VectorType>()->getVectorKind() ==7684                           VectorKind::AltiVecVector) ||7685                          (DestTy->castAs<VectorType>()->getVectorKind() ==7686                           VectorKind::AltiVecBool) ||7687                          (DestTy->castAs<VectorType>()->getVectorKind() ==7688                           VectorKind::AltiVecPixel));7689 7690  return (IsSrcTyAltivec || IsDestTyAltivec);7691}7692 7693bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {7694  assert(destTy->isVectorType() || srcTy->isVectorType());7695 7696  // Disallow lax conversions between scalars and ExtVectors (these7697  // conversions are allowed for other vector types because common headers7698  // depend on them).  Most scalar OP ExtVector cases are handled by the7699  // splat path anyway, which does what we want (convert, not bitcast).7700  // What this rules out for ExtVectors is crazy things like char4*float.7701  if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;7702  if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;7703 7704  return areVectorTypesSameSize(srcTy, destTy);7705}7706 7707bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {7708  assert(destTy->isVectorType() || srcTy->isVectorType());7709 7710  switch (Context.getLangOpts().getLaxVectorConversions()) {7711  case LangOptions::LaxVectorConversionKind::None:7712    return false;7713 7714  case LangOptions::LaxVectorConversionKind::Integer:7715    if (!srcTy->isIntegralOrEnumerationType()) {7716      auto *Vec = srcTy->getAs<VectorType>();7717      if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())7718        return false;7719    }7720    if (!destTy->isIntegralOrEnumerationType()) {7721      auto *Vec = destTy->getAs<VectorType>();7722      if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())7723        return false;7724    }7725    // OK, integer (vector) -> integer (vector) bitcast.7726    break;7727 7728    case LangOptions::LaxVectorConversionKind::All:7729    break;7730  }7731 7732  return areLaxCompatibleVectorTypes(srcTy, destTy);7733}7734 7735bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,7736                           CastKind &Kind) {7737  if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {7738    if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {7739      return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)7740             << DestTy << SrcTy << R;7741    }7742  } else if (SrcTy->isMatrixType()) {7743    return Diag(R.getBegin(),7744                diag::err_invalid_conversion_between_matrix_and_type)7745           << SrcTy << DestTy << R;7746  } else if (DestTy->isMatrixType()) {7747    return Diag(R.getBegin(),7748                diag::err_invalid_conversion_between_matrix_and_type)7749           << DestTy << SrcTy << R;7750  }7751 7752  Kind = CK_MatrixCast;7753  return false;7754}7755 7756bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,7757                           CastKind &Kind) {7758  assert(VectorTy->isVectorType() && "Not a vector type!");7759 7760  if (Ty->isVectorType() || Ty->isIntegralType(Context)) {7761    if (!areLaxCompatibleVectorTypes(Ty, VectorTy))7762      return Diag(R.getBegin(),7763                  Ty->isVectorType() ?7764                  diag::err_invalid_conversion_between_vectors :7765                  diag::err_invalid_conversion_between_vector_and_integer)7766        << VectorTy << Ty << R;7767  } else7768    return Diag(R.getBegin(),7769                diag::err_invalid_conversion_between_vector_and_scalar)7770      << VectorTy << Ty << R;7771 7772  Kind = CK_BitCast;7773  return false;7774}7775 7776ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {7777  QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();7778 7779  if (DestElemTy == SplattedExpr->getType())7780    return SplattedExpr;7781 7782  assert(DestElemTy->isFloatingType() ||7783         DestElemTy->isIntegralOrEnumerationType());7784 7785  CastKind CK;7786  if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {7787    // OpenCL requires that we convert `true` boolean expressions to -1, but7788    // only when splatting vectors.7789    if (DestElemTy->isFloatingType()) {7790      // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast7791      // in two steps: boolean to signed integral, then to floating.7792      ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,7793                                                 CK_BooleanToSignedIntegral);7794      SplattedExpr = CastExprRes.get();7795      CK = CK_IntegralToFloating;7796    } else {7797      CK = CK_BooleanToSignedIntegral;7798    }7799  } else {7800    ExprResult CastExprRes = SplattedExpr;7801    CK = PrepareScalarCast(CastExprRes, DestElemTy);7802    if (CastExprRes.isInvalid())7803      return ExprError();7804    SplattedExpr = CastExprRes.get();7805  }7806  return ImpCastExprToType(SplattedExpr, DestElemTy, CK);7807}7808 7809ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,7810                                    Expr *CastExpr, CastKind &Kind) {7811  assert(DestTy->isExtVectorType() && "Not an extended vector type!");7812 7813  QualType SrcTy = CastExpr->getType();7814 7815  // If SrcTy is a VectorType, the total size must match to explicitly cast to7816  // an ExtVectorType.7817  // In OpenCL, casts between vectors of different types are not allowed.7818  // (See OpenCL 6.2).7819  if (SrcTy->isVectorType()) {7820    if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||7821        (getLangOpts().OpenCL &&7822         !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {7823      Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)7824        << DestTy << SrcTy << R;7825      return ExprError();7826    }7827    Kind = CK_BitCast;7828    return CastExpr;7829  }7830 7831  // All non-pointer scalars can be cast to ExtVector type.  The appropriate7832  // conversion will take place first from scalar to elt type, and then7833  // splat from elt type to vector.7834  if (SrcTy->isPointerType())7835    return Diag(R.getBegin(),7836                diag::err_invalid_conversion_between_vector_and_scalar)7837      << DestTy << SrcTy << R;7838 7839  Kind = CK_VectorSplat;7840  return prepareVectorSplat(DestTy, CastExpr);7841}7842 7843/// Check that a call to alloc_size function specifies sufficient space for the7844/// destination type.7845static void CheckSufficientAllocSize(Sema &S, QualType DestType,7846                                     const Expr *E) {7847  QualType SourceType = E->getType();7848  if (!DestType->isPointerType() || !SourceType->isPointerType() ||7849      DestType == SourceType)7850    return;7851 7852  const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());7853  if (!CE)7854    return;7855 7856  // Find the total size allocated by the function call.7857  if (!CE->getCalleeAllocSizeAttr())7858    return;7859  std::optional<llvm::APInt> AllocSize =7860      CE->evaluateBytesReturnedByAllocSizeCall(S.Context);7861  // Allocations of size zero are permitted as a special case. They are usually7862  // done intentionally.7863  if (!AllocSize || AllocSize->isZero())7864    return;7865  auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());7866 7867  QualType TargetType = DestType->getPointeeType();7868  // Find the destination size. As a special case function types have size of7869  // one byte to match the sizeof operator behavior.7870  auto LhsSize = TargetType->isFunctionType()7871                     ? CharUnits::One()7872                     : S.Context.getTypeSizeInCharsIfKnown(TargetType);7873  if (LhsSize && Size < LhsSize)7874    S.Diag(E->getExprLoc(), diag::warn_alloc_size)7875        << Size.getQuantity() << TargetType << LhsSize->getQuantity();7876}7877 7878ExprResult7879Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,7880                    Declarator &D, ParsedType &Ty,7881                    SourceLocation RParenLoc, Expr *CastExpr) {7882  assert(!D.isInvalidType() && (CastExpr != nullptr) &&7883         "ActOnCastExpr(): missing type or expr");7884 7885  TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());7886  if (D.isInvalidType())7887    return ExprError();7888 7889  if (getLangOpts().CPlusPlus) {7890    // Check that there are no default arguments (C++ only).7891    CheckExtraCXXDefaultArguments(D);7892  }7893 7894  checkUnusedDeclAttributes(D);7895 7896  QualType castType = castTInfo->getType();7897  Ty = CreateParsedType(castType, castTInfo);7898 7899  bool isVectorLiteral = false;7900 7901  // Check for an altivec or OpenCL literal,7902  // i.e. all the elements are integer constants.7903  ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);7904  ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);7905  if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)7906       && castType->isVectorType() && (PE || PLE)) {7907    if (PLE && PLE->getNumExprs() == 0) {7908      Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);7909      return ExprError();7910    }7911    if (PE || PLE->getNumExprs() == 1) {7912      Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));7913      if (!E->isTypeDependent() && !E->getType()->isVectorType())7914        isVectorLiteral = true;7915    }7916    else7917      isVectorLiteral = true;7918  }7919 7920  // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'7921  // then handle it as such.7922  if (isVectorLiteral)7923    return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);7924 7925  // If the Expr being casted is a ParenListExpr, handle it specially.7926  // This is not an AltiVec-style cast, so turn the ParenListExpr into a7927  // sequence of BinOp comma operators.7928  if (isa<ParenListExpr>(CastExpr)) {7929    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);7930    if (Result.isInvalid()) return ExprError();7931    CastExpr = Result.get();7932  }7933 7934  if (getLangOpts().CPlusPlus && !castType->isVoidType())7935    Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();7936 7937  ObjC().CheckTollFreeBridgeCast(castType, CastExpr);7938 7939  ObjC().CheckObjCBridgeRelatedCast(castType, CastExpr);7940 7941  DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);7942 7943  CheckSufficientAllocSize(*this, castType, CastExpr);7944 7945  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);7946}7947 7948ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,7949                                    SourceLocation RParenLoc, Expr *E,7950                                    TypeSourceInfo *TInfo) {7951  assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&7952         "Expected paren or paren list expression");7953 7954  Expr **exprs;7955  unsigned numExprs;7956  Expr *subExpr;7957  SourceLocation LiteralLParenLoc, LiteralRParenLoc;7958  if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {7959    LiteralLParenLoc = PE->getLParenLoc();7960    LiteralRParenLoc = PE->getRParenLoc();7961    exprs = PE->getExprs();7962    numExprs = PE->getNumExprs();7963  } else { // isa<ParenExpr> by assertion at function entrance7964    LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();7965    LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();7966    subExpr = cast<ParenExpr>(E)->getSubExpr();7967    exprs = &subExpr;7968    numExprs = 1;7969  }7970 7971  QualType Ty = TInfo->getType();7972  assert(Ty->isVectorType() && "Expected vector type");7973 7974  SmallVector<Expr *, 8> initExprs;7975  const VectorType *VTy = Ty->castAs<VectorType>();7976  unsigned numElems = VTy->getNumElements();7977 7978  // '(...)' form of vector initialization in AltiVec: the number of7979  // initializers must be one or must match the size of the vector.7980  // If a single value is specified in the initializer then it will be7981  // replicated to all the components of the vector7982  if (CheckAltivecInitFromScalar(E->getSourceRange(), Ty,7983                                 VTy->getElementType()))7984    return ExprError();7985  if (ShouldSplatAltivecScalarInCast(VTy)) {7986    // The number of initializers must be one or must match the size of the7987    // vector. If a single value is specified in the initializer then it will7988    // be replicated to all the components of the vector7989    if (numExprs == 1) {7990      QualType ElemTy = VTy->getElementType();7991      ExprResult Literal = DefaultLvalueConversion(exprs[0]);7992      if (Literal.isInvalid())7993        return ExprError();7994      Literal = ImpCastExprToType(Literal.get(), ElemTy,7995                                  PrepareScalarCast(Literal, ElemTy));7996      return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());7997    }7998    else if (numExprs < numElems) {7999      Diag(E->getExprLoc(),8000           diag::err_incorrect_number_of_vector_initializers);8001      return ExprError();8002    }8003    else8004      initExprs.append(exprs, exprs + numExprs);8005  }8006  else {8007    // For OpenCL, when the number of initializers is a single value,8008    // it will be replicated to all components of the vector.8009    if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&8010        numExprs == 1) {8011      QualType ElemTy = VTy->getElementType();8012      ExprResult Literal = DefaultLvalueConversion(exprs[0]);8013      if (Literal.isInvalid())8014        return ExprError();8015      Literal = ImpCastExprToType(Literal.get(), ElemTy,8016                                  PrepareScalarCast(Literal, ElemTy));8017      return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());8018    }8019 8020    initExprs.append(exprs, exprs + numExprs);8021  }8022  // FIXME: This means that pretty-printing the final AST will produce curly8023  // braces instead of the original commas.8024  InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,8025                                                   initExprs, LiteralRParenLoc);8026  initE->setType(Ty);8027  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);8028}8029 8030ExprResult8031Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {8032  ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);8033  if (!E)8034    return OrigExpr;8035 8036  ExprResult Result(E->getExpr(0));8037 8038  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)8039    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),8040                        E->getExpr(i));8041 8042  if (Result.isInvalid()) return ExprError();8043 8044  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());8045}8046 8047ExprResult Sema::ActOnParenListExpr(SourceLocation L,8048                                    SourceLocation R,8049                                    MultiExprArg Val) {8050  return ParenListExpr::Create(Context, L, Val, R);8051}8052 8053ExprResult Sema::ActOnCXXParenListInitExpr(ArrayRef<Expr *> Args, QualType T,8054                                           unsigned NumUserSpecifiedExprs,8055                                           SourceLocation InitLoc,8056                                           SourceLocation LParenLoc,8057                                           SourceLocation RParenLoc) {8058  return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,8059                                      InitLoc, LParenLoc, RParenLoc);8060}8061 8062bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,8063                                      SourceLocation QuestionLoc) {8064  const Expr *NullExpr = LHSExpr;8065  const Expr *NonPointerExpr = RHSExpr;8066  Expr::NullPointerConstantKind NullKind =8067      NullExpr->isNullPointerConstant(Context,8068                                      Expr::NPC_ValueDependentIsNotNull);8069 8070  if (NullKind == Expr::NPCK_NotNull) {8071    NullExpr = RHSExpr;8072    NonPointerExpr = LHSExpr;8073    NullKind =8074        NullExpr->isNullPointerConstant(Context,8075                                        Expr::NPC_ValueDependentIsNotNull);8076  }8077 8078  if (NullKind == Expr::NPCK_NotNull)8079    return false;8080 8081  if (NullKind == Expr::NPCK_ZeroExpression)8082    return false;8083 8084  if (NullKind == Expr::NPCK_ZeroLiteral) {8085    // In this case, check to make sure that we got here from a "NULL"8086    // string in the source code.8087    NullExpr = NullExpr->IgnoreParenImpCasts();8088    SourceLocation loc = NullExpr->getExprLoc();8089    if (!findMacroSpelling(loc, "NULL"))8090      return false;8091  }8092 8093  int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);8094  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)8095      << NonPointerExpr->getType() << DiagType8096      << NonPointerExpr->getSourceRange();8097  return true;8098}8099 8100/// Return false if the condition expression is valid, true otherwise.8101static bool checkCondition(Sema &S, const Expr *Cond,8102                           SourceLocation QuestionLoc) {8103  QualType CondTy = Cond->getType();8104 8105  // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.8106  if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {8107    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)8108      << CondTy << Cond->getSourceRange();8109    return true;8110  }8111 8112  // C99 6.5.15p28113  if (CondTy->isScalarType()) return false;8114 8115  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)8116    << CondTy << Cond->getSourceRange();8117  return true;8118}8119 8120/// Return false if the NullExpr can be promoted to PointerTy,8121/// true otherwise.8122static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,8123                                        QualType PointerTy) {8124  if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||8125      !NullExpr.get()->isNullPointerConstant(S.Context,8126                                            Expr::NPC_ValueDependentIsNull))8127    return true;8128 8129  NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);8130  return false;8131}8132 8133/// Checks compatibility between two pointers and return the resulting8134/// type.8135static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,8136                                                     ExprResult &RHS,8137                                                     SourceLocation Loc) {8138  QualType LHSTy = LHS.get()->getType();8139  QualType RHSTy = RHS.get()->getType();8140 8141  if (S.Context.hasSameType(LHSTy, RHSTy)) {8142    // Two identical pointers types are always compatible.8143    return S.Context.getCommonSugaredType(LHSTy, RHSTy);8144  }8145 8146  QualType lhptee, rhptee;8147 8148  // Get the pointee types.8149  bool IsBlockPointer = false;8150  if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {8151    lhptee = LHSBTy->getPointeeType();8152    rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();8153    IsBlockPointer = true;8154  } else {8155    lhptee = LHSTy->castAs<PointerType>()->getPointeeType();8156    rhptee = RHSTy->castAs<PointerType>()->getPointeeType();8157  }8158 8159  // C99 6.5.15p6: If both operands are pointers to compatible types or to8160  // differently qualified versions of compatible types, the result type is8161  // a pointer to an appropriately qualified version of the composite8162  // type.8163 8164  // Only CVR-qualifiers exist in the standard, and the differently-qualified8165  // clause doesn't make sense for our extensions. E.g. address space 2 should8166  // be incompatible with address space 3: they may live on different devices or8167  // anything.8168  Qualifiers lhQual = lhptee.getQualifiers();8169  Qualifiers rhQual = rhptee.getQualifiers();8170 8171  LangAS ResultAddrSpace = LangAS::Default;8172  LangAS LAddrSpace = lhQual.getAddressSpace();8173  LangAS RAddrSpace = rhQual.getAddressSpace();8174 8175  // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address8176  // spaces is disallowed.8177  if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))8178    ResultAddrSpace = LAddrSpace;8179  else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))8180    ResultAddrSpace = RAddrSpace;8181  else {8182    S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)8183        << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()8184        << RHS.get()->getSourceRange();8185    return QualType();8186  }8187 8188  unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();8189  auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;8190  lhQual.removeCVRQualifiers();8191  rhQual.removeCVRQualifiers();8192 8193  if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {8194    S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)8195        << LHSTy << RHSTy << LHS.get()->getSourceRange()8196        << RHS.get()->getSourceRange();8197    return QualType();8198  }8199 8200  // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers8201  // (C99 6.7.3) for address spaces. We assume that the check should behave in8202  // the same manner as it's defined for CVR qualifiers, so for OpenCL two8203  // qual types are compatible iff8204  //  * corresponded types are compatible8205  //  * CVR qualifiers are equal8206  //  * address spaces are equal8207  // Thus for conditional operator we merge CVR and address space unqualified8208  // pointees and if there is a composite type we return a pointer to it with8209  // merged qualifiers.8210  LHSCastKind =8211      LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;8212  RHSCastKind =8213      RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;8214  lhQual.removeAddressSpace();8215  rhQual.removeAddressSpace();8216 8217  lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);8218  rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);8219 8220  QualType CompositeTy = S.Context.mergeTypes(8221      lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,8222      /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);8223 8224  if (CompositeTy.isNull()) {8225    // In this situation, we assume void* type. No especially good8226    // reason, but this is what gcc does, and we do have to pick8227    // to get a consistent AST.8228    QualType incompatTy;8229    incompatTy = S.Context.getPointerType(8230        S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));8231    LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);8232    RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);8233 8234    // FIXME: For OpenCL the warning emission and cast to void* leaves a room8235    // for casts between types with incompatible address space qualifiers.8236    // For the following code the compiler produces casts between global and8237    // local address spaces of the corresponded innermost pointees:8238    // local int *global *a;8239    // global int *global *b;8240    // a = (0 ? a : b); // see C99 6.5.16.1.p1.8241    S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)8242        << LHSTy << RHSTy << LHS.get()->getSourceRange()8243        << RHS.get()->getSourceRange();8244 8245    return incompatTy;8246  }8247 8248  // The pointer types are compatible.8249  // In case of OpenCL ResultTy should have the address space qualifier8250  // which is a superset of address spaces of both the 2nd and the 3rd8251  // operands of the conditional operator.8252  QualType ResultTy = [&, ResultAddrSpace]() {8253    if (S.getLangOpts().OpenCL) {8254      Qualifiers CompositeQuals = CompositeTy.getQualifiers();8255      CompositeQuals.setAddressSpace(ResultAddrSpace);8256      return S.Context8257          .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)8258          .withCVRQualifiers(MergedCVRQual);8259    }8260    return CompositeTy.withCVRQualifiers(MergedCVRQual);8261  }();8262  if (IsBlockPointer)8263    ResultTy = S.Context.getBlockPointerType(ResultTy);8264  else8265    ResultTy = S.Context.getPointerType(ResultTy);8266 8267  LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);8268  RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);8269  return ResultTy;8270}8271 8272/// Return the resulting type when the operands are both block pointers.8273static QualType checkConditionalBlockPointerCompatibility(Sema &S,8274                                                          ExprResult &LHS,8275                                                          ExprResult &RHS,8276                                                          SourceLocation Loc) {8277  QualType LHSTy = LHS.get()->getType();8278  QualType RHSTy = RHS.get()->getType();8279 8280  if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {8281    if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {8282      QualType destType = S.Context.getPointerType(S.Context.VoidTy);8283      LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);8284      RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);8285      return destType;8286    }8287    S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)8288      << LHSTy << RHSTy << LHS.get()->getSourceRange()8289      << RHS.get()->getSourceRange();8290    return QualType();8291  }8292 8293  // We have 2 block pointer types.8294  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);8295}8296 8297/// Return the resulting type when the operands are both pointers.8298static QualType8299checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,8300                                            ExprResult &RHS,8301                                            SourceLocation Loc) {8302  // get the pointer types8303  QualType LHSTy = LHS.get()->getType();8304  QualType RHSTy = RHS.get()->getType();8305 8306  // get the "pointed to" types8307  QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();8308  QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();8309 8310  // ignore qualifiers on void (C99 6.5.15p3, clause 6)8311  if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {8312    // Figure out necessary qualifiers (C99 6.5.15p6)8313    QualType destPointee8314      = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());8315    QualType destType = S.Context.getPointerType(destPointee);8316    // Add qualifiers if necessary.8317    LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);8318    // Promote to void*.8319    RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);8320    return destType;8321  }8322  if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {8323    QualType destPointee8324      = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());8325    QualType destType = S.Context.getPointerType(destPointee);8326    // Add qualifiers if necessary.8327    RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);8328    // Promote to void*.8329    LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);8330    return destType;8331  }8332 8333  return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);8334}8335 8336/// Return false if the first expression is not an integer and the second8337/// expression is not a pointer, true otherwise.8338static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,8339                                        Expr* PointerExpr, SourceLocation Loc,8340                                        bool IsIntFirstExpr) {8341  if (!PointerExpr->getType()->isPointerType() ||8342      !Int.get()->getType()->isIntegerType())8343    return false;8344 8345  Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;8346  Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();8347 8348  S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)8349    << Expr1->getType() << Expr2->getType()8350    << Expr1->getSourceRange() << Expr2->getSourceRange();8351  Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),8352                            CK_IntegralToPointer);8353  return true;8354}8355 8356/// Simple conversion between integer and floating point types.8357///8358/// Used when handling the OpenCL conditional operator where the8359/// condition is a vector while the other operands are scalar.8360///8361/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar8362/// types are either integer or floating type. Between the two8363/// operands, the type with the higher rank is defined as the "result8364/// type". The other operand needs to be promoted to the same type. No8365/// other type promotion is allowed. We cannot use8366/// UsualArithmeticConversions() for this purpose, since it always8367/// promotes promotable types.8368static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,8369                                            ExprResult &RHS,8370                                            SourceLocation QuestionLoc) {8371  LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());8372  if (LHS.isInvalid())8373    return QualType();8374  RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());8375  if (RHS.isInvalid())8376    return QualType();8377 8378  // For conversion purposes, we ignore any qualifiers.8379  // For example, "const float" and "float" are equivalent.8380  QualType LHSType =8381    S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();8382  QualType RHSType =8383    S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();8384 8385  if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {8386    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)8387      << LHSType << LHS.get()->getSourceRange();8388    return QualType();8389  }8390 8391  if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {8392    S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)8393      << RHSType << RHS.get()->getSourceRange();8394    return QualType();8395  }8396 8397  // If both types are identical, no conversion is needed.8398  if (LHSType == RHSType)8399    return LHSType;8400 8401  // Now handle "real" floating types (i.e. float, double, long double).8402  if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())8403    return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,8404                                 /*IsCompAssign = */ false);8405 8406  // Finally, we have two differing integer types.8407  return handleIntegerConversion<doIntegralCast, doIntegralCast>8408  (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);8409}8410 8411/// Convert scalar operands to a vector that matches the8412///        condition in length.8413///8414/// Used when handling the OpenCL conditional operator where the8415/// condition is a vector while the other operands are scalar.8416///8417/// We first compute the "result type" for the scalar operands8418/// according to OpenCL v1.1 s6.3.i. Both operands are then converted8419/// into a vector of that type where the length matches the condition8420/// vector type. s6.11.6 requires that the element types of the result8421/// and the condition must have the same number of bits.8422static QualType8423OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,8424                              QualType CondTy, SourceLocation QuestionLoc) {8425  QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);8426  if (ResTy.isNull()) return QualType();8427 8428  const VectorType *CV = CondTy->getAs<VectorType>();8429  assert(CV);8430 8431  // Determine the vector result type8432  unsigned NumElements = CV->getNumElements();8433  QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);8434 8435  // Ensure that all types have the same number of bits8436  if (S.Context.getTypeSize(CV->getElementType())8437      != S.Context.getTypeSize(ResTy)) {8438    // Since VectorTy is created internally, it does not pretty print8439    // with an OpenCL name. Instead, we just print a description.8440    std::string EleTyName = ResTy.getUnqualifiedType().getAsString();8441    SmallString<64> Str;8442    llvm::raw_svector_ostream OS(Str);8443    OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";8444    S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)8445      << CondTy << OS.str();8446    return QualType();8447  }8448 8449  // Convert operands to the vector result type8450  LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);8451  RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);8452 8453  return VectorTy;8454}8455 8456/// Return false if this is a valid OpenCL condition vector8457static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,8458                                       SourceLocation QuestionLoc) {8459  // OpenCL v1.1 s6.11.6 says the elements of the vector must be of8460  // integral type.8461  const VectorType *CondTy = Cond->getType()->getAs<VectorType>();8462  assert(CondTy);8463  QualType EleTy = CondTy->getElementType();8464  if (EleTy->isIntegerType()) return false;8465 8466  S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)8467    << Cond->getType() << Cond->getSourceRange();8468  return true;8469}8470 8471/// Return false if the vector condition type and the vector8472///        result type are compatible.8473///8474/// OpenCL v1.1 s6.11.6 requires that both vector types have the same8475/// number of elements, and their element types have the same number8476/// of bits.8477static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,8478                              SourceLocation QuestionLoc) {8479  const VectorType *CV = CondTy->getAs<VectorType>();8480  const VectorType *RV = VecResTy->getAs<VectorType>();8481  assert(CV && RV);8482 8483  if (CV->getNumElements() != RV->getNumElements()) {8484    S.Diag(QuestionLoc, diag::err_conditional_vector_size)8485      << CondTy << VecResTy;8486    return true;8487  }8488 8489  QualType CVE = CV->getElementType();8490  QualType RVE = RV->getElementType();8491 8492  // Boolean vectors are permitted outside of OpenCL mode.8493  if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&8494      (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {8495    S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)8496        << CondTy << VecResTy;8497    return true;8498  }8499 8500  return false;8501}8502 8503/// Return the resulting type for the conditional operator in8504///        OpenCL (aka "ternary selection operator", OpenCL v1.18505///        s6.3.i) when the condition is a vector type.8506static QualType8507OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,8508                             ExprResult &LHS, ExprResult &RHS,8509                             SourceLocation QuestionLoc) {8510  Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());8511  if (Cond.isInvalid())8512    return QualType();8513  QualType CondTy = Cond.get()->getType();8514 8515  if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))8516    return QualType();8517 8518  // If either operand is a vector then find the vector type of the8519  // result as specified in OpenCL v1.1 s6.3.i.8520  if (LHS.get()->getType()->isVectorType() ||8521      RHS.get()->getType()->isVectorType()) {8522    bool IsBoolVecLang =8523        !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;8524    QualType VecResTy =8525        S.CheckVectorOperands(LHS, RHS, QuestionLoc,8526                              /*isCompAssign*/ false,8527                              /*AllowBothBool*/ true,8528                              /*AllowBoolConversions*/ false,8529                              /*AllowBooleanOperation*/ IsBoolVecLang,8530                              /*ReportInvalid*/ true);8531    if (VecResTy.isNull())8532      return QualType();8533    // The result type must match the condition type as specified in8534    // OpenCL v1.1 s6.11.6.8535    if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))8536      return QualType();8537    return VecResTy;8538  }8539 8540  // Both operands are scalar.8541  return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);8542}8543 8544/// Return true if the Expr is block type8545static bool checkBlockType(Sema &S, const Expr *E) {8546  if (E->getType()->isBlockPointerType()) {8547    S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);8548    return true;8549  }8550 8551  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {8552    QualType Ty = CE->getCallee()->getType();8553    if (Ty->isBlockPointerType()) {8554      S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);8555      return true;8556    }8557  }8558  return false;8559}8560 8561/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.8562/// In that case, LHS = cond.8563/// C99 6.5.158564QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,8565                                        ExprResult &RHS, ExprValueKind &VK,8566                                        ExprObjectKind &OK,8567                                        SourceLocation QuestionLoc) {8568 8569  ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());8570  if (!LHSResult.isUsable()) return QualType();8571  LHS = LHSResult;8572 8573  ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());8574  if (!RHSResult.isUsable()) return QualType();8575  RHS = RHSResult;8576 8577  // C++ is sufficiently different to merit its own checker.8578  if (getLangOpts().CPlusPlus)8579    return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);8580 8581  VK = VK_PRValue;8582  OK = OK_Ordinary;8583 8584  if (Context.isDependenceAllowed() &&8585      (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||8586       RHS.get()->isTypeDependent())) {8587    assert(!getLangOpts().CPlusPlus);8588    assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||8589            RHS.get()->containsErrors()) &&8590           "should only occur in error-recovery path.");8591    return Context.DependentTy;8592  }8593 8594  // The OpenCL operator with a vector condition is sufficiently8595  // different to merit its own checker.8596  if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||8597      Cond.get()->getType()->isExtVectorType())8598    return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);8599 8600  // First, check the condition.8601  Cond = UsualUnaryConversions(Cond.get());8602  if (Cond.isInvalid())8603    return QualType();8604  if (checkCondition(*this, Cond.get(), QuestionLoc))8605    return QualType();8606 8607  // Handle vectors.8608  if (LHS.get()->getType()->isVectorType() ||8609      RHS.get()->getType()->isVectorType())8610    return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,8611                               /*AllowBothBool*/ true,8612                               /*AllowBoolConversions*/ false,8613                               /*AllowBooleanOperation*/ false,8614                               /*ReportInvalid*/ true);8615 8616  QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,8617                                              ArithConvKind::Conditional);8618  if (LHS.isInvalid() || RHS.isInvalid())8619    return QualType();8620 8621  // WebAssembly tables are not allowed as conditional LHS or RHS.8622  QualType LHSTy = LHS.get()->getType();8623  QualType RHSTy = RHS.get()->getType();8624  if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {8625    Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)8626        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();8627    return QualType();8628  }8629 8630  // Diagnose attempts to convert between __ibm128, __float128 and long double8631  // where such conversions currently can't be handled.8632  if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {8633    Diag(QuestionLoc,8634         diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy8635      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();8636    return QualType();8637  }8638 8639  // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary8640  // selection operator (?:).8641  if (getLangOpts().OpenCL &&8642      ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {8643    return QualType();8644  }8645 8646  // If both operands have arithmetic type, do the usual arithmetic conversions8647  // to find a common type: C99 6.5.15p3,5.8648  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {8649    // Disallow invalid arithmetic conversions, such as those between bit-8650    // precise integers types of different sizes, or between a bit-precise8651    // integer and another type.8652    if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {8653      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)8654          << LHSTy << RHSTy << LHS.get()->getSourceRange()8655          << RHS.get()->getSourceRange();8656      return QualType();8657    }8658 8659    LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));8660    RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));8661 8662    return ResTy;8663  }8664 8665  // If both operands are the same structure or union type, the result is that8666  // type.8667  // FIXME: Type of conditional expression must be complete in C mode.8668  if (LHSTy->isRecordType() &&8669      Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p38670    return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),8671                                        RHSTy.getUnqualifiedType());8672 8673  // C99 6.5.15p5: "If both operands have void type, the result has void type."8674  // The following || allows only one side to be void (a GCC-ism).8675  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {8676    QualType ResTy;8677    if (LHSTy->isVoidType() && RHSTy->isVoidType()) {8678      ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);8679    } else if (RHSTy->isVoidType()) {8680      ResTy = RHSTy;8681      Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)8682          << RHS.get()->getSourceRange();8683    } else {8684      ResTy = LHSTy;8685      Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)8686          << LHS.get()->getSourceRange();8687    }8688    LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);8689    RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);8690    return ResTy;8691  }8692 8693  // C23 6.5.15p7:8694  //   ... if both the second and third operands have nullptr_t type, the8695  //   result also has that type.8696  if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))8697    return ResTy;8698 8699  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has8700  // the type of the other operand."8701  if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;8702  if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;8703 8704  // All objective-c pointer type analysis is done here.8705  QualType compositeType =8706      ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);8707  if (LHS.isInvalid() || RHS.isInvalid())8708    return QualType();8709  if (!compositeType.isNull())8710    return compositeType;8711 8712 8713  // Handle block pointer types.8714  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())8715    return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,8716                                                     QuestionLoc);8717 8718  // Check constraints for C object pointers types (C99 6.5.15p3,6).8719  if (LHSTy->isPointerType() && RHSTy->isPointerType())8720    return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,8721                                                       QuestionLoc);8722 8723  // GCC compatibility: soften pointer/integer mismatch.  Note that8724  // null pointers have been filtered out by this point.8725  if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,8726      /*IsIntFirstExpr=*/true))8727    return RHSTy;8728  if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,8729      /*IsIntFirstExpr=*/false))8730    return LHSTy;8731 8732  // Emit a better diagnostic if one of the expressions is a null pointer8733  // constant and the other is not a pointer type. In this case, the user most8734  // likely forgot to take the address of the other expression.8735  if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))8736    return QualType();8737 8738  // Finally, if the LHS and RHS types are canonically the same type, we can8739  // use the common sugared type.8740  if (Context.hasSameType(LHSTy, RHSTy))8741    return Context.getCommonSugaredType(LHSTy, RHSTy);8742 8743  // Otherwise, the operands are not compatible.8744  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)8745    << LHSTy << RHSTy << LHS.get()->getSourceRange()8746    << RHS.get()->getSourceRange();8747  return QualType();8748}8749 8750/// SuggestParentheses - Emit a note with a fixit hint that wraps8751/// ParenRange in parentheses.8752static void SuggestParentheses(Sema &Self, SourceLocation Loc,8753                               const PartialDiagnostic &Note,8754                               SourceRange ParenRange) {8755  SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());8756  if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&8757      EndLoc.isValid()) {8758    Self.Diag(Loc, Note)8759      << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")8760      << FixItHint::CreateInsertion(EndLoc, ")");8761  } else {8762    // We can't display the parentheses, so just show the bare note.8763    Self.Diag(Loc, Note) << ParenRange;8764  }8765}8766 8767static bool IsArithmeticOp(BinaryOperatorKind Opc) {8768  return BinaryOperator::isAdditiveOp(Opc) ||8769         BinaryOperator::isMultiplicativeOp(Opc) ||8770         BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;8771  // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and8772  // not any of the logical operators.  Bitwise-xor is commonly used as a8773  // logical-xor because there is no logical-xor operator.  The logical8774  // operators, including uses of xor, have a high false positive rate for8775  // precedence warnings.8776}8777 8778/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary8779/// expression, either using a built-in or overloaded operator,8780/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side8781/// expression.8782static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,8783                                   const Expr **RHSExprs) {8784  // Don't strip parenthesis: we should not warn if E is in parenthesis.8785  E = E->IgnoreImpCasts();8786  E = E->IgnoreConversionOperatorSingleStep();8787  E = E->IgnoreImpCasts();8788  if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {8789    E = MTE->getSubExpr();8790    E = E->IgnoreImpCasts();8791  }8792 8793  // Built-in binary operator.8794  if (const auto *OP = dyn_cast<BinaryOperator>(E);8795      OP && IsArithmeticOp(OP->getOpcode())) {8796    *Opcode = OP->getOpcode();8797    *RHSExprs = OP->getRHS();8798    return true;8799  }8800 8801  // Overloaded operator.8802  if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {8803    if (Call->getNumArgs() != 2)8804      return false;8805 8806    // Make sure this is really a binary operator that is safe to pass into8807    // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.8808    OverloadedOperatorKind OO = Call->getOperator();8809    if (OO < OO_Plus || OO > OO_Arrow ||8810        OO == OO_PlusPlus || OO == OO_MinusMinus)8811      return false;8812 8813    BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);8814    if (IsArithmeticOp(OpKind)) {8815      *Opcode = OpKind;8816      *RHSExprs = Call->getArg(1);8817      return true;8818    }8819  }8820 8821  return false;8822}8823 8824/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type8825/// or is a logical expression such as (x==y) which has int type, but is8826/// commonly interpreted as boolean.8827static bool ExprLooksBoolean(const Expr *E) {8828  E = E->IgnoreParenImpCasts();8829 8830  if (E->getType()->isBooleanType())8831    return true;8832  if (const auto *OP = dyn_cast<BinaryOperator>(E))8833    return OP->isComparisonOp() || OP->isLogicalOp();8834  if (const auto *OP = dyn_cast<UnaryOperator>(E))8835    return OP->getOpcode() == UO_LNot;8836  if (E->getType()->isPointerType())8837    return true;8838  // FIXME: What about overloaded operator calls returning "unspecified boolean8839  // type"s (commonly pointer-to-members)?8840 8841  return false;8842}8843 8844/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator8845/// and binary operator are mixed in a way that suggests the programmer assumed8846/// the conditional operator has higher precedence, for example:8847/// "int x = a + someBinaryCondition ? 1 : 2".8848static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,8849                                          Expr *Condition, const Expr *LHSExpr,8850                                          const Expr *RHSExpr) {8851  BinaryOperatorKind CondOpcode;8852  const Expr *CondRHS;8853 8854  if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))8855    return;8856  if (!ExprLooksBoolean(CondRHS))8857    return;8858 8859  // The condition is an arithmetic binary expression, with a right-8860  // hand side that looks boolean, so warn.8861 8862  unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)8863                        ? diag::warn_precedence_bitwise_conditional8864                        : diag::warn_precedence_conditional;8865 8866  Self.Diag(OpLoc, DiagID)8867      << Condition->getSourceRange()8868      << BinaryOperator::getOpcodeStr(CondOpcode);8869 8870  SuggestParentheses(8871      Self, OpLoc,8872      Self.PDiag(diag::note_precedence_silence)8873          << BinaryOperator::getOpcodeStr(CondOpcode),8874      SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));8875 8876  SuggestParentheses(Self, OpLoc,8877                     Self.PDiag(diag::note_precedence_conditional_first),8878                     SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));8879}8880 8881/// Compute the nullability of a conditional expression.8882static QualType computeConditionalNullability(QualType ResTy, bool IsBin,8883                                              QualType LHSTy, QualType RHSTy,8884                                              ASTContext &Ctx) {8885  if (!ResTy->isAnyPointerType())8886    return ResTy;8887 8888  auto GetNullability = [](QualType Ty) {8889    std::optional<NullabilityKind> Kind = Ty->getNullability();8890    if (Kind) {8891      // For our purposes, treat _Nullable_result as _Nullable.8892      if (*Kind == NullabilityKind::NullableResult)8893        return NullabilityKind::Nullable;8894      return *Kind;8895    }8896    return NullabilityKind::Unspecified;8897  };8898 8899  auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);8900  NullabilityKind MergedKind;8901 8902  // Compute nullability of a binary conditional expression.8903  if (IsBin) {8904    if (LHSKind == NullabilityKind::NonNull)8905      MergedKind = NullabilityKind::NonNull;8906    else8907      MergedKind = RHSKind;8908  // Compute nullability of a normal conditional expression.8909  } else {8910    if (LHSKind == NullabilityKind::Nullable ||8911        RHSKind == NullabilityKind::Nullable)8912      MergedKind = NullabilityKind::Nullable;8913    else if (LHSKind == NullabilityKind::NonNull)8914      MergedKind = RHSKind;8915    else if (RHSKind == NullabilityKind::NonNull)8916      MergedKind = LHSKind;8917    else8918      MergedKind = NullabilityKind::Unspecified;8919  }8920 8921  // Return if ResTy already has the correct nullability.8922  if (GetNullability(ResTy) == MergedKind)8923    return ResTy;8924 8925  // Strip all nullability from ResTy.8926  while (ResTy->getNullability())8927    ResTy = ResTy.getSingleStepDesugaredType(Ctx);8928 8929  // Create a new AttributedType with the new nullability kind.8930  return Ctx.getAttributedType(MergedKind, ResTy, ResTy);8931}8932 8933ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,8934                                    SourceLocation ColonLoc,8935                                    Expr *CondExpr, Expr *LHSExpr,8936                                    Expr *RHSExpr) {8937  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS8938  // was the condition.8939  OpaqueValueExpr *opaqueValue = nullptr;8940  Expr *commonExpr = nullptr;8941  if (!LHSExpr) {8942    commonExpr = CondExpr;8943    // Lower out placeholder types first.  This is important so that we don't8944    // try to capture a placeholder. This happens in few cases in C++; such8945    // as Objective-C++'s dictionary subscripting syntax.8946    if (commonExpr->hasPlaceholderType()) {8947      ExprResult result = CheckPlaceholderExpr(commonExpr);8948      if (!result.isUsable()) return ExprError();8949      commonExpr = result.get();8950    }8951    // We usually want to apply unary conversions *before* saving, except8952    // in the special case of a C++ l-value conditional.8953    if (!(getLangOpts().CPlusPlus8954          && !commonExpr->isTypeDependent()8955          && commonExpr->getValueKind() == RHSExpr->getValueKind()8956          && commonExpr->isGLValue()8957          && commonExpr->isOrdinaryOrBitFieldObject()8958          && RHSExpr->isOrdinaryOrBitFieldObject()8959          && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {8960      ExprResult commonRes = UsualUnaryConversions(commonExpr);8961      if (commonRes.isInvalid())8962        return ExprError();8963      commonExpr = commonRes.get();8964    }8965 8966    // If the common expression is a class or array prvalue, materialize it8967    // so that we can safely refer to it multiple times.8968    if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||8969                                    commonExpr->getType()->isArrayType())) {8970      ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);8971      if (MatExpr.isInvalid())8972        return ExprError();8973      commonExpr = MatExpr.get();8974    }8975 8976    opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),8977                                                commonExpr->getType(),8978                                                commonExpr->getValueKind(),8979                                                commonExpr->getObjectKind(),8980                                                commonExpr);8981    LHSExpr = CondExpr = opaqueValue;8982  }8983 8984  QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();8985  ExprValueKind VK = VK_PRValue;8986  ExprObjectKind OK = OK_Ordinary;8987  ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;8988  QualType result = CheckConditionalOperands(Cond, LHS, RHS,8989                                             VK, OK, QuestionLoc);8990  if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||8991      RHS.isInvalid())8992    return ExprError();8993 8994  DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),8995                                RHS.get());8996 8997  CheckBoolLikeConversion(Cond.get(), QuestionLoc);8998 8999  result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,9000                                         Context);9001 9002  if (!commonExpr)9003    return new (Context)9004        ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,9005                            RHS.get(), result, VK, OK);9006 9007  return new (Context) BinaryConditionalOperator(9008      commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,9009      ColonLoc, result, VK, OK);9010}9011 9012bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {9013  unsigned FromAttributes = 0, ToAttributes = 0;9014  if (const auto *FromFn =9015          dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))9016    FromAttributes =9017        FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;9018  if (const auto *ToFn =9019          dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))9020    ToAttributes =9021        ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;9022 9023  return FromAttributes != ToAttributes;9024}9025 9026// checkPointerTypesForAssignment - This is a very tricky routine (despite9027// being closely modeled after the C99 spec:-). The odd characteristic of this9028// routine is it effectively iqnores the qualifiers on the top level pointee.9029// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].9030// FIXME: add a couple examples in this comment.9031static AssignConvertType checkPointerTypesForAssignment(Sema &S,9032                                                        QualType LHSType,9033                                                        QualType RHSType,9034                                                        SourceLocation Loc) {9035  assert(LHSType.isCanonical() && "LHS not canonicalized!");9036  assert(RHSType.isCanonical() && "RHS not canonicalized!");9037 9038  // get the "pointed to" type (ignoring qualifiers at the top level)9039  const Type *lhptee, *rhptee;9040  Qualifiers lhq, rhq;9041  std::tie(lhptee, lhq) =9042      cast<PointerType>(LHSType)->getPointeeType().split().asPair();9043  std::tie(rhptee, rhq) =9044      cast<PointerType>(RHSType)->getPointeeType().split().asPair();9045 9046  AssignConvertType ConvTy = AssignConvertType::Compatible;9047 9048  // C99 6.5.16.1p1: This following citation is common to constraints9049  // 3 & 4 (below). ...and the type *pointed to* by the left has all the9050  // qualifiers of the type *pointed to* by the right;9051 9052  // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.9053  if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&9054      lhq.compatiblyIncludesObjCLifetime(rhq)) {9055    // Ignore lifetime for further calculation.9056    lhq.removeObjCLifetime();9057    rhq.removeObjCLifetime();9058  }9059 9060  if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {9061    // Treat address-space mismatches as fatal.9062    if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))9063      return AssignConvertType::IncompatiblePointerDiscardsQualifiers;9064 9065    // It's okay to add or remove GC or lifetime qualifiers when converting to9066    // and from void*.9067    else if (lhq.withoutObjCGCAttr().withoutObjCLifetime().compatiblyIncludes(9068                 rhq.withoutObjCGCAttr().withoutObjCLifetime(),9069                 S.getASTContext()) &&9070             (lhptee->isVoidType() || rhptee->isVoidType()))9071      ; // keep old9072 9073    // Treat lifetime mismatches as fatal.9074    else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())9075      ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;9076 9077    // Treat pointer-auth mismatches as fatal.9078    else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))9079      ConvTy = AssignConvertType::IncompatiblePointerDiscardsQualifiers;9080 9081    // For GCC/MS compatibility, other qualifier mismatches are treated9082    // as still compatible in C.9083    else9084      ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;9085  }9086 9087  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or9088  // incomplete type and the other is a pointer to a qualified or unqualified9089  // version of void...9090  if (lhptee->isVoidType()) {9091    if (rhptee->isIncompleteOrObjectType())9092      return ConvTy;9093 9094    // As an extension, we allow cast to/from void* to function pointer.9095    assert(rhptee->isFunctionType());9096    return AssignConvertType::FunctionVoidPointer;9097  }9098 9099  if (rhptee->isVoidType()) {9100    // In C, void * to another pointer type is compatible, but we want to note9101    // that there will be an implicit conversion happening here.9102    if (lhptee->isIncompleteOrObjectType())9103      return ConvTy == AssignConvertType::Compatible &&9104                     !S.getLangOpts().CPlusPlus9105                 ? AssignConvertType::CompatibleVoidPtrToNonVoidPtr9106                 : ConvTy;9107 9108    // As an extension, we allow cast to/from void* to function pointer.9109    assert(lhptee->isFunctionType());9110    return AssignConvertType::FunctionVoidPointer;9111  }9112 9113  if (!S.Diags.isIgnored(9114          diag::warn_typecheck_convert_incompatible_function_pointer_strict,9115          Loc) &&9116      RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&9117      !S.TryFunctionConversion(RHSType, LHSType, RHSType))9118    return AssignConvertType::IncompatibleFunctionPointerStrict;9119 9120  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or9121  // unqualified versions of compatible types, ...9122  QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);9123  if (!S.Context.typesAreCompatible(ltrans, rtrans)) {9124    // Check if the pointee types are compatible ignoring the sign.9125    // We explicitly check for char so that we catch "char" vs9126    // "unsigned char" on systems where "char" is unsigned.9127    if (lhptee->isCharType())9128      ltrans = S.Context.UnsignedCharTy;9129    else if (lhptee->hasSignedIntegerRepresentation())9130      ltrans = S.Context.getCorrespondingUnsignedType(ltrans);9131 9132    if (rhptee->isCharType())9133      rtrans = S.Context.UnsignedCharTy;9134    else if (rhptee->hasSignedIntegerRepresentation())9135      rtrans = S.Context.getCorrespondingUnsignedType(rtrans);9136 9137    if (ltrans == rtrans) {9138      // Types are compatible ignoring the sign. Qualifier incompatibility9139      // takes priority over sign incompatibility because the sign9140      // warning can be disabled.9141      if (!S.IsAssignConvertCompatible(ConvTy))9142        return ConvTy;9143 9144      return AssignConvertType::IncompatiblePointerSign;9145    }9146 9147    // If we are a multi-level pointer, it's possible that our issue is simply9148    // one of qualification - e.g. char ** -> const char ** is not allowed. If9149    // the eventual target type is the same and the pointers have the same9150    // level of indirection, this must be the issue.9151    if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {9152      do {9153        std::tie(lhptee, lhq) =9154          cast<PointerType>(lhptee)->getPointeeType().split().asPair();9155        std::tie(rhptee, rhq) =9156          cast<PointerType>(rhptee)->getPointeeType().split().asPair();9157 9158        // Inconsistent address spaces at this point is invalid, even if the9159        // address spaces would be compatible.9160        // FIXME: This doesn't catch address space mismatches for pointers of9161        // different nesting levels, like:9162        //   __local int *** a;9163        //   int ** b = a;9164        // It's not clear how to actually determine when such pointers are9165        // invalidly incompatible.9166        if (lhq.getAddressSpace() != rhq.getAddressSpace())9167          return AssignConvertType::9168              IncompatibleNestedPointerAddressSpaceMismatch;9169 9170      } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));9171 9172      if (lhptee == rhptee)9173        return AssignConvertType::IncompatibleNestedPointerQualifiers;9174    }9175 9176    // General pointer incompatibility takes priority over qualifiers.9177    if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())9178      return AssignConvertType::IncompatibleFunctionPointer;9179    return AssignConvertType::IncompatiblePointer;9180  }9181  // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed9182  // hasSameType, so we can skip further checks.9183  const auto *LFT = ltrans->getAs<FunctionType>();9184  const auto *RFT = rtrans->getAs<FunctionType>();9185  if (!S.getLangOpts().CPlusPlus && LFT && RFT) {9186    // The invocation of IsFunctionConversion below will try to transform rtrans9187    // to obtain an exact match for ltrans. This should not fail because of9188    // mismatches in result type and parameter types, they were already checked9189    // by typesAreCompatible above. So we will recreate rtrans (or where9190    // appropriate ltrans) using the result type and parameter types from ltrans9191    // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.9192    const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);9193    const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);9194    if (LFPT && RFPT) {9195      rtrans = S.Context.getFunctionType(LFPT->getReturnType(),9196                                         LFPT->getParamTypes(),9197                                         RFPT->getExtProtoInfo());9198    } else if (LFPT) {9199      FunctionProtoType::ExtProtoInfo EPI;9200      EPI.ExtInfo = RFT->getExtInfo();9201      rtrans = S.Context.getFunctionType(LFPT->getReturnType(),9202                                         LFPT->getParamTypes(), EPI);9203    } else if (RFPT) {9204      // In this case, we want to retain rtrans as a FunctionProtoType, to keep9205      // all of its ExtProtoInfo. Transform ltrans instead.9206      FunctionProtoType::ExtProtoInfo EPI;9207      EPI.ExtInfo = LFT->getExtInfo();9208      ltrans = S.Context.getFunctionType(RFPT->getReturnType(),9209                                         RFPT->getParamTypes(), EPI);9210    } else {9211      rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),9212                                                RFT->getExtInfo());9213    }9214    if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&9215        !S.IsFunctionConversion(rtrans, ltrans))9216      return AssignConvertType::IncompatibleFunctionPointer;9217  }9218  return ConvTy;9219}9220 9221/// checkBlockPointerTypesForAssignment - This routine determines whether two9222/// block pointer types are compatible or whether a block and normal pointer9223/// are compatible. It is more restrict than comparing two function pointer9224// types.9225static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S,9226                                                             QualType LHSType,9227                                                             QualType RHSType) {9228  assert(LHSType.isCanonical() && "LHS not canonicalized!");9229  assert(RHSType.isCanonical() && "RHS not canonicalized!");9230 9231  QualType lhptee, rhptee;9232 9233  // get the "pointed to" type (ignoring qualifiers at the top level)9234  lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();9235  rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();9236 9237  // In C++, the types have to match exactly.9238  if (S.getLangOpts().CPlusPlus)9239    return AssignConvertType::IncompatibleBlockPointer;9240 9241  AssignConvertType ConvTy = AssignConvertType::Compatible;9242 9243  // For blocks we enforce that qualifiers are identical.9244  Qualifiers LQuals = lhptee.getLocalQualifiers();9245  Qualifiers RQuals = rhptee.getLocalQualifiers();9246  if (S.getLangOpts().OpenCL) {9247    LQuals.removeAddressSpace();9248    RQuals.removeAddressSpace();9249  }9250  if (LQuals != RQuals)9251    ConvTy = AssignConvertType::CompatiblePointerDiscardsQualifiers;9252 9253  // FIXME: OpenCL doesn't define the exact compile time semantics for a block9254  // assignment.9255  // The current behavior is similar to C++ lambdas. A block might be9256  // assigned to a variable iff its return type and parameters are compatible9257  // (C99 6.2.7) with the corresponding return type and parameters of the LHS of9258  // an assignment. Presumably it should behave in way that a function pointer9259  // assignment does in C, so for each parameter and return type:9260  //  * CVR and address space of LHS should be a superset of CVR and address9261  //  space of RHS.9262  //  * unqualified types should be compatible.9263  if (S.getLangOpts().OpenCL) {9264    if (!S.Context.typesAreBlockPointerCompatible(9265            S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),9266            S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))9267      return AssignConvertType::IncompatibleBlockPointer;9268  } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))9269    return AssignConvertType::IncompatibleBlockPointer;9270 9271  return ConvTy;9272}9273 9274/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types9275/// for assignment compatibility.9276static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S,9277                                                            QualType LHSType,9278                                                            QualType RHSType) {9279  assert(LHSType.isCanonical() && "LHS was not canonicalized!");9280  assert(RHSType.isCanonical() && "RHS was not canonicalized!");9281 9282  if (LHSType->isObjCBuiltinType()) {9283    // Class is not compatible with ObjC object pointers.9284    if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&9285        !RHSType->isObjCQualifiedClassType())9286      return AssignConvertType::IncompatiblePointer;9287    return AssignConvertType::Compatible;9288  }9289  if (RHSType->isObjCBuiltinType()) {9290    if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&9291        !LHSType->isObjCQualifiedClassType())9292      return AssignConvertType::IncompatiblePointer;9293    return AssignConvertType::Compatible;9294  }9295  QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();9296  QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();9297 9298  if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&9299      // make an exception for id<P>9300      !LHSType->isObjCQualifiedIdType())9301    return AssignConvertType::CompatiblePointerDiscardsQualifiers;9302 9303  if (S.Context.typesAreCompatible(LHSType, RHSType))9304    return AssignConvertType::Compatible;9305  if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())9306    return AssignConvertType::IncompatibleObjCQualifiedId;9307  return AssignConvertType::IncompatiblePointer;9308}9309 9310AssignConvertType Sema::CheckAssignmentConstraints(SourceLocation Loc,9311                                                   QualType LHSType,9312                                                   QualType RHSType) {9313  // Fake up an opaque expression.  We don't actually care about what9314  // cast operations are required, so if CheckAssignmentConstraints9315  // adds casts to this they'll be wasted, but fortunately that doesn't9316  // usually happen on valid code.9317  OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);9318  ExprResult RHSPtr = &RHSExpr;9319  CastKind K;9320 9321  return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);9322}9323 9324/// This helper function returns true if QT is a vector type that has element9325/// type ElementType.9326static bool isVector(QualType QT, QualType ElementType) {9327  if (const VectorType *VT = QT->getAs<VectorType>())9328    return VT->getElementType().getCanonicalType() == ElementType;9329  return false;9330}9331 9332/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently9333/// has code to accommodate several GCC extensions when type checking9334/// pointers. Here are some objectionable examples that GCC considers warnings:9335///9336///  int a, *pint;9337///  short *pshort;9338///  struct foo *pfoo;9339///9340///  pint = pshort; // warning: assignment from incompatible pointer type9341///  a = pint; // warning: assignment makes integer from pointer without a cast9342///  pint = a; // warning: assignment makes pointer from integer without a cast9343///  pint = pfoo; // warning: assignment from incompatible pointer type9344///9345/// As a result, the code for dealing with pointers is more complex than the9346/// C99 spec dictates.9347///9348/// Sets 'Kind' for any result kind except Incompatible.9349AssignConvertType Sema::CheckAssignmentConstraints(QualType LHSType,9350                                                   ExprResult &RHS,9351                                                   CastKind &Kind,9352                                                   bool ConvertRHS) {9353  QualType RHSType = RHS.get()->getType();9354  QualType OrigLHSType = LHSType;9355 9356  // Get canonical types.  We're not formatting these types, just comparing9357  // them.9358  LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();9359  RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();9360 9361  // Common case: no conversion required.9362  if (LHSType == RHSType) {9363    Kind = CK_NoOp;9364    return AssignConvertType::Compatible;9365  }9366 9367  // If the LHS has an __auto_type, there are no additional type constraints9368  // to be worried about.9369  if (const auto *AT = dyn_cast<AutoType>(LHSType)) {9370    if (AT->isGNUAutoType()) {9371      Kind = CK_NoOp;9372      return AssignConvertType::Compatible;9373    }9374  }9375 9376  // If we have an atomic type, try a non-atomic assignment, then just add an9377  // atomic qualification step.9378  if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {9379    AssignConvertType Result =9380        CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);9381    if (!IsAssignConvertCompatible(Result))9382      return Result;9383    if (Kind != CK_NoOp && ConvertRHS)9384      RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);9385    Kind = CK_NonAtomicToAtomic;9386    return Result;9387  }9388 9389  // If the left-hand side is a reference type, then we are in a9390  // (rare!) case where we've allowed the use of references in C,9391  // e.g., as a parameter type in a built-in function. In this case,9392  // just make sure that the type referenced is compatible with the9393  // right-hand side type. The caller is responsible for adjusting9394  // LHSType so that the resulting expression does not have reference9395  // type.9396  if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {9397    if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {9398      Kind = CK_LValueBitCast;9399      return AssignConvertType::Compatible;9400    }9401    return AssignConvertType::Incompatible;9402  }9403 9404  // Allow scalar to ExtVector assignments, assignment to bool, and assignments9405  // of an ExtVector type to the same ExtVector type.9406  if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {9407    if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {9408      // Implicit conversions require the same number of elements.9409      if (LHSExtType->getNumElements() != RHSExtType->getNumElements())9410        return AssignConvertType::Incompatible;9411 9412      if (LHSType->isExtVectorBoolType() &&9413          RHSExtType->getElementType()->isIntegerType()) {9414        Kind = CK_IntegralToBoolean;9415        return AssignConvertType::Compatible;9416      }9417      return AssignConvertType::Incompatible;9418    }9419    if (RHSType->isArithmeticType()) {9420      // CK_VectorSplat does T -> vector T, so first cast to the element type.9421      if (ConvertRHS)9422        RHS = prepareVectorSplat(LHSType, RHS.get());9423      Kind = CK_VectorSplat;9424      return AssignConvertType::Compatible;9425    }9426  }9427 9428  // Conversions to or from vector type.9429  if (LHSType->isVectorType() || RHSType->isVectorType()) {9430    if (LHSType->isVectorType() && RHSType->isVectorType()) {9431      // Allow assignments of an AltiVec vector type to an equivalent GCC9432      // vector type and vice versa9433      if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {9434        Kind = CK_BitCast;9435        return AssignConvertType::Compatible;9436      }9437 9438      // If we are allowing lax vector conversions, and LHS and RHS are both9439      // vectors, the total size only needs to be the same. This is a bitcast;9440      // no bits are changed but the result type is different.9441      if (isLaxVectorConversion(RHSType, LHSType)) {9442        // The default for lax vector conversions with Altivec vectors will9443        // change, so if we are converting between vector types where9444        // at least one is an Altivec vector, emit a warning.9445        if (Context.getTargetInfo().getTriple().isPPC() &&9446            anyAltivecTypes(RHSType, LHSType) &&9447            !Context.areCompatibleVectorTypes(RHSType, LHSType))9448          Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)9449              << RHSType << LHSType;9450        Kind = CK_BitCast;9451        return AssignConvertType::IncompatibleVectors;9452      }9453    }9454 9455    // When the RHS comes from another lax conversion (e.g. binops between9456    // scalars and vectors) the result is canonicalized as a vector. When the9457    // LHS is also a vector, the lax is allowed by the condition above. Handle9458    // the case where LHS is a scalar.9459    if (LHSType->isScalarType()) {9460      const VectorType *VecType = RHSType->getAs<VectorType>();9461      if (VecType && VecType->getNumElements() == 1 &&9462          isLaxVectorConversion(RHSType, LHSType)) {9463        if (Context.getTargetInfo().getTriple().isPPC() &&9464            (VecType->getVectorKind() == VectorKind::AltiVecVector ||9465             VecType->getVectorKind() == VectorKind::AltiVecBool ||9466             VecType->getVectorKind() == VectorKind::AltiVecPixel))9467          Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)9468              << RHSType << LHSType;9469        ExprResult *VecExpr = &RHS;9470        *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);9471        Kind = CK_BitCast;9472        return AssignConvertType::Compatible;9473      }9474    }9475 9476    // Allow assignments between fixed-length and sizeless SVE vectors.9477    if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||9478        (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))9479      if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||9480          ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {9481        Kind = CK_BitCast;9482        return AssignConvertType::Compatible;9483      }9484 9485    // Allow assignments between fixed-length and sizeless RVV vectors.9486    if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||9487        (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {9488      if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||9489          Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {9490        Kind = CK_BitCast;9491        return AssignConvertType::Compatible;9492      }9493    }9494 9495    return AssignConvertType::Incompatible;9496  }9497 9498  // Diagnose attempts to convert between __ibm128, __float128 and long double9499  // where such conversions currently can't be handled.9500  if (unsupportedTypeConversion(*this, LHSType, RHSType))9501    return AssignConvertType::Incompatible;9502 9503  // Disallow assigning a _Complex to a real type in C++ mode since it simply9504  // discards the imaginary part.9505  if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&9506      !LHSType->getAs<ComplexType>())9507    return AssignConvertType::Incompatible;9508 9509  // Arithmetic conversions.9510  if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&9511      !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {9512    if (ConvertRHS)9513      Kind = PrepareScalarCast(RHS, LHSType);9514    return AssignConvertType::Compatible;9515  }9516 9517  // Conversions to normal pointers.9518  if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {9519    // U* -> T*9520    if (isa<PointerType>(RHSType)) {9521      LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();9522      LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();9523      if (AddrSpaceL != AddrSpaceR)9524        Kind = CK_AddressSpaceConversion;9525      else if (Context.hasCvrSimilarType(RHSType, LHSType))9526        Kind = CK_NoOp;9527      else9528        Kind = CK_BitCast;9529      return checkPointerTypesForAssignment(*this, LHSType, RHSType,9530                                            RHS.get()->getBeginLoc());9531    }9532 9533    // int -> T*9534    if (RHSType->isIntegerType()) {9535      Kind = CK_IntegralToPointer; // FIXME: null?9536      return AssignConvertType::IntToPointer;9537    }9538 9539    // C pointers are not compatible with ObjC object pointers,9540    // with two exceptions:9541    if (isa<ObjCObjectPointerType>(RHSType)) {9542      //  - conversions to void*9543      if (LHSPointer->getPointeeType()->isVoidType()) {9544        Kind = CK_BitCast;9545        return AssignConvertType::Compatible;9546      }9547 9548      //  - conversions from 'Class' to the redefinition type9549      if (RHSType->isObjCClassType() &&9550          Context.hasSameType(LHSType,9551                              Context.getObjCClassRedefinitionType())) {9552        Kind = CK_BitCast;9553        return AssignConvertType::Compatible;9554      }9555 9556      Kind = CK_BitCast;9557      return AssignConvertType::IncompatiblePointer;9558    }9559 9560    // U^ -> void*9561    if (RHSType->getAs<BlockPointerType>()) {9562      if (LHSPointer->getPointeeType()->isVoidType()) {9563        LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();9564        LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()9565                                ->getPointeeType()9566                                .getAddressSpace();9567        Kind =9568            AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;9569        return AssignConvertType::Compatible;9570      }9571    }9572 9573    return AssignConvertType::Incompatible;9574  }9575 9576  // Conversions to block pointers.9577  if (isa<BlockPointerType>(LHSType)) {9578    // U^ -> T^9579    if (RHSType->isBlockPointerType()) {9580      LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()9581                              ->getPointeeType()9582                              .getAddressSpace();9583      LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()9584                              ->getPointeeType()9585                              .getAddressSpace();9586      Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;9587      return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);9588    }9589 9590    // int or null -> T^9591    if (RHSType->isIntegerType()) {9592      Kind = CK_IntegralToPointer; // FIXME: null9593      return AssignConvertType::IntToBlockPointer;9594    }9595 9596    // id -> T^9597    if (getLangOpts().ObjC && RHSType->isObjCIdType()) {9598      Kind = CK_AnyPointerToBlockPointerCast;9599      return AssignConvertType::Compatible;9600    }9601 9602    // void* -> T^9603    if (const PointerType *RHSPT = RHSType->getAs<PointerType>())9604      if (RHSPT->getPointeeType()->isVoidType()) {9605        Kind = CK_AnyPointerToBlockPointerCast;9606        return AssignConvertType::Compatible;9607      }9608 9609    return AssignConvertType::Incompatible;9610  }9611 9612  // Conversions to Objective-C pointers.9613  if (isa<ObjCObjectPointerType>(LHSType)) {9614    // A* -> B*9615    if (RHSType->isObjCObjectPointerType()) {9616      Kind = CK_BitCast;9617      AssignConvertType result =9618          checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);9619      if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&9620          result == AssignConvertType::Compatible &&9621          !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))9622        result = AssignConvertType::IncompatibleObjCWeakRef;9623      return result;9624    }9625 9626    // int or null -> A*9627    if (RHSType->isIntegerType()) {9628      Kind = CK_IntegralToPointer; // FIXME: null9629      return AssignConvertType::IntToPointer;9630    }9631 9632    // In general, C pointers are not compatible with ObjC object pointers,9633    // with two exceptions:9634    if (isa<PointerType>(RHSType)) {9635      Kind = CK_CPointerToObjCPointerCast;9636 9637      //  - conversions from 'void*'9638      if (RHSType->isVoidPointerType()) {9639        return AssignConvertType::Compatible;9640      }9641 9642      //  - conversions to 'Class' from its redefinition type9643      if (LHSType->isObjCClassType() &&9644          Context.hasSameType(RHSType,9645                              Context.getObjCClassRedefinitionType())) {9646        return AssignConvertType::Compatible;9647      }9648 9649      return AssignConvertType::IncompatiblePointer;9650    }9651 9652    // Only under strict condition T^ is compatible with an Objective-C pointer.9653    if (RHSType->isBlockPointerType() &&9654        LHSType->isBlockCompatibleObjCPointerType(Context)) {9655      if (ConvertRHS)9656        maybeExtendBlockObject(RHS);9657      Kind = CK_BlockPointerToObjCPointerCast;9658      return AssignConvertType::Compatible;9659    }9660 9661    return AssignConvertType::Incompatible;9662  }9663 9664  // Conversion to nullptr_t (C23 only)9665  if (getLangOpts().C23 && LHSType->isNullPtrType() &&9666      RHS.get()->isNullPointerConstant(Context,9667                                       Expr::NPC_ValueDependentIsNull)) {9668    // null -> nullptr_t9669    Kind = CK_NullToPointer;9670    return AssignConvertType::Compatible;9671  }9672 9673  // Conversions from pointers that are not covered by the above.9674  if (isa<PointerType>(RHSType)) {9675    // T* -> _Bool9676    if (LHSType == Context.BoolTy) {9677      Kind = CK_PointerToBoolean;9678      return AssignConvertType::Compatible;9679    }9680 9681    // T* -> int9682    if (LHSType->isIntegerType()) {9683      Kind = CK_PointerToIntegral;9684      return AssignConvertType::PointerToInt;9685    }9686 9687    return AssignConvertType::Incompatible;9688  }9689 9690  // Conversions from Objective-C pointers that are not covered by the above.9691  if (isa<ObjCObjectPointerType>(RHSType)) {9692    // T* -> _Bool9693    if (LHSType == Context.BoolTy) {9694      Kind = CK_PointerToBoolean;9695      return AssignConvertType::Compatible;9696    }9697 9698    // T* -> int9699    if (LHSType->isIntegerType()) {9700      Kind = CK_PointerToIntegral;9701      return AssignConvertType::PointerToInt;9702    }9703 9704    return AssignConvertType::Incompatible;9705  }9706 9707  // struct A -> struct B9708  if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {9709    if (Context.typesAreCompatible(LHSType, RHSType)) {9710      Kind = CK_NoOp;9711      return AssignConvertType::Compatible;9712    }9713  }9714 9715  if (LHSType->isSamplerT() && RHSType->isIntegerType()) {9716    Kind = CK_IntToOCLSampler;9717    return AssignConvertType::Compatible;9718  }9719 9720  return AssignConvertType::Incompatible;9721}9722 9723/// Constructs a transparent union from an expression that is9724/// used to initialize the transparent union.9725static void ConstructTransparentUnion(Sema &S, ASTContext &C,9726                                      ExprResult &EResult, QualType UnionType,9727                                      FieldDecl *Field) {9728  // Build an initializer list that designates the appropriate member9729  // of the transparent union.9730  Expr *E = EResult.get();9731  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),9732                                                   E, SourceLocation());9733  Initializer->setType(UnionType);9734  Initializer->setInitializedFieldInUnion(Field);9735 9736  // Build a compound literal constructing a value of the transparent9737  // union type from this initializer list.9738  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);9739  EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,9740                                        VK_PRValue, Initializer, false);9741}9742 9743AssignConvertType9744Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,9745                                               ExprResult &RHS) {9746  QualType RHSType = RHS.get()->getType();9747 9748  // If the ArgType is a Union type, we want to handle a potential9749  // transparent_union GCC extension.9750  const RecordType *UT = ArgType->getAsUnionType();9751  if (!UT)9752    return AssignConvertType::Incompatible;9753 9754  RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();9755  if (!UD->hasAttr<TransparentUnionAttr>())9756    return AssignConvertType::Incompatible;9757 9758  // The field to initialize within the transparent union.9759  FieldDecl *InitField = nullptr;9760  // It's compatible if the expression matches any of the fields.9761  for (auto *it : UD->fields()) {9762    if (it->getType()->isPointerType()) {9763      // If the transparent union contains a pointer type, we allow:9764      // 1) void pointer9765      // 2) null pointer constant9766      if (RHSType->isPointerType())9767        if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {9768          RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);9769          InitField = it;9770          break;9771        }9772 9773      if (RHS.get()->isNullPointerConstant(Context,9774                                           Expr::NPC_ValueDependentIsNull)) {9775        RHS = ImpCastExprToType(RHS.get(), it->getType(),9776                                CK_NullToPointer);9777        InitField = it;9778        break;9779      }9780    }9781 9782    CastKind Kind;9783    if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==9784        AssignConvertType::Compatible) {9785      RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);9786      InitField = it;9787      break;9788    }9789  }9790 9791  if (!InitField)9792    return AssignConvertType::Incompatible;9793 9794  ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);9795  return AssignConvertType::Compatible;9796}9797 9798AssignConvertType Sema::CheckSingleAssignmentConstraints(QualType LHSType,9799                                                         ExprResult &CallerRHS,9800                                                         bool Diagnose,9801                                                         bool DiagnoseCFAudited,9802                                                         bool ConvertRHS) {9803  // We need to be able to tell the caller whether we diagnosed a problem, if9804  // they ask us to issue diagnostics.9805  assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");9806 9807  // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,9808  // we can't avoid *all* modifications at the moment, so we need some somewhere9809  // to put the updated value.9810  ExprResult LocalRHS = CallerRHS;9811  ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;9812 9813  if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {9814    if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {9815      if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&9816          !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {9817        Diag(RHS.get()->getExprLoc(),9818             diag::warn_noderef_to_dereferenceable_pointer)9819            << RHS.get()->getSourceRange();9820      }9821    }9822  }9823 9824  if (getLangOpts().CPlusPlus) {9825    if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {9826      // C++ 5.17p3: If the left operand is not of class type, the9827      // expression is implicitly converted (C++ 4) to the9828      // cv-unqualified type of the left operand.9829      QualType RHSType = RHS.get()->getType();9830      if (Diagnose) {9831        RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),9832                                        AssignmentAction::Assigning);9833      } else {9834        ImplicitConversionSequence ICS =9835            TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),9836                                  /*SuppressUserConversions=*/false,9837                                  AllowedExplicit::None,9838                                  /*InOverloadResolution=*/false,9839                                  /*CStyle=*/false,9840                                  /*AllowObjCWritebackConversion=*/false);9841        if (ICS.isFailure())9842          return AssignConvertType::Incompatible;9843        RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),9844                                        ICS, AssignmentAction::Assigning);9845      }9846      if (RHS.isInvalid())9847        return AssignConvertType::Incompatible;9848      AssignConvertType result = AssignConvertType::Compatible;9849      if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&9850          !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))9851        result = AssignConvertType::IncompatibleObjCWeakRef;9852      return result;9853    }9854 9855    // FIXME: Currently, we fall through and treat C++ classes like C9856    // structures.9857    // FIXME: We also fall through for atomics; not sure what should9858    // happen there, though.9859  } else if (RHS.get()->getType() == Context.OverloadTy) {9860    // As a set of extensions to C, we support overloading on functions. These9861    // functions need to be resolved here.9862    DeclAccessPair DAP;9863    if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(9864            RHS.get(), LHSType, /*Complain=*/false, DAP))9865      RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);9866    else9867      return AssignConvertType::Incompatible;9868  }9869 9870  // This check seems unnatural, however it is necessary to ensure the proper9871  // conversion of functions/arrays. If the conversion were done for all9872  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary9873  // expressions that suppress this implicit conversion (&, sizeof). This needs9874  // to happen before we check for null pointer conversions because C does not9875  // undergo the same implicit conversions as C++ does above (by the calls to9876  // TryImplicitConversion() and PerformImplicitConversion()) which insert the9877  // lvalue to rvalue cast before checking for null pointer constraints. This9878  // addresses code like: nullptr_t val; int *ptr; ptr = val;9879  //9880  // Suppress this for references: C++ 8.5.3p5.9881  if (!LHSType->isReferenceType()) {9882    // FIXME: We potentially allocate here even if ConvertRHS is false.9883    RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);9884    if (RHS.isInvalid())9885      return AssignConvertType::Incompatible;9886  }9887 9888  // The constraints are expressed in terms of the atomic, qualified, or9889  // unqualified type of the LHS.9890  QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();9891 9892  // C99 6.5.16.1p1: the left operand is a pointer and the right is9893  // a null pointer constant <C23>or its type is nullptr_t;</C23>.9894  if ((LHSTypeAfterConversion->isPointerType() ||9895       LHSTypeAfterConversion->isObjCObjectPointerType() ||9896       LHSTypeAfterConversion->isBlockPointerType()) &&9897      ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||9898       RHS.get()->isNullPointerConstant(Context,9899                                        Expr::NPC_ValueDependentIsNull))) {9900    AssignConvertType Ret = AssignConvertType::Compatible;9901    if (Diagnose || ConvertRHS) {9902      CastKind Kind;9903      CXXCastPath Path;9904      CheckPointerConversion(RHS.get(), LHSType, Kind, Path,9905                             /*IgnoreBaseAccess=*/false, Diagnose);9906 9907      // If there is a conversion of some kind, check to see what kind of9908      // pointer conversion happened so we can diagnose a C++ compatibility9909      // diagnostic if the conversion is invalid. This only matters if the RHS9910      // is some kind of void pointer. We have a carve-out when the RHS is from9911      // a macro expansion because the use of a macro may indicate different9912      // code between C and C++. Consider: char *s = NULL; where NULL is9913      // defined as (void *)0 in C (which would be invalid in C++), but 0 in9914      // C++, which is valid in C++.9915      if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&9916          !RHS.get()->getBeginLoc().isMacroID()) {9917        QualType CanRHS =9918            RHS.get()->getType().getCanonicalType().getUnqualifiedType();9919        QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();9920        if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {9921          Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,9922                                               RHS.get()->getExprLoc());9923          // Anything that's not considered perfectly compatible would be9924          // incompatible in C++.9925          if (Ret != AssignConvertType::Compatible)9926            Ret = AssignConvertType::CompatibleVoidPtrToNonVoidPtr;9927        }9928      }9929 9930      if (ConvertRHS)9931        RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);9932    }9933    return Ret;9934  }9935  // C23 6.5.16.1p1: the left operand has type atomic, qualified, or9936  // unqualified bool, and the right operand is a pointer or its type is9937  // nullptr_t.9938  if (getLangOpts().C23 && LHSType->isBooleanType() &&9939      RHS.get()->getType()->isNullPtrType()) {9940    // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only9941    // only handles nullptr -> _Bool due to needing an extra conversion9942    // step.9943    // We model this by converting from nullptr -> void * and then let the9944    // conversion from void * -> _Bool happen naturally.9945    if (Diagnose || ConvertRHS) {9946      CastKind Kind;9947      CXXCastPath Path;9948      CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,9949                             /*IgnoreBaseAccess=*/false, Diagnose);9950      if (ConvertRHS)9951        RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,9952                                &Path);9953    }9954  }9955 9956  // OpenCL queue_t type assignment.9957  if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(9958                                 Context, Expr::NPC_ValueDependentIsNull)) {9959    RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);9960    return AssignConvertType::Compatible;9961  }9962 9963  CastKind Kind;9964  AssignConvertType result =9965      CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);9966 9967  // If assigning a void * created by an allocation function call to some other9968  // type, check that the allocated size is sufficient for that type.9969  if (result != AssignConvertType::Incompatible &&9970      RHS.get()->getType()->isVoidPointerType())9971    CheckSufficientAllocSize(*this, LHSType, RHS.get());9972 9973  // C99 6.5.16.1p2: The value of the right operand is converted to the9974  // type of the assignment expression.9975  // CheckAssignmentConstraints allows the left-hand side to be a reference,9976  // so that we can use references in built-in functions even in C.9977  // The getNonReferenceType() call makes sure that the resulting expression9978  // does not have reference type.9979  if (result != AssignConvertType::Incompatible &&9980      RHS.get()->getType() != LHSType) {9981    QualType Ty = LHSType.getNonLValueExprType(Context);9982    Expr *E = RHS.get();9983 9984    // Check for various Objective-C errors. If we are not reporting9985    // diagnostics and just checking for errors, e.g., during overload9986    // resolution, return Incompatible to indicate the failure.9987    if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&9988        ObjC().CheckObjCConversion(SourceRange(), Ty, E,9989                                   CheckedConversionKind::Implicit, Diagnose,9990                                   DiagnoseCFAudited) != SemaObjC::ACR_okay) {9991      if (!Diagnose)9992        return AssignConvertType::Incompatible;9993    }9994    if (getLangOpts().ObjC &&9995        (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,9996                                                  E->getType(), E, Diagnose) ||9997         ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {9998      if (!Diagnose)9999        return AssignConvertType::Incompatible;10000      // Replace the expression with a corrected version and continue so we10001      // can find further errors.10002      RHS = E;10003      return AssignConvertType::Compatible;10004    }10005 10006    if (ConvertRHS)10007      RHS = ImpCastExprToType(E, Ty, Kind);10008  }10009 10010  return result;10011}10012 10013namespace {10014/// The original operand to an operator, prior to the application of the usual10015/// arithmetic conversions and converting the arguments of a builtin operator10016/// candidate.10017struct OriginalOperand {10018  explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {10019    if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))10020      Op = MTE->getSubExpr();10021    if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))10022      Op = BTE->getSubExpr();10023    if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {10024      Orig = ICE->getSubExprAsWritten();10025      Conversion = ICE->getConversionFunction();10026    }10027  }10028 10029  QualType getType() const { return Orig->getType(); }10030 10031  Expr *Orig;10032  NamedDecl *Conversion;10033};10034}10035 10036QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,10037                               ExprResult &RHS) {10038  OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());10039 10040  Diag(Loc, diag::err_typecheck_invalid_operands)10041    << OrigLHS.getType() << OrigRHS.getType()10042    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();10043 10044  // If a user-defined conversion was applied to either of the operands prior10045  // to applying the built-in operator rules, tell the user about it.10046  if (OrigLHS.Conversion) {10047    Diag(OrigLHS.Conversion->getLocation(),10048         diag::note_typecheck_invalid_operands_converted)10049      << 0 << LHS.get()->getType();10050  }10051  if (OrigRHS.Conversion) {10052    Diag(OrigRHS.Conversion->getLocation(),10053         diag::note_typecheck_invalid_operands_converted)10054      << 1 << RHS.get()->getType();10055  }10056 10057  return QualType();10058}10059 10060QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,10061                                            ExprResult &RHS) {10062  QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();10063  QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();10064 10065  bool LHSNatVec = LHSType->isVectorType();10066  bool RHSNatVec = RHSType->isVectorType();10067 10068  if (!(LHSNatVec && RHSNatVec)) {10069    Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();10070    Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();10071    Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)10072        << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()10073        << Vector->getSourceRange();10074    return QualType();10075  }10076 10077  Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)10078      << 1 << LHSType << RHSType << LHS.get()->getSourceRange()10079      << RHS.get()->getSourceRange();10080 10081  return QualType();10082}10083 10084/// Try to convert a value of non-vector type to a vector type by converting10085/// the type to the element type of the vector and then performing a splat.10086/// If the language is OpenCL, we only use conversions that promote scalar10087/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except10088/// for float->int.10089///10090/// OpenCL V2.0 6.2.6.p2:10091/// An error shall occur if any scalar operand type has greater rank10092/// than the type of the vector element.10093///10094/// \param scalar - if non-null, actually perform the conversions10095/// \return true if the operation fails (but without diagnosing the failure)10096static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,10097                                     QualType scalarTy,10098                                     QualType vectorEltTy,10099                                     QualType vectorTy,10100                                     unsigned &DiagID) {10101  // The conversion to apply to the scalar before splatting it,10102  // if necessary.10103  CastKind scalarCast = CK_NoOp;10104 10105  if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {10106    scalarCast = CK_IntegralToBoolean;10107  } else if (vectorEltTy->isIntegralType(S.Context)) {10108    if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||10109        (scalarTy->isIntegerType() &&10110         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {10111      DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;10112      return true;10113    }10114    if (!scalarTy->isIntegralType(S.Context))10115      return true;10116    scalarCast = CK_IntegralCast;10117  } else if (vectorEltTy->isRealFloatingType()) {10118    if (scalarTy->isRealFloatingType()) {10119      if (S.getLangOpts().OpenCL &&10120          S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {10121        DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;10122        return true;10123      }10124      scalarCast = CK_FloatingCast;10125    }10126    else if (scalarTy->isIntegralType(S.Context))10127      scalarCast = CK_IntegralToFloating;10128    else10129      return true;10130  } else {10131    return true;10132  }10133 10134  // Adjust scalar if desired.10135  if (scalar) {10136    if (scalarCast != CK_NoOp)10137      *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);10138    *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);10139  }10140  return false;10141}10142 10143/// Convert vector E to a vector with the same number of elements but different10144/// element type.10145static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {10146  const auto *VecTy = E->getType()->getAs<VectorType>();10147  assert(VecTy && "Expression E must be a vector");10148  QualType NewVecTy =10149      VecTy->isExtVectorType()10150          ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())10151          : S.Context.getVectorType(ElementType, VecTy->getNumElements(),10152                                    VecTy->getVectorKind());10153 10154  // Look through the implicit cast. Return the subexpression if its type is10155  // NewVecTy.10156  if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))10157    if (ICE->getSubExpr()->getType() == NewVecTy)10158      return ICE->getSubExpr();10159 10160  auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;10161  return S.ImpCastExprToType(E, NewVecTy, Cast);10162}10163 10164/// Test if a (constant) integer Int can be casted to another integer type10165/// IntTy without losing precision.10166static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,10167                                      QualType OtherIntTy) {10168  if (Int->get()->containsErrors())10169    return false;10170 10171  QualType IntTy = Int->get()->getType().getUnqualifiedType();10172 10173  // Reject cases where the value of the Int is unknown as that would10174  // possibly cause truncation, but accept cases where the scalar can be10175  // demoted without loss of precision.10176  Expr::EvalResult EVResult;10177  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);10178  int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);10179  bool IntSigned = IntTy->hasSignedIntegerRepresentation();10180  bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();10181 10182  if (CstInt) {10183    // If the scalar is constant and is of a higher order and has more active10184    // bits that the vector element type, reject it.10185    llvm::APSInt Result = EVResult.Val.getInt();10186    unsigned NumBits = IntSigned10187                           ? (Result.isNegative() ? Result.getSignificantBits()10188                                                  : Result.getActiveBits())10189                           : Result.getActiveBits();10190    if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)10191      return true;10192 10193    // If the signedness of the scalar type and the vector element type10194    // differs and the number of bits is greater than that of the vector10195    // element reject it.10196    return (IntSigned != OtherIntSigned &&10197            NumBits > S.Context.getIntWidth(OtherIntTy));10198  }10199 10200  // Reject cases where the value of the scalar is not constant and it's10201  // order is greater than that of the vector element type.10202  return (Order < 0);10203}10204 10205/// Test if a (constant) integer Int can be casted to floating point type10206/// FloatTy without losing precision.10207static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,10208                                     QualType FloatTy) {10209  if (Int->get()->containsErrors())10210    return false;10211 10212  QualType IntTy = Int->get()->getType().getUnqualifiedType();10213 10214  // Determine if the integer constant can be expressed as a floating point10215  // number of the appropriate type.10216  Expr::EvalResult EVResult;10217  bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);10218 10219  uint64_t Bits = 0;10220  if (CstInt) {10221    // Reject constants that would be truncated if they were converted to10222    // the floating point type. Test by simple to/from conversion.10223    // FIXME: Ideally the conversion to an APFloat and from an APFloat10224    //        could be avoided if there was a convertFromAPInt method10225    //        which could signal back if implicit truncation occurred.10226    llvm::APSInt Result = EVResult.Val.getInt();10227    llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));10228    Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),10229                           llvm::APFloat::rmTowardZero);10230    llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),10231                             !IntTy->hasSignedIntegerRepresentation());10232    bool Ignored = false;10233    Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,10234                           &Ignored);10235    if (Result != ConvertBack)10236      return true;10237  } else {10238    // Reject types that cannot be fully encoded into the mantissa of10239    // the float.10240    Bits = S.Context.getTypeSize(IntTy);10241    unsigned FloatPrec = llvm::APFloat::semanticsPrecision(10242        S.Context.getFloatTypeSemantics(FloatTy));10243    if (Bits > FloatPrec)10244      return true;10245  }10246 10247  return false;10248}10249 10250/// Attempt to convert and splat Scalar into a vector whose types matches10251/// Vector following GCC conversion rules. The rule is that implicit10252/// conversion can occur when Scalar can be casted to match Vector's element10253/// type without causing truncation of Scalar.10254static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,10255                                        ExprResult *Vector) {10256  QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();10257  QualType VectorTy = Vector->get()->getType().getUnqualifiedType();10258  QualType VectorEltTy;10259 10260  if (const auto *VT = VectorTy->getAs<VectorType>()) {10261    assert(!isa<ExtVectorType>(VT) &&10262           "ExtVectorTypes should not be handled here!");10263    VectorEltTy = VT->getElementType();10264  } else if (VectorTy->isSveVLSBuiltinType()) {10265    VectorEltTy =10266        VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());10267  } else {10268    llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");10269  }10270 10271  // Reject cases where the vector element type or the scalar element type are10272  // not integral or floating point types.10273  if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())10274    return true;10275 10276  // The conversion to apply to the scalar before splatting it,10277  // if necessary.10278  CastKind ScalarCast = CK_NoOp;10279 10280  // Accept cases where the vector elements are integers and the scalar is10281  // an integer.10282  // FIXME: Notionally if the scalar was a floating point value with a precise10283  //        integral representation, we could cast it to an appropriate integer10284  //        type and then perform the rest of the checks here. GCC will perform10285  //        this conversion in some cases as determined by the input language.10286  //        We should accept it on a language independent basis.10287  if (VectorEltTy->isIntegralType(S.Context) &&10288      ScalarTy->isIntegralType(S.Context) &&10289      S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {10290 10291    if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))10292      return true;10293 10294    ScalarCast = CK_IntegralCast;10295  } else if (VectorEltTy->isIntegralType(S.Context) &&10296             ScalarTy->isRealFloatingType()) {10297    if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))10298      ScalarCast = CK_FloatingToIntegral;10299    else10300      return true;10301  } else if (VectorEltTy->isRealFloatingType()) {10302    if (ScalarTy->isRealFloatingType()) {10303 10304      // Reject cases where the scalar type is not a constant and has a higher10305      // Order than the vector element type.10306      llvm::APFloat Result(0.0);10307 10308      // Determine whether this is a constant scalar. In the event that the10309      // value is dependent (and thus cannot be evaluated by the constant10310      // evaluator), skip the evaluation. This will then diagnose once the10311      // expression is instantiated.10312      bool CstScalar = Scalar->get()->isValueDependent() ||10313                       Scalar->get()->EvaluateAsFloat(Result, S.Context);10314      int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);10315      if (!CstScalar && Order < 0)10316        return true;10317 10318      // If the scalar cannot be safely casted to the vector element type,10319      // reject it.10320      if (CstScalar) {10321        bool Truncated = false;10322        Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),10323                       llvm::APFloat::rmNearestTiesToEven, &Truncated);10324        if (Truncated)10325          return true;10326      }10327 10328      ScalarCast = CK_FloatingCast;10329    } else if (ScalarTy->isIntegralType(S.Context)) {10330      if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))10331        return true;10332 10333      ScalarCast = CK_IntegralToFloating;10334    } else10335      return true;10336  } else if (ScalarTy->isEnumeralType())10337    return true;10338 10339  // Adjust scalar if desired.10340  if (ScalarCast != CK_NoOp)10341    *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);10342  *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);10343  return false;10344}10345 10346QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,10347                                   SourceLocation Loc, bool IsCompAssign,10348                                   bool AllowBothBool,10349                                   bool AllowBoolConversions,10350                                   bool AllowBoolOperation,10351                                   bool ReportInvalid) {10352  if (!IsCompAssign) {10353    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());10354    if (LHS.isInvalid())10355      return QualType();10356  }10357  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());10358  if (RHS.isInvalid())10359    return QualType();10360 10361  // For conversion purposes, we ignore any qualifiers.10362  // For example, "const float" and "float" are equivalent.10363  QualType LHSType = LHS.get()->getType().getUnqualifiedType();10364  QualType RHSType = RHS.get()->getType().getUnqualifiedType();10365 10366  const VectorType *LHSVecType = LHSType->getAs<VectorType>();10367  const VectorType *RHSVecType = RHSType->getAs<VectorType>();10368  assert(LHSVecType || RHSVecType);10369 10370  if (getLangOpts().HLSL)10371    return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,10372                                              IsCompAssign);10373 10374  // Any operation with MFloat8 type is only possible with C intrinsics10375  if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||10376      (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))10377    return InvalidOperands(Loc, LHS, RHS);10378 10379  // AltiVec-style "vector bool op vector bool" combinations are allowed10380  // for some operators but not others.10381  if (!AllowBothBool && LHSVecType &&10382      LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&10383      RHSVecType->getVectorKind() == VectorKind::AltiVecBool)10384    return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();10385 10386  // This operation may not be performed on boolean vectors.10387  if (!AllowBoolOperation &&10388      (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))10389    return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();10390 10391  // If the vector types are identical, return.10392  if (Context.hasSameType(LHSType, RHSType))10393    return Context.getCommonSugaredType(LHSType, RHSType);10394 10395  // If we have compatible AltiVec and GCC vector types, use the AltiVec type.10396  if (LHSVecType && RHSVecType &&10397      Context.areCompatibleVectorTypes(LHSType, RHSType)) {10398    if (isa<ExtVectorType>(LHSVecType)) {10399      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);10400      return LHSType;10401    }10402 10403    if (!IsCompAssign)10404      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);10405    return RHSType;10406  }10407 10408  // AllowBoolConversions says that bool and non-bool AltiVec vectors10409  // can be mixed, with the result being the non-bool type.  The non-bool10410  // operand must have integer element type.10411  if (AllowBoolConversions && LHSVecType && RHSVecType &&10412      LHSVecType->getNumElements() == RHSVecType->getNumElements() &&10413      (Context.getTypeSize(LHSVecType->getElementType()) ==10414       Context.getTypeSize(RHSVecType->getElementType()))) {10415    if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&10416        LHSVecType->getElementType()->isIntegerType() &&10417        RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {10418      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);10419      return LHSType;10420    }10421    if (!IsCompAssign &&10422        LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&10423        RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&10424        RHSVecType->getElementType()->isIntegerType()) {10425      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);10426      return RHSType;10427    }10428  }10429 10430  // Expressions containing fixed-length and sizeless SVE/RVV vectors are10431  // invalid since the ambiguity can affect the ABI.10432  auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,10433                               unsigned &SVEorRVV) {10434    const VectorType *VecType = SecondType->getAs<VectorType>();10435    SVEorRVV = 0;10436    if (FirstType->isSizelessBuiltinType() && VecType) {10437      if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||10438          VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)10439        return true;10440      if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||10441          VecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||10442          VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_1 ||10443          VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_2 ||10444          VecType->getVectorKind() == VectorKind::RVVFixedLengthMask_4) {10445        SVEorRVV = 1;10446        return true;10447      }10448    }10449 10450    return false;10451  };10452 10453  unsigned SVEorRVV;10454  if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||10455      IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {10456    Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)10457        << SVEorRVV << LHSType << RHSType;10458    return QualType();10459  }10460 10461  // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are10462  // invalid since the ambiguity can affect the ABI.10463  auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,10464                                  unsigned &SVEorRVV) {10465    const VectorType *FirstVecType = FirstType->getAs<VectorType>();10466    const VectorType *SecondVecType = SecondType->getAs<VectorType>();10467 10468    SVEorRVV = 0;10469    if (FirstVecType && SecondVecType) {10470      if (FirstVecType->getVectorKind() == VectorKind::Generic) {10471        if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||10472            SecondVecType->getVectorKind() ==10473                VectorKind::SveFixedLengthPredicate)10474          return true;10475        if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||10476            SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||10477            SecondVecType->getVectorKind() ==10478                VectorKind::RVVFixedLengthMask_1 ||10479            SecondVecType->getVectorKind() ==10480                VectorKind::RVVFixedLengthMask_2 ||10481            SecondVecType->getVectorKind() ==10482                VectorKind::RVVFixedLengthMask_4) {10483          SVEorRVV = 1;10484          return true;10485        }10486      }10487      return false;10488    }10489 10490    if (SecondVecType &&10491        SecondVecType->getVectorKind() == VectorKind::Generic) {10492      if (FirstType->isSVESizelessBuiltinType())10493        return true;10494      if (FirstType->isRVVSizelessBuiltinType()) {10495        SVEorRVV = 1;10496        return true;10497      }10498    }10499 10500    return false;10501  };10502 10503  if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||10504      IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {10505    Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)10506        << SVEorRVV << LHSType << RHSType;10507    return QualType();10508  }10509 10510  // If there's a vector type and a scalar, try to convert the scalar to10511  // the vector element type and splat.10512  unsigned DiagID = diag::err_typecheck_vector_not_convertable;10513  if (!RHSVecType) {10514    if (isa<ExtVectorType>(LHSVecType)) {10515      if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,10516                                    LHSVecType->getElementType(), LHSType,10517                                    DiagID))10518        return LHSType;10519    } else {10520      if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))10521        return LHSType;10522    }10523  }10524  if (!LHSVecType) {10525    if (isa<ExtVectorType>(RHSVecType)) {10526      if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),10527                                    LHSType, RHSVecType->getElementType(),10528                                    RHSType, DiagID))10529        return RHSType;10530    } else {10531      if (LHS.get()->isLValue() ||10532          !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))10533        return RHSType;10534    }10535  }10536 10537  // FIXME: The code below also handles conversion between vectors and10538  // non-scalars, we should break this down into fine grained specific checks10539  // and emit proper diagnostics.10540  QualType VecType = LHSVecType ? LHSType : RHSType;10541  const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;10542  QualType OtherType = LHSVecType ? RHSType : LHSType;10543  ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;10544  if (isLaxVectorConversion(OtherType, VecType)) {10545    if (Context.getTargetInfo().getTriple().isPPC() &&10546        anyAltivecTypes(RHSType, LHSType) &&10547        !Context.areCompatibleVectorTypes(RHSType, LHSType))10548      Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;10549    // If we're allowing lax vector conversions, only the total (data) size10550    // needs to be the same. For non compound assignment, if one of the types is10551    // scalar, the result is always the vector type.10552    if (!IsCompAssign) {10553      *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);10554      return VecType;10555    // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding10556    // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'10557    // type. Note that this is already done by non-compound assignments in10558    // CheckAssignmentConstraints. If it's a scalar type, only bitcast for10559    // <1 x T> -> T. The result is also a vector type.10560    } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||10561               (OtherType->isScalarType() && VT->getNumElements() == 1)) {10562      ExprResult *RHSExpr = &RHS;10563      *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);10564      return VecType;10565    }10566  }10567 10568  // Okay, the expression is invalid.10569 10570  // If there's a non-vector, non-real operand, diagnose that.10571  if ((!RHSVecType && !RHSType->isRealType()) ||10572      (!LHSVecType && !LHSType->isRealType())) {10573    Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)10574      << LHSType << RHSType10575      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();10576    return QualType();10577  }10578 10579  // OpenCL V1.1 6.2.6.p1:10580  // If the operands are of more than one vector type, then an error shall10581  // occur. Implicit conversions between vector types are not permitted, per10582  // section 6.2.1.10583  if (getLangOpts().OpenCL &&10584      RHSVecType && isa<ExtVectorType>(RHSVecType) &&10585      LHSVecType && isa<ExtVectorType>(LHSVecType)) {10586    Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType10587                                                           << RHSType;10588    return QualType();10589  }10590 10591 10592  // If there is a vector type that is not a ExtVector and a scalar, we reach10593  // this point if scalar could not be converted to the vector's element type10594  // without truncation.10595  if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||10596      (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {10597    QualType Scalar = LHSVecType ? RHSType : LHSType;10598    QualType Vector = LHSVecType ? LHSType : RHSType;10599    unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;10600    Diag(Loc,10601         diag::err_typecheck_vector_not_convertable_implict_truncation)10602        << ScalarOrVector << Scalar << Vector;10603 10604    return QualType();10605  }10606 10607  // Otherwise, use the generic diagnostic.10608  Diag(Loc, DiagID)10609    << LHSType << RHSType10610    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();10611  return QualType();10612}10613 10614QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,10615                                           SourceLocation Loc,10616                                           bool IsCompAssign,10617                                           ArithConvKind OperationKind) {10618  if (!IsCompAssign) {10619    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());10620    if (LHS.isInvalid())10621      return QualType();10622  }10623  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());10624  if (RHS.isInvalid())10625    return QualType();10626 10627  QualType LHSType = LHS.get()->getType().getUnqualifiedType();10628  QualType RHSType = RHS.get()->getType().getUnqualifiedType();10629 10630  const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();10631  const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();10632 10633  unsigned DiagID = diag::err_typecheck_invalid_operands;10634  if ((OperationKind == ArithConvKind::Arithmetic) &&10635      ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||10636       (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {10637    Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()10638                      << RHS.get()->getSourceRange();10639    return QualType();10640  }10641 10642  if (Context.hasSameType(LHSType, RHSType))10643    return LHSType;10644 10645  if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {10646    if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))10647      return LHSType;10648  }10649  if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {10650    if (LHS.get()->isLValue() ||10651        !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))10652      return RHSType;10653  }10654 10655  if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||10656      (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {10657    Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)10658        << LHSType << RHSType << LHS.get()->getSourceRange()10659        << RHS.get()->getSourceRange();10660    return QualType();10661  }10662 10663  if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&10664      Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=10665          Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {10666    Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)10667        << LHSType << RHSType << LHS.get()->getSourceRange()10668        << RHS.get()->getSourceRange();10669    return QualType();10670  }10671 10672  if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {10673    QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;10674    QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;10675    bool ScalarOrVector =10676        LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();10677 10678    Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)10679        << ScalarOrVector << Scalar << Vector;10680 10681    return QualType();10682  }10683 10684  Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()10685                    << RHS.get()->getSourceRange();10686  return QualType();10687}10688 10689// checkArithmeticNull - Detect when a NULL constant is used improperly in an10690// expression.  These are mainly cases where the null pointer is used as an10691// integer instead of a pointer.10692static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,10693                                SourceLocation Loc, bool IsCompare) {10694  // The canonical way to check for a GNU null is with isNullPointerConstant,10695  // but we use a bit of a hack here for speed; this is a relatively10696  // hot path, and isNullPointerConstant is slow.10697  bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());10698  bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());10699 10700  QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();10701 10702  // Avoid analyzing cases where the result will either be invalid (and10703  // diagnosed as such) or entirely valid and not something to warn about.10704  if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||10705      NonNullType->isMemberPointerType() || NonNullType->isFunctionType())10706    return;10707 10708  // Comparison operations would not make sense with a null pointer no matter10709  // what the other expression is.10710  if (!IsCompare) {10711    S.Diag(Loc, diag::warn_null_in_arithmetic_operation)10712        << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())10713        << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());10714    return;10715  }10716 10717  // The rest of the operations only make sense with a null pointer10718  // if the other expression is a pointer.10719  if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||10720      NonNullType->canDecayToPointerType())10721    return;10722 10723  S.Diag(Loc, diag::warn_null_in_comparison_operation)10724      << LHSNull /* LHS is NULL */ << NonNullType10725      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();10726}10727 10728static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy,10729                                                 SourceLocation OpLoc) {10730  // If the divisor is real, then this is real/real or complex/real division.10731  // Either way there can be no precision loss.10732  auto *CT = DivisorTy->getAs<ComplexType>();10733  if (!CT)10734    return;10735 10736  QualType ElementType = CT->getElementType().getCanonicalType();10737  bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==10738                                LangOptions::ComplexRangeKind::CX_Promoted;10739  if (!ElementType->isFloatingType() || !IsComplexRangePromoted)10740    return;10741 10742  ASTContext &Ctx = S.getASTContext();10743  QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);10744  const llvm::fltSemantics &ElementTypeSemantics =10745      Ctx.getFloatTypeSemantics(ElementType);10746  const llvm::fltSemantics &HigherElementTypeSemantics =10747      Ctx.getFloatTypeSemantics(HigherElementType);10748 10749  if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >10750       llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||10751      (HigherElementType == Ctx.LongDoubleTy &&10752       !Ctx.getTargetInfo().hasLongDoubleType())) {10753    // Retain the location of the first use of higher precision type.10754    if (!S.LocationOfExcessPrecisionNotSatisfied.isValid())10755      S.LocationOfExcessPrecisionNotSatisfied = OpLoc;10756    for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {10757      if (Type == HigherElementType) {10758        Num++;10759        return;10760      }10761    }10762    S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(10763        HigherElementType, S.ExcessPrecisionNotSatisfied.size()));10764  }10765}10766 10767static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,10768                                          SourceLocation Loc) {10769  const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);10770  const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);10771  if (!LUE || !RUE)10772    return;10773  if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||10774      RUE->getKind() != UETT_SizeOf)10775    return;10776 10777  const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();10778  QualType LHSTy = LHSArg->getType();10779  QualType RHSTy;10780 10781  if (RUE->isArgumentType())10782    RHSTy = RUE->getArgumentType().getNonReferenceType();10783  else10784    RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();10785 10786  if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {10787    if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))10788      return;10789 10790    S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();10791    if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {10792      if (const ValueDecl *LHSArgDecl = DRE->getDecl())10793        S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)10794            << LHSArgDecl;10795    }10796  } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {10797    QualType ArrayElemTy = ArrayTy->getElementType();10798    if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||10799        ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||10800        RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||10801        S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))10802      return;10803    S.Diag(Loc, diag::warn_division_sizeof_array)10804        << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;10805    if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {10806      if (const ValueDecl *LHSArgDecl = DRE->getDecl())10807        S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)10808            << LHSArgDecl;10809    }10810 10811    S.Diag(Loc, diag::note_precedence_silence) << RHS;10812  }10813}10814 10815static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,10816                                               ExprResult &RHS,10817                                               SourceLocation Loc, bool IsDiv) {10818  // Check for division/remainder by zero.10819  Expr::EvalResult RHSValue;10820  if (!RHS.get()->isValueDependent() &&10821      RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&10822      RHSValue.Val.getInt() == 0)10823    S.DiagRuntimeBehavior(Loc, RHS.get(),10824                          S.PDiag(diag::warn_remainder_division_by_zero)10825                            << IsDiv << RHS.get()->getSourceRange());10826}10827 10828static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,10829                                const ExprResult &LHS, const ExprResult &RHS,10830                                BinaryOperatorKind Opc) {10831  if (!LHS.isUsable() || !RHS.isUsable())10832    return;10833  const Expr *LHSExpr = LHS.get();10834  const Expr *RHSExpr = RHS.get();10835  const QualType LHSType = LHSExpr->getType();10836  const QualType RHSType = RHSExpr->getType();10837  const bool LHSIsScoped = LHSType->isScopedEnumeralType();10838  const bool RHSIsScoped = RHSType->isScopedEnumeralType();10839  if (!LHSIsScoped && !RHSIsScoped)10840    return;10841  if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)10842    return;10843  if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())10844    return;10845  if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())10846    return;10847  auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {10848    SourceLocation BeginLoc = expr->getBeginLoc();10849    QualType IntType = type->castAs<EnumType>()10850                           ->getDecl()10851                           ->getDefinitionOrSelf()10852                           ->getIntegerType();10853    std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";10854    S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)10855        << FixItHint::CreateInsertion(BeginLoc, InsertionString)10856        << FixItHint::CreateInsertion(expr->getEndLoc(), ")");10857  };10858  if (LHSIsScoped) {10859    DiagnosticHelper(LHSExpr, LHSType);10860  }10861  if (RHSIsScoped) {10862    DiagnosticHelper(RHSExpr, RHSType);10863  }10864}10865 10866QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,10867                                           SourceLocation Loc,10868                                           BinaryOperatorKind Opc) {10869  bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;10870  bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;10871 10872  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);10873 10874  QualType LHSTy = LHS.get()->getType();10875  QualType RHSTy = RHS.get()->getType();10876  if (LHSTy->isVectorType() || RHSTy->isVectorType())10877    return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,10878                               /*AllowBothBool*/ getLangOpts().AltiVec,10879                               /*AllowBoolConversions*/ false,10880                               /*AllowBooleanOperation*/ false,10881                               /*ReportInvalid*/ true);10882  if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())10883    return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,10884                                       ArithConvKind::Arithmetic);10885  if (!IsDiv &&10886      (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))10887    return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);10888  // For division, only matrix-by-scalar is supported. Other combinations with10889  // matrix types are invalid.10890  if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())10891    return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);10892 10893  QualType compType = UsualArithmeticConversions(10894      LHS, RHS, Loc,10895      IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);10896  if (LHS.isInvalid() || RHS.isInvalid())10897    return QualType();10898 10899  if (compType.isNull() || !compType->isArithmeticType()) {10900    QualType ResultTy = InvalidOperands(Loc, LHS, RHS);10901    diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);10902    return ResultTy;10903  }10904  if (IsDiv) {10905    DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);10906    DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);10907    DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);10908  }10909  return compType;10910}10911 10912QualType Sema::CheckRemainderOperands(10913  ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {10914  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);10915 10916  // Note: This check is here to simplify the double exclusions of10917  // scalar and vector HLSL checks. No getLangOpts().HLSL10918  // is needed since all languages exlcude doubles.10919  if (LHS.get()->getType()->isDoubleType() ||10920      RHS.get()->getType()->isDoubleType() ||10921      (LHS.get()->getType()->isVectorType() && LHS.get()10922                                                   ->getType()10923                                                   ->getAs<VectorType>()10924                                                   ->getElementType()10925                                                   ->isDoubleType()) ||10926      (RHS.get()->getType()->isVectorType() && RHS.get()10927                                                   ->getType()10928                                                   ->getAs<VectorType>()10929                                                   ->getElementType()10930                                                   ->isDoubleType()))10931    return InvalidOperands(Loc, LHS, RHS);10932 10933  if (LHS.get()->getType()->isVectorType() ||10934      RHS.get()->getType()->isVectorType()) {10935    if ((LHS.get()->getType()->hasIntegerRepresentation() &&10936         RHS.get()->getType()->hasIntegerRepresentation()) ||10937        (getLangOpts().HLSL &&10938         (LHS.get()->getType()->hasFloatingRepresentation() ||10939          RHS.get()->getType()->hasFloatingRepresentation())))10940      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,10941                                 /*AllowBothBool*/ getLangOpts().AltiVec,10942                                 /*AllowBoolConversions*/ false,10943                                 /*AllowBooleanOperation*/ false,10944                                 /*ReportInvalid*/ true);10945    return InvalidOperands(Loc, LHS, RHS);10946  }10947 10948  if (LHS.get()->getType()->isSveVLSBuiltinType() ||10949      RHS.get()->getType()->isSveVLSBuiltinType()) {10950    if (LHS.get()->getType()->hasIntegerRepresentation() &&10951        RHS.get()->getType()->hasIntegerRepresentation())10952      return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,10953                                         ArithConvKind::Arithmetic);10954 10955    return InvalidOperands(Loc, LHS, RHS);10956  }10957 10958  QualType compType = UsualArithmeticConversions(10959      LHS, RHS, Loc,10960      IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);10961  if (LHS.isInvalid() || RHS.isInvalid())10962    return QualType();10963 10964  if (compType.isNull() ||10965      (!compType->isIntegerType() &&10966       !(getLangOpts().HLSL && compType->isFloatingType()))) {10967    QualType ResultTy = InvalidOperands(Loc, LHS, RHS);10968    diagnoseScopedEnums(*this, Loc, LHS, RHS,10969                        IsCompAssign ? BO_RemAssign : BO_Rem);10970    return ResultTy;10971  }10972  DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);10973  return compType;10974}10975 10976/// Diagnose invalid arithmetic on two void pointers.10977static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,10978                                                Expr *LHSExpr, Expr *RHSExpr) {10979  S.Diag(Loc, S.getLangOpts().CPlusPlus10980                ? diag::err_typecheck_pointer_arith_void_type10981                : diag::ext_gnu_void_ptr)10982    << 1 /* two pointers */ << LHSExpr->getSourceRange()10983                            << RHSExpr->getSourceRange();10984}10985 10986/// Diagnose invalid arithmetic on a void pointer.10987static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,10988                                            Expr *Pointer) {10989  S.Diag(Loc, S.getLangOpts().CPlusPlus10990                ? diag::err_typecheck_pointer_arith_void_type10991                : diag::ext_gnu_void_ptr)10992    << 0 /* one pointer */ << Pointer->getSourceRange();10993}10994 10995/// Diagnose invalid arithmetic on a null pointer.10996///10997/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'10998/// idiom, which we recognize as a GNU extension.10999///11000static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,11001                                            Expr *Pointer, bool IsGNUIdiom) {11002  if (IsGNUIdiom)11003    S.Diag(Loc, diag::warn_gnu_null_ptr_arith)11004      << Pointer->getSourceRange();11005  else11006    S.Diag(Loc, diag::warn_pointer_arith_null_ptr)11007      << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();11008}11009 11010/// Diagnose invalid subraction on a null pointer.11011///11012static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,11013                                             Expr *Pointer, bool BothNull) {11014  // Null - null is valid in C++ [expr.add]p711015  if (BothNull && S.getLangOpts().CPlusPlus)11016    return;11017 11018  // Is this s a macro from a system header?11019  if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(Loc))11020    return;11021 11022  S.DiagRuntimeBehavior(Loc, Pointer,11023                        S.PDiag(diag::warn_pointer_sub_null_ptr)11024                            << S.getLangOpts().CPlusPlus11025                            << Pointer->getSourceRange());11026}11027 11028/// Diagnose invalid arithmetic on two function pointers.11029static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,11030                                                    Expr *LHS, Expr *RHS) {11031  assert(LHS->getType()->isAnyPointerType());11032  assert(RHS->getType()->isAnyPointerType());11033  S.Diag(Loc, S.getLangOpts().CPlusPlus11034                ? diag::err_typecheck_pointer_arith_function_type11035                : diag::ext_gnu_ptr_func_arith)11036    << 1 /* two pointers */ << LHS->getType()->getPointeeType()11037    // We only show the second type if it differs from the first.11038    << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),11039                                                   RHS->getType())11040    << RHS->getType()->getPointeeType()11041    << LHS->getSourceRange() << RHS->getSourceRange();11042}11043 11044/// Diagnose invalid arithmetic on a function pointer.11045static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,11046                                                Expr *Pointer) {11047  assert(Pointer->getType()->isAnyPointerType());11048  S.Diag(Loc, S.getLangOpts().CPlusPlus11049                ? diag::err_typecheck_pointer_arith_function_type11050                : diag::ext_gnu_ptr_func_arith)11051    << 0 /* one pointer */ << Pointer->getType()->getPointeeType()11052    << 0 /* one pointer, so only one type */11053    << Pointer->getSourceRange();11054}11055 11056/// Emit error if Operand is incomplete pointer type11057///11058/// \returns True if pointer has incomplete type11059static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,11060                                                 Expr *Operand) {11061  QualType ResType = Operand->getType();11062  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())11063    ResType = ResAtomicType->getValueType();11064 11065  assert(ResType->isAnyPointerType());11066  QualType PointeeTy = ResType->getPointeeType();11067  return S.RequireCompleteSizedType(11068      Loc, PointeeTy,11069      diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,11070      Operand->getSourceRange());11071}11072 11073/// Check the validity of an arithmetic pointer operand.11074///11075/// If the operand has pointer type, this code will check for pointer types11076/// which are invalid in arithmetic operations. These will be diagnosed11077/// appropriately, including whether or not the use is supported as an11078/// extension.11079///11080/// \returns True when the operand is valid to use (even if as an extension).11081static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,11082                                            Expr *Operand) {11083  QualType ResType = Operand->getType();11084  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())11085    ResType = ResAtomicType->getValueType();11086 11087  if (!ResType->isAnyPointerType()) return true;11088 11089  QualType PointeeTy = ResType->getPointeeType();11090  if (PointeeTy->isVoidType()) {11091    diagnoseArithmeticOnVoidPointer(S, Loc, Operand);11092    return !S.getLangOpts().CPlusPlus;11093  }11094  if (PointeeTy->isFunctionType()) {11095    diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);11096    return !S.getLangOpts().CPlusPlus;11097  }11098 11099  if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;11100 11101  return true;11102}11103 11104/// Check the validity of a binary arithmetic operation w.r.t. pointer11105/// operands.11106///11107/// This routine will diagnose any invalid arithmetic on pointer operands much11108/// like \see checkArithmeticOpPointerOperand. However, it has special logic11109/// for emitting a single diagnostic even for operations where both LHS and RHS11110/// are (potentially problematic) pointers.11111///11112/// \returns True when the operand is valid to use (even if as an extension).11113static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,11114                                                Expr *LHSExpr, Expr *RHSExpr) {11115  bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();11116  bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();11117  if (!isLHSPointer && !isRHSPointer) return true;11118 11119  QualType LHSPointeeTy, RHSPointeeTy;11120  if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();11121  if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();11122 11123  // if both are pointers check if operation is valid wrt address spaces11124  if (isLHSPointer && isRHSPointer) {11125    if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,11126                                                S.getASTContext())) {11127      S.Diag(Loc,11128             diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)11129          << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/11130          << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();11131      return false;11132    }11133  }11134 11135  // Check for arithmetic on pointers to incomplete types.11136  bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();11137  bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();11138  if (isLHSVoidPtr || isRHSVoidPtr) {11139    if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);11140    else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);11141    else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);11142 11143    return !S.getLangOpts().CPlusPlus;11144  }11145 11146  bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();11147  bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();11148  if (isLHSFuncPtr || isRHSFuncPtr) {11149    if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);11150    else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,11151                                                                RHSExpr);11152    else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);11153 11154    return !S.getLangOpts().CPlusPlus;11155  }11156 11157  if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))11158    return false;11159  if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))11160    return false;11161 11162  return true;11163}11164 11165/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string11166/// literal.11167static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,11168                                  Expr *LHSExpr, Expr *RHSExpr) {11169  StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());11170  Expr* IndexExpr = RHSExpr;11171  if (!StrExpr) {11172    StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());11173    IndexExpr = LHSExpr;11174  }11175 11176  bool IsStringPlusInt = StrExpr &&11177      IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();11178  if (!IsStringPlusInt || IndexExpr->isValueDependent())11179    return;11180 11181  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());11182  Self.Diag(OpLoc, diag::warn_string_plus_int)11183      << DiagRange << IndexExpr->IgnoreImpCasts()->getType();11184 11185  // Only print a fixit for "str" + int, not for int + "str".11186  if (IndexExpr == RHSExpr) {11187    SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());11188    Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)11189        << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")11190        << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")11191        << FixItHint::CreateInsertion(EndLoc, "]");11192  } else11193    Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);11194}11195 11196/// Emit a warning when adding a char literal to a string.11197static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,11198                                   Expr *LHSExpr, Expr *RHSExpr) {11199  const Expr *StringRefExpr = LHSExpr;11200  const CharacterLiteral *CharExpr =11201      dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());11202 11203  if (!CharExpr) {11204    CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());11205    StringRefExpr = RHSExpr;11206  }11207 11208  if (!CharExpr || !StringRefExpr)11209    return;11210 11211  const QualType StringType = StringRefExpr->getType();11212 11213  // Return if not a PointerType.11214  if (!StringType->isAnyPointerType())11215    return;11216 11217  // Return if not a CharacterType.11218  if (!StringType->getPointeeType()->isAnyCharacterType())11219    return;11220 11221  ASTContext &Ctx = Self.getASTContext();11222  SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());11223 11224  const QualType CharType = CharExpr->getType();11225  if (!CharType->isAnyCharacterType() &&11226      CharType->isIntegerType() &&11227      llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {11228    Self.Diag(OpLoc, diag::warn_string_plus_char)11229        << DiagRange << Ctx.CharTy;11230  } else {11231    Self.Diag(OpLoc, diag::warn_string_plus_char)11232        << DiagRange << CharExpr->getType();11233  }11234 11235  // Only print a fixit for str + char, not for char + str.11236  if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {11237    SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());11238    Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)11239        << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")11240        << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")11241        << FixItHint::CreateInsertion(EndLoc, "]");11242  } else {11243    Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);11244  }11245}11246 11247/// Emit error when two pointers are incompatible.11248static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,11249                                           Expr *LHSExpr, Expr *RHSExpr) {11250  assert(LHSExpr->getType()->isAnyPointerType());11251  assert(RHSExpr->getType()->isAnyPointerType());11252  S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)11253    << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()11254    << RHSExpr->getSourceRange();11255}11256 11257// C99 6.5.611258QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,11259                                     SourceLocation Loc, BinaryOperatorKind Opc,11260                                     QualType* CompLHSTy) {11261  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);11262 11263  if (LHS.get()->getType()->isVectorType() ||11264      RHS.get()->getType()->isVectorType()) {11265    QualType compType =11266        CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,11267                            /*AllowBothBool*/ getLangOpts().AltiVec,11268                            /*AllowBoolConversions*/ getLangOpts().ZVector,11269                            /*AllowBooleanOperation*/ false,11270                            /*ReportInvalid*/ true);11271    if (CompLHSTy) *CompLHSTy = compType;11272    return compType;11273  }11274 11275  if (LHS.get()->getType()->isSveVLSBuiltinType() ||11276      RHS.get()->getType()->isSveVLSBuiltinType()) {11277    QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,11278                                                    ArithConvKind::Arithmetic);11279    if (CompLHSTy)11280      *CompLHSTy = compType;11281    return compType;11282  }11283 11284  if (LHS.get()->getType()->isConstantMatrixType() ||11285      RHS.get()->getType()->isConstantMatrixType()) {11286    QualType compType =11287        CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);11288    if (CompLHSTy)11289      *CompLHSTy = compType;11290    return compType;11291  }11292 11293  QualType compType = UsualArithmeticConversions(11294      LHS, RHS, Loc,11295      CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);11296  if (LHS.isInvalid() || RHS.isInvalid())11297    return QualType();11298 11299  // Diagnose "string literal" '+' int and string '+' "char literal".11300  if (Opc == BO_Add) {11301    diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());11302    diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());11303  }11304 11305  // handle the common case first (both operands are arithmetic).11306  if (!compType.isNull() && compType->isArithmeticType()) {11307    if (CompLHSTy) *CompLHSTy = compType;11308    return compType;11309  }11310 11311  // Type-checking.  Ultimately the pointer's going to be in PExp;11312  // note that we bias towards the LHS being the pointer.11313  Expr *PExp = LHS.get(), *IExp = RHS.get();11314 11315  bool isObjCPointer;11316  if (PExp->getType()->isPointerType()) {11317    isObjCPointer = false;11318  } else if (PExp->getType()->isObjCObjectPointerType()) {11319    isObjCPointer = true;11320  } else {11321    std::swap(PExp, IExp);11322    if (PExp->getType()->isPointerType()) {11323      isObjCPointer = false;11324    } else if (PExp->getType()->isObjCObjectPointerType()) {11325      isObjCPointer = true;11326    } else {11327      QualType ResultTy = InvalidOperands(Loc, LHS, RHS);11328      diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);11329      return ResultTy;11330    }11331  }11332  assert(PExp->getType()->isAnyPointerType());11333 11334  if (!IExp->getType()->isIntegerType())11335    return InvalidOperands(Loc, LHS, RHS);11336 11337  // Adding to a null pointer results in undefined behavior.11338  if (PExp->IgnoreParenCasts()->isNullPointerConstant(11339          Context, Expr::NPC_ValueDependentIsNotNull)) {11340    // In C++ adding zero to a null pointer is defined.11341    Expr::EvalResult KnownVal;11342    if (!getLangOpts().CPlusPlus ||11343        (!IExp->isValueDependent() &&11344         (!IExp->EvaluateAsInt(KnownVal, Context) ||11345          KnownVal.Val.getInt() != 0))) {11346      // Check the conditions to see if this is the 'p = nullptr + n' idiom.11347      bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(11348          Context, BO_Add, PExp, IExp);11349      diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);11350    }11351  }11352 11353  if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))11354    return QualType();11355 11356  if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))11357    return QualType();11358 11359  // Arithmetic on label addresses is normally allowed, except when we add11360  // a ptrauth signature to the addresses.11361  if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {11362    Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)11363        << /*addition*/ 1;11364    return QualType();11365  }11366 11367  // Check array bounds for pointer arithemtic11368  CheckArrayAccess(PExp, IExp);11369 11370  if (CompLHSTy) {11371    QualType LHSTy = Context.isPromotableBitField(LHS.get());11372    if (LHSTy.isNull()) {11373      LHSTy = LHS.get()->getType();11374      if (Context.isPromotableIntegerType(LHSTy))11375        LHSTy = Context.getPromotedIntegerType(LHSTy);11376    }11377    *CompLHSTy = LHSTy;11378  }11379 11380  return PExp->getType();11381}11382 11383// C99 6.5.611384QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,11385                                        SourceLocation Loc,11386                                        BinaryOperatorKind Opc,11387                                        QualType *CompLHSTy) {11388  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);11389 11390  if (LHS.get()->getType()->isVectorType() ||11391      RHS.get()->getType()->isVectorType()) {11392    QualType compType =11393        CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,11394                            /*AllowBothBool*/ getLangOpts().AltiVec,11395                            /*AllowBoolConversions*/ getLangOpts().ZVector,11396                            /*AllowBooleanOperation*/ false,11397                            /*ReportInvalid*/ true);11398    if (CompLHSTy) *CompLHSTy = compType;11399    return compType;11400  }11401 11402  if (LHS.get()->getType()->isSveVLSBuiltinType() ||11403      RHS.get()->getType()->isSveVLSBuiltinType()) {11404    QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,11405                                                    ArithConvKind::Arithmetic);11406    if (CompLHSTy)11407      *CompLHSTy = compType;11408    return compType;11409  }11410 11411  if (LHS.get()->getType()->isConstantMatrixType() ||11412      RHS.get()->getType()->isConstantMatrixType()) {11413    QualType compType =11414        CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);11415    if (CompLHSTy)11416      *CompLHSTy = compType;11417    return compType;11418  }11419 11420  QualType compType = UsualArithmeticConversions(11421      LHS, RHS, Loc,11422      CompLHSTy ? ArithConvKind::CompAssign : ArithConvKind::Arithmetic);11423  if (LHS.isInvalid() || RHS.isInvalid())11424    return QualType();11425 11426  // Enforce type constraints: C99 6.5.6p3.11427 11428  // Handle the common case first (both operands are arithmetic).11429  if (!compType.isNull() && compType->isArithmeticType()) {11430    if (CompLHSTy) *CompLHSTy = compType;11431    return compType;11432  }11433 11434  // Either ptr - int   or   ptr - ptr.11435  if (LHS.get()->getType()->isAnyPointerType()) {11436    QualType lpointee = LHS.get()->getType()->getPointeeType();11437 11438    // Diagnose bad cases where we step over interface counts.11439    if (LHS.get()->getType()->isObjCObjectPointerType() &&11440        checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))11441      return QualType();11442 11443    // Arithmetic on label addresses is normally allowed, except when we add11444    // a ptrauth signature to the addresses.11445    if (isa<AddrLabelExpr>(LHS.get()) &&11446        getLangOpts().PointerAuthIndirectGotos) {11447      Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)11448          << /*subtraction*/ 0;11449      return QualType();11450    }11451 11452    // The result type of a pointer-int computation is the pointer type.11453    if (RHS.get()->getType()->isIntegerType()) {11454      // Subtracting from a null pointer should produce a warning.11455      // The last argument to the diagnose call says this doesn't match the11456      // GNU int-to-pointer idiom.11457      if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,11458                                           Expr::NPC_ValueDependentIsNotNull)) {11459        // In C++ adding zero to a null pointer is defined.11460        Expr::EvalResult KnownVal;11461        if (!getLangOpts().CPlusPlus ||11462            (!RHS.get()->isValueDependent() &&11463             (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||11464              KnownVal.Val.getInt() != 0))) {11465          diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);11466        }11467      }11468 11469      if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))11470        return QualType();11471 11472      // Check array bounds for pointer arithemtic11473      CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,11474                       /*AllowOnePastEnd*/true, /*IndexNegated*/true);11475 11476      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();11477      return LHS.get()->getType();11478    }11479 11480    // Handle pointer-pointer subtractions.11481    if (const PointerType *RHSPTy11482          = RHS.get()->getType()->getAs<PointerType>()) {11483      QualType rpointee = RHSPTy->getPointeeType();11484 11485      if (getLangOpts().CPlusPlus) {11486        // Pointee types must be the same: C++ [expr.add]11487        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {11488          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());11489        }11490      } else {11491        // Pointee types must be compatible C99 6.5.6p311492        if (!Context.typesAreCompatible(11493                Context.getCanonicalType(lpointee).getUnqualifiedType(),11494                Context.getCanonicalType(rpointee).getUnqualifiedType())) {11495          diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());11496          return QualType();11497        }11498      }11499 11500      if (!checkArithmeticBinOpPointerOperands(*this, Loc,11501                                               LHS.get(), RHS.get()))11502        return QualType();11503 11504      bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(11505          Context, Expr::NPC_ValueDependentIsNotNull);11506      bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(11507          Context, Expr::NPC_ValueDependentIsNotNull);11508 11509      // Subtracting nullptr or from nullptr is suspect11510      if (LHSIsNullPtr)11511        diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);11512      if (RHSIsNullPtr)11513        diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);11514 11515      // The pointee type may have zero size.  As an extension, a structure or11516      // union may have zero size or an array may have zero length.  In this11517      // case subtraction does not make sense.11518      if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {11519        CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);11520        if (ElementSize.isZero()) {11521          Diag(Loc,diag::warn_sub_ptr_zero_size_types)11522            << rpointee.getUnqualifiedType()11523            << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11524        }11525      }11526 11527      if (CompLHSTy) *CompLHSTy = LHS.get()->getType();11528      return Context.getPointerDiffType();11529    }11530  }11531 11532  QualType ResultTy = InvalidOperands(Loc, LHS, RHS);11533  diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);11534  return ResultTy;11535}11536 11537static bool isScopedEnumerationType(QualType T) {11538  if (const EnumType *ET = T->getAsCanonical<EnumType>())11539    return ET->getDecl()->isScoped();11540  return false;11541}11542 11543static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,11544                                   SourceLocation Loc, BinaryOperatorKind Opc,11545                                   QualType LHSType) {11546  // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),11547  // so skip remaining warnings as we don't want to modify values within Sema.11548  if (S.getLangOpts().OpenCL)11549    return;11550 11551  if (Opc == BO_Shr &&11552      LHS.get()->IgnoreParenImpCasts()->getType()->isBooleanType())11553    S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();11554 11555  // Check right/shifter operand11556  Expr::EvalResult RHSResult;11557  if (RHS.get()->isValueDependent() ||11558      !RHS.get()->EvaluateAsInt(RHSResult, S.Context))11559    return;11560  llvm::APSInt Right = RHSResult.Val.getInt();11561 11562  if (Right.isNegative()) {11563    S.DiagRuntimeBehavior(Loc, RHS.get(),11564                          S.PDiag(diag::warn_shift_negative)11565                              << RHS.get()->getSourceRange());11566    return;11567  }11568 11569  QualType LHSExprType = LHS.get()->getType();11570  uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);11571  if (LHSExprType->isBitIntType())11572    LeftSize = S.Context.getIntWidth(LHSExprType);11573  else if (LHSExprType->isFixedPointType()) {11574    auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);11575    LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();11576  }11577  if (Right.uge(LeftSize)) {11578    S.DiagRuntimeBehavior(Loc, RHS.get(),11579                          S.PDiag(diag::warn_shift_gt_typewidth)11580                              << RHS.get()->getSourceRange());11581    return;11582  }11583 11584  // FIXME: We probably need to handle fixed point types specially here.11585  if (Opc != BO_Shl || LHSExprType->isFixedPointType())11586    return;11587 11588  // When left shifting an ICE which is signed, we can check for overflow which11589  // according to C++ standards prior to C++2a has undefined behavior11590  // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one11591  // more than the maximum value representable in the result type, so never11592  // warn for those. (FIXME: Unsigned left-shift overflow in a constant11593  // expression is still probably a bug.)11594  Expr::EvalResult LHSResult;11595  if (LHS.get()->isValueDependent() ||11596      LHSType->hasUnsignedIntegerRepresentation() ||11597      !LHS.get()->EvaluateAsInt(LHSResult, S.Context))11598    return;11599  llvm::APSInt Left = LHSResult.Val.getInt();11600 11601  // Don't warn if signed overflow is defined, then all the rest of the11602  // diagnostics will not be triggered because the behavior is defined.11603  // Also don't warn in C++20 mode (and newer), as signed left shifts11604  // always wrap and never overflow.11605  if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)11606    return;11607 11608  // If LHS does not have a non-negative value then, the11609  // behavior is undefined before C++2a. Warn about it.11610  if (Left.isNegative()) {11611    S.DiagRuntimeBehavior(Loc, LHS.get(),11612                          S.PDiag(diag::warn_shift_lhs_negative)11613                              << LHS.get()->getSourceRange());11614    return;11615  }11616 11617  llvm::APInt ResultBits =11618      static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();11619  if (ResultBits.ule(LeftSize))11620    return;11621  llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());11622  Result = Result.shl(Right);11623 11624  // Print the bit representation of the signed integer as an unsigned11625  // hexadecimal number.11626  SmallString<40> HexResult;11627  Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);11628 11629  // If we are only missing a sign bit, this is less likely to result in actual11630  // bugs -- if the result is cast back to an unsigned type, it will have the11631  // expected value. Thus we place this behind a different warning that can be11632  // turned off separately if needed.11633  if (ResultBits - 1 == LeftSize) {11634    S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)11635        << HexResult << LHSType11636        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11637    return;11638  }11639 11640  S.Diag(Loc, diag::warn_shift_result_gt_typewidth)11641      << HexResult.str() << Result.getSignificantBits() << LHSType11642      << Left.getBitWidth() << LHS.get()->getSourceRange()11643      << RHS.get()->getSourceRange();11644}11645 11646/// Return the resulting type when a vector is shifted11647///        by a scalar or vector shift amount.11648static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,11649                                 SourceLocation Loc, bool IsCompAssign) {11650  // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.11651  if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&11652      !LHS.get()->getType()->isVectorType()) {11653    S.Diag(Loc, diag::err_shift_rhs_only_vector)11654      << RHS.get()->getType() << LHS.get()->getType()11655      << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11656    return QualType();11657  }11658 11659  if (!IsCompAssign) {11660    LHS = S.UsualUnaryConversions(LHS.get());11661    if (LHS.isInvalid()) return QualType();11662  }11663 11664  RHS = S.UsualUnaryConversions(RHS.get());11665  if (RHS.isInvalid()) return QualType();11666 11667  QualType LHSType = LHS.get()->getType();11668  // Note that LHS might be a scalar because the routine calls not only in11669  // OpenCL case.11670  const VectorType *LHSVecTy = LHSType->getAs<VectorType>();11671  QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;11672 11673  // Note that RHS might not be a vector.11674  QualType RHSType = RHS.get()->getType();11675  const VectorType *RHSVecTy = RHSType->getAs<VectorType>();11676  QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;11677 11678  // Do not allow shifts for boolean vectors.11679  if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||11680      (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {11681    S.Diag(Loc, diag::err_typecheck_invalid_operands)11682        << LHS.get()->getType() << RHS.get()->getType()11683        << LHS.get()->getSourceRange();11684    return QualType();11685  }11686 11687  // The operands need to be integers.11688  if (!LHSEleType->isIntegerType()) {11689    S.Diag(Loc, diag::err_typecheck_expect_int)11690      << LHS.get()->getType() << LHS.get()->getSourceRange();11691    return QualType();11692  }11693 11694  if (!RHSEleType->isIntegerType()) {11695    S.Diag(Loc, diag::err_typecheck_expect_int)11696      << RHS.get()->getType() << RHS.get()->getSourceRange();11697    return QualType();11698  }11699 11700  if (!LHSVecTy) {11701    assert(RHSVecTy);11702    if (IsCompAssign)11703      return RHSType;11704    if (LHSEleType != RHSEleType) {11705      LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);11706      LHSEleType = RHSEleType;11707    }11708    QualType VecTy =11709        S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());11710    LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);11711    LHSType = VecTy;11712  } else if (RHSVecTy) {11713    // OpenCL v1.1 s6.3.j says that for vector types, the operators11714    // are applied component-wise. So if RHS is a vector, then ensure11715    // that the number of elements is the same as LHS...11716    if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {11717      S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)11718        << LHS.get()->getType() << RHS.get()->getType()11719        << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11720      return QualType();11721    }11722    if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {11723      const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();11724      const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();11725      if (LHSBT != RHSBT &&11726          S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {11727        S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)11728            << LHS.get()->getType() << RHS.get()->getType()11729            << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11730      }11731    }11732  } else {11733    // ...else expand RHS to match the number of elements in LHS.11734    QualType VecTy =11735      S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());11736    RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);11737  }11738 11739  return LHSType;11740}11741 11742static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,11743                                         ExprResult &RHS, SourceLocation Loc,11744                                         bool IsCompAssign) {11745  if (!IsCompAssign) {11746    LHS = S.UsualUnaryConversions(LHS.get());11747    if (LHS.isInvalid())11748      return QualType();11749  }11750 11751  RHS = S.UsualUnaryConversions(RHS.get());11752  if (RHS.isInvalid())11753    return QualType();11754 11755  QualType LHSType = LHS.get()->getType();11756  const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();11757  QualType LHSEleType = LHSType->isSveVLSBuiltinType()11758                            ? LHSBuiltinTy->getSveEltType(S.getASTContext())11759                            : LHSType;11760 11761  // Note that RHS might not be a vector11762  QualType RHSType = RHS.get()->getType();11763  const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();11764  QualType RHSEleType = RHSType->isSveVLSBuiltinType()11765                            ? RHSBuiltinTy->getSveEltType(S.getASTContext())11766                            : RHSType;11767 11768  if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||11769      (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {11770    S.Diag(Loc, diag::err_typecheck_invalid_operands)11771        << LHSType << RHSType << LHS.get()->getSourceRange();11772    return QualType();11773  }11774 11775  if (!LHSEleType->isIntegerType()) {11776    S.Diag(Loc, diag::err_typecheck_expect_int)11777        << LHS.get()->getType() << LHS.get()->getSourceRange();11778    return QualType();11779  }11780 11781  if (!RHSEleType->isIntegerType()) {11782    S.Diag(Loc, diag::err_typecheck_expect_int)11783        << RHS.get()->getType() << RHS.get()->getSourceRange();11784    return QualType();11785  }11786 11787  if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&11788      (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=11789       S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {11790    S.Diag(Loc, diag::err_typecheck_invalid_operands)11791        << LHSType << RHSType << LHS.get()->getSourceRange()11792        << RHS.get()->getSourceRange();11793    return QualType();11794  }11795 11796  if (!LHSType->isSveVLSBuiltinType()) {11797    assert(RHSType->isSveVLSBuiltinType());11798    if (IsCompAssign)11799      return RHSType;11800    if (LHSEleType != RHSEleType) {11801      LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);11802      LHSEleType = RHSEleType;11803    }11804    const llvm::ElementCount VecSize =11805        S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;11806    QualType VecTy =11807        S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());11808    LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);11809    LHSType = VecTy;11810  } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {11811    if (S.Context.getTypeSize(RHSBuiltinTy) !=11812        S.Context.getTypeSize(LHSBuiltinTy)) {11813      S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)11814          << LHSType << RHSType << LHS.get()->getSourceRange()11815          << RHS.get()->getSourceRange();11816      return QualType();11817    }11818  } else {11819    const llvm::ElementCount VecSize =11820        S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;11821    if (LHSEleType != RHSEleType) {11822      RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);11823      RHSEleType = LHSEleType;11824    }11825    QualType VecTy =11826        S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());11827    RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);11828  }11829 11830  return LHSType;11831}11832 11833// C99 6.5.711834QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,11835                                  SourceLocation Loc, BinaryOperatorKind Opc,11836                                  bool IsCompAssign) {11837  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);11838 11839  // Vector shifts promote their scalar inputs to vector type.11840  if (LHS.get()->getType()->isVectorType() ||11841      RHS.get()->getType()->isVectorType()) {11842    if (LangOpts.ZVector) {11843      // The shift operators for the z vector extensions work basically11844      // like general shifts, except that neither the LHS nor the RHS is11845      // allowed to be a "vector bool".11846      if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())11847        if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)11848          return InvalidOperands(Loc, LHS, RHS);11849      if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())11850        if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)11851          return InvalidOperands(Loc, LHS, RHS);11852    }11853    return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);11854  }11855 11856  if (LHS.get()->getType()->isSveVLSBuiltinType() ||11857      RHS.get()->getType()->isSveVLSBuiltinType())11858    return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);11859 11860  // Shifts don't perform usual arithmetic conversions, they just do integer11861  // promotions on each operand. C99 6.5.7p311862 11863  // For the LHS, do usual unary conversions, but then reset them away11864  // if this is a compound assignment.11865  ExprResult OldLHS = LHS;11866  LHS = UsualUnaryConversions(LHS.get());11867  if (LHS.isInvalid())11868    return QualType();11869  QualType LHSType = LHS.get()->getType();11870  if (IsCompAssign) LHS = OldLHS;11871 11872  // The RHS is simpler.11873  RHS = UsualUnaryConversions(RHS.get());11874  if (RHS.isInvalid())11875    return QualType();11876  QualType RHSType = RHS.get()->getType();11877 11878  // C99 6.5.7p2: Each of the operands shall have integer type.11879  // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.11880  if ((!LHSType->isFixedPointOrIntegerType() &&11881       !LHSType->hasIntegerRepresentation()) ||11882      !RHSType->hasIntegerRepresentation()) {11883    QualType ResultTy = InvalidOperands(Loc, LHS, RHS);11884    diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);11885    return ResultTy;11886  }11887 11888  DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);11889 11890  // "The type of the result is that of the promoted left operand."11891  return LHSType;11892}11893 11894/// Diagnose bad pointer comparisons.11895static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,11896                                              ExprResult &LHS, ExprResult &RHS,11897                                              bool IsError) {11898  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers11899                      : diag::ext_typecheck_comparison_of_distinct_pointers)11900    << LHS.get()->getType() << RHS.get()->getType()11901    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11902}11903 11904/// Returns false if the pointers are converted to a composite type,11905/// true otherwise.11906static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,11907                                           ExprResult &LHS, ExprResult &RHS) {11908  // C++ [expr.rel]p2:11909  //   [...] Pointer conversions (4.10) and qualification11910  //   conversions (4.4) are performed on pointer operands (or on11911  //   a pointer operand and a null pointer constant) to bring11912  //   them to their composite pointer type. [...]11913  //11914  // C++ [expr.eq]p1 uses the same notion for (in)equality11915  // comparisons of pointers.11916 11917  QualType LHSType = LHS.get()->getType();11918  QualType RHSType = RHS.get()->getType();11919  assert(LHSType->isPointerType() || RHSType->isPointerType() ||11920         LHSType->isMemberPointerType() || RHSType->isMemberPointerType());11921 11922  QualType T = S.FindCompositePointerType(Loc, LHS, RHS);11923  if (T.isNull()) {11924    if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&11925        (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))11926      diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);11927    else11928      S.InvalidOperands(Loc, LHS, RHS);11929    return true;11930  }11931 11932  return false;11933}11934 11935static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,11936                                                    ExprResult &LHS,11937                                                    ExprResult &RHS,11938                                                    bool IsError) {11939  S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void11940                      : diag::ext_typecheck_comparison_of_fptr_to_void)11941    << LHS.get()->getType() << RHS.get()->getType()11942    << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();11943}11944 11945static bool isObjCObjectLiteral(ExprResult &E) {11946  switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {11947  case Stmt::ObjCArrayLiteralClass:11948  case Stmt::ObjCDictionaryLiteralClass:11949  case Stmt::ObjCStringLiteralClass:11950  case Stmt::ObjCBoxedExprClass:11951    return true;11952  default:11953    // Note that ObjCBoolLiteral is NOT an object literal!11954    return false;11955  }11956}11957 11958static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {11959  const ObjCObjectPointerType *Type =11960    LHS->getType()->getAs<ObjCObjectPointerType>();11961 11962  // If this is not actually an Objective-C object, bail out.11963  if (!Type)11964    return false;11965 11966  // Get the LHS object's interface type.11967  QualType InterfaceType = Type->getPointeeType();11968 11969  // If the RHS isn't an Objective-C object, bail out.11970  if (!RHS->getType()->isObjCObjectPointerType())11971    return false;11972 11973  // Try to find the -isEqual: method.11974  Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();11975  ObjCMethodDecl *Method =11976      S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,11977                                        /*IsInstance=*/true);11978  if (!Method) {11979    if (Type->isObjCIdType()) {11980      // For 'id', just check the global pool.11981      Method =11982          S.ObjC().LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),11983                                                    /*receiverId=*/true);11984    } else {11985      // Check protocols.11986      Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,11987                                                    /*IsInstance=*/true);11988    }11989  }11990 11991  if (!Method)11992    return false;11993 11994  QualType T = Method->parameters()[0]->getType();11995  if (!T->isObjCObjectPointerType())11996    return false;11997 11998  QualType R = Method->getReturnType();11999  if (!R->isScalarType())12000    return false;12001 12002  return true;12003}12004 12005static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,12006                                          ExprResult &LHS, ExprResult &RHS,12007                                          BinaryOperator::Opcode Opc){12008  Expr *Literal;12009  Expr *Other;12010  if (isObjCObjectLiteral(LHS)) {12011    Literal = LHS.get();12012    Other = RHS.get();12013  } else {12014    Literal = RHS.get();12015    Other = LHS.get();12016  }12017 12018  // Don't warn on comparisons against nil.12019  Other = Other->IgnoreParenCasts();12020  if (Other->isNullPointerConstant(S.getASTContext(),12021                                   Expr::NPC_ValueDependentIsNotNull))12022    return;12023 12024  // This should be kept in sync with warn_objc_literal_comparison.12025  // LK_String should always be after the other literals, since it has its own12026  // warning flag.12027  SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);12028  assert(LiteralKind != SemaObjC::LK_Block);12029  if (LiteralKind == SemaObjC::LK_None) {12030    llvm_unreachable("Unknown Objective-C object literal kind");12031  }12032 12033  if (LiteralKind == SemaObjC::LK_String)12034    S.Diag(Loc, diag::warn_objc_string_literal_comparison)12035      << Literal->getSourceRange();12036  else12037    S.Diag(Loc, diag::warn_objc_literal_comparison)12038      << LiteralKind << Literal->getSourceRange();12039 12040  if (BinaryOperator::isEqualityOp(Opc) &&12041      hasIsEqualMethod(S, LHS.get(), RHS.get())) {12042    SourceLocation Start = LHS.get()->getBeginLoc();12043    SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());12044    CharSourceRange OpRange =12045      CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));12046 12047    S.Diag(Loc, diag::note_objc_literal_comparison_isequal)12048      << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")12049      << FixItHint::CreateReplacement(OpRange, " isEqual:")12050      << FixItHint::CreateInsertion(End, "]");12051  }12052}12053 12054/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.12055static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,12056                                           ExprResult &RHS, SourceLocation Loc,12057                                           BinaryOperatorKind Opc) {12058  // Check that left hand side is !something.12059  UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());12060  if (!UO || UO->getOpcode() != UO_LNot) return;12061 12062  // Only check if the right hand side is non-bool arithmetic type.12063  if (RHS.get()->isKnownToHaveBooleanValue()) return;12064 12065  // Make sure that the something in !something is not bool.12066  Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();12067  if (SubExpr->isKnownToHaveBooleanValue()) return;12068 12069  // Emit warning.12070  bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;12071  S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)12072      << Loc << IsBitwiseOp;12073 12074  // First note suggest !(x < y)12075  SourceLocation FirstOpen = SubExpr->getBeginLoc();12076  SourceLocation FirstClose = RHS.get()->getEndLoc();12077  FirstClose = S.getLocForEndOfToken(FirstClose);12078  if (FirstClose.isInvalid())12079    FirstOpen = SourceLocation();12080  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)12081      << IsBitwiseOp12082      << FixItHint::CreateInsertion(FirstOpen, "(")12083      << FixItHint::CreateInsertion(FirstClose, ")");12084 12085  // Second note suggests (!x) < y12086  SourceLocation SecondOpen = LHS.get()->getBeginLoc();12087  SourceLocation SecondClose = LHS.get()->getEndLoc();12088  SecondClose = S.getLocForEndOfToken(SecondClose);12089  if (SecondClose.isInvalid())12090    SecondOpen = SourceLocation();12091  S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)12092      << FixItHint::CreateInsertion(SecondOpen, "(")12093      << FixItHint::CreateInsertion(SecondClose, ")");12094}12095 12096// Returns true if E refers to a non-weak array.12097static bool checkForArray(const Expr *E) {12098  const ValueDecl *D = nullptr;12099  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {12100    D = DR->getDecl();12101  } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {12102    if (Mem->isImplicitAccess())12103      D = Mem->getMemberDecl();12104  }12105  if (!D)12106    return false;12107  return D->getType()->isArrayType() && !D->isWeak();12108}12109 12110/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a12111/// pointer and size is an unsigned integer. Return whether the result is12112/// always true/false.12113static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,12114                                                     const Expr *RHS,12115                                                     BinaryOperatorKind Opc) {12116  if (!LHS->getType()->isPointerType() ||12117      S.getLangOpts().PointerOverflowDefined)12118    return std::nullopt;12119 12120  // Canonicalize to >= or < predicate.12121  switch (Opc) {12122  case BO_GE:12123  case BO_LT:12124    break;12125  case BO_GT:12126    std::swap(LHS, RHS);12127    Opc = BO_LT;12128    break;12129  case BO_LE:12130    std::swap(LHS, RHS);12131    Opc = BO_GE;12132    break;12133  default:12134    return std::nullopt;12135  }12136 12137  auto *BO = dyn_cast<BinaryOperator>(LHS);12138  if (!BO || BO->getOpcode() != BO_Add)12139    return std::nullopt;12140 12141  Expr *Other;12142  if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))12143    Other = BO->getRHS();12144  else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))12145    Other = BO->getLHS();12146  else12147    return std::nullopt;12148 12149  if (!Other->getType()->isUnsignedIntegerType())12150    return std::nullopt;12151 12152  return Opc == BO_GE;12153}12154 12155/// Diagnose some forms of syntactically-obvious tautological comparison.12156static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,12157                                           Expr *LHS, Expr *RHS,12158                                           BinaryOperatorKind Opc) {12159  Expr *LHSStripped = LHS->IgnoreParenImpCasts();12160  Expr *RHSStripped = RHS->IgnoreParenImpCasts();12161 12162  QualType LHSType = LHS->getType();12163  QualType RHSType = RHS->getType();12164  if (LHSType->hasFloatingRepresentation() ||12165      (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||12166      S.inTemplateInstantiation())12167    return;12168 12169  // WebAssembly Tables cannot be compared, therefore shouldn't emit12170  // Tautological diagnostics.12171  if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())12172    return;12173 12174  // Comparisons between two array types are ill-formed for operator<=>, so12175  // we shouldn't emit any additional warnings about it.12176  if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())12177    return;12178 12179  // For non-floating point types, check for self-comparisons of the form12180  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and12181  // often indicate logic errors in the program.12182  //12183  // NOTE: Don't warn about comparison expressions resulting from macro12184  // expansion. Also don't warn about comparisons which are only self12185  // comparisons within a template instantiation. The warnings should catch12186  // obvious cases in the definition of the template anyways. The idea is to12187  // warn when the typed comparison operator will always evaluate to the same12188  // result.12189 12190  // Used for indexing into %select in warn_comparison_always12191  enum {12192    AlwaysConstant,12193    AlwaysTrue,12194    AlwaysFalse,12195    AlwaysEqual, // std::strong_ordering::equal from operator<=>12196  };12197 12198  // C++1a [array.comp]:12199  //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two12200  //   operands of array type.12201  // C++2a [depr.array.comp]:12202  //   Equality and relational comparisons ([expr.eq], [expr.rel]) between two12203  //   operands of array type are deprecated.12204  if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&12205      RHSStripped->getType()->isArrayType()) {12206    auto IsDeprArrayComparionIgnored =12207        S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);12208    auto DiagID = S.getLangOpts().CPlusPlus2612209                      ? diag::warn_array_comparison_cxx2612210                  : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored12211                      ? diag::warn_array_comparison12212                      : diag::warn_depr_array_comparison;12213    S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()12214                        << LHSStripped->getType() << RHSStripped->getType();12215    // Carry on to produce the tautological comparison warning, if this12216    // expression is potentially-evaluated, we can resolve the array to a12217    // non-weak declaration, and so on.12218  }12219 12220  if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {12221    if (Expr::isSameComparisonOperand(LHS, RHS)) {12222      unsigned Result;12223      switch (Opc) {12224      case BO_EQ:12225      case BO_LE:12226      case BO_GE:12227        Result = AlwaysTrue;12228        break;12229      case BO_NE:12230      case BO_LT:12231      case BO_GT:12232        Result = AlwaysFalse;12233        break;12234      case BO_Cmp:12235        Result = AlwaysEqual;12236        break;12237      default:12238        Result = AlwaysConstant;12239        break;12240      }12241      S.DiagRuntimeBehavior(Loc, nullptr,12242                            S.PDiag(diag::warn_comparison_always)12243                                << 0 /*self-comparison*/12244                                << Result);12245    } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {12246      // What is it always going to evaluate to?12247      unsigned Result;12248      switch (Opc) {12249      case BO_EQ: // e.g. array1 == array212250        Result = AlwaysFalse;12251        break;12252      case BO_NE: // e.g. array1 != array212253        Result = AlwaysTrue;12254        break;12255      default: // e.g. array1 <= array212256        // The best we can say is 'a constant'12257        Result = AlwaysConstant;12258        break;12259      }12260      S.DiagRuntimeBehavior(Loc, nullptr,12261                            S.PDiag(diag::warn_comparison_always)12262                                << 1 /*array comparison*/12263                                << Result);12264    } else if (std::optional<bool> Res =12265                   isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {12266      S.DiagRuntimeBehavior(Loc, nullptr,12267                            S.PDiag(diag::warn_comparison_always)12268                                << 2 /*pointer comparison*/12269                                << (*Res ? AlwaysTrue : AlwaysFalse));12270    }12271  }12272 12273  if (isa<CastExpr>(LHSStripped))12274    LHSStripped = LHSStripped->IgnoreParenCasts();12275  if (isa<CastExpr>(RHSStripped))12276    RHSStripped = RHSStripped->IgnoreParenCasts();12277 12278  // Warn about comparisons against a string constant (unless the other12279  // operand is null); the user probably wants string comparison function.12280  Expr *LiteralString = nullptr;12281  Expr *LiteralStringStripped = nullptr;12282  if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&12283      !RHSStripped->isNullPointerConstant(S.Context,12284                                          Expr::NPC_ValueDependentIsNull)) {12285    LiteralString = LHS;12286    LiteralStringStripped = LHSStripped;12287  } else if ((isa<StringLiteral>(RHSStripped) ||12288              isa<ObjCEncodeExpr>(RHSStripped)) &&12289             !LHSStripped->isNullPointerConstant(S.Context,12290                                          Expr::NPC_ValueDependentIsNull)) {12291    LiteralString = RHS;12292    LiteralStringStripped = RHSStripped;12293  }12294 12295  if (LiteralString) {12296    S.DiagRuntimeBehavior(Loc, nullptr,12297                          S.PDiag(diag::warn_stringcompare)12298                              << isa<ObjCEncodeExpr>(LiteralStringStripped)12299                              << LiteralString->getSourceRange());12300  }12301}12302 12303static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {12304  switch (CK) {12305  default: {12306#ifndef NDEBUG12307    llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)12308                 << "\n";12309#endif12310    llvm_unreachable("unhandled cast kind");12311  }12312  case CK_UserDefinedConversion:12313    return ICK_Identity;12314  case CK_LValueToRValue:12315    return ICK_Lvalue_To_Rvalue;12316  case CK_ArrayToPointerDecay:12317    return ICK_Array_To_Pointer;12318  case CK_FunctionToPointerDecay:12319    return ICK_Function_To_Pointer;12320  case CK_IntegralCast:12321    return ICK_Integral_Conversion;12322  case CK_FloatingCast:12323    return ICK_Floating_Conversion;12324  case CK_IntegralToFloating:12325  case CK_FloatingToIntegral:12326    return ICK_Floating_Integral;12327  case CK_IntegralComplexCast:12328  case CK_FloatingComplexCast:12329  case CK_FloatingComplexToIntegralComplex:12330  case CK_IntegralComplexToFloatingComplex:12331    return ICK_Complex_Conversion;12332  case CK_FloatingComplexToReal:12333  case CK_FloatingRealToComplex:12334  case CK_IntegralComplexToReal:12335  case CK_IntegralRealToComplex:12336    return ICK_Complex_Real;12337  case CK_HLSLArrayRValue:12338    return ICK_HLSL_Array_RValue;12339  }12340}12341 12342static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,12343                                             QualType FromType,12344                                             SourceLocation Loc) {12345  // Check for a narrowing implicit conversion.12346  StandardConversionSequence SCS;12347  SCS.setAsIdentityConversion();12348  SCS.setToType(0, FromType);12349  SCS.setToType(1, ToType);12350  if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))12351    SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());12352 12353  APValue PreNarrowingValue;12354  QualType PreNarrowingType;12355  switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,12356                               PreNarrowingType,12357                               /*IgnoreFloatToIntegralConversion*/ true)) {12358  case NK_Dependent_Narrowing:12359    // Implicit conversion to a narrower type, but the expression is12360    // value-dependent so we can't tell whether it's actually narrowing.12361  case NK_Not_Narrowing:12362    return false;12363 12364  case NK_Constant_Narrowing:12365    // Implicit conversion to a narrower type, and the value is not a constant12366    // expression.12367    S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)12368        << /*Constant*/ 112369        << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;12370    return true;12371 12372  case NK_Variable_Narrowing:12373    // Implicit conversion to a narrower type, and the value is not a constant12374    // expression.12375  case NK_Type_Narrowing:12376    S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)12377        << /*Constant*/ 0 << FromType << ToType;12378    // TODO: It's not a constant expression, but what if the user intended it12379    // to be? Can we produce notes to help them figure out why it isn't?12380    return true;12381  }12382  llvm_unreachable("unhandled case in switch");12383}12384 12385static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,12386                                                         ExprResult &LHS,12387                                                         ExprResult &RHS,12388                                                         SourceLocation Loc) {12389  QualType LHSType = LHS.get()->getType();12390  QualType RHSType = RHS.get()->getType();12391  // Dig out the original argument type and expression before implicit casts12392  // were applied. These are the types/expressions we need to check the12393  // [expr.spaceship] requirements against.12394  ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();12395  ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();12396  QualType LHSStrippedType = LHSStripped.get()->getType();12397  QualType RHSStrippedType = RHSStripped.get()->getType();12398 12399  // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the12400  // other is not, the program is ill-formed.12401  if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {12402    S.InvalidOperands(Loc, LHSStripped, RHSStripped);12403    return QualType();12404  }12405 12406  // FIXME: Consider combining this with checkEnumArithmeticConversions.12407  int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +12408                    RHSStrippedType->isEnumeralType();12409  if (NumEnumArgs == 1) {12410    bool LHSIsEnum = LHSStrippedType->isEnumeralType();12411    QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;12412    if (OtherTy->hasFloatingRepresentation()) {12413      S.InvalidOperands(Loc, LHSStripped, RHSStripped);12414      return QualType();12415    }12416  }12417  if (NumEnumArgs == 2) {12418    // C++2a [expr.spaceship]p5: If both operands have the same enumeration12419    // type E, the operator yields the result of converting the operands12420    // to the underlying type of E and applying <=> to the converted operands.12421    if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {12422      S.InvalidOperands(Loc, LHS, RHS);12423      return QualType();12424    }12425    QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();12426    assert(IntType->isArithmeticType());12427 12428    // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we12429    // promote the boolean type, and all other promotable integer types, to12430    // avoid this.12431    if (S.Context.isPromotableIntegerType(IntType))12432      IntType = S.Context.getPromotedIntegerType(IntType);12433 12434    LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);12435    RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);12436    LHSType = RHSType = IntType;12437  }12438 12439  // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the12440  // usual arithmetic conversions are applied to the operands.12441  QualType Type =12442      S.UsualArithmeticConversions(LHS, RHS, Loc, ArithConvKind::Comparison);12443  if (LHS.isInvalid() || RHS.isInvalid())12444    return QualType();12445  if (Type.isNull()) {12446    QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);12447    diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);12448    return ResultTy;12449  }12450 12451  std::optional<ComparisonCategoryType> CCT =12452      getComparisonCategoryForBuiltinCmp(Type);12453  if (!CCT)12454    return S.InvalidOperands(Loc, LHS, RHS);12455 12456  bool HasNarrowing = checkThreeWayNarrowingConversion(12457      S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());12458  HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,12459                                                   RHS.get()->getBeginLoc());12460  if (HasNarrowing)12461    return QualType();12462 12463  assert(!Type.isNull() && "composite type for <=> has not been set");12464 12465  return S.CheckComparisonCategoryType(12466      *CCT, Loc, Sema::ComparisonCategoryUsage::OperatorInExpression);12467}12468 12469static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,12470                                                 ExprResult &RHS,12471                                                 SourceLocation Loc,12472                                                 BinaryOperatorKind Opc) {12473  if (Opc == BO_Cmp)12474    return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);12475 12476  // C99 6.5.8p3 / C99 6.5.9p412477  QualType Type =12478      S.UsualArithmeticConversions(LHS, RHS, Loc, ArithConvKind::Comparison);12479  if (LHS.isInvalid() || RHS.isInvalid())12480    return QualType();12481  if (Type.isNull()) {12482    QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);12483    diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);12484    return ResultTy;12485  }12486  assert(Type->isArithmeticType() || Type->isEnumeralType());12487 12488  if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))12489    return S.InvalidOperands(Loc, LHS, RHS);12490 12491  // Check for comparisons of floating point operands using != and ==.12492  if (Type->hasFloatingRepresentation())12493    S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);12494 12495  // The result of comparisons is 'bool' in C++, 'int' in C.12496  return S.Context.getLogicalOperationType();12497}12498 12499void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {12500  if (!NullE.get()->getType()->isAnyPointerType())12501    return;12502  int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;12503  if (!E.get()->getType()->isAnyPointerType() &&12504      E.get()->isNullPointerConstant(Context,12505                                     Expr::NPC_ValueDependentIsNotNull) ==12506        Expr::NPCK_ZeroExpression) {12507    if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {12508      if (CL->getValue() == 0)12509        Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)12510            << NullValue12511            << FixItHint::CreateReplacement(E.get()->getExprLoc(),12512                                            NullValue ? "NULL" : "(void *)0");12513    } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {12514        TypeSourceInfo *TI = CE->getTypeInfoAsWritten();12515        QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();12516        if (T == Context.CharTy)12517          Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)12518              << NullValue12519              << FixItHint::CreateReplacement(E.get()->getExprLoc(),12520                                              NullValue ? "NULL" : "(void *)0");12521      }12522  }12523}12524 12525// C99 6.5.8, C++ [expr.rel]12526QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,12527                                    SourceLocation Loc,12528                                    BinaryOperatorKind Opc) {12529  bool IsRelational = BinaryOperator::isRelationalOp(Opc);12530  bool IsThreeWay = Opc == BO_Cmp;12531  bool IsOrdered = IsRelational || IsThreeWay;12532  auto IsAnyPointerType = [](ExprResult E) {12533    QualType Ty = E.get()->getType();12534    return Ty->isPointerType() || Ty->isMemberPointerType();12535  };12536 12537  // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer12538  // type, array-to-pointer, ..., conversions are performed on both operands to12539  // bring them to their composite type.12540  // Otherwise, all comparisons expect an rvalue, so convert to rvalue before12541  // any type-related checks.12542  if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {12543    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());12544    if (LHS.isInvalid())12545      return QualType();12546    RHS = DefaultFunctionArrayLvalueConversion(RHS.get());12547    if (RHS.isInvalid())12548      return QualType();12549  } else {12550    LHS = DefaultLvalueConversion(LHS.get());12551    if (LHS.isInvalid())12552      return QualType();12553    RHS = DefaultLvalueConversion(RHS.get());12554    if (RHS.isInvalid())12555      return QualType();12556  }12557 12558  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);12559  if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {12560    CheckPtrComparisonWithNullChar(LHS, RHS);12561    CheckPtrComparisonWithNullChar(RHS, LHS);12562  }12563 12564  // Handle vector comparisons separately.12565  if (LHS.get()->getType()->isVectorType() ||12566      RHS.get()->getType()->isVectorType())12567    return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);12568 12569  if (LHS.get()->getType()->isSveVLSBuiltinType() ||12570      RHS.get()->getType()->isSveVLSBuiltinType())12571    return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);12572 12573  diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);12574  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);12575 12576  QualType LHSType = LHS.get()->getType();12577  QualType RHSType = RHS.get()->getType();12578  if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&12579      (RHSType->isArithmeticType() || RHSType->isEnumeralType()))12580    return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);12581 12582  if ((LHSType->isPointerType() &&12583       LHSType->getPointeeType().isWebAssemblyReferenceType()) ||12584      (RHSType->isPointerType() &&12585       RHSType->getPointeeType().isWebAssemblyReferenceType()))12586    return InvalidOperands(Loc, LHS, RHS);12587 12588  const Expr::NullPointerConstantKind LHSNullKind =12589      LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);12590  const Expr::NullPointerConstantKind RHSNullKind =12591      RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);12592  bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;12593  bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;12594 12595  auto computeResultTy = [&]() {12596    if (Opc != BO_Cmp)12597      return QualType(Context.getLogicalOperationType());12598    assert(getLangOpts().CPlusPlus);12599    assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));12600 12601    QualType CompositeTy = LHS.get()->getType();12602    assert(!CompositeTy->isReferenceType());12603 12604    std::optional<ComparisonCategoryType> CCT =12605        getComparisonCategoryForBuiltinCmp(CompositeTy);12606    if (!CCT)12607      return InvalidOperands(Loc, LHS, RHS);12608 12609    if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {12610      // P0946R0: Comparisons between a null pointer constant and an object12611      // pointer result in std::strong_equality, which is ill-formed under12612      // P1959R0.12613      Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)12614          << (LHSIsNull ? LHS.get()->getSourceRange()12615                        : RHS.get()->getSourceRange());12616      return QualType();12617    }12618 12619    return CheckComparisonCategoryType(12620        *CCT, Loc, ComparisonCategoryUsage::OperatorInExpression);12621  };12622 12623  if (!IsOrdered && LHSIsNull != RHSIsNull) {12624    bool IsEquality = Opc == BO_EQ;12625    if (RHSIsNull)12626      DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,12627                                   RHS.get()->getSourceRange());12628    else12629      DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,12630                                   LHS.get()->getSourceRange());12631  }12632 12633  if (IsOrdered && LHSType->isFunctionPointerType() &&12634      RHSType->isFunctionPointerType()) {12635    // Valid unless a relational comparison of function pointers12636    bool IsError = Opc == BO_Cmp;12637    auto DiagID =12638        IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers12639        : getLangOpts().CPlusPlus12640            ? diag::warn_typecheck_ordered_comparison_of_function_pointers12641            : diag::ext_typecheck_ordered_comparison_of_function_pointers;12642    Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()12643                      << RHS.get()->getSourceRange();12644    if (IsError)12645      return QualType();12646  }12647 12648  if ((LHSType->isIntegerType() && !LHSIsNull) ||12649      (RHSType->isIntegerType() && !RHSIsNull)) {12650    // Skip normal pointer conversion checks in this case; we have better12651    // diagnostics for this below.12652  } else if (getLangOpts().CPlusPlus) {12653    // Equality comparison of a function pointer to a void pointer is invalid,12654    // but we allow it as an extension.12655    // FIXME: If we really want to allow this, should it be part of composite12656    // pointer type computation so it works in conditionals too?12657    if (!IsOrdered &&12658        ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||12659         (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {12660      // This is a gcc extension compatibility comparison.12661      // In a SFINAE context, we treat this as a hard error to maintain12662      // conformance with the C++ standard.12663      bool IsError = isSFINAEContext();12664      diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);12665 12666      if (IsError)12667        return QualType();12668 12669      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);12670      return computeResultTy();12671    }12672 12673    // C++ [expr.eq]p2:12674    //   If at least one operand is a pointer [...] bring them to their12675    //   composite pointer type.12676    // C++ [expr.spaceship]p612677    //  If at least one of the operands is of pointer type, [...] bring them12678    //  to their composite pointer type.12679    // C++ [expr.rel]p2:12680    //   If both operands are pointers, [...] bring them to their composite12681    //   pointer type.12682    // For <=>, the only valid non-pointer types are arrays and functions, and12683    // we already decayed those, so this is really the same as the relational12684    // comparison rule.12685    if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=12686            (IsOrdered ? 2 : 1) &&12687        (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||12688                                         RHSType->isObjCObjectPointerType()))) {12689      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))12690        return QualType();12691      return computeResultTy();12692    }12693  } else if (LHSType->isPointerType() &&12694             RHSType->isPointerType()) { // C99 6.5.8p212695    // All of the following pointer-related warnings are GCC extensions, except12696    // when handling null pointer constants.12697    QualType LCanPointeeTy =12698      LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();12699    QualType RCanPointeeTy =12700      RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();12701 12702    // C99 6.5.9p2 and C99 6.5.8p212703    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),12704                                   RCanPointeeTy.getUnqualifiedType())) {12705      if (IsRelational) {12706        // Pointers both need to point to complete or incomplete types12707        if ((LCanPointeeTy->isIncompleteType() !=12708             RCanPointeeTy->isIncompleteType()) &&12709            !getLangOpts().C11) {12710          Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)12711              << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()12712              << LHSType << RHSType << LCanPointeeTy->isIncompleteType()12713              << RCanPointeeTy->isIncompleteType();12714        }12715      }12716    } else if (!IsRelational &&12717               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {12718      // Valid unless comparison between non-null pointer and function pointer12719      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())12720          && !LHSIsNull && !RHSIsNull)12721        diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,12722                                                /*isError*/false);12723    } else {12724      // Invalid12725      diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);12726    }12727    if (LCanPointeeTy != RCanPointeeTy) {12728      // Treat NULL constant as a special case in OpenCL.12729      if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {12730        if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,12731                                                     getASTContext())) {12732          Diag(Loc,12733               diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)12734              << LHSType << RHSType << 0 /* comparison */12735              << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();12736        }12737      }12738      LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();12739      LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();12740      CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion12741                                               : CK_BitCast;12742 12743      const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();12744      const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();12745      bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();12746      bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();12747      bool ChangingCFIUncheckedCallee =12748          LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;12749 12750      if (LHSIsNull && !RHSIsNull)12751        LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);12752      else if (!ChangingCFIUncheckedCallee)12753        RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);12754    }12755    return computeResultTy();12756  }12757 12758 12759  // C++ [expr.eq]p4:12760  //   Two operands of type std::nullptr_t or one operand of type12761  //   std::nullptr_t and the other a null pointer constant compare12762  //   equal.12763  // C23 6.5.9p5:12764  //   If both operands have type nullptr_t or one operand has type nullptr_t12765  //   and the other is a null pointer constant, they compare equal if the12766  //   former is a null pointer.12767  if (!IsOrdered && LHSIsNull && RHSIsNull) {12768    if (LHSType->isNullPtrType()) {12769      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12770      return computeResultTy();12771    }12772    if (RHSType->isNullPtrType()) {12773      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12774      return computeResultTy();12775    }12776  }12777 12778  if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {12779    // C23 6.5.9p6:12780    //   Otherwise, at least one operand is a pointer. If one is a pointer and12781    //   the other is a null pointer constant or has type nullptr_t, they12782    //   compare equal12783    if (LHSIsNull && RHSType->isPointerType()) {12784      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12785      return computeResultTy();12786    }12787    if (RHSIsNull && LHSType->isPointerType()) {12788      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12789      return computeResultTy();12790    }12791  }12792 12793  // Comparison of Objective-C pointers and block pointers against nullptr_t.12794  // These aren't covered by the composite pointer type rules.12795  if (!IsOrdered && RHSType->isNullPtrType() &&12796      (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {12797    RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12798    return computeResultTy();12799  }12800  if (!IsOrdered && LHSType->isNullPtrType() &&12801      (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {12802    LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12803    return computeResultTy();12804  }12805 12806  if (getLangOpts().CPlusPlus) {12807    if (IsRelational &&12808        ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||12809         (RHSType->isNullPtrType() && LHSType->isPointerType()))) {12810      // HACK: Relational comparison of nullptr_t against a pointer type is12811      // invalid per DR583, but we allow it within std::less<> and friends,12812      // since otherwise common uses of it break.12813      // FIXME: Consider removing this hack once LWG fixes std::less<> and12814      // friends to have std::nullptr_t overload candidates.12815      DeclContext *DC = CurContext;12816      if (isa<FunctionDecl>(DC))12817        DC = DC->getParent();12818      if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {12819        if (CTSD->isInStdNamespace() &&12820            llvm::StringSwitch<bool>(CTSD->getName())12821                .Cases({"less", "less_equal", "greater", "greater_equal"}, true)12822                .Default(false)) {12823          if (RHSType->isNullPtrType())12824            RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12825          else12826            LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12827          return computeResultTy();12828        }12829      }12830    }12831 12832    // C++ [expr.eq]p2:12833    //   If at least one operand is a pointer to member, [...] bring them to12834    //   their composite pointer type.12835    if (!IsOrdered &&12836        (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {12837      if (convertPointersToCompositeType(*this, Loc, LHS, RHS))12838        return QualType();12839      else12840        return computeResultTy();12841    }12842  }12843 12844  // Handle block pointer types.12845  if (!IsOrdered && LHSType->isBlockPointerType() &&12846      RHSType->isBlockPointerType()) {12847    QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();12848    QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();12849 12850    if (!LHSIsNull && !RHSIsNull &&12851        !Context.typesAreCompatible(lpointee, rpointee)) {12852      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)12853        << LHSType << RHSType << LHS.get()->getSourceRange()12854        << RHS.get()->getSourceRange();12855    }12856    RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);12857    return computeResultTy();12858  }12859 12860  // Allow block pointers to be compared with null pointer constants.12861  if (!IsOrdered12862      && ((LHSType->isBlockPointerType() && RHSType->isPointerType())12863          || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {12864    if (!LHSIsNull && !RHSIsNull) {12865      if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()12866             ->getPointeeType()->isVoidType())12867            || (LHSType->isPointerType() && LHSType->castAs<PointerType>()12868                ->getPointeeType()->isVoidType())))12869        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)12870          << LHSType << RHSType << LHS.get()->getSourceRange()12871          << RHS.get()->getSourceRange();12872    }12873    if (LHSIsNull && !RHSIsNull)12874      LHS = ImpCastExprToType(LHS.get(), RHSType,12875                              RHSType->isPointerType() ? CK_BitCast12876                                : CK_AnyPointerToBlockPointerCast);12877    else12878      RHS = ImpCastExprToType(RHS.get(), LHSType,12879                              LHSType->isPointerType() ? CK_BitCast12880                                : CK_AnyPointerToBlockPointerCast);12881    return computeResultTy();12882  }12883 12884  if (LHSType->isObjCObjectPointerType() ||12885      RHSType->isObjCObjectPointerType()) {12886    const PointerType *LPT = LHSType->getAs<PointerType>();12887    const PointerType *RPT = RHSType->getAs<PointerType>();12888    if (LPT || RPT) {12889      bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;12890      bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;12891 12892      if (!LPtrToVoid && !RPtrToVoid &&12893          !Context.typesAreCompatible(LHSType, RHSType)) {12894        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,12895                                          /*isError*/false);12896      }12897      // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than12898      // the RHS, but we have test coverage for this behavior.12899      // FIXME: Consider using convertPointersToCompositeType in C++.12900      if (LHSIsNull && !RHSIsNull) {12901        Expr *E = LHS.get();12902        if (getLangOpts().ObjCAutoRefCount)12903          ObjC().CheckObjCConversion(SourceRange(), RHSType, E,12904                                     CheckedConversionKind::Implicit);12905        LHS = ImpCastExprToType(E, RHSType,12906                                RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);12907      }12908      else {12909        Expr *E = RHS.get();12910        if (getLangOpts().ObjCAutoRefCount)12911          ObjC().CheckObjCConversion(SourceRange(), LHSType, E,12912                                     CheckedConversionKind::Implicit,12913                                     /*Diagnose=*/true,12914                                     /*DiagnoseCFAudited=*/false, Opc);12915        RHS = ImpCastExprToType(E, LHSType,12916                                LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);12917      }12918      return computeResultTy();12919    }12920    if (LHSType->isObjCObjectPointerType() &&12921        RHSType->isObjCObjectPointerType()) {12922      if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))12923        diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,12924                                          /*isError*/false);12925      if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))12926        diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);12927 12928      if (LHSIsNull && !RHSIsNull)12929        LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);12930      else12931        RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);12932      return computeResultTy();12933    }12934 12935    if (!IsOrdered && LHSType->isBlockPointerType() &&12936        RHSType->isBlockCompatibleObjCPointerType(Context)) {12937      LHS = ImpCastExprToType(LHS.get(), RHSType,12938                              CK_BlockPointerToObjCPointerCast);12939      return computeResultTy();12940    } else if (!IsOrdered &&12941               LHSType->isBlockCompatibleObjCPointerType(Context) &&12942               RHSType->isBlockPointerType()) {12943      RHS = ImpCastExprToType(RHS.get(), LHSType,12944                              CK_BlockPointerToObjCPointerCast);12945      return computeResultTy();12946    }12947  }12948  if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||12949      (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {12950    unsigned DiagID = 0;12951    bool isError = false;12952    if (LangOpts.DebuggerSupport) {12953      // Under a debugger, allow the comparison of pointers to integers,12954      // since users tend to want to compare addresses.12955    } else if ((LHSIsNull && LHSType->isIntegerType()) ||12956               (RHSIsNull && RHSType->isIntegerType())) {12957      if (IsOrdered) {12958        isError = getLangOpts().CPlusPlus;12959        DiagID =12960          isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero12961                  : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;12962      }12963    } else if (getLangOpts().CPlusPlus) {12964      DiagID = diag::err_typecheck_comparison_of_pointer_integer;12965      isError = true;12966    } else if (IsOrdered)12967      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;12968    else12969      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;12970 12971    if (DiagID) {12972      Diag(Loc, DiagID)12973        << LHSType << RHSType << LHS.get()->getSourceRange()12974        << RHS.get()->getSourceRange();12975      if (isError)12976        return QualType();12977    }12978 12979    if (LHSType->isIntegerType())12980      LHS = ImpCastExprToType(LHS.get(), RHSType,12981                        LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);12982    else12983      RHS = ImpCastExprToType(RHS.get(), LHSType,12984                        RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);12985    return computeResultTy();12986  }12987 12988  // Handle block pointers.12989  if (!IsOrdered && RHSIsNull12990      && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {12991    RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);12992    return computeResultTy();12993  }12994  if (!IsOrdered && LHSIsNull12995      && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {12996    LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);12997    return computeResultTy();12998  }12999 13000  if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {13001    if (LHSType->isClkEventT() && RHSType->isClkEventT()) {13002      return computeResultTy();13003    }13004 13005    if (LHSType->isQueueT() && RHSType->isQueueT()) {13006      return computeResultTy();13007    }13008 13009    if (LHSIsNull && RHSType->isQueueT()) {13010      LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);13011      return computeResultTy();13012    }13013 13014    if (LHSType->isQueueT() && RHSIsNull) {13015      RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);13016      return computeResultTy();13017    }13018  }13019 13020  return InvalidOperands(Loc, LHS, RHS);13021}13022 13023QualType Sema::GetSignedVectorType(QualType V) {13024  const VectorType *VTy = V->castAs<VectorType>();13025  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());13026 13027  if (isa<ExtVectorType>(VTy)) {13028    if (VTy->isExtVectorBoolType())13029      return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());13030    if (TypeSize == Context.getTypeSize(Context.CharTy))13031      return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());13032    if (TypeSize == Context.getTypeSize(Context.ShortTy))13033      return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());13034    if (TypeSize == Context.getTypeSize(Context.IntTy))13035      return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());13036    if (TypeSize == Context.getTypeSize(Context.Int128Ty))13037      return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());13038    if (TypeSize == Context.getTypeSize(Context.LongTy))13039      return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());13040    assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&13041           "Unhandled vector element size in vector compare");13042    return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());13043  }13044 13045  if (TypeSize == Context.getTypeSize(Context.Int128Ty))13046    return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),13047                                 VectorKind::Generic);13048  if (TypeSize == Context.getTypeSize(Context.LongLongTy))13049    return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),13050                                 VectorKind::Generic);13051  if (TypeSize == Context.getTypeSize(Context.LongTy))13052    return Context.getVectorType(Context.LongTy, VTy->getNumElements(),13053                                 VectorKind::Generic);13054  if (TypeSize == Context.getTypeSize(Context.IntTy))13055    return Context.getVectorType(Context.IntTy, VTy->getNumElements(),13056                                 VectorKind::Generic);13057  if (TypeSize == Context.getTypeSize(Context.ShortTy))13058    return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),13059                                 VectorKind::Generic);13060  assert(TypeSize == Context.getTypeSize(Context.CharTy) &&13061         "Unhandled vector element size in vector compare");13062  return Context.getVectorType(Context.CharTy, VTy->getNumElements(),13063                               VectorKind::Generic);13064}13065 13066QualType Sema::GetSignedSizelessVectorType(QualType V) {13067  const BuiltinType *VTy = V->castAs<BuiltinType>();13068  assert(VTy->isSizelessBuiltinType() && "expected sizeless type");13069 13070  const QualType ETy = V->getSveEltType(Context);13071  const auto TypeSize = Context.getTypeSize(ETy);13072 13073  const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);13074  const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;13075  return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());13076}13077 13078QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,13079                                          SourceLocation Loc,13080                                          BinaryOperatorKind Opc) {13081  if (Opc == BO_Cmp) {13082    Diag(Loc, diag::err_three_way_vector_comparison);13083    return QualType();13084  }13085 13086  // Check to make sure we're operating on vectors of the same type and width,13087  // Allowing one side to be a scalar of element type.13088  QualType vType =13089      CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,13090                          /*AllowBothBool*/ true,13091                          /*AllowBoolConversions*/ getLangOpts().ZVector,13092                          /*AllowBooleanOperation*/ true,13093                          /*ReportInvalid*/ true);13094  if (vType.isNull())13095    return vType;13096 13097  QualType LHSType = LHS.get()->getType();13098 13099  // Determine the return type of a vector compare. By default clang will return13100  // a scalar for all vector compares except vector bool and vector pixel.13101  // With the gcc compiler we will always return a vector type and with the xl13102  // compiler we will always return a scalar type. This switch allows choosing13103  // which behavior is prefered.13104  if (getLangOpts().AltiVec) {13105    switch (getLangOpts().getAltivecSrcCompat()) {13106    case LangOptions::AltivecSrcCompatKind::Mixed:13107      // If AltiVec, the comparison results in a numeric type, i.e.13108      // bool for C++, int for C13109      if (vType->castAs<VectorType>()->getVectorKind() ==13110          VectorKind::AltiVecVector)13111        return Context.getLogicalOperationType();13112      else13113        Diag(Loc, diag::warn_deprecated_altivec_src_compat);13114      break;13115    case LangOptions::AltivecSrcCompatKind::GCC:13116      // For GCC we always return the vector type.13117      break;13118    case LangOptions::AltivecSrcCompatKind::XL:13119      return Context.getLogicalOperationType();13120      break;13121    }13122  }13123 13124  // For non-floating point types, check for self-comparisons of the form13125  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and13126  // often indicate logic errors in the program.13127  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);13128 13129  // Check for comparisons of floating point operands using != and ==.13130  if (LHSType->hasFloatingRepresentation()) {13131    assert(RHS.get()->getType()->hasFloatingRepresentation());13132    CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);13133  }13134 13135  // Return a signed type for the vector.13136  return GetSignedVectorType(vType);13137}13138 13139QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,13140                                                  ExprResult &RHS,13141                                                  SourceLocation Loc,13142                                                  BinaryOperatorKind Opc) {13143  if (Opc == BO_Cmp) {13144    Diag(Loc, diag::err_three_way_vector_comparison);13145    return QualType();13146  }13147 13148  // Check to make sure we're operating on vectors of the same type and width,13149  // Allowing one side to be a scalar of element type.13150  QualType vType = CheckSizelessVectorOperands(13151      LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);13152 13153  if (vType.isNull())13154    return vType;13155 13156  QualType LHSType = LHS.get()->getType();13157 13158  // For non-floating point types, check for self-comparisons of the form13159  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and13160  // often indicate logic errors in the program.13161  diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);13162 13163  // Check for comparisons of floating point operands using != and ==.13164  if (LHSType->hasFloatingRepresentation()) {13165    assert(RHS.get()->getType()->hasFloatingRepresentation());13166    CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);13167  }13168 13169  const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();13170  const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();13171 13172  if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&13173      RHSBuiltinTy->isSVEBool())13174    return LHSType;13175 13176  // Return a signed type for the vector.13177  return GetSignedSizelessVectorType(vType);13178}13179 13180static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,13181                                    const ExprResult &XorRHS,13182                                    const SourceLocation Loc) {13183  // Do not diagnose macros.13184  if (Loc.isMacroID())13185    return;13186 13187  // Do not diagnose if both LHS and RHS are macros.13188  if (XorLHS.get()->getExprLoc().isMacroID() &&13189      XorRHS.get()->getExprLoc().isMacroID())13190    return;13191 13192  bool Negative = false;13193  bool ExplicitPlus = false;13194  const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());13195  const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());13196 13197  if (!LHSInt)13198    return;13199  if (!RHSInt) {13200    // Check negative literals.13201    if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {13202      UnaryOperatorKind Opc = UO->getOpcode();13203      if (Opc != UO_Minus && Opc != UO_Plus)13204        return;13205      RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());13206      if (!RHSInt)13207        return;13208      Negative = (Opc == UO_Minus);13209      ExplicitPlus = !Negative;13210    } else {13211      return;13212    }13213  }13214 13215  const llvm::APInt &LeftSideValue = LHSInt->getValue();13216  llvm::APInt RightSideValue = RHSInt->getValue();13217  if (LeftSideValue != 2 && LeftSideValue != 10)13218    return;13219 13220  if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())13221    return;13222 13223  CharSourceRange ExprRange = CharSourceRange::getCharRange(13224      LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));13225  llvm::StringRef ExprStr =13226      Lexer::getSourceText(ExprRange, S.getSourceManager(), S.getLangOpts());13227 13228  CharSourceRange XorRange =13229      CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));13230  llvm::StringRef XorStr =13231      Lexer::getSourceText(XorRange, S.getSourceManager(), S.getLangOpts());13232  // Do not diagnose if xor keyword/macro is used.13233  if (XorStr == "xor")13234    return;13235 13236  std::string LHSStr = std::string(Lexer::getSourceText(13237      CharSourceRange::getTokenRange(LHSInt->getSourceRange()),13238      S.getSourceManager(), S.getLangOpts()));13239  std::string RHSStr = std::string(Lexer::getSourceText(13240      CharSourceRange::getTokenRange(RHSInt->getSourceRange()),13241      S.getSourceManager(), S.getLangOpts()));13242 13243  if (Negative) {13244    RightSideValue = -RightSideValue;13245    RHSStr = "-" + RHSStr;13246  } else if (ExplicitPlus) {13247    RHSStr = "+" + RHSStr;13248  }13249 13250  StringRef LHSStrRef = LHSStr;13251  StringRef RHSStrRef = RHSStr;13252  // Do not diagnose literals with digit separators, binary, hexadecimal, octal13253  // literals.13254  if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||13255      RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||13256      LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||13257      RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||13258      (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||13259      (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||13260      LHSStrRef.contains('\'') || RHSStrRef.contains('\''))13261    return;13262 13263  bool SuggestXor =13264      S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");13265  const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;13266  int64_t RightSideIntValue = RightSideValue.getSExtValue();13267  if (LeftSideValue == 2 && RightSideIntValue >= 0) {13268    std::string SuggestedExpr = "1 << " + RHSStr;13269    bool Overflow = false;13270    llvm::APInt One = (LeftSideValue - 1);13271    llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);13272    if (Overflow) {13273      if (RightSideIntValue < 64)13274        S.Diag(Loc, diag::warn_xor_used_as_pow_base)13275            << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)13276            << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);13277      else if (RightSideIntValue == 64)13278        S.Diag(Loc, diag::warn_xor_used_as_pow)13279            << ExprStr << toString(XorValue, 10, true);13280      else13281        return;13282    } else {13283      S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)13284          << ExprStr << toString(XorValue, 10, true) << SuggestedExpr13285          << toString(PowValue, 10, true)13286          << FixItHint::CreateReplacement(13287                 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);13288    }13289 13290    S.Diag(Loc, diag::note_xor_used_as_pow_silence)13291        << ("0x2 ^ " + RHSStr) << SuggestXor;13292  } else if (LeftSideValue == 10) {13293    std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);13294    S.Diag(Loc, diag::warn_xor_used_as_pow_base)13295        << ExprStr << toString(XorValue, 10, true) << SuggestedValue13296        << FixItHint::CreateReplacement(ExprRange, SuggestedValue);13297    S.Diag(Loc, diag::note_xor_used_as_pow_silence)13298        << ("0xA ^ " + RHSStr) << SuggestXor;13299  }13300}13301 13302QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,13303                                          SourceLocation Loc,13304                                          BinaryOperatorKind Opc) {13305  // Ensure that either both operands are of the same vector type, or13306  // one operand is of a vector type and the other is of its element type.13307  QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,13308                                       /*AllowBothBool*/ true,13309                                       /*AllowBoolConversions*/ false,13310                                       /*AllowBooleanOperation*/ false,13311                                       /*ReportInvalid*/ false);13312  if (vType.isNull())13313    return InvalidOperands(Loc, LHS, RHS);13314  if (getLangOpts().OpenCL &&13315      getLangOpts().getOpenCLCompatibleVersion() < 120 &&13316      vType->hasFloatingRepresentation())13317    return InvalidOperands(Loc, LHS, RHS);13318  // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the13319  //        usage of the logical operators && and || with vectors in C. This13320  //        check could be notionally dropped.13321  if (!getLangOpts().CPlusPlus &&13322      !(isa<ExtVectorType>(vType->getAs<VectorType>())))13323    return InvalidLogicalVectorOperands(Loc, LHS, RHS);13324  // Beginning with HLSL 2021, HLSL disallows logical operators on vector13325  // operands and instead requires the use of the `and`, `or`, `any`, `all`, and13326  // `select` functions.13327  if (getLangOpts().HLSL &&13328      getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {13329    (void)InvalidOperands(Loc, LHS, RHS);13330    HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);13331    return QualType();13332  }13333 13334  return GetSignedVectorType(LHS.get()->getType());13335}13336 13337QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,13338                                              SourceLocation Loc,13339                                              bool IsCompAssign) {13340  if (!IsCompAssign) {13341    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());13342    if (LHS.isInvalid())13343      return QualType();13344  }13345  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());13346  if (RHS.isInvalid())13347    return QualType();13348 13349  // For conversion purposes, we ignore any qualifiers.13350  // For example, "const float" and "float" are equivalent.13351  QualType LHSType = LHS.get()->getType().getUnqualifiedType();13352  QualType RHSType = RHS.get()->getType().getUnqualifiedType();13353 13354  const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();13355  const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();13356  assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");13357 13358  if (Context.hasSameType(LHSType, RHSType))13359    return Context.getCommonSugaredType(LHSType, RHSType);13360 13361  // Type conversion may change LHS/RHS. Keep copies to the original results, in13362  // case we have to return InvalidOperands.13363  ExprResult OriginalLHS = LHS;13364  ExprResult OriginalRHS = RHS;13365  if (LHSMatType && !RHSMatType) {13366    RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());13367    if (!RHS.isInvalid())13368      return LHSType;13369 13370    return InvalidOperands(Loc, OriginalLHS, OriginalRHS);13371  }13372 13373  if (!LHSMatType && RHSMatType) {13374    LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());13375    if (!LHS.isInvalid())13376      return RHSType;13377    return InvalidOperands(Loc, OriginalLHS, OriginalRHS);13378  }13379 13380  return InvalidOperands(Loc, LHS, RHS);13381}13382 13383QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,13384                                           SourceLocation Loc,13385                                           bool IsCompAssign) {13386  if (!IsCompAssign) {13387    LHS = DefaultFunctionArrayLvalueConversion(LHS.get());13388    if (LHS.isInvalid())13389      return QualType();13390  }13391  RHS = DefaultFunctionArrayLvalueConversion(RHS.get());13392  if (RHS.isInvalid())13393    return QualType();13394 13395  auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();13396  auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();13397  assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");13398 13399  if (LHSMatType && RHSMatType) {13400    if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())13401      return InvalidOperands(Loc, LHS, RHS);13402 13403    if (Context.hasSameType(LHSMatType, RHSMatType))13404      return Context.getCommonSugaredType(13405          LHS.get()->getType().getUnqualifiedType(),13406          RHS.get()->getType().getUnqualifiedType());13407 13408    QualType LHSELTy = LHSMatType->getElementType(),13409             RHSELTy = RHSMatType->getElementType();13410    if (!Context.hasSameType(LHSELTy, RHSELTy))13411      return InvalidOperands(Loc, LHS, RHS);13412 13413    return Context.getConstantMatrixType(13414        Context.getCommonSugaredType(LHSELTy, RHSELTy),13415        LHSMatType->getNumRows(), RHSMatType->getNumColumns());13416  }13417  return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);13418}13419 13420static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {13421  switch (Opc) {13422  default:13423    return false;13424  case BO_And:13425  case BO_AndAssign:13426  case BO_Or:13427  case BO_OrAssign:13428  case BO_Xor:13429  case BO_XorAssign:13430    return true;13431  }13432}13433 13434inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,13435                                           SourceLocation Loc,13436                                           BinaryOperatorKind Opc) {13437  checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);13438 13439  bool IsCompAssign =13440      Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;13441 13442  bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);13443 13444  if (LHS.get()->getType()->isVectorType() ||13445      RHS.get()->getType()->isVectorType()) {13446    if (LHS.get()->getType()->hasIntegerRepresentation() &&13447        RHS.get()->getType()->hasIntegerRepresentation())13448      return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,13449                                 /*AllowBothBool*/ true,13450                                 /*AllowBoolConversions*/ getLangOpts().ZVector,13451                                 /*AllowBooleanOperation*/ LegalBoolVecOperator,13452                                 /*ReportInvalid*/ true);13453    return InvalidOperands(Loc, LHS, RHS);13454  }13455 13456  if (LHS.get()->getType()->isSveVLSBuiltinType() ||13457      RHS.get()->getType()->isSveVLSBuiltinType()) {13458    if (LHS.get()->getType()->hasIntegerRepresentation() &&13459        RHS.get()->getType()->hasIntegerRepresentation())13460      return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,13461                                         ArithConvKind::BitwiseOp);13462    return InvalidOperands(Loc, LHS, RHS);13463  }13464 13465  if (LHS.get()->getType()->isSveVLSBuiltinType() ||13466      RHS.get()->getType()->isSveVLSBuiltinType()) {13467    if (LHS.get()->getType()->hasIntegerRepresentation() &&13468        RHS.get()->getType()->hasIntegerRepresentation())13469      return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,13470                                         ArithConvKind::BitwiseOp);13471    return InvalidOperands(Loc, LHS, RHS);13472  }13473 13474  if (Opc == BO_And)13475    diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);13476 13477  if (LHS.get()->getType()->hasFloatingRepresentation() ||13478      RHS.get()->getType()->hasFloatingRepresentation())13479    return InvalidOperands(Loc, LHS, RHS);13480 13481  ExprResult LHSResult = LHS, RHSResult = RHS;13482  QualType compType = UsualArithmeticConversions(13483      LHSResult, RHSResult, Loc,13484      IsCompAssign ? ArithConvKind::CompAssign : ArithConvKind::BitwiseOp);13485  if (LHSResult.isInvalid() || RHSResult.isInvalid())13486    return QualType();13487  LHS = LHSResult.get();13488  RHS = RHSResult.get();13489 13490  if (Opc == BO_Xor)13491    diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);13492 13493  if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())13494    return compType;13495  QualType ResultTy = InvalidOperands(Loc, LHS, RHS);13496  diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);13497  return ResultTy;13498}13499 13500// C99 6.5.[13,14]13501inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,13502                                           SourceLocation Loc,13503                                           BinaryOperatorKind Opc) {13504  // Check vector operands differently.13505  if (LHS.get()->getType()->isVectorType() ||13506      RHS.get()->getType()->isVectorType())13507    return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);13508 13509  bool EnumConstantInBoolContext = false;13510  for (const ExprResult &HS : {LHS, RHS}) {13511    if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {13512      const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());13513      if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)13514        EnumConstantInBoolContext = true;13515    }13516  }13517 13518  if (EnumConstantInBoolContext)13519    Diag(Loc, diag::warn_enum_constant_in_bool_context);13520 13521  // WebAssembly tables can't be used with logical operators.13522  QualType LHSTy = LHS.get()->getType();13523  QualType RHSTy = RHS.get()->getType();13524  const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);13525  const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);13526  if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||13527      (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {13528    return InvalidOperands(Loc, LHS, RHS);13529  }13530 13531  // Diagnose cases where the user write a logical and/or but probably meant a13532  // bitwise one.  We do this when the LHS is a non-bool integer and the RHS13533  // is a constant.13534  if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&13535      !LHS.get()->getType()->isBooleanType() &&13536      RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&13537      // Don't warn in macros or template instantiations.13538      !Loc.isMacroID() && !inTemplateInstantiation()) {13539    // If the RHS can be constant folded, and if it constant folds to something13540    // that isn't 0 or 1 (which indicate a potential logical operation that13541    // happened to fold to true/false) then warn.13542    // Parens on the RHS are ignored.13543    Expr::EvalResult EVResult;13544    if (RHS.get()->EvaluateAsInt(EVResult, Context)) {13545      llvm::APSInt Result = EVResult.Val.getInt();13546      if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&13547           !RHS.get()->getExprLoc().isMacroID()) ||13548          (Result != 0 && Result != 1)) {13549        Diag(Loc, diag::warn_logical_instead_of_bitwise)13550            << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");13551        // Suggest replacing the logical operator with the bitwise version13552        Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)13553            << (Opc == BO_LAnd ? "&" : "|")13554            << FixItHint::CreateReplacement(13555                   SourceRange(Loc, getLocForEndOfToken(Loc)),13556                   Opc == BO_LAnd ? "&" : "|");13557        if (Opc == BO_LAnd)13558          // Suggest replacing "Foo() && kNonZero" with "Foo()"13559          Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)13560              << FixItHint::CreateRemoval(13561                     SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),13562                                 RHS.get()->getEndLoc()));13563      }13564    }13565  }13566 13567  if (!Context.getLangOpts().CPlusPlus) {13568    // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do13569    // not operate on the built-in scalar and vector float types.13570    if (Context.getLangOpts().OpenCL &&13571        Context.getLangOpts().OpenCLVersion < 120) {13572      if (LHS.get()->getType()->isFloatingType() ||13573          RHS.get()->getType()->isFloatingType())13574        return InvalidOperands(Loc, LHS, RHS);13575    }13576 13577    LHS = UsualUnaryConversions(LHS.get());13578    if (LHS.isInvalid())13579      return QualType();13580 13581    RHS = UsualUnaryConversions(RHS.get());13582    if (RHS.isInvalid())13583      return QualType();13584 13585    if (!LHS.get()->getType()->isScalarType() ||13586        !RHS.get()->getType()->isScalarType())13587      return InvalidOperands(Loc, LHS, RHS);13588 13589    return Context.IntTy;13590  }13591 13592  // The following is safe because we only use this method for13593  // non-overloadable operands.13594 13595  // C++ [expr.log.and]p113596  // C++ [expr.log.or]p113597  // The operands are both contextually converted to type bool.13598  ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());13599  if (LHSRes.isInvalid()) {13600    QualType ResultTy = InvalidOperands(Loc, LHS, RHS);13601    diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);13602    return ResultTy;13603  }13604  LHS = LHSRes;13605 13606  ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());13607  if (RHSRes.isInvalid()) {13608    QualType ResultTy = InvalidOperands(Loc, LHS, RHS);13609    diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);13610    return ResultTy;13611  }13612  RHS = RHSRes;13613 13614  // C++ [expr.log.and]p213615  // C++ [expr.log.or]p213616  // The result is a bool.13617  return Context.BoolTy;13618}13619 13620static bool IsReadonlyMessage(Expr *E, Sema &S) {13621  const MemberExpr *ME = dyn_cast<MemberExpr>(E);13622  if (!ME) return false;13623  if (!isa<FieldDecl>(ME->getMemberDecl())) return false;13624  ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(13625      ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());13626  if (!Base) return false;13627  return Base->getMethodDecl() != nullptr;13628}13629 13630/// Is the given expression (which must be 'const') a reference to a13631/// variable which was originally non-const, but which has become13632/// 'const' due to being captured within a block?13633enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };13634static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {13635  assert(E->isLValue() && E->getType().isConstQualified());13636  E = E->IgnoreParens();13637 13638  // Must be a reference to a declaration from an enclosing scope.13639  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);13640  if (!DRE) return NCCK_None;13641  if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;13642 13643  ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());13644 13645  // The declaration must be a value which is not declared 'const'.13646  if (!Value || Value->getType().isConstQualified())13647    return NCCK_None;13648 13649  BindingDecl *Binding = dyn_cast<BindingDecl>(Value);13650  if (Binding) {13651    assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");13652    assert(!isa<BlockDecl>(Binding->getDeclContext()));13653    return NCCK_Lambda;13654  }13655 13656  VarDecl *Var = dyn_cast<VarDecl>(Value);13657  if (!Var)13658    return NCCK_None;13659  if (Var->getType()->isReferenceType())13660    return NCCK_None;13661 13662  assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");13663 13664  // Decide whether the first capture was for a block or a lambda.13665  DeclContext *DC = S.CurContext, *Prev = nullptr;13666  // Decide whether the first capture was for a block or a lambda.13667  while (DC) {13668    // For init-capture, it is possible that the variable belongs to the13669    // template pattern of the current context.13670    if (auto *FD = dyn_cast<FunctionDecl>(DC))13671      if (Var->isInitCapture() &&13672          FD->getTemplateInstantiationPattern() == Var->getDeclContext())13673        break;13674    if (DC == Var->getDeclContext())13675      break;13676    Prev = DC;13677    DC = DC->getParent();13678  }13679  // Unless we have an init-capture, we've gone one step too far.13680  if (!Var->isInitCapture())13681    DC = Prev;13682  return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);13683}13684 13685static bool IsTypeModifiable(QualType Ty, bool IsDereference) {13686  Ty = Ty.getNonReferenceType();13687  if (IsDereference && Ty->isPointerType())13688    Ty = Ty->getPointeeType();13689  return !Ty.isConstQualified();13690}13691 13692// Update err_typecheck_assign_const and note_typecheck_assign_const13693// when this enum is changed.13694enum {13695  ConstFunction,13696  ConstVariable,13697  ConstMember,13698  ConstMethod,13699  NestedConstMember,13700  ConstUnknown,  // Keep as last element13701};13702 13703/// Emit the "read-only variable not assignable" error and print notes to give13704/// more information about why the variable is not assignable, such as pointing13705/// to the declaration of a const variable, showing that a method is const, or13706/// that the function is returning a const reference.13707static void DiagnoseConstAssignment(Sema &S, const Expr *E,13708                                    SourceLocation Loc) {13709  SourceRange ExprRange = E->getSourceRange();13710 13711  // Only emit one error on the first const found.  All other consts will emit13712  // a note to the error.13713  bool DiagnosticEmitted = false;13714 13715  // Track if the current expression is the result of a dereference, and if the13716  // next checked expression is the result of a dereference.13717  bool IsDereference = false;13718  bool NextIsDereference = false;13719 13720  // Loop to process MemberExpr chains.13721  while (true) {13722    IsDereference = NextIsDereference;13723 13724    E = E->IgnoreImplicit()->IgnoreParenImpCasts();13725    if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {13726      NextIsDereference = ME->isArrow();13727      const ValueDecl *VD = ME->getMemberDecl();13728      if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {13729        // Mutable fields can be modified even if the class is const.13730        if (Field->isMutable()) {13731          assert(DiagnosticEmitted && "Expected diagnostic not emitted.");13732          break;13733        }13734 13735        if (!IsTypeModifiable(Field->getType(), IsDereference)) {13736          if (!DiagnosticEmitted) {13737            S.Diag(Loc, diag::err_typecheck_assign_const)13738                << ExprRange << ConstMember << false /*static*/ << Field13739                << Field->getType();13740            DiagnosticEmitted = true;13741          }13742          S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)13743              << ConstMember << false /*static*/ << Field << Field->getType()13744              << Field->getSourceRange();13745        }13746        E = ME->getBase();13747        continue;13748      } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {13749        if (VDecl->getType().isConstQualified()) {13750          if (!DiagnosticEmitted) {13751            S.Diag(Loc, diag::err_typecheck_assign_const)13752                << ExprRange << ConstMember << true /*static*/ << VDecl13753                << VDecl->getType();13754            DiagnosticEmitted = true;13755          }13756          S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)13757              << ConstMember << true /*static*/ << VDecl << VDecl->getType()13758              << VDecl->getSourceRange();13759        }13760        // Static fields do not inherit constness from parents.13761        break;13762      }13763      break; // End MemberExpr13764    } else if (const ArraySubscriptExpr *ASE =13765                   dyn_cast<ArraySubscriptExpr>(E)) {13766      E = ASE->getBase()->IgnoreParenImpCasts();13767      continue;13768    } else if (const ExtVectorElementExpr *EVE =13769                   dyn_cast<ExtVectorElementExpr>(E)) {13770      E = EVE->getBase()->IgnoreParenImpCasts();13771      continue;13772    }13773    break;13774  }13775 13776  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {13777    // Function calls13778    const FunctionDecl *FD = CE->getDirectCallee();13779    if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {13780      if (!DiagnosticEmitted) {13781        S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange13782                                                      << ConstFunction << FD;13783        DiagnosticEmitted = true;13784      }13785      S.Diag(FD->getReturnTypeSourceRange().getBegin(),13786             diag::note_typecheck_assign_const)13787          << ConstFunction << FD << FD->getReturnType()13788          << FD->getReturnTypeSourceRange();13789    }13790  } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {13791    // Point to variable declaration.13792    if (const ValueDecl *VD = DRE->getDecl()) {13793      if (!IsTypeModifiable(VD->getType(), IsDereference)) {13794        if (!DiagnosticEmitted) {13795          S.Diag(Loc, diag::err_typecheck_assign_const)13796              << ExprRange << ConstVariable << VD << VD->getType();13797          DiagnosticEmitted = true;13798        }13799        S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)13800            << ConstVariable << VD << VD->getType() << VD->getSourceRange();13801      }13802    }13803  } else if (isa<CXXThisExpr>(E)) {13804    if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {13805      if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {13806        if (MD->isConst()) {13807          if (!DiagnosticEmitted) {13808            S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange13809                                                          << ConstMethod << MD;13810            DiagnosticEmitted = true;13811          }13812          S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)13813              << ConstMethod << MD << MD->getSourceRange();13814        }13815      }13816    }13817  }13818 13819  if (DiagnosticEmitted)13820    return;13821 13822  // Can't determine a more specific message, so display the generic error.13823  S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;13824}13825 13826enum OriginalExprKind {13827  OEK_Variable,13828  OEK_Member,13829  OEK_LValue13830};13831 13832static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,13833                                         const RecordType *Ty,13834                                         SourceLocation Loc, SourceRange Range,13835                                         OriginalExprKind OEK,13836                                         bool &DiagnosticEmitted) {13837  std::vector<const RecordType *> RecordTypeList;13838  RecordTypeList.push_back(Ty);13839  unsigned NextToCheckIndex = 0;13840  // We walk the record hierarchy breadth-first to ensure that we print13841  // diagnostics in field nesting order.13842  while (RecordTypeList.size() > NextToCheckIndex) {13843    bool IsNested = NextToCheckIndex > 0;13844    for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]13845                                      ->getDecl()13846                                      ->getDefinitionOrSelf()13847                                      ->fields()) {13848      // First, check every field for constness.13849      QualType FieldTy = Field->getType();13850      if (FieldTy.isConstQualified()) {13851        if (!DiagnosticEmitted) {13852          S.Diag(Loc, diag::err_typecheck_assign_const)13853              << Range << NestedConstMember << OEK << VD13854              << IsNested << Field;13855          DiagnosticEmitted = true;13856        }13857        S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)13858            << NestedConstMember << IsNested << Field13859            << FieldTy << Field->getSourceRange();13860      }13861 13862      // Then we append it to the list to check next in order.13863      FieldTy = FieldTy.getCanonicalType();13864      if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {13865        if (!llvm::is_contained(RecordTypeList, FieldRecTy))13866          RecordTypeList.push_back(FieldRecTy);13867      }13868    }13869    ++NextToCheckIndex;13870  }13871}13872 13873/// Emit an error for the case where a record we are trying to assign to has a13874/// const-qualified field somewhere in its hierarchy.13875static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,13876                                         SourceLocation Loc) {13877  QualType Ty = E->getType();13878  assert(Ty->isRecordType() && "lvalue was not record?");13879  SourceRange Range = E->getSourceRange();13880  const auto *RTy = Ty->getAsCanonical<RecordType>();13881  bool DiagEmitted = false;13882 13883  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))13884    DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,13885            Range, OEK_Member, DiagEmitted);13886  else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))13887    DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,13888            Range, OEK_Variable, DiagEmitted);13889  else13890    DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,13891            Range, OEK_LValue, DiagEmitted);13892  if (!DiagEmitted)13893    DiagnoseConstAssignment(S, E, Loc);13894}13895 13896/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,13897/// emit an error and return true.  If so, return false.13898static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {13899  assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));13900 13901  S.CheckShadowingDeclModification(E, Loc);13902 13903  SourceLocation OrigLoc = Loc;13904  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,13905                                                              &Loc);13906  if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))13907    IsLV = Expr::MLV_InvalidMessageExpression;13908  if (IsLV == Expr::MLV_Valid)13909    return false;13910 13911  unsigned DiagID = 0;13912  bool NeedType = false;13913  switch (IsLV) { // C99 6.5.16p213914  case Expr::MLV_ConstQualified:13915    // Use a specialized diagnostic when we're assigning to an object13916    // from an enclosing function or block.13917    if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {13918      if (NCCK == NCCK_Block)13919        DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;13920      else13921        DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;13922      break;13923    }13924 13925    // In ARC, use some specialized diagnostics for occasions where we13926    // infer 'const'.  These are always pseudo-strong variables.13927    if (S.getLangOpts().ObjCAutoRefCount) {13928      DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());13929      if (declRef && isa<VarDecl>(declRef->getDecl())) {13930        VarDecl *var = cast<VarDecl>(declRef->getDecl());13931 13932        // Use the normal diagnostic if it's pseudo-__strong but the13933        // user actually wrote 'const'.13934        if (var->isARCPseudoStrong() &&13935            (!var->getTypeSourceInfo() ||13936             !var->getTypeSourceInfo()->getType().isConstQualified())) {13937          // There are three pseudo-strong cases:13938          //  - self13939          ObjCMethodDecl *method = S.getCurMethodDecl();13940          if (method && var == method->getSelfDecl()) {13941            DiagID = method->isClassMethod()13942              ? diag::err_typecheck_arc_assign_self_class_method13943              : diag::err_typecheck_arc_assign_self;13944 13945          //  - Objective-C externally_retained attribute.13946          } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||13947                     isa<ParmVarDecl>(var)) {13948            DiagID = diag::err_typecheck_arc_assign_externally_retained;13949 13950          //  - fast enumeration variables13951          } else {13952            DiagID = diag::err_typecheck_arr_assign_enumeration;13953          }13954 13955          SourceRange Assign;13956          if (Loc != OrigLoc)13957            Assign = SourceRange(OrigLoc, OrigLoc);13958          S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;13959          // We need to preserve the AST regardless, so migration tool13960          // can do its job.13961          return false;13962        }13963      }13964    }13965 13966    // If none of the special cases above are triggered, then this is a13967    // simple const assignment.13968    if (DiagID == 0) {13969      DiagnoseConstAssignment(S, E, Loc);13970      return true;13971    }13972 13973    break;13974  case Expr::MLV_ConstAddrSpace:13975    DiagnoseConstAssignment(S, E, Loc);13976    return true;13977  case Expr::MLV_ConstQualifiedField:13978    DiagnoseRecursiveConstFields(S, E, Loc);13979    return true;13980  case Expr::MLV_ArrayType:13981  case Expr::MLV_ArrayTemporary:13982    DiagID = diag::err_typecheck_array_not_modifiable_lvalue;13983    NeedType = true;13984    break;13985  case Expr::MLV_NotObjectType:13986    DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;13987    NeedType = true;13988    break;13989  case Expr::MLV_LValueCast:13990    DiagID = diag::err_typecheck_lvalue_casts_not_supported;13991    break;13992  case Expr::MLV_Valid:13993    llvm_unreachable("did not take early return for MLV_Valid");13994  case Expr::MLV_InvalidExpression:13995  case Expr::MLV_MemberFunction:13996  case Expr::MLV_ClassTemporary:13997    DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;13998    break;13999  case Expr::MLV_IncompleteType:14000  case Expr::MLV_IncompleteVoidType:14001    return S.RequireCompleteType(Loc, E->getType(),14002             diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);14003  case Expr::MLV_DuplicateVectorComponents:14004    DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;14005    break;14006  case Expr::MLV_NoSetterProperty:14007    llvm_unreachable("readonly properties should be processed differently");14008  case Expr::MLV_InvalidMessageExpression:14009    DiagID = diag::err_readonly_message_assignment;14010    break;14011  case Expr::MLV_SubObjCPropertySetting:14012    DiagID = diag::err_no_subobject_property_setting;14013    break;14014  }14015 14016  SourceRange Assign;14017  if (Loc != OrigLoc)14018    Assign = SourceRange(OrigLoc, OrigLoc);14019  if (NeedType)14020    S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;14021  else14022    S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;14023  return true;14024}14025 14026static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,14027                                         SourceLocation Loc,14028                                         Sema &Sema) {14029  if (Sema.inTemplateInstantiation())14030    return;14031  if (Sema.isUnevaluatedContext())14032    return;14033  if (Loc.isInvalid() || Loc.isMacroID())14034    return;14035  if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())14036    return;14037 14038  // C / C++ fields14039  MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);14040  MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);14041  if (ML && MR) {14042    if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))14043      return;14044    const ValueDecl *LHSDecl =14045        cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());14046    const ValueDecl *RHSDecl =14047        cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());14048    if (LHSDecl != RHSDecl)14049      return;14050    if (LHSDecl->getType().isVolatileQualified())14051      return;14052    if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())14053      if (RefTy->getPointeeType().isVolatileQualified())14054        return;14055 14056    Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;14057  }14058 14059  // Objective-C instance variables14060  ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);14061  ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);14062  if (OL && OR && OL->getDecl() == OR->getDecl()) {14063    DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());14064    DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());14065    if (RL && RR && RL->getDecl() == RR->getDecl())14066      Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;14067  }14068}14069 14070// C99 6.5.16.114071QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,14072                                       SourceLocation Loc,14073                                       QualType CompoundType,14074                                       BinaryOperatorKind Opc) {14075  assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));14076 14077  // Verify that LHS is a modifiable lvalue, and emit error if not.14078  if (CheckForModifiableLvalue(LHSExpr, Loc, *this))14079    return QualType();14080 14081  QualType LHSType = LHSExpr->getType();14082  QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :14083                                             CompoundType;14084 14085  if (RHS.isUsable()) {14086    // Even if this check fails don't return early to allow the best14087    // possible error recovery and to allow any subsequent diagnostics to14088    // work.14089    const ValueDecl *Assignee = nullptr;14090    bool ShowFullyQualifiedAssigneeName = false;14091    // In simple cases describe what is being assigned to14092    if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {14093      Assignee = DR->getDecl();14094    } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {14095      Assignee = ME->getMemberDecl();14096      ShowFullyQualifiedAssigneeName = true;14097    }14098 14099    BoundsSafetyCheckAssignmentToCountAttrPtr(14100        LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,14101        ShowFullyQualifiedAssigneeName);14102  }14103 14104  // OpenCL v1.2 s6.1.1.1 p2:14105  // The half data type can only be used to declare a pointer to a buffer that14106  // contains half values14107  if (getLangOpts().OpenCL &&14108      !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&14109      LHSType->isHalfType()) {14110    Diag(Loc, diag::err_opencl_half_load_store) << 114111        << LHSType.getUnqualifiedType();14112    return QualType();14113  }14114 14115  // WebAssembly tables can't be used on RHS of an assignment expression.14116  if (RHSType->isWebAssemblyTableType()) {14117    Diag(Loc, diag::err_wasm_table_art) << 0;14118    return QualType();14119  }14120 14121  AssignConvertType ConvTy;14122  if (CompoundType.isNull()) {14123    Expr *RHSCheck = RHS.get();14124 14125    CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);14126 14127    QualType LHSTy(LHSType);14128    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);14129    if (RHS.isInvalid())14130      return QualType();14131    // Special case of NSObject attributes on c-style pointer types.14132    if (ConvTy == AssignConvertType::IncompatiblePointer &&14133        ((Context.isObjCNSObjectType(LHSType) &&14134          RHSType->isObjCObjectPointerType()) ||14135         (Context.isObjCNSObjectType(RHSType) &&14136          LHSType->isObjCObjectPointerType())))14137      ConvTy = AssignConvertType::Compatible;14138 14139    if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())14140      Diag(Loc, diag::err_objc_object_assignment) << LHSType;14141 14142    // If the RHS is a unary plus or minus, check to see if they = and + are14143    // right next to each other.  If so, the user may have typo'd "x =+ 4"14144    // instead of "x += 4".14145    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))14146      RHSCheck = ICE->getSubExpr();14147    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {14148      if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&14149          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&14150          // Only if the two operators are exactly adjacent.14151          Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&14152          // And there is a space or other character before the subexpr of the14153          // unary +/-.  We don't want to warn on "x=-1".14154          Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&14155          UO->getSubExpr()->getBeginLoc().isFileID()) {14156        Diag(Loc, diag::warn_not_compound_assign)14157          << (UO->getOpcode() == UO_Plus ? "+" : "-")14158          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());14159      }14160    }14161 14162    if (IsAssignConvertCompatible(ConvTy)) {14163      if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {14164        // Warn about retain cycles where a block captures the LHS, but14165        // not if the LHS is a simple variable into which the block is14166        // being stored...unless that variable can be captured by reference!14167        const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();14168        const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);14169        if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())14170          ObjC().checkRetainCycles(LHSExpr, RHS.get());14171      }14172 14173      if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||14174          LHSType.isNonWeakInMRRWithObjCWeak(Context)) {14175        // It is safe to assign a weak reference into a strong variable.14176        // Although this code can still have problems:14177        //   id x = self.weakProp;14178        //   id y = self.weakProp;14179        // we do not warn to warn spuriously when 'x' and 'y' are on separate14180        // paths through the function. This should be revisited if14181        // -Wrepeated-use-of-weak is made flow-sensitive.14182        // For ObjCWeak only, we do not warn if the assign is to a non-weak14183        // variable, which will be valid for the current autorelease scope.14184        if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,14185                             RHS.get()->getBeginLoc()))14186          getCurFunction()->markSafeWeakUse(RHS.get());14187 14188      } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {14189        checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());14190      }14191    }14192  } else {14193    // Compound assignment "x += y"14194    ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);14195  }14196 14197  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),14198                               AssignmentAction::Assigning))14199    return QualType();14200 14201  CheckForNullPointerDereference(*this, LHSExpr);14202 14203  AssignedEntity AE{LHSExpr};14204  checkAssignmentLifetime(*this, AE, RHS.get());14205 14206  if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {14207    if (CompoundType.isNull()) {14208      // C++2a [expr.ass]p5:14209      //   A simple-assignment whose left operand is of a volatile-qualified14210      //   type is deprecated unless the assignment is either a discarded-value14211      //   expression or an unevaluated operand14212      ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);14213    }14214  }14215 14216  // C11 6.5.16p3: The type of an assignment expression is the type of the14217  // left operand would have after lvalue conversion.14218  // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has14219  // qualified type, the value has the unqualified version of the type of the14220  // lvalue; additionally, if the lvalue has atomic type, the value has the14221  // non-atomic version of the type of the lvalue.14222  // C++ 5.17p1: the type of the assignment expression is that of its left14223  // operand.14224  return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();14225}14226 14227// Scenarios to ignore if expression E is:14228// 1. an explicit cast expression into void14229// 2. a function call expression that returns void14230static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {14231  E = E->IgnoreParens();14232 14233  if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {14234    if (CE->getCastKind() == CK_ToVoid) {14235      return true;14236    }14237 14238    // static_cast<void> on a dependent type will not show up as CK_ToVoid.14239    if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&14240        CE->getSubExpr()->getType()->isDependentType()) {14241      return true;14242    }14243  }14244 14245  if (const auto *CE = dyn_cast<CallExpr>(E))14246    return CE->getCallReturnType(Context)->isVoidType();14247  return false;14248}14249 14250void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {14251  // No warnings in macros14252  if (Loc.isMacroID())14253    return;14254 14255  // Don't warn in template instantiations.14256  if (inTemplateInstantiation())14257    return;14258 14259  // Scope isn't fine-grained enough to explicitly list the specific cases, so14260  // instead, skip more than needed, then call back into here with the14261  // CommaVisitor in SemaStmt.cpp.14262  // The listed locations are the initialization and increment portions14263  // of a for loop.  The additional checks are on the condition of14264  // if statements, do/while loops, and for loops.14265  // Differences in scope flags for C89 mode requires the extra logic.14266  const unsigned ForIncrementFlags =14267      getLangOpts().C99 || getLangOpts().CPlusPlus14268          ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope14269          : Scope::ContinueScope | Scope::BreakScope;14270  const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;14271  const unsigned ScopeFlags = getCurScope()->getFlags();14272  if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||14273      (ScopeFlags & ForInitFlags) == ForInitFlags)14274    return;14275 14276  // If there are multiple comma operators used together, get the RHS of the14277  // of the comma operator as the LHS.14278  while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {14279    if (BO->getOpcode() != BO_Comma)14280      break;14281    LHS = BO->getRHS();14282  }14283 14284  // Only allow some expressions on LHS to not warn.14285  if (IgnoreCommaOperand(LHS, Context))14286    return;14287 14288  Diag(Loc, diag::warn_comma_operator);14289  Diag(LHS->getBeginLoc(), diag::note_cast_to_void)14290      << LHS->getSourceRange()14291      << FixItHint::CreateInsertion(LHS->getBeginLoc(),14292                                    LangOpts.CPlusPlus ? "static_cast<void>("14293                                                       : "(void)(")14294      << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),14295                                    ")");14296}14297 14298// C99 6.5.1714299static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,14300                                   SourceLocation Loc) {14301  LHS = S.CheckPlaceholderExpr(LHS.get());14302  RHS = S.CheckPlaceholderExpr(RHS.get());14303  if (LHS.isInvalid() || RHS.isInvalid())14304    return QualType();14305 14306  // C's comma performs lvalue conversion (C99 6.3.2.1) on both its14307  // operands, but not unary promotions.14308  // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).14309 14310  // So we treat the LHS as a ignored value, and in C++ we allow the14311  // containing site to determine what should be done with the RHS.14312  LHS = S.IgnoredValueConversions(LHS.get());14313  if (LHS.isInvalid())14314    return QualType();14315 14316  S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);14317 14318  if (!S.getLangOpts().CPlusPlus) {14319    RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());14320    if (RHS.isInvalid())14321      return QualType();14322    if (!RHS.get()->getType()->isVoidType())14323      S.RequireCompleteType(Loc, RHS.get()->getType(),14324                            diag::err_incomplete_type);14325  }14326 14327  if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))14328    S.DiagnoseCommaOperator(LHS.get(), Loc);14329 14330  return RHS.get()->getType();14331}14332 14333/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine14334/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.14335static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,14336                                               ExprValueKind &VK,14337                                               ExprObjectKind &OK,14338                                               SourceLocation OpLoc, bool IsInc,14339                                               bool IsPrefix) {14340  QualType ResType = Op->getType();14341  // Atomic types can be used for increment / decrement where the non-atomic14342  // versions can, so ignore the _Atomic() specifier for the purpose of14343  // checking.14344  if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())14345    ResType = ResAtomicType->getValueType();14346 14347  assert(!ResType.isNull() && "no type for increment/decrement expression");14348 14349  if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {14350    // Decrement of bool is not allowed.14351    if (!IsInc) {14352      S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();14353      return QualType();14354    }14355    // Increment of bool sets it to true, but is deprecated.14356    S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool14357                                              : diag::warn_increment_bool)14358      << Op->getSourceRange();14359  } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {14360    // Error on enum increments and decrements in C++ mode14361    S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;14362    return QualType();14363  } else if (ResType->isRealType()) {14364    // OK!14365  } else if (ResType->isPointerType()) {14366    // C99 6.5.2.4p2, 6.5.6p214367    if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))14368      return QualType();14369  } else if (ResType->isObjCObjectPointerType()) {14370    // On modern runtimes, ObjC pointer arithmetic is forbidden.14371    // Otherwise, we just need a complete type.14372    if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||14373        checkArithmeticOnObjCPointer(S, OpLoc, Op))14374      return QualType();14375  } else if (ResType->isAnyComplexType()) {14376    // C99 does not support ++/-- on complex types, we allow as an extension.14377    S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex14378                                      : diag::ext_c2y_increment_complex)14379        << IsInc << Op->getSourceRange();14380  } else if (ResType->isPlaceholderType()) {14381    ExprResult PR = S.CheckPlaceholderExpr(Op);14382    if (PR.isInvalid()) return QualType();14383    return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,14384                                          IsInc, IsPrefix);14385  } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {14386    // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )14387  } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&14388             (ResType->castAs<VectorType>()->getVectorKind() !=14389              VectorKind::AltiVecBool)) {14390    // The z vector extensions allow ++ and -- for non-bool vectors.14391  } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&14392             ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {14393    // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.14394  } else {14395    S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)14396      << ResType << int(IsInc) << Op->getSourceRange();14397    return QualType();14398  }14399  // At this point, we know we have a real, complex or pointer type.14400  // Now make sure the operand is a modifiable lvalue.14401  if (CheckForModifiableLvalue(Op, OpLoc, S))14402    return QualType();14403  if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {14404    // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:14405    //   An operand with volatile-qualified type is deprecated14406    S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)14407        << IsInc << ResType;14408  }14409  // In C++, a prefix increment is the same type as the operand. Otherwise14410  // (in C or with postfix), the increment is the unqualified type of the14411  // operand.14412  if (IsPrefix && S.getLangOpts().CPlusPlus) {14413    VK = VK_LValue;14414    OK = Op->getObjectKind();14415    return ResType;14416  } else {14417    VK = VK_PRValue;14418    return ResType.getUnqualifiedType();14419  }14420}14421 14422/// getPrimaryDecl - Helper function for CheckAddressOfOperand().14423/// This routine allows us to typecheck complex/recursive expressions14424/// where the declaration is needed for type checking. We only need to14425/// handle cases when the expression references a function designator14426/// or is an lvalue. Here are some examples:14427///  - &(x) => x14428///  - &*****f => f for f a function designator.14429///  - &s.xx => s14430///  - &s.zz[1].yy -> s, if zz is an array14431///  - *(x + 1) -> x, if x is an array14432///  - &"123"[2] -> 014433///  - & __real__ x -> x14434///14435/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to14436/// members.14437static ValueDecl *getPrimaryDecl(Expr *E) {14438  switch (E->getStmtClass()) {14439  case Stmt::DeclRefExprClass:14440    return cast<DeclRefExpr>(E)->getDecl();14441  case Stmt::MemberExprClass:14442    // If this is an arrow operator, the address is an offset from14443    // the base's value, so the object the base refers to is14444    // irrelevant.14445    if (cast<MemberExpr>(E)->isArrow())14446      return nullptr;14447    // Otherwise, the expression refers to a part of the base14448    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());14449  case Stmt::ArraySubscriptExprClass: {14450    // FIXME: This code shouldn't be necessary!  We should catch the implicit14451    // promotion of register arrays earlier.14452    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();14453    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {14454      if (ICE->getSubExpr()->getType()->isArrayType())14455        return getPrimaryDecl(ICE->getSubExpr());14456    }14457    return nullptr;14458  }14459  case Stmt::UnaryOperatorClass: {14460    UnaryOperator *UO = cast<UnaryOperator>(E);14461 14462    switch(UO->getOpcode()) {14463    case UO_Real:14464    case UO_Imag:14465    case UO_Extension:14466      return getPrimaryDecl(UO->getSubExpr());14467    default:14468      return nullptr;14469    }14470  }14471  case Stmt::ParenExprClass:14472    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());14473  case Stmt::ImplicitCastExprClass:14474    // If the result of an implicit cast is an l-value, we care about14475    // the sub-expression; otherwise, the result here doesn't matter.14476    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());14477  case Stmt::CXXUuidofExprClass:14478    return cast<CXXUuidofExpr>(E)->getGuidDecl();14479  default:14480    return nullptr;14481  }14482}14483 14484namespace {14485enum {14486  AO_Bit_Field = 0,14487  AO_Vector_Element = 1,14488  AO_Property_Expansion = 2,14489  AO_Register_Variable = 3,14490  AO_Matrix_Element = 4,14491  AO_No_Error = 514492};14493}14494/// Diagnose invalid operand for address of operations.14495///14496/// \param Type The type of operand which cannot have its address taken.14497static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,14498                                         Expr *E, unsigned Type) {14499  S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();14500}14501 14502bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,14503                                                 const Expr *Op,14504                                                 const CXXMethodDecl *MD) {14505  const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());14506 14507  if (Op != DRE)14508    return Diag(OpLoc, diag::err_parens_pointer_member_function)14509           << Op->getSourceRange();14510 14511  // Taking the address of a dtor is illegal per C++ [class.dtor]p2.14512  if (isa<CXXDestructorDecl>(MD))14513    return Diag(OpLoc, diag::err_typecheck_addrof_dtor)14514           << DRE->getSourceRange();14515 14516  if (DRE->getQualifier())14517    return false;14518 14519  if (MD->getParent()->getName().empty())14520    return Diag(OpLoc, diag::err_unqualified_pointer_member_function)14521           << DRE->getSourceRange();14522 14523  SmallString<32> Str;14524  StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);14525  return Diag(OpLoc, diag::err_unqualified_pointer_member_function)14526         << DRE->getSourceRange()14527         << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);14528}14529 14530QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {14531  if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){14532    if (PTy->getKind() == BuiltinType::Overload) {14533      Expr *E = OrigOp.get()->IgnoreParens();14534      if (!isa<OverloadExpr>(E)) {14535        assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);14536        Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)14537          << OrigOp.get()->getSourceRange();14538        return QualType();14539      }14540 14541      OverloadExpr *Ovl = cast<OverloadExpr>(E);14542      if (isa<UnresolvedMemberExpr>(Ovl))14543        if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {14544          Diag(OpLoc, diag::err_invalid_form_pointer_member_function)14545            << OrigOp.get()->getSourceRange();14546          return QualType();14547        }14548 14549      return Context.OverloadTy;14550    }14551 14552    if (PTy->getKind() == BuiltinType::UnknownAny)14553      return Context.UnknownAnyTy;14554 14555    if (PTy->getKind() == BuiltinType::BoundMember) {14556      Diag(OpLoc, diag::err_invalid_form_pointer_member_function)14557        << OrigOp.get()->getSourceRange();14558      return QualType();14559    }14560 14561    OrigOp = CheckPlaceholderExpr(OrigOp.get());14562    if (OrigOp.isInvalid()) return QualType();14563  }14564 14565  if (OrigOp.get()->isTypeDependent())14566    return Context.DependentTy;14567 14568  assert(!OrigOp.get()->hasPlaceholderType());14569 14570  // Make sure to ignore parentheses in subsequent checks14571  Expr *op = OrigOp.get()->IgnoreParens();14572 14573  // In OpenCL captures for blocks called as lambda functions14574  // are located in the private address space. Blocks used in14575  // enqueue_kernel can be located in a different address space14576  // depending on a vendor implementation. Thus preventing14577  // taking an address of the capture to avoid invalid AS casts.14578  if (LangOpts.OpenCL) {14579    auto* VarRef = dyn_cast<DeclRefExpr>(op);14580    if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {14581      Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);14582      return QualType();14583    }14584  }14585 14586  if (getLangOpts().C99) {14587    // Implement C99-only parts of addressof rules.14588    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {14589      if (uOp->getOpcode() == UO_Deref)14590        // Per C99 6.5.3.2, the address of a deref always returns a valid result14591        // (assuming the deref expression is valid).14592        return uOp->getSubExpr()->getType();14593    }14594    // Technically, there should be a check for array subscript14595    // expressions here, but the result of one is always an lvalue anyway.14596  }14597  ValueDecl *dcl = getPrimaryDecl(op);14598 14599  if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))14600    if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,14601                                           op->getBeginLoc()))14602      return QualType();14603 14604  Expr::LValueClassification lval = op->ClassifyLValue(Context);14605  unsigned AddressOfError = AO_No_Error;14606 14607  if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {14608    bool IsError = isSFINAEContext();14609    Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary14610                        : diag::ext_typecheck_addrof_temporary)14611        << op->getType() << op->getSourceRange();14612    if (IsError)14613      return QualType();14614    // Materialize the temporary as an lvalue so that we can take its address.14615    OrigOp = op =14616        CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);14617  } else if (isa<ObjCSelectorExpr>(op)) {14618    return Context.getPointerType(op->getType());14619  } else if (lval == Expr::LV_MemberFunction) {14620    // If it's an instance method, make a member pointer.14621    // The expression must have exactly the form &A::foo.14622 14623    // If the underlying expression isn't a decl ref, give up.14624    if (!isa<DeclRefExpr>(op)) {14625      Diag(OpLoc, diag::err_invalid_form_pointer_member_function)14626        << OrigOp.get()->getSourceRange();14627      return QualType();14628    }14629    DeclRefExpr *DRE = cast<DeclRefExpr>(op);14630    CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());14631 14632    CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);14633    QualType MPTy = Context.getMemberPointerType(14634        op->getType(), DRE->getQualifier(), MD->getParent());14635 14636    if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&14637        !isUnevaluatedContext() && !MPTy->isDependentType()) {14638      // When pointer authentication is enabled, argument and return types of14639      // vitual member functions must be complete. This is because vitrual14640      // member function pointers are implemented using virtual dispatch14641      // thunks and the thunks cannot be emitted if the argument or return14642      // types are incomplete.14643      auto ReturnOrParamTypeIsIncomplete = [&](QualType T,14644                                               SourceLocation DeclRefLoc,14645                                               SourceLocation RetArgTypeLoc) {14646        if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {14647          Diag(DeclRefLoc,14648               diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);14649          Diag(RetArgTypeLoc,14650               diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)14651              << T;14652          return true;14653        }14654        return false;14655      };14656      QualType RetTy = MD->getReturnType();14657      bool IsIncomplete =14658          !RetTy->isVoidType() &&14659          ReturnOrParamTypeIsIncomplete(14660              RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());14661      for (auto *PVD : MD->parameters())14662        IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,14663                                                      PVD->getBeginLoc());14664      if (IsIncomplete)14665        return QualType();14666    }14667 14668    // Under the MS ABI, lock down the inheritance model now.14669    if (Context.getTargetInfo().getCXXABI().isMicrosoft())14670      (void)isCompleteType(OpLoc, MPTy);14671    return MPTy;14672  } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {14673    // C99 6.5.3.2p114674    // The operand must be either an l-value or a function designator14675    if (!op->getType()->isFunctionType()) {14676      // Use a special diagnostic for loads from property references.14677      if (isa<PseudoObjectExpr>(op)) {14678        AddressOfError = AO_Property_Expansion;14679      } else {14680        Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)14681          << op->getType() << op->getSourceRange();14682        return QualType();14683      }14684    } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {14685      if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))14686        CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);14687    }14688 14689  } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p114690    // The operand cannot be a bit-field14691    AddressOfError = AO_Bit_Field;14692  } else if (op->getObjectKind() == OK_VectorComponent) {14693    // The operand cannot be an element of a vector14694    AddressOfError = AO_Vector_Element;14695  } else if (op->getObjectKind() == OK_MatrixComponent) {14696    // The operand cannot be an element of a matrix.14697    AddressOfError = AO_Matrix_Element;14698  } else if (dcl) { // C99 6.5.3.2p114699    // We have an lvalue with a decl. Make sure the decl is not declared14700    // with the register storage-class specifier.14701    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {14702      // in C++ it is not error to take address of a register14703      // variable (c++03 7.1.1P3)14704      if (vd->getStorageClass() == SC_Register &&14705          !getLangOpts().CPlusPlus) {14706        AddressOfError = AO_Register_Variable;14707      }14708    } else if (isa<MSPropertyDecl>(dcl)) {14709      AddressOfError = AO_Property_Expansion;14710    } else if (isa<FunctionTemplateDecl>(dcl)) {14711      return Context.OverloadTy;14712    } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {14713      // Okay: we can take the address of a field.14714      // Could be a pointer to member, though, if there is an explicit14715      // scope qualifier for the class.14716 14717      // [C++26] [expr.prim.id.general]14718      // If an id-expression E denotes a non-static non-type member14719      // of some class C [...] and if E is a qualified-id, E is14720      // not the un-parenthesized operand of the unary & operator [...]14721      // the id-expression is transformed into a class member access expression.14722      if (auto *DRE = dyn_cast<DeclRefExpr>(op);14723          DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {14724        DeclContext *Ctx = dcl->getDeclContext();14725        if (Ctx && Ctx->isRecord()) {14726          if (dcl->getType()->isReferenceType()) {14727            Diag(OpLoc,14728                 diag::err_cannot_form_pointer_to_member_of_reference_type)14729              << dcl->getDeclName() << dcl->getType();14730            return QualType();14731          }14732 14733          while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())14734            Ctx = Ctx->getParent();14735 14736          QualType MPTy = Context.getMemberPointerType(14737              op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));14738          // Under the MS ABI, lock down the inheritance model now.14739          if (Context.getTargetInfo().getCXXABI().isMicrosoft())14740            (void)isCompleteType(OpLoc, MPTy);14741          return MPTy;14742        }14743      }14744    } else if (!isa<FunctionDecl, TemplateParamObjectDecl,14745                    NonTypeTemplateParmDecl, BindingDecl, MSGuidDecl,14746                    UnnamedGlobalConstantDecl>(dcl))14747      llvm_unreachable("Unknown/unexpected decl type");14748  }14749 14750  if (AddressOfError != AO_No_Error) {14751    diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);14752    return QualType();14753  }14754 14755  if (lval == Expr::LV_IncompleteVoidType) {14756    // Taking the address of a void variable is technically illegal, but we14757    // allow it in cases which are otherwise valid.14758    // Example: "extern void x; void* y = &x;".14759    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();14760  }14761 14762  // If the operand has type "type", the result has type "pointer to type".14763  if (op->getType()->isObjCObjectType())14764    return Context.getObjCObjectPointerType(op->getType());14765 14766  // Cannot take the address of WebAssembly references or tables.14767  if (Context.getTargetInfo().getTriple().isWasm()) {14768    QualType OpTy = op->getType();14769    if (OpTy.isWebAssemblyReferenceType()) {14770      Diag(OpLoc, diag::err_wasm_ca_reference)14771          << 1 << OrigOp.get()->getSourceRange();14772      return QualType();14773    }14774    if (OpTy->isWebAssemblyTableType()) {14775      Diag(OpLoc, diag::err_wasm_table_pr)14776          << 1 << OrigOp.get()->getSourceRange();14777      return QualType();14778    }14779  }14780 14781  CheckAddressOfPackedMember(op);14782 14783  return Context.getPointerType(op->getType());14784}14785 14786static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {14787  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);14788  if (!DRE)14789    return;14790  const Decl *D = DRE->getDecl();14791  if (!D)14792    return;14793  const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);14794  if (!Param)14795    return;14796  if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))14797    if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())14798      return;14799  if (FunctionScopeInfo *FD = S.getCurFunction())14800    FD->ModifiedNonNullParams.insert(Param);14801}14802 14803/// CheckIndirectionOperand - Type check unary indirection (prefix '*').14804static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,14805                                        SourceLocation OpLoc,14806                                        bool IsAfterAmp = false) {14807  ExprResult ConvResult = S.UsualUnaryConversions(Op);14808  if (ConvResult.isInvalid())14809    return QualType();14810  Op = ConvResult.get();14811  QualType OpTy = Op->getType();14812  QualType Result;14813 14814  if (isa<CXXReinterpretCastExpr>(Op->IgnoreParens())) {14815    QualType OpOrigType = Op->IgnoreParenCasts()->getType();14816    S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,14817                                     Op->getSourceRange());14818  }14819 14820  if (const PointerType *PT = OpTy->getAs<PointerType>())14821  {14822    Result = PT->getPointeeType();14823  }14824  else if (const ObjCObjectPointerType *OPT =14825             OpTy->getAs<ObjCObjectPointerType>())14826    Result = OPT->getPointeeType();14827  else {14828    ExprResult PR = S.CheckPlaceholderExpr(Op);14829    if (PR.isInvalid()) return QualType();14830    if (PR.get() != Op)14831      return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);14832  }14833 14834  if (Result.isNull()) {14835    S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)14836      << OpTy << Op->getSourceRange();14837    return QualType();14838  }14839 14840  if (Result->isVoidType()) {14841    // C++ [expr.unary.op]p1:14842    //   [...] the expression to which [the unary * operator] is applied shall14843    //   be a pointer to an object type, or a pointer to a function type14844    LangOptions LO = S.getLangOpts();14845    if (LO.CPlusPlus)14846      S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)14847          << OpTy << Op->getSourceRange();14848    else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())14849      S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)14850          << OpTy << Op->getSourceRange();14851  }14852 14853  // Dereferences are usually l-values...14854  VK = VK_LValue;14855 14856  // ...except that certain expressions are never l-values in C.14857  if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())14858    VK = VK_PRValue;14859 14860  return Result;14861}14862 14863BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {14864  BinaryOperatorKind Opc;14865  switch (Kind) {14866  default: llvm_unreachable("Unknown binop!");14867  case tok::periodstar:           Opc = BO_PtrMemD; break;14868  case tok::arrowstar:            Opc = BO_PtrMemI; break;14869  case tok::star:                 Opc = BO_Mul; break;14870  case tok::slash:                Opc = BO_Div; break;14871  case tok::percent:              Opc = BO_Rem; break;14872  case tok::plus:                 Opc = BO_Add; break;14873  case tok::minus:                Opc = BO_Sub; break;14874  case tok::lessless:             Opc = BO_Shl; break;14875  case tok::greatergreater:       Opc = BO_Shr; break;14876  case tok::lessequal:            Opc = BO_LE; break;14877  case tok::less:                 Opc = BO_LT; break;14878  case tok::greaterequal:         Opc = BO_GE; break;14879  case tok::greater:              Opc = BO_GT; break;14880  case tok::exclaimequal:         Opc = BO_NE; break;14881  case tok::equalequal:           Opc = BO_EQ; break;14882  case tok::spaceship:            Opc = BO_Cmp; break;14883  case tok::amp:                  Opc = BO_And; break;14884  case tok::caret:                Opc = BO_Xor; break;14885  case tok::pipe:                 Opc = BO_Or; break;14886  case tok::ampamp:               Opc = BO_LAnd; break;14887  case tok::pipepipe:             Opc = BO_LOr; break;14888  case tok::equal:                Opc = BO_Assign; break;14889  case tok::starequal:            Opc = BO_MulAssign; break;14890  case tok::slashequal:           Opc = BO_DivAssign; break;14891  case tok::percentequal:         Opc = BO_RemAssign; break;14892  case tok::plusequal:            Opc = BO_AddAssign; break;14893  case tok::minusequal:           Opc = BO_SubAssign; break;14894  case tok::lesslessequal:        Opc = BO_ShlAssign; break;14895  case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;14896  case tok::ampequal:             Opc = BO_AndAssign; break;14897  case tok::caretequal:           Opc = BO_XorAssign; break;14898  case tok::pipeequal:            Opc = BO_OrAssign; break;14899  case tok::comma:                Opc = BO_Comma; break;14900  }14901  return Opc;14902}14903 14904static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(14905  tok::TokenKind Kind) {14906  UnaryOperatorKind Opc;14907  switch (Kind) {14908  default: llvm_unreachable("Unknown unary op!");14909  case tok::plusplus:     Opc = UO_PreInc; break;14910  case tok::minusminus:   Opc = UO_PreDec; break;14911  case tok::amp:          Opc = UO_AddrOf; break;14912  case tok::star:         Opc = UO_Deref; break;14913  case tok::plus:         Opc = UO_Plus; break;14914  case tok::minus:        Opc = UO_Minus; break;14915  case tok::tilde:        Opc = UO_Not; break;14916  case tok::exclaim:      Opc = UO_LNot; break;14917  case tok::kw___real:    Opc = UO_Real; break;14918  case tok::kw___imag:    Opc = UO_Imag; break;14919  case tok::kw___extension__: Opc = UO_Extension; break;14920  }14921  return Opc;14922}14923 14924const FieldDecl *14925Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {14926  // Explore the case for adding 'this->' to the LHS of a self assignment, very14927  // common for setters.14928  // struct A {14929  // int X;14930  // -void setX(int X) { X = X; }14931  // +void setX(int X) { this->X = X; }14932  // };14933 14934  // Only consider parameters for self assignment fixes.14935  if (!isa<ParmVarDecl>(SelfAssigned))14936    return nullptr;14937  const auto *Method =14938      dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));14939  if (!Method)14940    return nullptr;14941 14942  const CXXRecordDecl *Parent = Method->getParent();14943  // In theory this is fixable if the lambda explicitly captures this, but14944  // that's added complexity that's rarely going to be used.14945  if (Parent->isLambda())14946    return nullptr;14947 14948  // FIXME: Use an actual Lookup operation instead of just traversing fields14949  // in order to get base class fields.14950  auto Field =14951      llvm::find_if(Parent->fields(),14952                    [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {14953                      return F->getDeclName() == Name;14954                    });14955  return (Field != Parent->field_end()) ? *Field : nullptr;14956}14957 14958/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.14959/// This warning suppressed in the event of macro expansions.14960static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,14961                                   SourceLocation OpLoc, bool IsBuiltin) {14962  if (S.inTemplateInstantiation())14963    return;14964  if (S.isUnevaluatedContext())14965    return;14966  if (OpLoc.isInvalid() || OpLoc.isMacroID())14967    return;14968  LHSExpr = LHSExpr->IgnoreParenImpCasts();14969  RHSExpr = RHSExpr->IgnoreParenImpCasts();14970  const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);14971  const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);14972  if (!LHSDeclRef || !RHSDeclRef ||14973      LHSDeclRef->getLocation().isMacroID() ||14974      RHSDeclRef->getLocation().isMacroID())14975    return;14976  const ValueDecl *LHSDecl =14977    cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());14978  const ValueDecl *RHSDecl =14979    cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());14980  if (LHSDecl != RHSDecl)14981    return;14982  if (LHSDecl->getType().isVolatileQualified())14983    return;14984  if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())14985    if (RefTy->getPointeeType().isVolatileQualified())14986      return;14987 14988  auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin14989                                      : diag::warn_self_assignment_overloaded)14990              << LHSDeclRef->getType() << LHSExpr->getSourceRange()14991              << RHSExpr->getSourceRange();14992  if (const FieldDecl *SelfAssignField =14993          S.getSelfAssignmentClassMemberCandidate(RHSDecl))14994    Diag << 1 << SelfAssignField14995         << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");14996  else14997    Diag << 0;14998}14999 15000/// Check if a bitwise-& is performed on an Objective-C pointer.  This15001/// is usually indicative of introspection within the Objective-C pointer.15002static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,15003                                          SourceLocation OpLoc) {15004  if (!S.getLangOpts().ObjC)15005    return;15006 15007  const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;15008  const Expr *LHS = L.get();15009  const Expr *RHS = R.get();15010 15011  if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {15012    ObjCPointerExpr = LHS;15013    OtherExpr = RHS;15014  }15015  else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {15016    ObjCPointerExpr = RHS;15017    OtherExpr = LHS;15018  }15019 15020  // This warning is deliberately made very specific to reduce false15021  // positives with logic that uses '&' for hashing.  This logic mainly15022  // looks for code trying to introspect into tagged pointers, which15023  // code should generally never do.15024  if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {15025    unsigned Diag = diag::warn_objc_pointer_masking;15026    // Determine if we are introspecting the result of performSelectorXXX.15027    const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();15028    // Special case messages to -performSelector and friends, which15029    // can return non-pointer values boxed in a pointer value.15030    // Some clients may wish to silence warnings in this subcase.15031    if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {15032      Selector S = ME->getSelector();15033      StringRef SelArg0 = S.getNameForSlot(0);15034      if (SelArg0.starts_with("performSelector"))15035        Diag = diag::warn_objc_pointer_masking_performSelector;15036    }15037 15038    S.Diag(OpLoc, Diag)15039      << ObjCPointerExpr->getSourceRange();15040  }15041}15042 15043// This helper function promotes a binary operator's operands (which are of a15044// half vector type) to a vector of floats and then truncates the result to15045// a vector of either half or short.15046static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,15047                                      BinaryOperatorKind Opc, QualType ResultTy,15048                                      ExprValueKind VK, ExprObjectKind OK,15049                                      bool IsCompAssign, SourceLocation OpLoc,15050                                      FPOptionsOverride FPFeatures) {15051  auto &Context = S.getASTContext();15052  assert((isVector(ResultTy, Context.HalfTy) ||15053          isVector(ResultTy, Context.ShortTy)) &&15054         "Result must be a vector of half or short");15055  assert(isVector(LHS.get()->getType(), Context.HalfTy) &&15056         isVector(RHS.get()->getType(), Context.HalfTy) &&15057         "both operands expected to be a half vector");15058 15059  RHS = convertVector(RHS.get(), Context.FloatTy, S);15060  QualType BinOpResTy = RHS.get()->getType();15061 15062  // If Opc is a comparison, ResultType is a vector of shorts. In that case,15063  // change BinOpResTy to a vector of ints.15064  if (isVector(ResultTy, Context.ShortTy))15065    BinOpResTy = S.GetSignedVectorType(BinOpResTy);15066 15067  if (IsCompAssign)15068    return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,15069                                          ResultTy, VK, OK, OpLoc, FPFeatures,15070                                          BinOpResTy, BinOpResTy);15071 15072  LHS = convertVector(LHS.get(), Context.FloatTy, S);15073  auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,15074                                    BinOpResTy, VK, OK, OpLoc, FPFeatures);15075  return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);15076}15077 15078/// Returns true if conversion between vectors of halfs and vectors of floats15079/// is needed.15080static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,15081                                     Expr *E0, Expr *E1 = nullptr) {15082  if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||15083      Ctx.getTargetInfo().useFP16ConversionIntrinsics())15084    return false;15085 15086  auto HasVectorOfHalfType = [&Ctx](Expr *E) {15087    QualType Ty = E->IgnoreImplicit()->getType();15088 15089    // Don't promote half precision neon vectors like float16x4_t in arm_neon.h15090    // to vectors of floats. Although the element type of the vectors is __fp16,15091    // the vectors shouldn't be treated as storage-only types. See the15092    // discussion here: https://reviews.llvm.org/rG825235c140e715093    if (const VectorType *VT = Ty->getAs<VectorType>()) {15094      if (VT->getVectorKind() == VectorKind::Neon)15095        return false;15096      return VT->getElementType().getCanonicalType() == Ctx.HalfTy;15097    }15098    return false;15099  };15100 15101  return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));15102}15103 15104ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,15105                                    BinaryOperatorKind Opc, Expr *LHSExpr,15106                                    Expr *RHSExpr, bool ForFoldExpression) {15107  if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {15108    // The syntax only allows initializer lists on the RHS of assignment,15109    // so we don't need to worry about accepting invalid code for15110    // non-assignment operators.15111    // C++11 5.17p9:15112    //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning15113    //   of x = {} is x = T().15114    InitializationKind Kind = InitializationKind::CreateDirectList(15115        RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());15116    InitializedEntity Entity =15117        InitializedEntity::InitializeTemporary(LHSExpr->getType());15118    InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);15119    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);15120    if (Init.isInvalid())15121      return Init;15122    RHSExpr = Init.get();15123  }15124 15125  ExprResult LHS = LHSExpr, RHS = RHSExpr;15126  QualType ResultTy;     // Result type of the binary operator.15127  // The following two variables are used for compound assignment operators15128  QualType CompLHSTy;    // Type of LHS after promotions for computation15129  QualType CompResultTy; // Type of computation result15130  ExprValueKind VK = VK_PRValue;15131  ExprObjectKind OK = OK_Ordinary;15132  bool ConvertHalfVec = false;15133 15134  if (!LHS.isUsable() || !RHS.isUsable())15135    return ExprError();15136 15137  if (getLangOpts().OpenCL) {15138    QualType LHSTy = LHSExpr->getType();15139    QualType RHSTy = RHSExpr->getType();15140    // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by15141    // the ATOMIC_VAR_INIT macro.15142    if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {15143      SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());15144      if (BO_Assign == Opc)15145        Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;15146      else15147        ResultTy = InvalidOperands(OpLoc, LHS, RHS);15148      return ExprError();15149    }15150 15151    // OpenCL special types - image, sampler, pipe, and blocks are to be used15152    // only with a builtin functions and therefore should be disallowed here.15153    if (LHSTy->isImageType() || RHSTy->isImageType() ||15154        LHSTy->isSamplerT() || RHSTy->isSamplerT() ||15155        LHSTy->isPipeType() || RHSTy->isPipeType() ||15156        LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {15157      ResultTy = InvalidOperands(OpLoc, LHS, RHS);15158      return ExprError();15159    }15160  }15161 15162  checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);15163  checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);15164 15165  switch (Opc) {15166  case BO_Assign:15167    ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);15168    if (getLangOpts().CPlusPlus &&15169        LHS.get()->getObjectKind() != OK_ObjCProperty) {15170      VK = LHS.get()->getValueKind();15171      OK = LHS.get()->getObjectKind();15172    }15173    if (!ResultTy.isNull()) {15174      DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);15175      DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);15176 15177      // Avoid copying a block to the heap if the block is assigned to a local15178      // auto variable that is declared in the same scope as the block. This15179      // optimization is unsafe if the local variable is declared in an outer15180      // scope. For example:15181      //15182      // BlockTy b;15183      // {15184      //   b = ^{...};15185      // }15186      // // It is unsafe to invoke the block here if it wasn't copied to the15187      // // heap.15188      // b();15189 15190      if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))15191        if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))15192          if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))15193            if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))15194              BE->getBlockDecl()->setCanAvoidCopyToHeap();15195 15196      if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())15197        checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),15198                              NonTrivialCUnionContext::Assignment, NTCUK_Copy);15199    }15200    RecordModifiableNonNullParam(*this, LHS.get());15201    break;15202  case BO_PtrMemD:15203  case BO_PtrMemI:15204    ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,15205                                            Opc == BO_PtrMemI);15206    break;15207  case BO_Mul:15208  case BO_Div:15209    ConvertHalfVec = true;15210    ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);15211    break;15212  case BO_Rem:15213    ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);15214    break;15215  case BO_Add:15216    ConvertHalfVec = true;15217    ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);15218    break;15219  case BO_Sub:15220    ConvertHalfVec = true;15221    ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);15222    break;15223  case BO_Shl:15224  case BO_Shr:15225    ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);15226    break;15227  case BO_LE:15228  case BO_LT:15229  case BO_GE:15230  case BO_GT:15231    ConvertHalfVec = true;15232    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);15233 15234    if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);15235        !ForFoldExpression && BI && BI->isComparisonOp())15236      Diag(OpLoc, diag::warn_consecutive_comparison)15237          << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);15238 15239    break;15240  case BO_EQ:15241  case BO_NE:15242    ConvertHalfVec = true;15243    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);15244    break;15245  case BO_Cmp:15246    ConvertHalfVec = true;15247    ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);15248    assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());15249    break;15250  case BO_And:15251    checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);15252    [[fallthrough]];15253  case BO_Xor:15254  case BO_Or:15255    ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);15256    break;15257  case BO_LAnd:15258  case BO_LOr:15259    ConvertHalfVec = true;15260    ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);15261    break;15262  case BO_MulAssign:15263  case BO_DivAssign:15264    ConvertHalfVec = true;15265    CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);15266    CompLHSTy = CompResultTy;15267    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())15268      ResultTy =15269          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);15270    break;15271  case BO_RemAssign:15272    CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);15273    CompLHSTy = CompResultTy;15274    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())15275      ResultTy =15276          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);15277    break;15278  case BO_AddAssign:15279    ConvertHalfVec = true;15280    CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);15281    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())15282      ResultTy =15283          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);15284    break;15285  case BO_SubAssign:15286    ConvertHalfVec = true;15287    CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);15288    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())15289      ResultTy =15290          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);15291    break;15292  case BO_ShlAssign:15293  case BO_ShrAssign:15294    CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);15295    CompLHSTy = CompResultTy;15296    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())15297      ResultTy =15298          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);15299    break;15300  case BO_AndAssign:15301  case BO_OrAssign: // fallthrough15302    DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);15303    [[fallthrough]];15304  case BO_XorAssign:15305    CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);15306    CompLHSTy = CompResultTy;15307    if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())15308      ResultTy =15309          CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);15310    break;15311  case BO_Comma:15312    ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);15313    if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {15314      VK = RHS.get()->getValueKind();15315      OK = RHS.get()->getObjectKind();15316    }15317    break;15318  }15319  if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())15320    return ExprError();15321 15322  // Some of the binary operations require promoting operands of half vector to15323  // float vectors and truncating the result back to half vector. For now, we do15324  // this only when HalfArgsAndReturn is set (that is, when the target is arm or15325  // arm64).15326  assert(15327      (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==15328                              isVector(LHS.get()->getType(), Context.HalfTy)) &&15329      "both sides are half vectors or neither sides are");15330  ConvertHalfVec =15331      needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());15332 15333  // Check for array bounds violations for both sides of the BinaryOperator15334  CheckArrayAccess(LHS.get());15335  CheckArrayAccess(RHS.get());15336 15337  if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {15338    NamedDecl *ObjectSetClass = LookupSingleName(TUScope,15339                                                 &Context.Idents.get("object_setClass"),15340                                                 SourceLocation(), LookupOrdinaryName);15341    if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {15342      SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());15343      Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)15344          << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),15345                                        "object_setClass(")15346          << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),15347                                          ",")15348          << FixItHint::CreateInsertion(RHSLocEnd, ")");15349    }15350    else15351      Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);15352  }15353  else if (const ObjCIvarRefExpr *OIRE =15354           dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))15355    DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());15356 15357  // Opc is not a compound assignment if CompResultTy is null.15358  if (CompResultTy.isNull()) {15359    if (ConvertHalfVec)15360      return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,15361                                 OpLoc, CurFPFeatureOverrides());15362    return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,15363                                  VK, OK, OpLoc, CurFPFeatureOverrides());15364  }15365 15366  // Handle compound assignments.15367  if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=15368      OK_ObjCProperty) {15369    VK = VK_LValue;15370    OK = LHS.get()->getObjectKind();15371  }15372 15373  // The LHS is not converted to the result type for fixed-point compound15374  // assignment as the common type is computed on demand. Reset the CompLHSTy15375  // to the LHS type we would have gotten after unary conversions.15376  if (CompResultTy->isFixedPointType())15377    CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();15378 15379  if (ConvertHalfVec)15380    return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,15381                               OpLoc, CurFPFeatureOverrides());15382 15383  return CompoundAssignOperator::Create(15384      Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,15385      CurFPFeatureOverrides(), CompLHSTy, CompResultTy);15386}15387 15388/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison15389/// operators are mixed in a way that suggests that the programmer forgot that15390/// comparison operators have higher precedence. The most typical example of15391/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".15392static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,15393                                      SourceLocation OpLoc, Expr *LHSExpr,15394                                      Expr *RHSExpr) {15395  BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);15396  BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);15397 15398  // Check that one of the sides is a comparison operator and the other isn't.15399  bool isLeftComp = LHSBO && LHSBO->isComparisonOp();15400  bool isRightComp = RHSBO && RHSBO->isComparisonOp();15401  if (isLeftComp == isRightComp)15402    return;15403 15404  // Bitwise operations are sometimes used as eager logical ops.15405  // Don't diagnose this.15406  bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();15407  bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();15408  if (isLeftBitwise || isRightBitwise)15409    return;15410 15411  SourceRange DiagRange = isLeftComp15412                              ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)15413                              : SourceRange(OpLoc, RHSExpr->getEndLoc());15414  StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();15415  SourceRange ParensRange =15416      isLeftComp15417          ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())15418          : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());15419 15420  Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)15421    << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;15422  SuggestParentheses(Self, OpLoc,15423    Self.PDiag(diag::note_precedence_silence) << OpStr,15424    (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());15425  SuggestParentheses(Self, OpLoc,15426    Self.PDiag(diag::note_precedence_bitwise_first)15427      << BinaryOperator::getOpcodeStr(Opc),15428    ParensRange);15429}15430 15431/// It accepts a '&&' expr that is inside a '||' one.15432/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression15433/// in parentheses.15434static void15435EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,15436                                       BinaryOperator *Bop) {15437  assert(Bop->getOpcode() == BO_LAnd);15438  Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)15439      << Bop->getSourceRange() << OpLoc;15440  SuggestParentheses(Self, Bop->getOperatorLoc(),15441    Self.PDiag(diag::note_precedence_silence)15442      << Bop->getOpcodeStr(),15443    Bop->getSourceRange());15444}15445 15446/// Look for '&&' in the left hand of a '||' expr.15447static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,15448                                             Expr *LHSExpr, Expr *RHSExpr) {15449  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {15450    if (Bop->getOpcode() == BO_LAnd) {15451      // If it's "string_literal && a || b" don't warn since the precedence15452      // doesn't matter.15453      if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))15454        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);15455    } else if (Bop->getOpcode() == BO_LOr) {15456      if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {15457        // If it's "a || b && string_literal || c" we didn't warn earlier for15458        // "a || b && string_literal", but warn now.15459        if (RBop->getOpcode() == BO_LAnd &&15460            isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))15461          return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);15462      }15463    }15464  }15465}15466 15467/// Look for '&&' in the right hand of a '||' expr.15468static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,15469                                             Expr *LHSExpr, Expr *RHSExpr) {15470  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {15471    if (Bop->getOpcode() == BO_LAnd) {15472      // If it's "a || b && string_literal" don't warn since the precedence15473      // doesn't matter.15474      if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))15475        return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);15476    }15477  }15478}15479 15480/// Look for bitwise op in the left or right hand of a bitwise op with15481/// lower precedence and emit a diagnostic together with a fixit hint that wraps15482/// the '&' expression in parentheses.15483static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,15484                                         SourceLocation OpLoc, Expr *SubExpr) {15485  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {15486    if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {15487      S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)15488        << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)15489        << Bop->getSourceRange() << OpLoc;15490      SuggestParentheses(S, Bop->getOperatorLoc(),15491        S.PDiag(diag::note_precedence_silence)15492          << Bop->getOpcodeStr(),15493        Bop->getSourceRange());15494    }15495  }15496}15497 15498static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,15499                                    Expr *SubExpr, StringRef Shift) {15500  if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {15501    if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {15502      StringRef Op = Bop->getOpcodeStr();15503      S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)15504          << Bop->getSourceRange() << OpLoc << Shift << Op;15505      SuggestParentheses(S, Bop->getOperatorLoc(),15506          S.PDiag(diag::note_precedence_silence) << Op,15507          Bop->getSourceRange());15508    }15509  }15510}15511 15512static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,15513                                 Expr *LHSExpr, Expr *RHSExpr) {15514  CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);15515  if (!OCE)15516    return;15517 15518  FunctionDecl *FD = OCE->getDirectCallee();15519  if (!FD || !FD->isOverloadedOperator())15520    return;15521 15522  OverloadedOperatorKind Kind = FD->getOverloadedOperator();15523  if (Kind != OO_LessLess && Kind != OO_GreaterGreater)15524    return;15525 15526  S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)15527      << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()15528      << (Kind == OO_LessLess);15529  SuggestParentheses(S, OCE->getOperatorLoc(),15530                     S.PDiag(diag::note_precedence_silence)15531                         << (Kind == OO_LessLess ? "<<" : ">>"),15532                     OCE->getSourceRange());15533  SuggestParentheses(15534      S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),15535      SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));15536}15537 15538/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky15539/// precedence.15540static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,15541                                    SourceLocation OpLoc, Expr *LHSExpr,15542                                    Expr *RHSExpr){15543  // Diagnose "arg1 'bitwise' arg2 'eq' arg3".15544  if (BinaryOperator::isBitwiseOp(Opc))15545    DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);15546 15547  // Diagnose "arg1 & arg2 | arg3"15548  if ((Opc == BO_Or || Opc == BO_Xor) &&15549      !OpLoc.isMacroID()/* Don't warn in macros. */) {15550    DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);15551    DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);15552  }15553 15554  // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.15555  // We don't warn for 'assert(a || b && "bad")' since this is safe.15556  if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {15557    DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);15558    DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);15559  }15560 15561  if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))15562      || Opc == BO_Shr) {15563    StringRef Shift = BinaryOperator::getOpcodeStr(Opc);15564    DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);15565    DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);15566  }15567 15568  // Warn on overloaded shift operators and comparisons, such as:15569  // cout << 5 == 4;15570  if (BinaryOperator::isComparisonOp(Opc))15571    DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);15572}15573 15574ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,15575                            tok::TokenKind Kind,15576                            Expr *LHSExpr, Expr *RHSExpr) {15577  BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);15578  assert(LHSExpr && "ActOnBinOp(): missing left expression");15579  assert(RHSExpr && "ActOnBinOp(): missing right expression");15580 15581  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"15582  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);15583 15584  BuiltinCountedByRefKind K = BinaryOperator::isAssignmentOp(Opc)15585                                  ? BuiltinCountedByRefKind::Assignment15586                                  : BuiltinCountedByRefKind::BinaryExpr;15587 15588  CheckInvalidBuiltinCountedByRef(LHSExpr, K);15589  CheckInvalidBuiltinCountedByRef(RHSExpr, K);15590 15591  return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);15592}15593 15594void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,15595                       UnresolvedSetImpl &Functions) {15596  OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);15597  if (OverOp != OO_None && OverOp != OO_Equal)15598    LookupOverloadedOperatorName(OverOp, S, Functions);15599 15600  // In C++20 onwards, we may have a second operator to look up.15601  if (getLangOpts().CPlusPlus20) {15602    if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(OverOp))15603      LookupOverloadedOperatorName(ExtraOp, S, Functions);15604  }15605}15606 15607/// Build an overloaded binary operator expression in the given scope.15608static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,15609                                       BinaryOperatorKind Opc,15610                                       Expr *LHS, Expr *RHS) {15611  switch (Opc) {15612  case BO_Assign:15613    // In the non-overloaded case, we warn about self-assignment (x = x) for15614    // both simple assignment and certain compound assignments where algebra15615    // tells us the operation yields a constant result.  When the operator is15616    // overloaded, we can't do the latter because we don't want to assume that15617    // those algebraic identities still apply; for example, a path-building15618    // library might use operator/= to append paths.  But it's still reasonable15619    // to assume that simple assignment is just moving/copying values around15620    // and so self-assignment is likely a bug.15621    DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);15622    [[fallthrough]];15623  case BO_DivAssign:15624  case BO_RemAssign:15625  case BO_SubAssign:15626  case BO_AndAssign:15627  case BO_OrAssign:15628  case BO_XorAssign:15629    CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);15630    break;15631  default:15632    break;15633  }15634 15635  // Find all of the overloaded operators visible from this point.15636  UnresolvedSet<16> Functions;15637  S.LookupBinOp(Sc, OpLoc, Opc, Functions);15638 15639  // Build the (potentially-overloaded, potentially-dependent)15640  // binary operation.15641  return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);15642}15643 15644ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,15645                            BinaryOperatorKind Opc, Expr *LHSExpr,15646                            Expr *RHSExpr, bool ForFoldExpression) {15647  if (!LHSExpr || !RHSExpr)15648    return ExprError();15649 15650  // We want to end up calling one of SemaPseudoObject::checkAssignment15651  // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if15652  // both expressions are overloadable or either is type-dependent),15653  // or CreateBuiltinBinOp (in any other case).  We also want to get15654  // any placeholder types out of the way.15655 15656  // Handle pseudo-objects in the LHS.15657  if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {15658    // Assignments with a pseudo-object l-value need special analysis.15659    if (pty->getKind() == BuiltinType::PseudoObject &&15660        BinaryOperator::isAssignmentOp(Opc))15661      return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);15662 15663    // Don't resolve overloads if the other type is overloadable.15664    if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {15665      // We can't actually test that if we still have a placeholder,15666      // though.  Fortunately, none of the exceptions we see in that15667      // code below are valid when the LHS is an overload set.  Note15668      // that an overload set can be dependently-typed, but it never15669      // instantiates to having an overloadable type.15670      ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);15671      if (resolvedRHS.isInvalid()) return ExprError();15672      RHSExpr = resolvedRHS.get();15673 15674      if (RHSExpr->isTypeDependent() ||15675          RHSExpr->getType()->isOverloadableType())15676        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);15677    }15678 15679    // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function15680    // template, diagnose the missing 'template' keyword instead of diagnosing15681    // an invalid use of a bound member function.15682    //15683    // Note that "A::x < b" might be valid if 'b' has an overloadable type due15684    // to C++1z [over.over]/1.4, but we already checked for that case above.15685    if (Opc == BO_LT && inTemplateInstantiation() &&15686        (pty->getKind() == BuiltinType::BoundMember ||15687         pty->getKind() == BuiltinType::Overload)) {15688      auto *OE = dyn_cast<OverloadExpr>(LHSExpr);15689      if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&15690          llvm::any_of(OE->decls(), [](NamedDecl *ND) {15691            return isa<FunctionTemplateDecl>(ND);15692          })) {15693        Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()15694                                : OE->getNameLoc(),15695             diag::err_template_kw_missing)15696            << OE->getName().getAsIdentifierInfo();15697        return ExprError();15698      }15699    }15700 15701    ExprResult LHS = CheckPlaceholderExpr(LHSExpr);15702    if (LHS.isInvalid()) return ExprError();15703    LHSExpr = LHS.get();15704  }15705 15706  // Handle pseudo-objects in the RHS.15707  if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {15708    // An overload in the RHS can potentially be resolved by the type15709    // being assigned to.15710    if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {15711      if (getLangOpts().CPlusPlus &&15712          (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||15713           LHSExpr->getType()->isOverloadableType()))15714        return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);15715 15716      return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,15717                                ForFoldExpression);15718    }15719 15720    // Don't resolve overloads if the other type is overloadable.15721    if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&15722        LHSExpr->getType()->isOverloadableType())15723      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);15724 15725    ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);15726    if (!resolvedRHS.isUsable()) return ExprError();15727    RHSExpr = resolvedRHS.get();15728  }15729 15730  if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||15731                             LHSExpr->getType()->isHLSLResourceRecordArray())) {15732    if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))15733      return ExprError();15734  }15735 15736  if (getLangOpts().CPlusPlus) {15737    // Otherwise, build an overloaded op if either expression is type-dependent15738    // or has an overloadable type.15739    if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||15740        LHSExpr->getType()->isOverloadableType() ||15741        RHSExpr->getType()->isOverloadableType())15742      return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);15743  }15744 15745  if (getLangOpts().RecoveryAST &&15746      (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {15747    assert(!getLangOpts().CPlusPlus);15748    assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&15749           "Should only occur in error-recovery path.");15750    if (BinaryOperator::isCompoundAssignmentOp(Opc))15751      // C [6.15.16] p3:15752      // An assignment expression has the value of the left operand after the15753      // assignment, but is not an lvalue.15754      return CompoundAssignOperator::Create(15755          Context, LHSExpr, RHSExpr, Opc,15756          LHSExpr->getType().getUnqualifiedType(), VK_PRValue, OK_Ordinary,15757          OpLoc, CurFPFeatureOverrides());15758    QualType ResultType;15759    switch (Opc) {15760    case BO_Assign:15761      ResultType = LHSExpr->getType().getUnqualifiedType();15762      break;15763    case BO_LT:15764    case BO_GT:15765    case BO_LE:15766    case BO_GE:15767    case BO_EQ:15768    case BO_NE:15769    case BO_LAnd:15770    case BO_LOr:15771      // These operators have a fixed result type regardless of operands.15772      ResultType = Context.IntTy;15773      break;15774    case BO_Comma:15775      ResultType = RHSExpr->getType();15776      break;15777    default:15778      ResultType = Context.DependentTy;15779      break;15780    }15781    return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,15782                                  VK_PRValue, OK_Ordinary, OpLoc,15783                                  CurFPFeatureOverrides());15784  }15785 15786  // Build a built-in binary operation.15787  return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);15788}15789 15790static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {15791  if (T.isNull() || T->isDependentType())15792    return false;15793 15794  if (!Ctx.isPromotableIntegerType(T))15795    return true;15796 15797  return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);15798}15799 15800ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,15801                                      UnaryOperatorKind Opc, Expr *InputExpr,15802                                      bool IsAfterAmp) {15803  ExprResult Input = InputExpr;15804  ExprValueKind VK = VK_PRValue;15805  ExprObjectKind OK = OK_Ordinary;15806  QualType resultType;15807  bool CanOverflow = false;15808 15809  bool ConvertHalfVec = false;15810  if (getLangOpts().OpenCL) {15811    QualType Ty = InputExpr->getType();15812    // The only legal unary operation for atomics is '&'.15813    if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||15814    // OpenCL special types - image, sampler, pipe, and blocks are to be used15815    // only with a builtin functions and therefore should be disallowed here.15816        (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()15817        || Ty->isBlockPointerType())) {15818      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15819                       << InputExpr->getType()15820                       << Input.get()->getSourceRange());15821    }15822  }15823 15824  if (getLangOpts().HLSL && OpLoc.isValid()) {15825    if (Opc == UO_AddrOf)15826      return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);15827    if (Opc == UO_Deref)15828      return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);15829  }15830 15831  if (InputExpr->isTypeDependent() &&15832      InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {15833    resultType = Context.DependentTy;15834  } else {15835    switch (Opc) {15836    case UO_PreInc:15837    case UO_PreDec:15838    case UO_PostInc:15839    case UO_PostDec:15840      resultType =15841          CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,15842                                         Opc == UO_PreInc || Opc == UO_PostInc,15843                                         Opc == UO_PreInc || Opc == UO_PreDec);15844      CanOverflow = isOverflowingIntegerType(Context, resultType);15845      break;15846    case UO_AddrOf:15847      resultType = CheckAddressOfOperand(Input, OpLoc);15848      CheckAddressOfNoDeref(InputExpr);15849      RecordModifiableNonNullParam(*this, InputExpr);15850      break;15851    case UO_Deref: {15852      Input = DefaultFunctionArrayLvalueConversion(Input.get());15853      if (Input.isInvalid())15854        return ExprError();15855      resultType =15856          CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);15857      break;15858    }15859    case UO_Plus:15860    case UO_Minus:15861      CanOverflow = Opc == UO_Minus &&15862                    isOverflowingIntegerType(Context, Input.get()->getType());15863      Input = UsualUnaryConversions(Input.get());15864      if (Input.isInvalid())15865        return ExprError();15866      // Unary plus and minus require promoting an operand of half vector to a15867      // float vector and truncating the result back to a half vector. For now,15868      // we do this only when HalfArgsAndReturns is set (that is, when the15869      // target is arm or arm64).15870      ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());15871 15872      // If the operand is a half vector, promote it to a float vector.15873      if (ConvertHalfVec)15874        Input = convertVector(Input.get(), Context.FloatTy, *this);15875      resultType = Input.get()->getType();15876      if (resultType->isArithmeticType()) // C99 6.5.3.3p115877        break;15878      else if (resultType->isVectorType() &&15879               // The z vector extensions don't allow + or - with bool vectors.15880               (!Context.getLangOpts().ZVector ||15881                resultType->castAs<VectorType>()->getVectorKind() !=15882                    VectorKind::AltiVecBool))15883        break;15884      else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -15885        break;15886      else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p615887               Opc == UO_Plus && resultType->isPointerType())15888        break;15889 15890      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15891                       << resultType << Input.get()->getSourceRange());15892 15893    case UO_Not: // bitwise complement15894      Input = UsualUnaryConversions(Input.get());15895      if (Input.isInvalid())15896        return ExprError();15897      resultType = Input.get()->getType();15898      // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.15899      if (resultType->isComplexType() || resultType->isComplexIntegerType())15900        // C99 does not support '~' for complex conjugation.15901        Diag(OpLoc, diag::ext_integer_complement_complex)15902            << resultType << Input.get()->getSourceRange();15903      else if (resultType->hasIntegerRepresentation())15904        break;15905      else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {15906        // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate15907        // on vector float types.15908        QualType T = resultType->castAs<ExtVectorType>()->getElementType();15909        if (!T->isIntegerType())15910          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15911                           << resultType << Input.get()->getSourceRange());15912      } else {15913        return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15914                         << resultType << Input.get()->getSourceRange());15915      }15916      break;15917 15918    case UO_LNot: // logical negation15919      // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).15920      Input = DefaultFunctionArrayLvalueConversion(Input.get());15921      if (Input.isInvalid())15922        return ExprError();15923      resultType = Input.get()->getType();15924 15925      // Though we still have to promote half FP to float...15926      if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {15927        Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)15928                    .get();15929        resultType = Context.FloatTy;15930      }15931 15932      // WebAsembly tables can't be used in unary expressions.15933      if (resultType->isPointerType() &&15934          resultType->getPointeeType().isWebAssemblyReferenceType()) {15935        return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15936                         << resultType << Input.get()->getSourceRange());15937      }15938 15939      if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {15940        // C99 6.5.3.3p1: ok, fallthrough;15941        if (Context.getLangOpts().CPlusPlus) {15942          // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:15943          // operand contextually converted to bool.15944          Input = ImpCastExprToType(Input.get(), Context.BoolTy,15945                                    ScalarTypeToBooleanCastKind(resultType));15946        } else if (Context.getLangOpts().OpenCL &&15947                   Context.getLangOpts().OpenCLVersion < 120) {15948          // OpenCL v1.1 6.3.h: The logical operator not (!) does not15949          // operate on scalar float types.15950          if (!resultType->isIntegerType() && !resultType->isPointerType())15951            return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15952                             << resultType << Input.get()->getSourceRange());15953        }15954      } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&15955                 !resultType->hasBooleanRepresentation()) {15956        // HLSL unary logical 'not' behaves like C++, which states that the15957        // operand is converted to bool and the result is bool, however HLSL15958        // extends this property to vectors.15959        const VectorType *VTy = resultType->castAs<VectorType>();15960        resultType =15961            Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());15962 15963        Input = ImpCastExprToType(15964                    Input.get(), resultType,15965                    ScalarTypeToBooleanCastKind(VTy->getElementType()))15966                    .get();15967        break;15968      } else if (resultType->isExtVectorType()) {15969        if (Context.getLangOpts().OpenCL &&15970            Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {15971          // OpenCL v1.1 6.3.h: The logical operator not (!) does not15972          // operate on vector float types.15973          QualType T = resultType->castAs<ExtVectorType>()->getElementType();15974          if (!T->isIntegerType())15975            return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15976                             << resultType << Input.get()->getSourceRange());15977        }15978        // Vector logical not returns the signed variant of the operand type.15979        resultType = GetSignedVectorType(resultType);15980        break;15981      } else if (Context.getLangOpts().CPlusPlus &&15982                 resultType->isVectorType()) {15983        const VectorType *VTy = resultType->castAs<VectorType>();15984        if (VTy->getVectorKind() != VectorKind::Generic)15985          return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15986                           << resultType << Input.get()->getSourceRange());15987 15988        // Vector logical not returns the signed variant of the operand type.15989        resultType = GetSignedVectorType(resultType);15990        break;15991      } else {15992        return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)15993                         << resultType << Input.get()->getSourceRange());15994      }15995 15996      // LNot always has type int. C99 6.5.3.3p5.15997      // In C++, it's bool. C++ 5.3.1p815998      resultType = Context.getLogicalOperationType();15999      break;16000    case UO_Real:16001    case UO_Imag:16002      resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);16003      // _Real maps ordinary l-values into ordinary l-values. _Imag maps16004      // ordinary complex l-values to ordinary l-values and all other values to16005      // r-values.16006      if (Input.isInvalid())16007        return ExprError();16008      if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {16009        if (Input.get()->isGLValue() &&16010            Input.get()->getObjectKind() == OK_Ordinary)16011          VK = Input.get()->getValueKind();16012      } else if (!getLangOpts().CPlusPlus) {16013        // In C, a volatile scalar is read by __imag. In C++, it is not.16014        Input = DefaultLvalueConversion(Input.get());16015      }16016      break;16017    case UO_Extension:16018      resultType = Input.get()->getType();16019      VK = Input.get()->getValueKind();16020      OK = Input.get()->getObjectKind();16021      break;16022    case UO_Coawait:16023      // It's unnecessary to represent the pass-through operator co_await in the16024      // AST; just return the input expression instead.16025      assert(!Input.get()->getType()->isDependentType() &&16026             "the co_await expression must be non-dependant before "16027             "building operator co_await");16028      return Input;16029    }16030  }16031  if (resultType.isNull() || Input.isInvalid())16032    return ExprError();16033 16034  // Check for array bounds violations in the operand of the UnaryOperator,16035  // except for the '*' and '&' operators that have to be handled specially16036  // by CheckArrayAccess (as there are special cases like &array[arraysize]16037  // that are explicitly defined as valid by the standard).16038  if (Opc != UO_AddrOf && Opc != UO_Deref)16039    CheckArrayAccess(Input.get());16040 16041  auto *UO =16042      UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,16043                            OpLoc, CanOverflow, CurFPFeatureOverrides());16044 16045  if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&16046      !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&16047      !isUnevaluatedContext())16048    ExprEvalContexts.back().PossibleDerefs.insert(UO);16049 16050  // Convert the result back to a half vector.16051  if (ConvertHalfVec)16052    return convertVector(UO, Context.HalfTy, *this);16053  return UO;16054}16055 16056bool Sema::isQualifiedMemberAccess(Expr *E) {16057  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {16058    if (!DRE->getQualifier())16059      return false;16060 16061    ValueDecl *VD = DRE->getDecl();16062    if (!VD->isCXXClassMember())16063      return false;16064 16065    if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))16066      return true;16067    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))16068      return Method->isImplicitObjectMemberFunction();16069 16070    return false;16071  }16072 16073  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {16074    if (!ULE->getQualifier())16075      return false;16076 16077    for (NamedDecl *D : ULE->decls()) {16078      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {16079        if (Method->isImplicitObjectMemberFunction())16080          return true;16081      } else {16082        // Overload set does not contain methods.16083        break;16084      }16085    }16086 16087    return false;16088  }16089 16090  return false;16091}16092 16093ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,16094                              UnaryOperatorKind Opc, Expr *Input,16095                              bool IsAfterAmp) {16096  // First things first: handle placeholders so that the16097  // overloaded-operator check considers the right type.16098  if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {16099    // Increment and decrement of pseudo-object references.16100    if (pty->getKind() == BuiltinType::PseudoObject &&16101        UnaryOperator::isIncrementDecrementOp(Opc))16102      return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);16103 16104    // extension is always a builtin operator.16105    if (Opc == UO_Extension)16106      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);16107 16108    // & gets special logic for several kinds of placeholder.16109    // The builtin code knows what to do.16110    if (Opc == UO_AddrOf &&16111        (pty->getKind() == BuiltinType::Overload ||16112         pty->getKind() == BuiltinType::UnknownAny ||16113         pty->getKind() == BuiltinType::BoundMember))16114      return CreateBuiltinUnaryOp(OpLoc, Opc, Input);16115 16116    // Anything else needs to be handled now.16117    ExprResult Result = CheckPlaceholderExpr(Input);16118    if (Result.isInvalid()) return ExprError();16119    Input = Result.get();16120  }16121 16122  if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&16123      UnaryOperator::getOverloadedOperator(Opc) != OO_None &&16124      !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {16125    // Find all of the overloaded operators visible from this point.16126    UnresolvedSet<16> Functions;16127    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);16128    if (S && OverOp != OO_None)16129      LookupOverloadedOperatorName(OverOp, S, Functions);16130 16131    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);16132  }16133 16134  return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);16135}16136 16137ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,16138                              Expr *Input, bool IsAfterAmp) {16139  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,16140                      IsAfterAmp);16141}16142 16143ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,16144                                LabelDecl *TheDecl) {16145  TheDecl->markUsed(Context);16146  // Create the AST node.  The address of a label always has type 'void*'.16147  auto *Res = new (Context) AddrLabelExpr(16148      OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));16149 16150  if (getCurFunction())16151    getCurFunction()->AddrLabels.push_back(Res);16152 16153  return Res;16154}16155 16156void Sema::ActOnStartStmtExpr() {16157  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);16158  // Make sure we diagnose jumping into a statement expression.16159  setFunctionHasBranchProtectedScope();16160}16161 16162void Sema::ActOnStmtExprError() {16163  // Note that function is also called by TreeTransform when leaving a16164  // StmtExpr scope without rebuilding anything.16165 16166  DiscardCleanupsInEvaluationContext();16167  PopExpressionEvaluationContext();16168}16169 16170ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,16171                               SourceLocation RPLoc) {16172  return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));16173}16174 16175ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,16176                               SourceLocation RPLoc, unsigned TemplateDepth) {16177  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");16178  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);16179 16180  if (hasAnyUnrecoverableErrorsInThisFunction())16181    DiscardCleanupsInEvaluationContext();16182  assert(!Cleanup.exprNeedsCleanups() &&16183         "cleanups within StmtExpr not correctly bound!");16184  PopExpressionEvaluationContext();16185 16186  // FIXME: there are a variety of strange constraints to enforce here, for16187  // example, it is not possible to goto into a stmt expression apparently.16188  // More semantic analysis is needed.16189 16190  // If there are sub-stmts in the compound stmt, take the type of the last one16191  // as the type of the stmtexpr.16192  QualType Ty = Context.VoidTy;16193  bool StmtExprMayBindToTemp = false;16194  if (!Compound->body_empty()) {16195    if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {16196      if (const Expr *Value = LastStmt->getExprStmt()) {16197        StmtExprMayBindToTemp = true;16198        Ty = Value->getType();16199      }16200    }16201  }16202 16203  // FIXME: Check that expression type is complete/non-abstract; statement16204  // expressions are not lvalues.16205  Expr *ResStmtExpr =16206      new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);16207  if (StmtExprMayBindToTemp)16208    return MaybeBindToTemporary(ResStmtExpr);16209  return ResStmtExpr;16210}16211 16212ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {16213  if (ER.isInvalid())16214    return ExprError();16215 16216  // Do function/array conversion on the last expression, but not16217  // lvalue-to-rvalue.  However, initialize an unqualified type.16218  ER = DefaultFunctionArrayConversion(ER.get());16219  if (ER.isInvalid())16220    return ExprError();16221  Expr *E = ER.get();16222 16223  if (E->isTypeDependent())16224    return E;16225 16226  // In ARC, if the final expression ends in a consume, splice16227  // the consume out and bind it later.  In the alternate case16228  // (when dealing with a retainable type), the result16229  // initialization will create a produce.  In both cases the16230  // result will be +1, and we'll need to balance that out with16231  // a bind.16232  auto *Cast = dyn_cast<ImplicitCastExpr>(E);16233  if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)16234    return Cast->getSubExpr();16235 16236  // FIXME: Provide a better location for the initialization.16237  return PerformCopyInitialization(16238      InitializedEntity::InitializeStmtExprResult(16239          E->getBeginLoc(), E->getType().getAtomicUnqualifiedType()),16240      SourceLocation(), E);16241}16242 16243ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,16244                                      TypeSourceInfo *TInfo,16245                                      ArrayRef<OffsetOfComponent> Components,16246                                      SourceLocation RParenLoc) {16247  QualType ArgTy = TInfo->getType();16248  bool Dependent = ArgTy->isDependentType();16249  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();16250 16251  // We must have at least one component that refers to the type, and the first16252  // one is known to be a field designator.  Verify that the ArgTy represents16253  // a struct/union/class.16254  if (!Dependent && !ArgTy->isRecordType())16255    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)16256                       << ArgTy << TypeRange);16257 16258  // Type must be complete per C99 7.17p3 because a declaring a variable16259  // with an incomplete type would be ill-formed.16260  if (!Dependent16261      && RequireCompleteType(BuiltinLoc, ArgTy,16262                             diag::err_offsetof_incomplete_type, TypeRange))16263    return ExprError();16264 16265  bool DidWarnAboutNonPOD = false;16266  QualType CurrentType = ArgTy;16267  SmallVector<OffsetOfNode, 4> Comps;16268  SmallVector<Expr*, 4> Exprs;16269  for (const OffsetOfComponent &OC : Components) {16270    if (OC.isBrackets) {16271      // Offset of an array sub-field.  TODO: Should we allow vector elements?16272      if (!CurrentType->isDependentType()) {16273        const ArrayType *AT = Context.getAsArrayType(CurrentType);16274        if(!AT)16275          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)16276                           << CurrentType);16277        CurrentType = AT->getElementType();16278      } else16279        CurrentType = Context.DependentTy;16280 16281      ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));16282      if (IdxRval.isInvalid())16283        return ExprError();16284      Expr *Idx = IdxRval.get();16285 16286      // The expression must be an integral expression.16287      // FIXME: An integral constant expression?16288      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&16289          !Idx->getType()->isIntegerType())16290        return ExprError(16291            Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)16292            << Idx->getSourceRange());16293 16294      // Record this array index.16295      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));16296      Exprs.push_back(Idx);16297      continue;16298    }16299 16300    // Offset of a field.16301    if (CurrentType->isDependentType()) {16302      // We have the offset of a field, but we can't look into the dependent16303      // type. Just record the identifier of the field.16304      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));16305      CurrentType = Context.DependentTy;16306      continue;16307    }16308 16309    // We need to have a complete type to look into.16310    if (RequireCompleteType(OC.LocStart, CurrentType,16311                            diag::err_offsetof_incomplete_type))16312      return ExprError();16313 16314    // Look for the designated field.16315    auto *RD = CurrentType->getAsRecordDecl();16316    if (!RD)16317      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)16318                       << CurrentType);16319 16320    // C++ [lib.support.types]p5:16321    //   The macro offsetof accepts a restricted set of type arguments in this16322    //   International Standard. type shall be a POD structure or a POD union16323    //   (clause 9).16324    // C++11 [support.types]p4:16325    //   If type is not a standard-layout class (Clause 9), the results are16326    //   undefined.16327    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {16328      bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();16329      unsigned DiagID =16330        LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type16331                            : diag::ext_offsetof_non_pod_type;16332 16333      if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {16334        Diag(BuiltinLoc, DiagID)16335            << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;16336        DidWarnAboutNonPOD = true;16337      }16338    }16339 16340    // Look for the field.16341    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);16342    LookupQualifiedName(R, RD);16343    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();16344    IndirectFieldDecl *IndirectMemberDecl = nullptr;16345    if (!MemberDecl) {16346      if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))16347        MemberDecl = IndirectMemberDecl->getAnonField();16348    }16349 16350    if (!MemberDecl) {16351      // Lookup could be ambiguous when looking up a placeholder variable16352      // __builtin_offsetof(S, _).16353      // In that case we would already have emitted a diagnostic16354      if (!R.isAmbiguous())16355        Diag(BuiltinLoc, diag::err_no_member)16356            << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);16357      return ExprError();16358    }16359 16360    // C99 7.17p3:16361    //   (If the specified member is a bit-field, the behavior is undefined.)16362    //16363    // We diagnose this as an error.16364    if (MemberDecl->isBitField()) {16365      Diag(OC.LocEnd, diag::err_offsetof_bitfield)16366        << MemberDecl->getDeclName()16367        << SourceRange(BuiltinLoc, RParenLoc);16368      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);16369      return ExprError();16370    }16371 16372    RecordDecl *Parent = MemberDecl->getParent();16373    if (IndirectMemberDecl)16374      Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());16375 16376    // If the member was found in a base class, introduce OffsetOfNodes for16377    // the base class indirections.16378    CXXBasePaths Paths;16379    if (IsDerivedFrom(OC.LocStart, CurrentType,16380                      Context.getCanonicalTagType(Parent), Paths)) {16381      if (Paths.getDetectedVirtual()) {16382        Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)16383          << MemberDecl->getDeclName()16384          << SourceRange(BuiltinLoc, RParenLoc);16385        return ExprError();16386      }16387 16388      CXXBasePath &Path = Paths.front();16389      for (const CXXBasePathElement &B : Path)16390        Comps.push_back(OffsetOfNode(B.Base));16391    }16392 16393    if (IndirectMemberDecl) {16394      for (auto *FI : IndirectMemberDecl->chain()) {16395        assert(isa<FieldDecl>(FI));16396        Comps.push_back(OffsetOfNode(OC.LocStart,16397                                     cast<FieldDecl>(FI), OC.LocEnd));16398      }16399    } else16400      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));16401 16402    CurrentType = MemberDecl->getType().getNonReferenceType();16403  }16404 16405  return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,16406                              Comps, Exprs, RParenLoc);16407}16408 16409ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,16410                                      SourceLocation BuiltinLoc,16411                                      SourceLocation TypeLoc,16412                                      ParsedType ParsedArgTy,16413                                      ArrayRef<OffsetOfComponent> Components,16414                                      SourceLocation RParenLoc) {16415 16416  TypeSourceInfo *ArgTInfo;16417  QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);16418  if (ArgTy.isNull())16419    return ExprError();16420 16421  if (!ArgTInfo)16422    ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);16423 16424  return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);16425}16426 16427 16428ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,16429                                 Expr *CondExpr,16430                                 Expr *LHSExpr, Expr *RHSExpr,16431                                 SourceLocation RPLoc) {16432  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");16433 16434  ExprValueKind VK = VK_PRValue;16435  ExprObjectKind OK = OK_Ordinary;16436  QualType resType;16437  bool CondIsTrue = false;16438  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {16439    resType = Context.DependentTy;16440  } else {16441    // The conditional expression is required to be a constant expression.16442    llvm::APSInt condEval(32);16443    ExprResult CondICE = VerifyIntegerConstantExpression(16444        CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);16445    if (CondICE.isInvalid())16446      return ExprError();16447    CondExpr = CondICE.get();16448    CondIsTrue = condEval.getZExtValue();16449 16450    // If the condition is > zero, then the AST type is the same as the LHSExpr.16451    Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;16452 16453    resType = ActiveExpr->getType();16454    VK = ActiveExpr->getValueKind();16455    OK = ActiveExpr->getObjectKind();16456  }16457 16458  return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,16459                                  resType, VK, OK, RPLoc, CondIsTrue);16460}16461 16462//===----------------------------------------------------------------------===//16463// Clang Extensions.16464//===----------------------------------------------------------------------===//16465 16466void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {16467  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);16468 16469  if (LangOpts.CPlusPlus) {16470    MangleNumberingContext *MCtx;16471    Decl *ManglingContextDecl;16472    std::tie(MCtx, ManglingContextDecl) =16473        getCurrentMangleNumberContext(Block->getDeclContext());16474    if (MCtx) {16475      unsigned ManglingNumber = MCtx->getManglingNumber(Block);16476      Block->setBlockMangling(ManglingNumber, ManglingContextDecl);16477    }16478  }16479 16480  PushBlockScope(CurScope, Block);16481  CurContext->addDecl(Block);16482  if (CurScope)16483    PushDeclContext(CurScope, Block);16484  else16485    CurContext = Block;16486 16487  getCurBlock()->HasImplicitReturnType = true;16488 16489  // Enter a new evaluation context to insulate the block from any16490  // cleanups from the enclosing full-expression.16491  PushExpressionEvaluationContext(16492      ExpressionEvaluationContext::PotentiallyEvaluated);16493}16494 16495void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,16496                               Scope *CurScope) {16497  assert(ParamInfo.getIdentifier() == nullptr &&16498         "block-id should have no identifier!");16499  assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);16500  BlockScopeInfo *CurBlock = getCurBlock();16501 16502  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);16503  QualType T = Sig->getType();16504  DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block);16505 16506  // GetTypeForDeclarator always produces a function type for a block16507  // literal signature.  Furthermore, it is always a FunctionProtoType16508  // unless the function was written with a typedef.16509  assert(T->isFunctionType() &&16510         "GetTypeForDeclarator made a non-function block signature");16511 16512  // Look for an explicit signature in that function type.16513  FunctionProtoTypeLoc ExplicitSignature;16514 16515  if ((ExplicitSignature = Sig->getTypeLoc()16516                               .getAsAdjusted<FunctionProtoTypeLoc>())) {16517 16518    // Check whether that explicit signature was synthesized by16519    // GetTypeForDeclarator.  If so, don't save that as part of the16520    // written signature.16521    if (ExplicitSignature.getLocalRangeBegin() ==16522        ExplicitSignature.getLocalRangeEnd()) {16523      // This would be much cheaper if we stored TypeLocs instead of16524      // TypeSourceInfos.16525      TypeLoc Result = ExplicitSignature.getReturnLoc();16526      unsigned Size = Result.getFullDataSize();16527      Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);16528      Sig->getTypeLoc().initializeFullCopy(Result, Size);16529 16530      ExplicitSignature = FunctionProtoTypeLoc();16531    }16532  }16533 16534  CurBlock->TheDecl->setSignatureAsWritten(Sig);16535  CurBlock->FunctionType = T;16536 16537  const auto *Fn = T->castAs<FunctionType>();16538  QualType RetTy = Fn->getReturnType();16539  bool isVariadic =16540      (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());16541 16542  CurBlock->TheDecl->setIsVariadic(isVariadic);16543 16544  // Context.DependentTy is used as a placeholder for a missing block16545  // return type.  TODO:  what should we do with declarators like:16546  //   ^ * { ... }16547  // If the answer is "apply template argument deduction"....16548  if (RetTy != Context.DependentTy) {16549    CurBlock->ReturnType = RetTy;16550    CurBlock->TheDecl->setBlockMissingReturnType(false);16551    CurBlock->HasImplicitReturnType = false;16552  }16553 16554  // Push block parameters from the declarator if we had them.16555  SmallVector<ParmVarDecl*, 8> Params;16556  if (ExplicitSignature) {16557    for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {16558      ParmVarDecl *Param = ExplicitSignature.getParam(I);16559      if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&16560          !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {16561        // Diagnose this as an extension in C17 and earlier.16562        if (!getLangOpts().C23)16563          Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);16564      }16565      Params.push_back(Param);16566    }16567 16568  // Fake up parameter variables if we have a typedef, like16569  //   ^ fntype { ... }16570  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {16571    for (const auto &I : Fn->param_types()) {16572      ParmVarDecl *Param = BuildParmVarDeclForTypedef(16573          CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);16574      Params.push_back(Param);16575    }16576  }16577 16578  // Set the parameters on the block decl.16579  if (!Params.empty()) {16580    CurBlock->TheDecl->setParams(Params);16581    CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),16582                             /*CheckParameterNames=*/false);16583  }16584 16585  // Finally we can process decl attributes.16586  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);16587 16588  // Put the parameter variables in scope.16589  for (auto *AI : CurBlock->TheDecl->parameters()) {16590    AI->setOwningFunction(CurBlock->TheDecl);16591 16592    // If this has an identifier, add it to the scope stack.16593    if (AI->getIdentifier()) {16594      CheckShadow(CurBlock->TheScope, AI);16595 16596      PushOnScopeChains(AI, CurBlock->TheScope);16597    }16598 16599    if (AI->isInvalidDecl())16600      CurBlock->TheDecl->setInvalidDecl();16601  }16602}16603 16604void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {16605  // Leave the expression-evaluation context.16606  DiscardCleanupsInEvaluationContext();16607  PopExpressionEvaluationContext();16608 16609  // Pop off CurBlock, handle nested blocks.16610  PopDeclContext();16611  PopFunctionScopeInfo();16612}16613 16614ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,16615                                    Stmt *Body, Scope *CurScope) {16616  // If blocks are disabled, emit an error.16617  if (!LangOpts.Blocks)16618    Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;16619 16620  // Leave the expression-evaluation context.16621  if (hasAnyUnrecoverableErrorsInThisFunction())16622    DiscardCleanupsInEvaluationContext();16623  assert(!Cleanup.exprNeedsCleanups() &&16624         "cleanups within block not correctly bound!");16625  PopExpressionEvaluationContext();16626 16627  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());16628  BlockDecl *BD = BSI->TheDecl;16629 16630  maybeAddDeclWithEffects(BD);16631 16632  if (BSI->HasImplicitReturnType)16633    deduceClosureReturnType(*BSI);16634 16635  QualType RetTy = Context.VoidTy;16636  if (!BSI->ReturnType.isNull())16637    RetTy = BSI->ReturnType;16638 16639  bool NoReturn = BD->hasAttr<NoReturnAttr>();16640  QualType BlockTy;16641 16642  // If the user wrote a function type in some form, try to use that.16643  if (!BSI->FunctionType.isNull()) {16644    const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();16645 16646    FunctionType::ExtInfo Ext = FTy->getExtInfo();16647    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);16648 16649    // Turn protoless block types into nullary block types.16650    if (isa<FunctionNoProtoType>(FTy)) {16651      FunctionProtoType::ExtProtoInfo EPI;16652      EPI.ExtInfo = Ext;16653      BlockTy = Context.getFunctionType(RetTy, {}, EPI);16654 16655      // Otherwise, if we don't need to change anything about the function type,16656      // preserve its sugar structure.16657    } else if (FTy->getReturnType() == RetTy &&16658               (!NoReturn || FTy->getNoReturnAttr())) {16659      BlockTy = BSI->FunctionType;16660 16661    // Otherwise, make the minimal modifications to the function type.16662    } else {16663      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);16664      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();16665      EPI.TypeQuals = Qualifiers();16666      EPI.ExtInfo = Ext;16667      BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);16668    }16669 16670  // If we don't have a function type, just build one from nothing.16671  } else {16672    FunctionProtoType::ExtProtoInfo EPI;16673    EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);16674    BlockTy = Context.getFunctionType(RetTy, {}, EPI);16675  }16676 16677  DiagnoseUnusedParameters(BD->parameters());16678  BlockTy = Context.getBlockPointerType(BlockTy);16679 16680  // If needed, diagnose invalid gotos and switches in the block.16681  if (getCurFunction()->NeedsScopeChecking() &&16682      !PP.isCodeCompletionEnabled())16683    DiagnoseInvalidJumps(cast<CompoundStmt>(Body));16684 16685  BD->setBody(cast<CompoundStmt>(Body));16686 16687  if (Body && getCurFunction()->HasPotentialAvailabilityViolations)16688    DiagnoseUnguardedAvailabilityViolations(BD);16689 16690  // Try to apply the named return value optimization. We have to check again16691  // if we can do this, though, because blocks keep return statements around16692  // to deduce an implicit return type.16693  if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&16694      !BD->isDependentContext())16695    computeNRVO(Body, BSI);16696 16697  if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||16698      RetTy.hasNonTrivialToPrimitiveCopyCUnion())16699    checkNonTrivialCUnion(RetTy, BD->getCaretLocation(),16700                          NonTrivialCUnionContext::FunctionReturn,16701                          NTCUK_Destruct | NTCUK_Copy);16702 16703  PopDeclContext();16704 16705  // Set the captured variables on the block.16706  SmallVector<BlockDecl::Capture, 4> Captures;16707  for (Capture &Cap : BSI->Captures) {16708    if (Cap.isInvalid() || Cap.isThisCapture())16709      continue;16710    // Cap.getVariable() is always a VarDecl because16711    // blocks cannot capture structured bindings or other ValueDecl kinds.16712    auto *Var = cast<VarDecl>(Cap.getVariable());16713    Expr *CopyExpr = nullptr;16714    if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {16715      if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {16716        // The capture logic needs the destructor, so make sure we mark it.16717        // Usually this is unnecessary because most local variables have16718        // their destructors marked at declaration time, but parameters are16719        // an exception because it's technically only the call site that16720        // actually requires the destructor.16721        if (isa<ParmVarDecl>(Var))16722          FinalizeVarWithDestructor(Var, Record);16723 16724        // Enter a separate potentially-evaluated context while building block16725        // initializers to isolate their cleanups from those of the block16726        // itself.16727        // FIXME: Is this appropriate even when the block itself occurs in an16728        // unevaluated operand?16729        EnterExpressionEvaluationContext EvalContext(16730            *this, ExpressionEvaluationContext::PotentiallyEvaluated);16731 16732        SourceLocation Loc = Cap.getLocation();16733 16734        ExprResult Result = BuildDeclarationNameExpr(16735            CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);16736 16737        // According to the blocks spec, the capture of a variable from16738        // the stack requires a const copy constructor.  This is not true16739        // of the copy/move done to move a __block variable to the heap.16740        if (!Result.isInvalid() &&16741            !Result.get()->getType().isConstQualified()) {16742          Result = ImpCastExprToType(Result.get(),16743                                     Result.get()->getType().withConst(),16744                                     CK_NoOp, VK_LValue);16745        }16746 16747        if (!Result.isInvalid()) {16748          Result = PerformCopyInitialization(16749              InitializedEntity::InitializeBlock(Var->getLocation(),16750                                                 Cap.getCaptureType()),16751              Loc, Result.get());16752        }16753 16754        // Build a full-expression copy expression if initialization16755        // succeeded and used a non-trivial constructor.  Recover from16756        // errors by pretending that the copy isn't necessary.16757        if (!Result.isInvalid() &&16758            !cast<CXXConstructExpr>(Result.get())->getConstructor()16759                ->isTrivial()) {16760          Result = MaybeCreateExprWithCleanups(Result);16761          CopyExpr = Result.get();16762        }16763      }16764    }16765 16766    BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),16767                              CopyExpr);16768    Captures.push_back(NewCap);16769  }16770  BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);16771 16772  // Pop the block scope now but keep it alive to the end of this function.16773  AnalysisBasedWarnings::Policy WP =16774      AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());16775  PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);16776 16777  BlockExpr *Result = new (Context)16778      BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);16779 16780  // If the block isn't obviously global, i.e. it captures anything at16781  // all, then we need to do a few things in the surrounding context:16782  if (Result->getBlockDecl()->hasCaptures()) {16783    // First, this expression has a new cleanup object.16784    ExprCleanupObjects.push_back(Result->getBlockDecl());16785    Cleanup.setExprNeedsCleanups(true);16786 16787    // It also gets a branch-protected scope if any of the captured16788    // variables needs destruction.16789    for (const auto &CI : Result->getBlockDecl()->captures()) {16790      const VarDecl *var = CI.getVariable();16791      if (var->getType().isDestructedType() != QualType::DK_none) {16792        setFunctionHasBranchProtectedScope();16793        break;16794      }16795    }16796  }16797 16798  if (getCurFunction())16799    getCurFunction()->addBlock(BD);16800 16801  // This can happen if the block's return type is deduced, but16802  // the return expression is invalid.16803  if (BD->isInvalidDecl())16804    return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),16805                              {Result}, Result->getType());16806  return Result;16807}16808 16809ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,16810                            SourceLocation RPLoc) {16811  TypeSourceInfo *TInfo;16812  GetTypeFromParser(Ty, &TInfo);16813  return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);16814}16815 16816ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,16817                                Expr *E, TypeSourceInfo *TInfo,16818                                SourceLocation RPLoc) {16819  Expr *OrigExpr = E;16820  bool IsMS = false;16821 16822  // CUDA device global function does not support varargs.16823  if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {16824    if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {16825      CUDAFunctionTarget T = CUDA().IdentifyTarget(F);16826      if (T == CUDAFunctionTarget::Global)16827        return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));16828    }16829  }16830 16831  // NVPTX does not support va_arg expression.16832  if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&16833      Context.getTargetInfo().getTriple().isNVPTX())16834    targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);16835 16836  // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()16837  // as Microsoft ABI on an actual Microsoft platform, where16838  // __builtin_ms_va_list and __builtin_va_list are the same.)16839  if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&16840      Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {16841    QualType MSVaListType = Context.getBuiltinMSVaListType();16842    if (Context.hasSameType(MSVaListType, E->getType())) {16843      if (CheckForModifiableLvalue(E, BuiltinLoc, *this))16844        return ExprError();16845      IsMS = true;16846    }16847  }16848 16849  // Get the va_list type16850  QualType VaListType = Context.getBuiltinVaListType();16851  if (!IsMS) {16852    if (VaListType->isArrayType()) {16853      // Deal with implicit array decay; for example, on x86-64,16854      // va_list is an array, but it's supposed to decay to16855      // a pointer for va_arg.16856      VaListType = Context.getArrayDecayedType(VaListType);16857      // Make sure the input expression also decays appropriately.16858      ExprResult Result = UsualUnaryConversions(E);16859      if (Result.isInvalid())16860        return ExprError();16861      E = Result.get();16862    } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {16863      // If va_list is a record type and we are compiling in C++ mode,16864      // check the argument using reference binding.16865      InitializedEntity Entity = InitializedEntity::InitializeParameter(16866          Context, Context.getLValueReferenceType(VaListType), false);16867      ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);16868      if (Init.isInvalid())16869        return ExprError();16870      E = Init.getAs<Expr>();16871    } else {16872      // Otherwise, the va_list argument must be an l-value because16873      // it is modified by va_arg.16874      if (!E->isTypeDependent() &&16875          CheckForModifiableLvalue(E, BuiltinLoc, *this))16876        return ExprError();16877    }16878  }16879 16880  if (!IsMS && !E->isTypeDependent() &&16881      !Context.hasSameType(VaListType, E->getType()))16882    return ExprError(16883        Diag(E->getBeginLoc(),16884             diag::err_first_argument_to_va_arg_not_of_type_va_list)16885        << OrigExpr->getType() << E->getSourceRange());16886 16887  if (!TInfo->getType()->isDependentType()) {16888    if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),16889                            diag::err_second_parameter_to_va_arg_incomplete,16890                            TInfo->getTypeLoc()))16891      return ExprError();16892 16893    if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),16894                               TInfo->getType(),16895                               diag::err_second_parameter_to_va_arg_abstract,16896                               TInfo->getTypeLoc()))16897      return ExprError();16898 16899    if (!TInfo->getType().isPODType(Context)) {16900      Diag(TInfo->getTypeLoc().getBeginLoc(),16901           TInfo->getType()->isObjCLifetimeType()16902             ? diag::warn_second_parameter_to_va_arg_ownership_qualified16903             : diag::warn_second_parameter_to_va_arg_not_pod)16904        << TInfo->getType()16905        << TInfo->getTypeLoc().getSourceRange();16906    }16907 16908    if (TInfo->getType()->isArrayType()) {16909      DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,16910                          PDiag(diag::warn_second_parameter_to_va_arg_array)16911                              << TInfo->getType()16912                              << TInfo->getTypeLoc().getSourceRange());16913    }16914 16915    // Check for va_arg where arguments of the given type will be promoted16916    // (i.e. this va_arg is guaranteed to have undefined behavior).16917    QualType PromoteType;16918    if (Context.isPromotableIntegerType(TInfo->getType())) {16919      PromoteType = Context.getPromotedIntegerType(TInfo->getType());16920      // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,16921      // and C23 7.16.1.1p2 says, in part:16922      //   If type is not compatible with the type of the actual next argument16923      //   (as promoted according to the default argument promotions), the16924      //   behavior is undefined, except for the following cases:16925      //     - both types are pointers to qualified or unqualified versions of16926      //       compatible types;16927      //     - one type is compatible with a signed integer type, the other16928      //       type is compatible with the corresponding unsigned integer type,16929      //       and the value is representable in both types;16930      //     - one type is pointer to qualified or unqualified void and the16931      //       other is a pointer to a qualified or unqualified character type;16932      //     - or, the type of the next argument is nullptr_t and type is a16933      //       pointer type that has the same representation and alignment16934      //       requirements as a pointer to a character type.16935      // Given that type compatibility is the primary requirement (ignoring16936      // qualifications), you would think we could call typesAreCompatible()16937      // directly to test this. However, in C++, that checks for *same type*,16938      // which causes false positives when passing an enumeration type to16939      // va_arg. Instead, get the underlying type of the enumeration and pass16940      // that.16941      QualType UnderlyingType = TInfo->getType();16942      if (const auto *ED = UnderlyingType->getAsEnumDecl())16943        UnderlyingType = ED->getIntegerType();16944      if (Context.typesAreCompatible(PromoteType, UnderlyingType,16945                                     /*CompareUnqualified*/ true))16946        PromoteType = QualType();16947 16948      // If the types are still not compatible, we need to test whether the16949      // promoted type and the underlying type are the same except for16950      // signedness. Ask the AST for the correctly corresponding type and see16951      // if that's compatible.16952      if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&16953          PromoteType->isUnsignedIntegerType() !=16954              UnderlyingType->isUnsignedIntegerType()) {16955        UnderlyingType =16956            UnderlyingType->isUnsignedIntegerType()16957                ? Context.getCorrespondingSignedType(UnderlyingType)16958                : Context.getCorrespondingUnsignedType(UnderlyingType);16959        if (Context.typesAreCompatible(PromoteType, UnderlyingType,16960                                       /*CompareUnqualified*/ true))16961          PromoteType = QualType();16962      }16963    }16964    if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))16965      PromoteType = Context.DoubleTy;16966    if (!PromoteType.isNull())16967      DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,16968                  PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)16969                          << TInfo->getType()16970                          << PromoteType16971                          << TInfo->getTypeLoc().getSourceRange());16972  }16973 16974  QualType T = TInfo->getType().getNonLValueExprType(Context);16975  return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);16976}16977 16978ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {16979  // The type of __null will be int or long, depending on the size of16980  // pointers on the target.16981  QualType Ty;16982  unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);16983  if (pw == Context.getTargetInfo().getIntWidth())16984    Ty = Context.IntTy;16985  else if (pw == Context.getTargetInfo().getLongWidth())16986    Ty = Context.LongTy;16987  else if (pw == Context.getTargetInfo().getLongLongWidth())16988    Ty = Context.LongLongTy;16989  else {16990    llvm_unreachable("I don't know size of pointer!");16991  }16992 16993  return new (Context) GNUNullExpr(Ty, TokenLoc);16994}16995 16996static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {16997  CXXRecordDecl *ImplDecl = nullptr;16998 16999  // Fetch the std::source_location::__impl decl.17000  if (NamespaceDecl *Std = S.getStdNamespace()) {17001    LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),17002                          Loc, Sema::LookupOrdinaryName);17003    if (S.LookupQualifiedName(ResultSL, Std)) {17004      if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {17005        LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),17006                                Loc, Sema::LookupOrdinaryName);17007        if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&17008            S.LookupQualifiedName(ResultImpl, SLDecl)) {17009          ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();17010        }17011      }17012    }17013  }17014 17015  if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {17016    S.Diag(Loc, diag::err_std_source_location_impl_not_found);17017    return nullptr;17018  }17019 17020  // Verify that __impl is a trivial struct type, with no base classes, and with17021  // only the four expected fields.17022  if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||17023      ImplDecl->getNumBases() != 0) {17024    S.Diag(Loc, diag::err_std_source_location_impl_malformed);17025    return nullptr;17026  }17027 17028  unsigned Count = 0;17029  for (FieldDecl *F : ImplDecl->fields()) {17030    StringRef Name = F->getName();17031 17032    if (Name == "_M_file_name") {17033      if (F->getType() !=17034          S.Context.getPointerType(S.Context.CharTy.withConst()))17035        break;17036      Count++;17037    } else if (Name == "_M_function_name") {17038      if (F->getType() !=17039          S.Context.getPointerType(S.Context.CharTy.withConst()))17040        break;17041      Count++;17042    } else if (Name == "_M_line") {17043      if (!F->getType()->isIntegerType())17044        break;17045      Count++;17046    } else if (Name == "_M_column") {17047      if (!F->getType()->isIntegerType())17048        break;17049      Count++;17050    } else {17051      Count = 100; // invalid17052      break;17053    }17054  }17055  if (Count != 4) {17056    S.Diag(Loc, diag::err_std_source_location_impl_malformed);17057    return nullptr;17058  }17059 17060  return ImplDecl;17061}17062 17063ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,17064                                    SourceLocation BuiltinLoc,17065                                    SourceLocation RPLoc) {17066  QualType ResultTy;17067  switch (Kind) {17068  case SourceLocIdentKind::File:17069  case SourceLocIdentKind::FileName:17070  case SourceLocIdentKind::Function:17071  case SourceLocIdentKind::FuncSig: {17072    QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);17073    ResultTy =17074        Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());17075    break;17076  }17077  case SourceLocIdentKind::Line:17078  case SourceLocIdentKind::Column:17079    ResultTy = Context.UnsignedIntTy;17080    break;17081  case SourceLocIdentKind::SourceLocStruct:17082    if (!StdSourceLocationImplDecl) {17083      StdSourceLocationImplDecl =17084          LookupStdSourceLocationImpl(*this, BuiltinLoc);17085      if (!StdSourceLocationImplDecl)17086        return ExprError();17087    }17088    ResultTy = Context.getPointerType(17089        Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());17090    break;17091  }17092 17093  return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);17094}17095 17096ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,17097                                    SourceLocation BuiltinLoc,17098                                    SourceLocation RPLoc,17099                                    DeclContext *ParentContext) {17100  return new (Context)17101      SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);17102}17103 17104ExprResult Sema::ActOnEmbedExpr(SourceLocation EmbedKeywordLoc,17105                                StringLiteral *BinaryData, StringRef FileName) {17106  EmbedDataStorage *Data = new (Context) EmbedDataStorage;17107  Data->BinaryData = BinaryData;17108  Data->FileName = FileName;17109  return new (Context)17110      EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,17111                Data->getDataElementCount());17112}17113 17114static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,17115                                              const Expr *SrcExpr) {17116  if (!DstType->isFunctionPointerType() ||17117      !SrcExpr->getType()->isFunctionType())17118    return false;17119 17120  auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());17121  if (!DRE)17122    return false;17123 17124  auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());17125  if (!FD)17126    return false;17127 17128  return !S.checkAddressOfFunctionIsAvailable(FD,17129                                              /*Complain=*/true,17130                                              SrcExpr->getBeginLoc());17131}17132 17133bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,17134                                    SourceLocation Loc,17135                                    QualType DstType, QualType SrcType,17136                                    Expr *SrcExpr, AssignmentAction Action,17137                                    bool *Complained) {17138  if (Complained)17139    *Complained = false;17140 17141  // Decode the result (notice that AST's are still created for extensions).17142  bool CheckInferredResultType = false;17143  bool isInvalid = false;17144  unsigned DiagKind = 0;17145  ConversionFixItGenerator ConvHints;17146  bool MayHaveConvFixit = false;17147  bool MayHaveFunctionDiff = false;17148  const ObjCInterfaceDecl *IFace = nullptr;17149  const ObjCProtocolDecl *PDecl = nullptr;17150 17151  switch (ConvTy) {17152  case AssignConvertType::Compatible:17153    DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);17154    return false;17155  case AssignConvertType::CompatibleVoidPtrToNonVoidPtr:17156    // Still a valid conversion, but we may want to diagnose for C++17157    // compatibility reasons.17158    DiagKind = diag::warn_compatible_implicit_pointer_conv;17159    break;17160  case AssignConvertType::PointerToInt:17161    if (getLangOpts().CPlusPlus) {17162      DiagKind = diag::err_typecheck_convert_pointer_int;17163      isInvalid = true;17164    } else {17165      DiagKind = diag::ext_typecheck_convert_pointer_int;17166    }17167    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);17168    MayHaveConvFixit = true;17169    break;17170  case AssignConvertType::IntToPointer:17171    if (getLangOpts().CPlusPlus) {17172      DiagKind = diag::err_typecheck_convert_int_pointer;17173      isInvalid = true;17174    } else {17175      DiagKind = diag::ext_typecheck_convert_int_pointer;17176    }17177    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);17178    MayHaveConvFixit = true;17179    break;17180  case AssignConvertType::IncompatibleFunctionPointerStrict:17181    DiagKind =17182        diag::warn_typecheck_convert_incompatible_function_pointer_strict;17183    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);17184    MayHaveConvFixit = true;17185    break;17186  case AssignConvertType::IncompatibleFunctionPointer:17187    if (getLangOpts().CPlusPlus) {17188      DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;17189      isInvalid = true;17190    } else {17191      DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;17192    }17193    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);17194    MayHaveConvFixit = true;17195    break;17196  case AssignConvertType::IncompatiblePointer:17197    if (Action == AssignmentAction::Passing_CFAudited) {17198      DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;17199    } else if (getLangOpts().CPlusPlus) {17200      DiagKind = diag::err_typecheck_convert_incompatible_pointer;17201      isInvalid = true;17202    } else {17203      DiagKind = diag::ext_typecheck_convert_incompatible_pointer;17204    }17205    CheckInferredResultType = DstType->isObjCObjectPointerType() &&17206      SrcType->isObjCObjectPointerType();17207    if (CheckInferredResultType) {17208      SrcType = SrcType.getUnqualifiedType();17209      DstType = DstType.getUnqualifiedType();17210    } else {17211      ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);17212    }17213    MayHaveConvFixit = true;17214    break;17215  case AssignConvertType::IncompatiblePointerSign:17216    if (getLangOpts().CPlusPlus) {17217      DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;17218      isInvalid = true;17219    } else {17220      DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;17221    }17222    break;17223  case AssignConvertType::FunctionVoidPointer:17224    if (getLangOpts().CPlusPlus) {17225      DiagKind = diag::err_typecheck_convert_pointer_void_func;17226      isInvalid = true;17227    } else {17228      DiagKind = diag::ext_typecheck_convert_pointer_void_func;17229    }17230    break;17231  case AssignConvertType::IncompatiblePointerDiscardsQualifiers: {17232    // Perform array-to-pointer decay if necessary.17233    if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);17234 17235    isInvalid = true;17236 17237    Qualifiers lhq = SrcType->getPointeeType().getQualifiers();17238    Qualifiers rhq = DstType->getPointeeType().getQualifiers();17239    if (lhq.getAddressSpace() != rhq.getAddressSpace()) {17240      DiagKind = diag::err_typecheck_incompatible_address_space;17241      break;17242    } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {17243      DiagKind = diag::err_typecheck_incompatible_ownership;17244      break;17245    } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {17246      DiagKind = diag::err_typecheck_incompatible_ptrauth;17247      break;17248    }17249 17250    llvm_unreachable("unknown error case for discarding qualifiers!");17251    // fallthrough17252  }17253  case AssignConvertType::CompatiblePointerDiscardsQualifiers:17254    // If the qualifiers lost were because we were applying the17255    // (deprecated) C++ conversion from a string literal to a char*17256    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:17257    // Ideally, this check would be performed in17258    // checkPointerTypesForAssignment. However, that would require a17259    // bit of refactoring (so that the second argument is an17260    // expression, rather than a type), which should be done as part17261    // of a larger effort to fix checkPointerTypesForAssignment for17262    // C++ semantics.17263    if (getLangOpts().CPlusPlus &&17264        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))17265      return false;17266    if (getLangOpts().CPlusPlus) {17267      DiagKind =  diag::err_typecheck_convert_discards_qualifiers;17268      isInvalid = true;17269    } else {17270      DiagKind =  diag::ext_typecheck_convert_discards_qualifiers;17271    }17272 17273    break;17274  case AssignConvertType::IncompatibleNestedPointerQualifiers:17275    if (getLangOpts().CPlusPlus) {17276      isInvalid = true;17277      DiagKind = diag::err_nested_pointer_qualifier_mismatch;17278    } else {17279      DiagKind = diag::ext_nested_pointer_qualifier_mismatch;17280    }17281    break;17282  case AssignConvertType::IncompatibleNestedPointerAddressSpaceMismatch:17283    DiagKind = diag::err_typecheck_incompatible_nested_address_space;17284    isInvalid = true;17285    break;17286  case AssignConvertType::IntToBlockPointer:17287    DiagKind = diag::err_int_to_block_pointer;17288    isInvalid = true;17289    break;17290  case AssignConvertType::IncompatibleBlockPointer:17291    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;17292    isInvalid = true;17293    break;17294  case AssignConvertType::IncompatibleObjCQualifiedId: {17295    if (SrcType->isObjCQualifiedIdType()) {17296      const ObjCObjectPointerType *srcOPT =17297                SrcType->castAs<ObjCObjectPointerType>();17298      for (auto *srcProto : srcOPT->quals()) {17299        PDecl = srcProto;17300        break;17301      }17302      if (const ObjCInterfaceType *IFaceT =17303            DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())17304        IFace = IFaceT->getDecl();17305    }17306    else if (DstType->isObjCQualifiedIdType()) {17307      const ObjCObjectPointerType *dstOPT =17308        DstType->castAs<ObjCObjectPointerType>();17309      for (auto *dstProto : dstOPT->quals()) {17310        PDecl = dstProto;17311        break;17312      }17313      if (const ObjCInterfaceType *IFaceT =17314            SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())17315        IFace = IFaceT->getDecl();17316    }17317    if (getLangOpts().CPlusPlus) {17318      DiagKind = diag::err_incompatible_qualified_id;17319      isInvalid = true;17320    } else {17321      DiagKind = diag::warn_incompatible_qualified_id;17322    }17323    break;17324  }17325  case AssignConvertType::IncompatibleVectors:17326    if (getLangOpts().CPlusPlus) {17327      DiagKind = diag::err_incompatible_vectors;17328      isInvalid = true;17329    } else {17330      DiagKind = diag::warn_incompatible_vectors;17331    }17332    break;17333  case AssignConvertType::IncompatibleObjCWeakRef:17334    DiagKind = diag::err_arc_weak_unavailable_assign;17335    isInvalid = true;17336    break;17337  case AssignConvertType::Incompatible:17338    if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {17339      if (Complained)17340        *Complained = true;17341      return true;17342    }17343 17344    DiagKind = diag::err_typecheck_convert_incompatible;17345    ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);17346    MayHaveConvFixit = true;17347    isInvalid = true;17348    MayHaveFunctionDiff = true;17349    break;17350  }17351 17352  QualType FirstType, SecondType;17353  switch (Action) {17354  case AssignmentAction::Assigning:17355  case AssignmentAction::Initializing:17356    // The destination type comes first.17357    FirstType = DstType;17358    SecondType = SrcType;17359    break;17360 17361  case AssignmentAction::Returning:17362  case AssignmentAction::Passing:17363  case AssignmentAction::Passing_CFAudited:17364  case AssignmentAction::Converting:17365  case AssignmentAction::Sending:17366  case AssignmentAction::Casting:17367    // The source type comes first.17368    FirstType = SrcType;17369    SecondType = DstType;17370    break;17371  }17372 17373  PartialDiagnostic FDiag = PDiag(DiagKind);17374  AssignmentAction ActionForDiag = Action;17375  if (Action == AssignmentAction::Passing_CFAudited)17376    ActionForDiag = AssignmentAction::Passing;17377 17378  FDiag << FirstType << SecondType << ActionForDiag17379        << SrcExpr->getSourceRange();17380 17381  if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||17382      DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {17383    auto isPlainChar = [](const clang::Type *Type) {17384      return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||17385             Type->isSpecificBuiltinType(BuiltinType::Char_U);17386    };17387    FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||17388              isPlainChar(SecondType->getPointeeOrArrayElementType()));17389  }17390 17391  // If we can fix the conversion, suggest the FixIts.17392  if (!ConvHints.isNull()) {17393    for (FixItHint &H : ConvHints.Hints)17394      FDiag << H;17395  }17396 17397  if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }17398 17399  if (MayHaveFunctionDiff)17400    HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);17401 17402  Diag(Loc, FDiag);17403  if ((DiagKind == diag::warn_incompatible_qualified_id ||17404       DiagKind == diag::err_incompatible_qualified_id) &&17405      PDecl && IFace && !IFace->hasDefinition())17406    Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)17407        << IFace << PDecl;17408 17409  if (SecondType == Context.OverloadTy)17410    NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,17411                              FirstType, /*TakingAddress=*/true);17412 17413  if (CheckInferredResultType)17414    ObjC().EmitRelatedResultTypeNote(SrcExpr);17415 17416  if (Action == AssignmentAction::Returning &&17417      ConvTy == AssignConvertType::IncompatiblePointer)17418    ObjC().EmitRelatedResultTypeNoteForReturn(DstType);17419 17420  if (Complained)17421    *Complained = true;17422  return isInvalid;17423}17424 17425ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,17426                                                 llvm::APSInt *Result,17427                                                 AllowFoldKind CanFold) {17428  class SimpleICEDiagnoser : public VerifyICEDiagnoser {17429  public:17430    SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,17431                                             QualType T) override {17432      return S.Diag(Loc, diag::err_ice_not_integral)17433             << T << S.LangOpts.CPlusPlus;17434    }17435    SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {17436      return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;17437    }17438  } Diagnoser;17439 17440  return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);17441}17442 17443ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,17444                                                 llvm::APSInt *Result,17445                                                 unsigned DiagID,17446                                                 AllowFoldKind CanFold) {17447  class IDDiagnoser : public VerifyICEDiagnoser {17448    unsigned DiagID;17449 17450  public:17451    IDDiagnoser(unsigned DiagID)17452      : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }17453 17454    SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {17455      return S.Diag(Loc, DiagID);17456    }17457  } Diagnoser(DiagID);17458 17459  return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);17460}17461 17462Sema::SemaDiagnosticBuilder17463Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,17464                                             QualType T) {17465  return diagnoseNotICE(S, Loc);17466}17467 17468Sema::SemaDiagnosticBuilder17469Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {17470  return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;17471}17472 17473ExprResult17474Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,17475                                      VerifyICEDiagnoser &Diagnoser,17476                                      AllowFoldKind CanFold) {17477  SourceLocation DiagLoc = E->getBeginLoc();17478 17479  if (getLangOpts().CPlusPlus11) {17480    // C++11 [expr.const]p5:17481    //   If an expression of literal class type is used in a context where an17482    //   integral constant expression is required, then that class type shall17483    //   have a single non-explicit conversion function to an integral or17484    //   unscoped enumeration type17485    ExprResult Converted;17486    class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {17487      VerifyICEDiagnoser &BaseDiagnoser;17488    public:17489      CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)17490          : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,17491                                BaseDiagnoser.Suppress, true),17492            BaseDiagnoser(BaseDiagnoser) {}17493 17494      SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,17495                                           QualType T) override {17496        return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);17497      }17498 17499      SemaDiagnosticBuilder diagnoseIncomplete(17500          Sema &S, SourceLocation Loc, QualType T) override {17501        return S.Diag(Loc, diag::err_ice_incomplete_type) << T;17502      }17503 17504      SemaDiagnosticBuilder diagnoseExplicitConv(17505          Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {17506        return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;17507      }17508 17509      SemaDiagnosticBuilder noteExplicitConv(17510          Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {17511        return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)17512                 << ConvTy->isEnumeralType() << ConvTy;17513      }17514 17515      SemaDiagnosticBuilder diagnoseAmbiguous(17516          Sema &S, SourceLocation Loc, QualType T) override {17517        return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;17518      }17519 17520      SemaDiagnosticBuilder noteAmbiguous(17521          Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {17522        return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)17523                 << ConvTy->isEnumeralType() << ConvTy;17524      }17525 17526      SemaDiagnosticBuilder diagnoseConversion(17527          Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {17528        llvm_unreachable("conversion functions are permitted");17529      }17530    } ConvertDiagnoser(Diagnoser);17531 17532    Converted = PerformContextualImplicitConversion(DiagLoc, E,17533                                                    ConvertDiagnoser);17534    if (Converted.isInvalid())17535      return Converted;17536    E = Converted.get();17537    // The 'explicit' case causes us to get a RecoveryExpr.  Give up here so we17538    // don't try to evaluate it later. We also don't want to return the17539    // RecoveryExpr here, as it results in this call succeeding, thus callers of17540    // this function will attempt to use 'Value'.17541    if (isa<RecoveryExpr>(E))17542      return ExprError();17543    if (!E->getType()->isIntegralOrUnscopedEnumerationType())17544      return ExprError();17545  } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {17546    // An ICE must be of integral or unscoped enumeration type.17547    if (!Diagnoser.Suppress)17548      Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())17549          << E->getSourceRange();17550    return ExprError();17551  }17552 17553  ExprResult RValueExpr = DefaultLvalueConversion(E);17554  if (RValueExpr.isInvalid())17555    return ExprError();17556 17557  E = RValueExpr.get();17558 17559  // Circumvent ICE checking in C++11 to avoid evaluating the expression twice17560  // in the non-ICE case.17561  if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {17562    SmallVector<PartialDiagnosticAt, 8> Notes;17563    if (Result)17564      *Result = E->EvaluateKnownConstIntCheckOverflow(Context, &Notes);17565    if (!isa<ConstantExpr>(E))17566      E = Result ? ConstantExpr::Create(Context, E, APValue(*Result))17567                 : ConstantExpr::Create(Context, E);17568 17569    if (Notes.empty())17570      return E;17571 17572    // If our only note is the usual "invalid subexpression" note, just point17573    // the caret at its location rather than producing an essentially17574    // redundant note.17575    if (Notes.size() == 1 && Notes[0].second.getDiagID() ==17576          diag::note_invalid_subexpr_in_const_expr) {17577      DiagLoc = Notes[0].first;17578      Notes.clear();17579    }17580 17581    if (getLangOpts().CPlusPlus) {17582      if (!Diagnoser.Suppress) {17583        Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();17584        for (const PartialDiagnosticAt &Note : Notes)17585          Diag(Note.first, Note.second);17586      }17587      return ExprError();17588    }17589 17590    Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();17591    for (const PartialDiagnosticAt &Note : Notes)17592      Diag(Note.first, Note.second);17593 17594    return E;17595  }17596 17597  Expr::EvalResult EvalResult;17598  SmallVector<PartialDiagnosticAt, 8> Notes;17599  EvalResult.Diag = &Notes;17600 17601  // Try to evaluate the expression, and produce diagnostics explaining why it's17602  // not a constant expression as a side-effect.17603  bool Folded =17604      E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&17605      EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&17606      (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);17607 17608  if (!isa<ConstantExpr>(E))17609    E = ConstantExpr::Create(Context, E, EvalResult.Val);17610 17611  // In C++11, we can rely on diagnostics being produced for any expression17612  // which is not a constant expression. If no diagnostics were produced, then17613  // this is a constant expression.17614  if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {17615    if (Result)17616      *Result = EvalResult.Val.getInt();17617    return E;17618  }17619 17620  // If our only note is the usual "invalid subexpression" note, just point17621  // the caret at its location rather than producing an essentially17622  // redundant note.17623  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==17624        diag::note_invalid_subexpr_in_const_expr) {17625    DiagLoc = Notes[0].first;17626    Notes.clear();17627  }17628 17629  if (!Folded || CanFold == AllowFoldKind::No) {17630    if (!Diagnoser.Suppress) {17631      Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();17632      for (const PartialDiagnosticAt &Note : Notes)17633        Diag(Note.first, Note.second);17634    }17635 17636    return ExprError();17637  }17638 17639  Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();17640  for (const PartialDiagnosticAt &Note : Notes)17641    Diag(Note.first, Note.second);17642 17643  if (Result)17644    *Result = EvalResult.Val.getInt();17645  return E;17646}17647 17648namespace {17649  // Handle the case where we conclude a expression which we speculatively17650  // considered to be unevaluated is actually evaluated.17651  class TransformToPE : public TreeTransform<TransformToPE> {17652    typedef TreeTransform<TransformToPE> BaseTransform;17653 17654  public:17655    TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }17656 17657    // Make sure we redo semantic analysis17658    bool AlwaysRebuild() { return true; }17659    bool ReplacingOriginal() { return true; }17660 17661    // We need to special-case DeclRefExprs referring to FieldDecls which17662    // are not part of a member pointer formation; normal TreeTransforming17663    // doesn't catch this case because of the way we represent them in the AST.17664    // FIXME: This is a bit ugly; is it really the best way to handle this17665    // case?17666    //17667    // Error on DeclRefExprs referring to FieldDecls.17668    ExprResult TransformDeclRefExpr(DeclRefExpr *E) {17669      if (isa<FieldDecl>(E->getDecl()) &&17670          !SemaRef.isUnevaluatedContext())17671        return SemaRef.Diag(E->getLocation(),17672                            diag::err_invalid_non_static_member_use)17673            << E->getDecl() << E->getSourceRange();17674 17675      return BaseTransform::TransformDeclRefExpr(E);17676    }17677 17678    // Exception: filter out member pointer formation17679    ExprResult TransformUnaryOperator(UnaryOperator *E) {17680      if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())17681        return E;17682 17683      return BaseTransform::TransformUnaryOperator(E);17684    }17685 17686    // The body of a lambda-expression is in a separate expression evaluation17687    // context so never needs to be transformed.17688    // FIXME: Ideally we wouldn't transform the closure type either, and would17689    // just recreate the capture expressions and lambda expression.17690    StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {17691      return SkipLambdaBody(E, Body);17692    }17693  };17694}17695 17696ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {17697  assert(isUnevaluatedContext() &&17698         "Should only transform unevaluated expressions");17699  ExprEvalContexts.back().Context =17700      ExprEvalContexts[ExprEvalContexts.size()-2].Context;17701  if (isUnevaluatedContext())17702    return E;17703  return TransformToPE(*this).TransformExpr(E);17704}17705 17706TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {17707  assert(isUnevaluatedContext() &&17708         "Should only transform unevaluated expressions");17709  ExprEvalContexts.back().Context = parentEvaluationContext().Context;17710  if (isUnevaluatedContext())17711    return TInfo;17712  return TransformToPE(*this).TransformType(TInfo);17713}17714 17715void17716Sema::PushExpressionEvaluationContext(17717    ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,17718    ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {17719  ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,17720                                LambdaContextDecl, ExprContext);17721 17722  // Discarded statements and immediate contexts nested in other17723  // discarded statements or immediate context are themselves17724  // a discarded statement or an immediate context, respectively.17725  ExprEvalContexts.back().InDiscardedStatement =17726      parentEvaluationContext().isDiscardedStatementContext();17727 17728  // C++23 [expr.const]/p1517729  // An expression or conversion is in an immediate function context if [...]17730  // it is a subexpression of a manifestly constant-evaluated expression or17731  // conversion.17732  const auto &Prev = parentEvaluationContext();17733  ExprEvalContexts.back().InImmediateFunctionContext =17734      Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();17735 17736  ExprEvalContexts.back().InImmediateEscalatingFunctionContext =17737      Prev.InImmediateEscalatingFunctionContext;17738 17739  Cleanup.reset();17740  if (!MaybeODRUseExprs.empty())17741    std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);17742}17743 17744void17745Sema::PushExpressionEvaluationContext(17746    ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,17747    ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {17748  Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;17749  PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);17750}17751 17752void Sema::PushExpressionEvaluationContextForFunction(17753    ExpressionEvaluationContext NewContext, FunctionDecl *FD) {17754  // [expr.const]/p14.117755  // An expression or conversion is in an immediate function context if it is17756  // potentially evaluated and either: its innermost enclosing non-block scope17757  // is a function parameter scope of an immediate function.17758  PushExpressionEvaluationContext(17759      FD && FD->isConsteval()17760          ? ExpressionEvaluationContext::ImmediateFunctionContext17761          : NewContext);17762  const Sema::ExpressionEvaluationContextRecord &Parent =17763      parentEvaluationContext();17764  Sema::ExpressionEvaluationContextRecord &Current = currentEvaluationContext();17765 17766  Current.InDiscardedStatement = false;17767 17768  if (FD) {17769 17770    // Each ExpressionEvaluationContextRecord also keeps track of whether the17771    // context is nested in an immediate function context, so smaller contexts17772    // that appear inside immediate functions (like variable initializers) are17773    // considered to be inside an immediate function context even though by17774    // themselves they are not immediate function contexts. But when a new17775    // function is entered, we need to reset this tracking, since the entered17776    // function might be not an immediate function.17777 17778    Current.InImmediateEscalatingFunctionContext =17779        getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();17780 17781    if (isLambdaMethod(FD))17782      Current.InImmediateFunctionContext =17783          FD->isConsteval() ||17784          (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||17785                                  Parent.isImmediateFunctionContext()));17786    else17787      Current.InImmediateFunctionContext = FD->isConsteval();17788  }17789}17790 17791namespace {17792 17793const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {17794  PossibleDeref = PossibleDeref->IgnoreParenImpCasts();17795  if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {17796    if (E->getOpcode() == UO_Deref)17797      return CheckPossibleDeref(S, E->getSubExpr());17798  } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {17799    return CheckPossibleDeref(S, E->getBase());17800  } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {17801    return CheckPossibleDeref(S, E->getBase());17802  } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {17803    QualType Inner;17804    QualType Ty = E->getType();17805    if (const auto *Ptr = Ty->getAs<PointerType>())17806      Inner = Ptr->getPointeeType();17807    else if (const auto *Arr = S.Context.getAsArrayType(Ty))17808      Inner = Arr->getElementType();17809    else17810      return nullptr;17811 17812    if (Inner->hasAttr(attr::NoDeref))17813      return E;17814  }17815  return nullptr;17816}17817 17818} // namespace17819 17820void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {17821  for (const Expr *E : Rec.PossibleDerefs) {17822    const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);17823    if (DeclRef) {17824      const ValueDecl *Decl = DeclRef->getDecl();17825      Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)17826          << Decl->getName() << E->getSourceRange();17827      Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();17828    } else {17829      Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)17830          << E->getSourceRange();17831    }17832  }17833  Rec.PossibleDerefs.clear();17834}17835 17836void Sema::CheckUnusedVolatileAssignment(Expr *E) {17837  if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)17838    return;17839 17840  // Note: ignoring parens here is not justified by the standard rules, but17841  // ignoring parentheses seems like a more reasonable approach, and this only17842  // drives a deprecation warning so doesn't affect conformance.17843  if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {17844    if (BO->getOpcode() == BO_Assign) {17845      auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;17846      llvm::erase(LHSs, BO->getLHS());17847    }17848  }17849}17850 17851void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {17852  assert(getLangOpts().CPlusPlus20 &&17853         ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&17854         "Cannot mark an immediate escalating expression outside of an "17855         "immediate escalating context");17856  if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());17857      Call && Call->getCallee()) {17858    if (auto *DeclRef =17859            dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))17860      DeclRef->setIsImmediateEscalating(true);17861  } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {17862    Ctr->setIsImmediateEscalating(true);17863  } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {17864    DeclRef->setIsImmediateEscalating(true);17865  } else {17866    assert(false && "expected an immediately escalating expression");17867  }17868  if (FunctionScopeInfo *FI = getCurFunction())17869    FI->FoundImmediateEscalatingExpression = true;17870}17871 17872ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {17873  if (isUnevaluatedContext() || !E.isUsable() || !Decl ||17874      !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||17875      isCheckingDefaultArgumentOrInitializer() ||17876      RebuildingImmediateInvocation || isImmediateFunctionContext())17877    return E;17878 17879  /// Opportunistically remove the callee from ReferencesToConsteval if we can.17880  /// It's OK if this fails; we'll also remove this in17881  /// HandleImmediateInvocations, but catching it here allows us to avoid17882  /// walking the AST looking for it in simple cases.17883  if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))17884    if (auto *DeclRef =17885            dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))17886      ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);17887 17888  // C++23 [expr.const]/p1617889  // An expression or conversion is immediate-escalating if it is not initially17890  // in an immediate function context and it is [...] an immediate invocation17891  // that is not a constant expression and is not a subexpression of an17892  // immediate invocation.17893  APValue Cached;17894  auto CheckConstantExpressionAndKeepResult = [&]() {17895    llvm::SmallVector<PartialDiagnosticAt, 8> Notes;17896    Expr::EvalResult Eval;17897    Eval.Diag = &Notes;17898    bool Res = E.get()->EvaluateAsConstantExpr(17899        Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);17900    if (Res && Notes.empty()) {17901      Cached = std::move(Eval.Val);17902      return true;17903    }17904    return false;17905  };17906 17907  if (!E.get()->isValueDependent() &&17908      ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&17909      !CheckConstantExpressionAndKeepResult()) {17910    MarkExpressionAsImmediateEscalating(E.get());17911    return E;17912  }17913 17914  if (Cleanup.exprNeedsCleanups()) {17915    // Since an immediate invocation is a full expression itself - it requires17916    // an additional ExprWithCleanups node, but it can participate to a bigger17917    // full expression which actually requires cleanups to be run after so17918    // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it17919    // may discard cleanups for outer expression too early.17920 17921    // Note that ExprWithCleanups created here must always have empty cleanup17922    // objects:17923    // - compound literals do not create cleanup objects in C++ and immediate17924    // invocations are C++-only.17925    // - blocks are not allowed inside constant expressions and compiler will17926    // issue an error if they appear there.17927    //17928    // Hence, in correct code any cleanup objects created inside current17929    // evaluation context must be outside the immediate invocation.17930    E = ExprWithCleanups::Create(getASTContext(), E.get(),17931                                 Cleanup.cleanupsHaveSideEffects(), {});17932  }17933 17934  ConstantExpr *Res = ConstantExpr::Create(17935      getASTContext(), E.get(),17936      ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),17937                                   getASTContext()),17938      /*IsImmediateInvocation*/ true);17939  if (Cached.hasValue())17940    Res->MoveIntoResult(Cached, getASTContext());17941  /// Value-dependent constant expressions should not be immediately17942  /// evaluated until they are instantiated.17943  if (!Res->isValueDependent())17944    ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);17945  return Res;17946}17947 17948static void EvaluateAndDiagnoseImmediateInvocation(17949    Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {17950  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;17951  Expr::EvalResult Eval;17952  Eval.Diag = &Notes;17953  ConstantExpr *CE = Candidate.getPointer();17954  bool Result = CE->EvaluateAsConstantExpr(17955      Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);17956  if (!Result || !Notes.empty()) {17957    SemaRef.FailedImmediateInvocations.insert(CE);17958    Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();17959    if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))17960      InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();17961    FunctionDecl *FD = nullptr;17962    if (auto *Call = dyn_cast<CallExpr>(InnerExpr))17963      FD = cast<FunctionDecl>(Call->getCalleeDecl());17964    else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))17965      FD = Call->getConstructor();17966    else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))17967      FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());17968 17969    assert(FD && FD->isImmediateFunction() &&17970           "could not find an immediate function in this expression");17971    if (FD->isInvalidDecl())17972      return;17973    SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)17974        << FD << FD->isConsteval();17975    if (auto Context =17976            SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {17977      SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)17978          << Context->Decl;17979      SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);17980    }17981    if (!FD->isConsteval())17982      SemaRef.DiagnoseImmediateEscalatingReason(FD);17983    for (auto &Note : Notes)17984      SemaRef.Diag(Note.first, Note.second);17985    return;17986  }17987  CE->MoveIntoResult(Eval.Val, SemaRef.getASTContext());17988}17989 17990static void RemoveNestedImmediateInvocation(17991    Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,17992    SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {17993  struct ComplexRemove : TreeTransform<ComplexRemove> {17994    using Base = TreeTransform<ComplexRemove>;17995    llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;17996    SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;17997    SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator17998        CurrentII;17999    ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,18000                  SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,18001                  SmallVector<Sema::ImmediateInvocationCandidate,18002                              4>::reverse_iterator Current)18003        : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}18004    void RemoveImmediateInvocation(ConstantExpr* E) {18005      auto It = std::find_if(CurrentII, IISet.rend(),18006                             [E](Sema::ImmediateInvocationCandidate Elem) {18007                               return Elem.getPointer() == E;18008                             });18009      // It is possible that some subexpression of the current immediate18010      // invocation was handled from another expression evaluation context. Do18011      // not handle the current immediate invocation if some of its18012      // subexpressions failed before.18013      if (It == IISet.rend()) {18014        if (SemaRef.FailedImmediateInvocations.contains(E))18015          CurrentII->setInt(1);18016      } else {18017        It->setInt(1); // Mark as deleted18018      }18019    }18020    ExprResult TransformConstantExpr(ConstantExpr *E) {18021      if (!E->isImmediateInvocation())18022        return Base::TransformConstantExpr(E);18023      RemoveImmediateInvocation(E);18024      return Base::TransformExpr(E->getSubExpr());18025    }18026    /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so18027    /// we need to remove its DeclRefExpr from the DRSet.18028    ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {18029      DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));18030      return Base::TransformCXXOperatorCallExpr(E);18031    }18032    /// Base::TransformUserDefinedLiteral doesn't preserve the18033    /// UserDefinedLiteral node.18034    ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }18035    /// Base::TransformInitializer skips ConstantExpr so we need to visit them18036    /// here.18037    ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {18038      if (!Init)18039        return Init;18040 18041      // We cannot use IgnoreImpCasts because we need to preserve18042      // full expressions.18043      while (true) {18044        if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))18045          Init = ICE->getSubExpr();18046        else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))18047          Init = ICE->getSubExpr();18048        else18049          break;18050      }18051      /// ConstantExprs are the first layer of implicit node to be removed so if18052      /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.18053      if (auto *CE = dyn_cast<ConstantExpr>(Init);18054          CE && CE->isImmediateInvocation())18055        RemoveImmediateInvocation(CE);18056      return Base::TransformInitializer(Init, NotCopyInit);18057    }18058    ExprResult TransformDeclRefExpr(DeclRefExpr *E) {18059      DRSet.erase(E);18060      return E;18061    }18062    ExprResult TransformLambdaExpr(LambdaExpr *E) {18063      // Do not rebuild lambdas to avoid creating a new type.18064      // Lambdas have already been processed inside their eval contexts.18065      return E;18066    }18067    bool AlwaysRebuild() { return false; }18068    bool ReplacingOriginal() { return true; }18069    bool AllowSkippingCXXConstructExpr() {18070      bool Res = AllowSkippingFirstCXXConstructExpr;18071      AllowSkippingFirstCXXConstructExpr = true;18072      return Res;18073    }18074    bool AllowSkippingFirstCXXConstructExpr = true;18075  } Transformer(SemaRef, Rec.ReferenceToConsteval,18076                Rec.ImmediateInvocationCandidates, It);18077 18078  /// CXXConstructExpr with a single argument are getting skipped by18079  /// TreeTransform in some situtation because they could be implicit. This18080  /// can only occur for the top-level CXXConstructExpr because it is used18081  /// nowhere in the expression being transformed therefore will not be rebuilt.18082  /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from18083  /// skipping the first CXXConstructExpr.18084  if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))18085    Transformer.AllowSkippingFirstCXXConstructExpr = false;18086 18087  ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());18088  // The result may not be usable in case of previous compilation errors.18089  // In this case evaluation of the expression may result in crash so just18090  // don't do anything further with the result.18091  if (Res.isUsable()) {18092    Res = SemaRef.MaybeCreateExprWithCleanups(Res);18093    It->getPointer()->setSubExpr(Res.get());18094  }18095}18096 18097static void18098HandleImmediateInvocations(Sema &SemaRef,18099                           Sema::ExpressionEvaluationContextRecord &Rec) {18100  if ((Rec.ImmediateInvocationCandidates.size() == 0 &&18101       Rec.ReferenceToConsteval.size() == 0) ||18102      Rec.isImmediateFunctionContext() || SemaRef.RebuildingImmediateInvocation)18103    return;18104 18105  // An expression or conversion is 'manifestly constant-evaluated' if it is:18106  // [...]18107  // - the initializer of a variable that is usable in constant expressions or18108  //   has constant initialization.18109  if (SemaRef.getLangOpts().CPlusPlus23 &&18110      Rec.ExprContext ==18111          Sema::ExpressionEvaluationContextRecord::EK_VariableInit) {18112    auto *VD = cast<VarDecl>(Rec.ManglingContextDecl);18113    if (VD->isUsableInConstantExpressions(SemaRef.Context) ||18114        VD->hasConstantInitialization()) {18115      // An expression or conversion is in an 'immediate function context' if it18116      // is potentially evaluated and either:18117      // [...]18118      // - it is a subexpression of a manifestly constant-evaluated expression18119      //   or conversion.18120      return;18121    }18122  }18123 18124  /// When we have more than 1 ImmediateInvocationCandidates or previously18125  /// failed immediate invocations, we need to check for nested18126  /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.18127  /// Otherwise we only need to remove ReferenceToConsteval in the immediate18128  /// invocation.18129  if (Rec.ImmediateInvocationCandidates.size() > 1 ||18130      !SemaRef.FailedImmediateInvocations.empty()) {18131 18132    /// Prevent sema calls during the tree transform from adding pointers that18133    /// are already in the sets.18134    llvm::SaveAndRestore DisableIITracking(18135        SemaRef.RebuildingImmediateInvocation, true);18136 18137    /// Prevent diagnostic during tree transfrom as they are duplicates18138    Sema::TentativeAnalysisScope DisableDiag(SemaRef);18139 18140    for (auto It = Rec.ImmediateInvocationCandidates.rbegin();18141         It != Rec.ImmediateInvocationCandidates.rend(); It++)18142      if (!It->getInt())18143        RemoveNestedImmediateInvocation(SemaRef, Rec, It);18144  } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&18145             Rec.ReferenceToConsteval.size()) {18146    struct SimpleRemove : DynamicRecursiveASTVisitor {18147      llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;18148      SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}18149      bool VisitDeclRefExpr(DeclRefExpr *E) override {18150        DRSet.erase(E);18151        return DRSet.size();18152      }18153    } Visitor(Rec.ReferenceToConsteval);18154    Visitor.TraverseStmt(18155        Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());18156  }18157  for (auto CE : Rec.ImmediateInvocationCandidates)18158    if (!CE.getInt())18159      EvaluateAndDiagnoseImmediateInvocation(SemaRef, CE);18160  for (auto *DR : Rec.ReferenceToConsteval) {18161    // If the expression is immediate escalating, it is not an error;18162    // The outer context itself becomes immediate and further errors,18163    // if any, will be handled by DiagnoseImmediateEscalatingReason.18164    if (DR->isImmediateEscalating())18165      continue;18166    auto *FD = cast<FunctionDecl>(DR->getDecl());18167    const NamedDecl *ND = FD;18168    if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);18169        MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))18170      ND = MD->getParent();18171 18172    // C++23 [expr.const]/p1618173    // An expression or conversion is immediate-escalating if it is not18174    // initially in an immediate function context and it is [...] a18175    // potentially-evaluated id-expression that denotes an immediate function18176    // that is not a subexpression of an immediate invocation.18177    bool ImmediateEscalating = false;18178    bool IsPotentiallyEvaluated =18179        Rec.Context ==18180            Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||18181        Rec.Context ==18182            Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;18183    if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)18184      ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;18185 18186    if (!Rec.InImmediateEscalatingFunctionContext ||18187        (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {18188      SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)18189          << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();18190      if (!FD->getBuiltinID())18191        SemaRef.Diag(ND->getLocation(), diag::note_declared_at);18192      if (auto Context =18193              SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {18194        SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)18195            << Context->Decl;18196        SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);18197      }18198      if (FD->isImmediateEscalating() && !FD->isConsteval())18199        SemaRef.DiagnoseImmediateEscalatingReason(FD);18200 18201    } else {18202      SemaRef.MarkExpressionAsImmediateEscalating(DR);18203    }18204  }18205}18206 18207void Sema::PopExpressionEvaluationContext() {18208  ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();18209  if (!Rec.Lambdas.empty()) {18210    using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;18211    if (!getLangOpts().CPlusPlus20 &&18212        (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||18213         Rec.isUnevaluated() ||18214         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {18215      unsigned D;18216      if (Rec.isUnevaluated()) {18217        // C++11 [expr.prim.lambda]p2:18218        //   A lambda-expression shall not appear in an unevaluated operand18219        //   (Clause 5).18220        D = diag::err_lambda_unevaluated_operand;18221      } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {18222        // C++1y [expr.const]p2:18223        //   A conditional-expression e is a core constant expression unless the18224        //   evaluation of e, following the rules of the abstract machine, would18225        //   evaluate [...] a lambda-expression.18226        D = diag::err_lambda_in_constant_expression;18227      } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {18228        // C++17 [expr.prim.lamda]p2:18229        // A lambda-expression shall not appear [...] in a template-argument.18230        D = diag::err_lambda_in_invalid_context;18231      } else18232        llvm_unreachable("Couldn't infer lambda error message.");18233 18234      for (const auto *L : Rec.Lambdas)18235        Diag(L->getBeginLoc(), D);18236    }18237  }18238 18239  // Append the collected materialized temporaries into previous context before18240  // exit if the previous also is a lifetime extending context.18241  if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&18242      parentEvaluationContext().InLifetimeExtendingContext &&18243      !Rec.ForRangeLifetimeExtendTemps.empty()) {18244    parentEvaluationContext().ForRangeLifetimeExtendTemps.append(18245        Rec.ForRangeLifetimeExtendTemps);18246  }18247 18248  WarnOnPendingNoDerefs(Rec);18249  HandleImmediateInvocations(*this, Rec);18250 18251  // Warn on any volatile-qualified simple-assignments that are not discarded-18252  // value expressions nor unevaluated operands (those cases get removed from18253  // this list by CheckUnusedVolatileAssignment).18254  for (auto *BO : Rec.VolatileAssignmentLHSs)18255    Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)18256        << BO->getType();18257 18258  // When are coming out of an unevaluated context, clear out any18259  // temporaries that we may have created as part of the evaluation of18260  // the expression in that context: they aren't relevant because they18261  // will never be constructed.18262  if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {18263    ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,18264                             ExprCleanupObjects.end());18265    Cleanup = Rec.ParentCleanup;18266    CleanupVarDeclMarking();18267    std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);18268  // Otherwise, merge the contexts together.18269  } else {18270    Cleanup.mergeFrom(Rec.ParentCleanup);18271    MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);18272  }18273 18274  DiagnoseMisalignedMembers();18275 18276  // Pop the current expression evaluation context off the stack.18277  ExprEvalContexts.pop_back();18278}18279 18280void Sema::DiscardCleanupsInEvaluationContext() {18281  ExprCleanupObjects.erase(18282         ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,18283         ExprCleanupObjects.end());18284  Cleanup.reset();18285  MaybeODRUseExprs.clear();18286}18287 18288ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {18289  ExprResult Result = CheckPlaceholderExpr(E);18290  if (Result.isInvalid())18291    return ExprError();18292  E = Result.get();18293  if (!E->getType()->isVariablyModifiedType())18294    return E;18295  return TransformToPotentiallyEvaluated(E);18296}18297 18298/// Are we in a context that is potentially constant evaluated per C++2018299/// [expr.const]p12?18300static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {18301  /// C++2a [expr.const]p12:18302  //   An expression or conversion is potentially constant evaluated if it is18303  switch (SemaRef.ExprEvalContexts.back().Context) {18304    case Sema::ExpressionEvaluationContext::ConstantEvaluated:18305    case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:18306 18307      // -- a manifestly constant-evaluated expression,18308    case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:18309    case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:18310    case Sema::ExpressionEvaluationContext::DiscardedStatement:18311      // -- a potentially-evaluated expression,18312    case Sema::ExpressionEvaluationContext::UnevaluatedList:18313      // -- an immediate subexpression of a braced-init-list,18314 18315      // -- [FIXME] an expression of the form & cast-expression that occurs18316      //    within a templated entity18317      // -- a subexpression of one of the above that is not a subexpression of18318      // a nested unevaluated operand.18319      return true;18320 18321    case Sema::ExpressionEvaluationContext::Unevaluated:18322    case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:18323      // Expressions in this context are never evaluated.18324      return false;18325  }18326  llvm_unreachable("Invalid context");18327}18328 18329/// Return true if this function has a calling convention that requires mangling18330/// in the size of the parameter pack.18331static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {18332  // These manglings are only applicable for targets whcih use Microsoft18333  // mangling scheme for C.18334  if (!S.Context.getTargetInfo().shouldUseMicrosoftCCforMangling())18335    return false;18336 18337  // If this is C++ and this isn't an extern "C" function, parameters do not18338  // need to be complete. In this case, C++ mangling will apply, which doesn't18339  // use the size of the parameters.18340  if (S.getLangOpts().CPlusPlus && !FD->isExternC())18341    return false;18342 18343  // Stdcall, fastcall, and vectorcall need this special treatment.18344  CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();18345  switch (CC) {18346  case CC_X86StdCall:18347  case CC_X86FastCall:18348  case CC_X86VectorCall:18349    return true;18350  default:18351    break;18352  }18353  return false;18354}18355 18356/// Require that all of the parameter types of function be complete. Normally,18357/// parameter types are only required to be complete when a function is called18358/// or defined, but to mangle functions with certain calling conventions, the18359/// mangler needs to know the size of the parameter list. In this situation,18360/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles18361/// the function as _foo@0, i.e. zero bytes of parameters, which will usually18362/// result in a linker error. Clang doesn't implement this behavior, and instead18363/// attempts to error at compile time.18364static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,18365                                                  SourceLocation Loc) {18366  class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {18367    FunctionDecl *FD;18368    ParmVarDecl *Param;18369 18370  public:18371    ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)18372        : FD(FD), Param(Param) {}18373 18374    void diagnose(Sema &S, SourceLocation Loc, QualType T) override {18375      CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();18376      StringRef CCName;18377      switch (CC) {18378      case CC_X86StdCall:18379        CCName = "stdcall";18380        break;18381      case CC_X86FastCall:18382        CCName = "fastcall";18383        break;18384      case CC_X86VectorCall:18385        CCName = "vectorcall";18386        break;18387      default:18388        llvm_unreachable("CC does not need mangling");18389      }18390 18391      S.Diag(Loc, diag::err_cconv_incomplete_param_type)18392          << Param->getDeclName() << FD->getDeclName() << CCName;18393    }18394  };18395 18396  for (ParmVarDecl *Param : FD->parameters()) {18397    ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);18398    S.RequireCompleteType(Loc, Param->getType(), Diagnoser);18399  }18400}18401 18402namespace {18403enum class OdrUseContext {18404  /// Declarations in this context are not odr-used.18405  None,18406  /// Declarations in this context are formally odr-used, but this is a18407  /// dependent context.18408  Dependent,18409  /// Declarations in this context are odr-used but not actually used (yet).18410  FormallyOdrUsed,18411  /// Declarations in this context are used.18412  Used18413};18414}18415 18416/// Are we within a context in which references to resolved functions or to18417/// variables result in odr-use?18418static OdrUseContext isOdrUseContext(Sema &SemaRef) {18419  const Sema::ExpressionEvaluationContextRecord &Context =18420      SemaRef.currentEvaluationContext();18421 18422  if (Context.isUnevaluated())18423    return OdrUseContext::None;18424 18425  if (SemaRef.CurContext->isDependentContext())18426    return OdrUseContext::Dependent;18427 18428  if (Context.isDiscardedStatementContext())18429    return OdrUseContext::FormallyOdrUsed;18430 18431  else if (Context.Context ==18432           Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed)18433    return OdrUseContext::FormallyOdrUsed;18434 18435  return OdrUseContext::Used;18436}18437 18438static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {18439  if (!Func->isConstexpr())18440    return false;18441 18442  if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())18443    return true;18444 18445  // Lambda conversion operators are never user provided.18446  if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))18447    return isLambdaConversionOperator(Conv);18448 18449  auto *CCD = dyn_cast<CXXConstructorDecl>(Func);18450  return CCD && CCD->getInheritedConstructor();18451}18452 18453void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,18454                                  bool MightBeOdrUse) {18455  assert(Func && "No function?");18456 18457  Func->setReferenced();18458 18459  // Recursive functions aren't really used until they're used from some other18460  // context.18461  bool IsRecursiveCall = CurContext == Func;18462 18463  // C++11 [basic.def.odr]p3:18464  //   A function whose name appears as a potentially-evaluated expression is18465  //   odr-used if it is the unique lookup result or the selected member of a18466  //   set of overloaded functions [...].18467  //18468  // We (incorrectly) mark overload resolution as an unevaluated context, so we18469  // can just check that here.18470  OdrUseContext OdrUse =18471      MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;18472  if (IsRecursiveCall && OdrUse == OdrUseContext::Used)18473    OdrUse = OdrUseContext::FormallyOdrUsed;18474 18475  // Trivial default constructors and destructors are never actually used.18476  // FIXME: What about other special members?18477  if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&18478      OdrUse == OdrUseContext::Used) {18479    if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))18480      if (Constructor->isDefaultConstructor())18481        OdrUse = OdrUseContext::FormallyOdrUsed;18482    if (isa<CXXDestructorDecl>(Func))18483      OdrUse = OdrUseContext::FormallyOdrUsed;18484  }18485 18486  // C++20 [expr.const]p12:18487  //   A function [...] is needed for constant evaluation if it is [...] a18488  //   constexpr function that is named by an expression that is potentially18489  //   constant evaluated18490  bool NeededForConstantEvaluation =18491      isPotentiallyConstantEvaluatedContext(*this) &&18492      isImplicitlyDefinableConstexprFunction(Func);18493 18494  // Determine whether we require a function definition to exist, per18495  // C++11 [temp.inst]p3:18496  //   Unless a function template specialization has been explicitly18497  //   instantiated or explicitly specialized, the function template18498  //   specialization is implicitly instantiated when the specialization is18499  //   referenced in a context that requires a function definition to exist.18500  // C++20 [temp.inst]p7:18501  //   The existence of a definition of a [...] function is considered to18502  //   affect the semantics of the program if the [...] function is needed for18503  //   constant evaluation by an expression18504  // C++20 [basic.def.odr]p10:18505  //   Every program shall contain exactly one definition of every non-inline18506  //   function or variable that is odr-used in that program outside of a18507  //   discarded statement18508  // C++20 [special]p1:18509  //   The implementation will implicitly define [defaulted special members]18510  //   if they are odr-used or needed for constant evaluation.18511  //18512  // Note that we skip the implicit instantiation of templates that are only18513  // used in unused default arguments or by recursive calls to themselves.18514  // This is formally non-conforming, but seems reasonable in practice.18515  bool NeedDefinition =18516      !IsRecursiveCall &&18517      (OdrUse == OdrUseContext::Used ||18518       (NeededForConstantEvaluation && !Func->isPureVirtual()));18519 18520  // C++14 [temp.expl.spec]p6:18521  //   If a template [...] is explicitly specialized then that specialization18522  //   shall be declared before the first use of that specialization that would18523  //   cause an implicit instantiation to take place, in every translation unit18524  //   in which such a use occurs18525  if (NeedDefinition &&18526      (Func->getTemplateSpecializationKind() != TSK_Undeclared ||18527       Func->getMemberSpecializationInfo()))18528    checkSpecializationReachability(Loc, Func);18529 18530  if (getLangOpts().CUDA)18531    CUDA().CheckCall(Loc, Func);18532 18533  // If we need a definition, try to create one.18534  if (NeedDefinition && !Func->getBody()) {18535    runWithSufficientStackSpace(Loc, [&] {18536      if (CXXConstructorDecl *Constructor =18537              dyn_cast<CXXConstructorDecl>(Func)) {18538        Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());18539        if (Constructor->isDefaulted() && !Constructor->isDeleted()) {18540          if (Constructor->isDefaultConstructor()) {18541            if (Constructor->isTrivial() &&18542                !Constructor->hasAttr<DLLExportAttr>())18543              return;18544            DefineImplicitDefaultConstructor(Loc, Constructor);18545          } else if (Constructor->isCopyConstructor()) {18546            DefineImplicitCopyConstructor(Loc, Constructor);18547          } else if (Constructor->isMoveConstructor()) {18548            DefineImplicitMoveConstructor(Loc, Constructor);18549          }18550        } else if (Constructor->getInheritedConstructor()) {18551          DefineInheritingConstructor(Loc, Constructor);18552        }18553      } else if (CXXDestructorDecl *Destructor =18554                     dyn_cast<CXXDestructorDecl>(Func)) {18555        Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());18556        if (Destructor->isDefaulted() && !Destructor->isDeleted()) {18557          if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())18558            return;18559          DefineImplicitDestructor(Loc, Destructor);18560        }18561        if (Destructor->isVirtual() && getLangOpts().AppleKext)18562          MarkVTableUsed(Loc, Destructor->getParent());18563      } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {18564        if (MethodDecl->isOverloadedOperator() &&18565            MethodDecl->getOverloadedOperator() == OO_Equal) {18566          MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());18567          if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {18568            if (MethodDecl->isCopyAssignmentOperator())18569              DefineImplicitCopyAssignment(Loc, MethodDecl);18570            else if (MethodDecl->isMoveAssignmentOperator())18571              DefineImplicitMoveAssignment(Loc, MethodDecl);18572          }18573        } else if (isa<CXXConversionDecl>(MethodDecl) &&18574                   MethodDecl->getParent()->isLambda()) {18575          CXXConversionDecl *Conversion =18576              cast<CXXConversionDecl>(MethodDecl->getFirstDecl());18577          if (Conversion->isLambdaToBlockPointerConversion())18578            DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);18579          else18580            DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);18581        } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)18582          MarkVTableUsed(Loc, MethodDecl->getParent());18583      }18584 18585      if (Func->isDefaulted() && !Func->isDeleted()) {18586        DefaultedComparisonKind DCK = getDefaultedComparisonKind(Func);18587        if (DCK != DefaultedComparisonKind::None)18588          DefineDefaultedComparison(Loc, Func, DCK);18589      }18590 18591      // Implicit instantiation of function templates and member functions of18592      // class templates.18593      if (Func->isImplicitlyInstantiable()) {18594        TemplateSpecializationKind TSK =18595            Func->getTemplateSpecializationKindForInstantiation();18596        SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();18597        bool FirstInstantiation = PointOfInstantiation.isInvalid();18598        if (FirstInstantiation) {18599          PointOfInstantiation = Loc;18600          if (auto *MSI = Func->getMemberSpecializationInfo())18601            MSI->setPointOfInstantiation(Loc);18602            // FIXME: Notify listener.18603          else18604            Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);18605        } else if (TSK != TSK_ImplicitInstantiation) {18606          // Use the point of use as the point of instantiation, instead of the18607          // point of explicit instantiation (which we track as the actual point18608          // of instantiation). This gives better backtraces in diagnostics.18609          PointOfInstantiation = Loc;18610        }18611 18612        if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||18613            Func->isConstexpr()) {18614          if (isa<CXXRecordDecl>(Func->getDeclContext()) &&18615              cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&18616              CodeSynthesisContexts.size())18617            PendingLocalImplicitInstantiations.push_back(18618                std::make_pair(Func, PointOfInstantiation));18619          else if (Func->isConstexpr())18620            // Do not defer instantiations of constexpr functions, to avoid the18621            // expression evaluator needing to call back into Sema if it sees a18622            // call to such a function.18623            InstantiateFunctionDefinition(PointOfInstantiation, Func);18624          else {18625            Func->setInstantiationIsPending(true);18626            PendingInstantiations.push_back(18627                std::make_pair(Func, PointOfInstantiation));18628            if (llvm::isTimeTraceVerbose()) {18629              llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {18630                std::string Name;18631                llvm::raw_string_ostream OS(Name);18632                Func->getNameForDiagnostic(OS, getPrintingPolicy(),18633                                           /*Qualified=*/true);18634                return Name;18635              });18636            }18637            // Notify the consumer that a function was implicitly instantiated.18638            Consumer.HandleCXXImplicitFunctionInstantiation(Func);18639          }18640        }18641      } else {18642        // Walk redefinitions, as some of them may be instantiable.18643        for (auto *i : Func->redecls()) {18644          if (!i->isUsed(false) && i->isImplicitlyInstantiable())18645            MarkFunctionReferenced(Loc, i, MightBeOdrUse);18646        }18647      }18648    });18649  }18650 18651  // If a constructor was defined in the context of a default parameter18652  // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed18653  // context), its initializers may not be referenced yet.18654  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {18655    EnterExpressionEvaluationContext EvalContext(18656        *this,18657        Constructor->isImmediateFunction()18658            ? ExpressionEvaluationContext::ImmediateFunctionContext18659            : ExpressionEvaluationContext::PotentiallyEvaluated,18660        Constructor);18661    for (CXXCtorInitializer *Init : Constructor->inits()) {18662      if (Init->isInClassMemberInitializer())18663        runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {18664          MarkDeclarationsReferencedInExpr(Init->getInit());18665        });18666    }18667  }18668 18669  // C++14 [except.spec]p17:18670  //   An exception-specification is considered to be needed when:18671  //   - the function is odr-used or, if it appears in an unevaluated operand,18672  //     would be odr-used if the expression were potentially-evaluated;18673  //18674  // Note, we do this even if MightBeOdrUse is false. That indicates that the18675  // function is a pure virtual function we're calling, and in that case the18676  // function was selected by overload resolution and we need to resolve its18677  // exception specification for a different reason.18678  const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();18679  if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))18680    ResolveExceptionSpec(Loc, FPT);18681 18682  // A callee could be called by a host function then by a device function.18683  // If we only try recording once, we will miss recording the use on device18684  // side. Therefore keep trying until it is recorded.18685  if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&18686      !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))18687    CUDA().RecordImplicitHostDeviceFuncUsedByDevice(Func);18688 18689  // If this is the first "real" use, act on that.18690  if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {18691    // Keep track of used but undefined functions.18692    if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {18693      if (mightHaveNonExternalLinkage(Func))18694        UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));18695      else if (Func->getMostRecentDecl()->isInlined() &&18696               !LangOpts.GNUInline &&18697               !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())18698        UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));18699      else if (isExternalWithNoLinkageType(Func))18700        UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));18701    }18702 18703    // Some x86 Windows calling conventions mangle the size of the parameter18704    // pack into the name. Computing the size of the parameters requires the18705    // parameter types to be complete. Check that now.18706    if (funcHasParameterSizeMangling(*this, Func))18707      CheckCompleteParameterTypesForMangler(*this, Func, Loc);18708 18709    // In the MS C++ ABI, the compiler emits destructor variants where they are18710    // used. If the destructor is used here but defined elsewhere, mark the18711    // virtual base destructors referenced. If those virtual base destructors18712    // are inline, this will ensure they are defined when emitting the complete18713    // destructor variant. This checking may be redundant if the destructor is18714    // provided later in this TU.18715    if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {18716      if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {18717        CXXRecordDecl *Parent = Dtor->getParent();18718        if (Parent->getNumVBases() > 0 && !Dtor->getBody())18719          CheckCompleteDestructorVariant(Loc, Dtor);18720      }18721    }18722 18723    Func->markUsed(Context);18724  }18725}18726 18727/// Directly mark a variable odr-used. Given a choice, prefer to use18728/// MarkVariableReferenced since it does additional checks and then18729/// calls MarkVarDeclODRUsed.18730/// If the variable must be captured:18731///  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext18732///  - else capture it in the DeclContext that maps to the18733///    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.18734static void18735MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,18736                   const unsigned *const FunctionScopeIndexToStopAt = nullptr) {18737  // Keep track of used but undefined variables.18738  // FIXME: We shouldn't suppress this warning for static data members.18739  VarDecl *Var = V->getPotentiallyDecomposedVarDecl();18740  assert(Var && "expected a capturable variable");18741 18742  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&18743      (!Var->isExternallyVisible() || Var->isInline() ||18744       SemaRef.isExternalWithNoLinkageType(Var)) &&18745      !(Var->isStaticDataMember() && Var->hasInit())) {18746    SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];18747    if (old.isInvalid())18748      old = Loc;18749  }18750  QualType CaptureType, DeclRefType;18751  if (SemaRef.LangOpts.OpenMP)18752    SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);18753  SemaRef.tryCaptureVariable(V, Loc, TryCaptureKind::Implicit,18754                             /*EllipsisLoc*/ SourceLocation(),18755                             /*BuildAndDiagnose*/ true, CaptureType,18756                             DeclRefType, FunctionScopeIndexToStopAt);18757 18758  if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {18759    auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);18760    auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);18761    auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);18762    if (VarTarget == SemaCUDA::CVT_Host &&18763        (UserTarget == CUDAFunctionTarget::Device ||18764         UserTarget == CUDAFunctionTarget::HostDevice ||18765         UserTarget == CUDAFunctionTarget::Global)) {18766      // Diagnose ODR-use of host global variables in device functions.18767      // Reference of device global variables in host functions is allowed18768      // through shadow variables therefore it is not diagnosed.18769      if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {18770        SemaRef.targetDiag(Loc, diag::err_ref_bad_target)18771            << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;18772        SemaRef.targetDiag(Var->getLocation(),18773                           Var->getType().isConstQualified()18774                               ? diag::note_cuda_const_var_unpromoted18775                               : diag::note_cuda_host_var);18776      }18777    } else if (VarTarget == SemaCUDA::CVT_Device &&18778               !Var->hasAttr<CUDASharedAttr>() &&18779               (UserTarget == CUDAFunctionTarget::Host ||18780                UserTarget == CUDAFunctionTarget::HostDevice)) {18781      // Record a CUDA/HIP device side variable if it is ODR-used18782      // by host code. This is done conservatively, when the variable is18783      // referenced in any of the following contexts:18784      //   - a non-function context18785      //   - a host function18786      //   - a host device function18787      // This makes the ODR-use of the device side variable by host code to18788      // be visible in the device compilation for the compiler to be able to18789      // emit template variables instantiated by host code only and to18790      // externalize the static device side variable ODR-used by host code.18791      if (!Var->hasExternalStorage())18792        SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(Var);18793      else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&18794               (!FD || (!FD->getDescribedFunctionTemplate() &&18795                        SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==18796                            GVA_StrongExternal)))18797        SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);18798    }18799  }18800 18801  V->markUsed(SemaRef.Context);18802}18803 18804void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,18805                                             SourceLocation Loc,18806                                             unsigned CapturingScopeIndex) {18807  MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);18808}18809 18810static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,18811                                                        SourceLocation loc,18812                                                        ValueDecl *var) {18813  DeclContext *VarDC = var->getDeclContext();18814 18815  //  If the parameter still belongs to the translation unit, then18816  //  we're actually just using one parameter in the declaration of18817  //  the next.18818  if (isa<ParmVarDecl>(var) &&18819      isa<TranslationUnitDecl>(VarDC))18820    return;18821 18822  // For C code, don't diagnose about capture if we're not actually in code18823  // right now; it's impossible to write a non-constant expression outside of18824  // function context, so we'll get other (more useful) diagnostics later.18825  //18826  // For C++, things get a bit more nasty... it would be nice to suppress this18827  // diagnostic for certain cases like using a local variable in an array bound18828  // for a member of a local class, but the correct predicate is not obvious.18829  if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())18830    return;18831 18832  unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;18833  unsigned ContextKind = 3; // unknown18834  if (isa<CXXMethodDecl>(VarDC) &&18835      cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {18836    ContextKind = 2;18837  } else if (isa<FunctionDecl>(VarDC)) {18838    ContextKind = 0;18839  } else if (isa<BlockDecl>(VarDC)) {18840    ContextKind = 1;18841  }18842 18843  S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)18844    << var << ValueKind << ContextKind << VarDC;18845  S.Diag(var->getLocation(), diag::note_entity_declared_at)18846      << var;18847 18848  // FIXME: Add additional diagnostic info about class etc. which prevents18849  // capture.18850}18851 18852static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,18853                                                 ValueDecl *Var,18854                                                 bool &SubCapturesAreNested,18855                                                 QualType &CaptureType,18856                                                 QualType &DeclRefType) {18857  // Check whether we've already captured it.18858  if (CSI->CaptureMap.count(Var)) {18859    // If we found a capture, any subcaptures are nested.18860    SubCapturesAreNested = true;18861 18862    // Retrieve the capture type for this variable.18863    CaptureType = CSI->getCapture(Var).getCaptureType();18864 18865    // Compute the type of an expression that refers to this variable.18866    DeclRefType = CaptureType.getNonReferenceType();18867 18868    // Similarly to mutable captures in lambda, all the OpenMP captures by copy18869    // are mutable in the sense that user can change their value - they are18870    // private instances of the captured declarations.18871    const Capture &Cap = CSI->getCapture(Var);18872    // C++ [expr.prim.lambda]p10:18873    //   The type of such a data member is [...] an lvalue reference to the18874    //   referenced function type if the entity is a reference to a function.18875    //   [...]18876    if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&18877        !(isa<LambdaScopeInfo>(CSI) &&18878          !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&18879        !(isa<CapturedRegionScopeInfo>(CSI) &&18880          cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))18881      DeclRefType.addConst();18882    return true;18883  }18884  return false;18885}18886 18887// Only block literals, captured statements, and lambda expressions can18888// capture; other scopes don't work.18889static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,18890                                                      ValueDecl *Var,18891                                                      SourceLocation Loc,18892                                                      const bool Diagnose,18893                                                      Sema &S) {18894  if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))18895    return getLambdaAwareParentOfDeclContext(DC);18896 18897  VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();18898  if (Underlying) {18899    if (Underlying->hasLocalStorage() && Diagnose)18900      diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);18901  }18902  return nullptr;18903}18904 18905// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture18906// certain types of variables (unnamed, variably modified types etc.)18907// so check for eligibility.18908static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,18909                                 SourceLocation Loc, const bool Diagnose,18910                                 Sema &S) {18911 18912  assert((isa<VarDecl, BindingDecl>(Var)) &&18913         "Only variables and structured bindings can be captured");18914 18915  bool IsBlock = isa<BlockScopeInfo>(CSI);18916  bool IsLambda = isa<LambdaScopeInfo>(CSI);18917 18918  // Lambdas are not allowed to capture unnamed variables18919  // (e.g. anonymous unions).18920  // FIXME: The C++11 rule don't actually state this explicitly, but I'm18921  // assuming that's the intent.18922  if (IsLambda && !Var->getDeclName()) {18923    if (Diagnose) {18924      S.Diag(Loc, diag::err_lambda_capture_anonymous_var);18925      S.Diag(Var->getLocation(), diag::note_declared_at);18926    }18927    return false;18928  }18929 18930  // Prohibit variably-modified types in blocks; they're difficult to deal with.18931  if (Var->getType()->isVariablyModifiedType() && IsBlock) {18932    if (Diagnose) {18933      S.Diag(Loc, diag::err_ref_vm_type);18934      S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;18935    }18936    return false;18937  }18938  // Prohibit structs with flexible array members too.18939  // We cannot capture what is in the tail end of the struct.18940  if (const auto *VTD = Var->getType()->getAsRecordDecl();18941      VTD && VTD->hasFlexibleArrayMember()) {18942    if (Diagnose) {18943      if (IsBlock)18944        S.Diag(Loc, diag::err_ref_flexarray_type);18945      else18946        S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;18947      S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;18948    }18949    return false;18950  }18951  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();18952  // Lambdas and captured statements are not allowed to capture __block18953  // variables; they don't support the expected semantics.18954  if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {18955    if (Diagnose) {18956      S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;18957      S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;18958    }18959    return false;18960  }18961  // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks18962  if (S.getLangOpts().OpenCL && IsBlock &&18963      Var->getType()->isBlockPointerType()) {18964    if (Diagnose)18965      S.Diag(Loc, diag::err_opencl_block_ref_block);18966    return false;18967  }18968 18969  if (isa<BindingDecl>(Var)) {18970    if (!IsLambda || !S.getLangOpts().CPlusPlus) {18971      if (Diagnose)18972        diagnoseUncapturableValueReferenceOrBinding(S, Loc, Var);18973      return false;18974    } else if (Diagnose && S.getLangOpts().CPlusPlus) {18975      S.Diag(Loc, S.LangOpts.CPlusPlus2018976                      ? diag::warn_cxx17_compat_capture_binding18977                      : diag::ext_capture_binding)18978          << Var;18979      S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;18980    }18981  }18982 18983  return true;18984}18985 18986// Returns true if the capture by block was successful.18987static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,18988                           SourceLocation Loc, const bool BuildAndDiagnose,18989                           QualType &CaptureType, QualType &DeclRefType,18990                           const bool Nested, Sema &S, bool Invalid) {18991  bool ByRef = false;18992 18993  // Blocks are not allowed to capture arrays, excepting OpenCL.18994  // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference18995  // (decayed to pointers).18996  if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {18997    if (BuildAndDiagnose) {18998      S.Diag(Loc, diag::err_ref_array_type);18999      S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;19000      Invalid = true;19001    } else {19002      return false;19003    }19004  }19005 19006  // Forbid the block-capture of autoreleasing variables.19007  if (!Invalid &&19008      CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {19009    if (BuildAndDiagnose) {19010      S.Diag(Loc, diag::err_arc_autoreleasing_capture)19011        << /*block*/ 0;19012      S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;19013      Invalid = true;19014    } else {19015      return false;19016    }19017  }19018 19019  // Warn about implicitly autoreleasing indirect parameters captured by blocks.19020  if (const auto *PT = CaptureType->getAs<PointerType>()) {19021    QualType PointeeTy = PT->getPointeeType();19022 19023    if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&19024        PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&19025        !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {19026      if (BuildAndDiagnose) {19027        SourceLocation VarLoc = Var->getLocation();19028        S.Diag(Loc, diag::warn_block_capture_autoreleasing);19029        S.Diag(VarLoc, diag::note_declare_parameter_strong);19030      }19031    }19032  }19033 19034  const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();19035  if (HasBlocksAttr || CaptureType->isReferenceType() ||19036      (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {19037    // Block capture by reference does not change the capture or19038    // declaration reference types.19039    ByRef = true;19040  } else {19041    // Block capture by copy introduces 'const'.19042    CaptureType = CaptureType.getNonReferenceType().withConst();19043    DeclRefType = CaptureType;19044  }19045 19046  // Actually capture the variable.19047  if (BuildAndDiagnose)19048    BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),19049                    CaptureType, Invalid);19050 19051  return !Invalid;19052}19053 19054/// Capture the given variable in the captured region.19055static bool captureInCapturedRegion(19056    CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,19057    const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,19058    const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,19059    Sema &S, bool Invalid) {19060  // By default, capture variables by reference.19061  bool ByRef = true;19062  if (IsTopScope && Kind != TryCaptureKind::Implicit) {19063    ByRef = (Kind == TryCaptureKind::ExplicitByRef);19064  } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {19065    // Using an LValue reference type is consistent with Lambdas (see below).19066    if (S.OpenMP().isOpenMPCapturedDecl(Var)) {19067      bool HasConst = DeclRefType.isConstQualified();19068      DeclRefType = DeclRefType.getUnqualifiedType();19069      // Don't lose diagnostics about assignments to const.19070      if (HasConst)19071        DeclRefType.addConst();19072    }19073    // Do not capture firstprivates in tasks.19074    if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,19075                                       RSI->OpenMPCaptureLevel) != OMPC_unknown)19076      return true;19077    ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,19078                                             RSI->OpenMPCaptureLevel);19079  }19080 19081  if (ByRef)19082    CaptureType = S.Context.getLValueReferenceType(DeclRefType);19083  else19084    CaptureType = DeclRefType;19085 19086  // Actually capture the variable.19087  if (BuildAndDiagnose)19088    RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,19089                    Loc, SourceLocation(), CaptureType, Invalid);19090 19091  return !Invalid;19092}19093 19094/// Capture the given variable in the lambda.19095static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,19096                            SourceLocation Loc, const bool BuildAndDiagnose,19097                            QualType &CaptureType, QualType &DeclRefType,19098                            const bool RefersToCapturedVariable,19099                            const TryCaptureKind Kind,19100                            SourceLocation EllipsisLoc, const bool IsTopScope,19101                            Sema &S, bool Invalid) {19102  // Determine whether we are capturing by reference or by value.19103  bool ByRef = false;19104  if (IsTopScope && Kind != TryCaptureKind::Implicit) {19105    ByRef = (Kind == TryCaptureKind::ExplicitByRef);19106  } else {19107    ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);19108  }19109 19110  if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&19111      CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {19112    S.Diag(Loc, diag::err_wasm_ca_reference) << 0;19113    Invalid = true;19114  }19115 19116  // Compute the type of the field that will capture this variable.19117  if (ByRef) {19118    // C++11 [expr.prim.lambda]p15:19119    //   An entity is captured by reference if it is implicitly or19120    //   explicitly captured but not captured by copy. It is19121    //   unspecified whether additional unnamed non-static data19122    //   members are declared in the closure type for entities19123    //   captured by reference.19124    //19125    // FIXME: It is not clear whether we want to build an lvalue reference19126    // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears19127    // to do the former, while EDG does the latter. Core issue 1249 will19128    // clarify, but for now we follow GCC because it's a more permissive and19129    // easily defensible position.19130    CaptureType = S.Context.getLValueReferenceType(DeclRefType);19131  } else {19132    // C++11 [expr.prim.lambda]p14:19133    //   For each entity captured by copy, an unnamed non-static19134    //   data member is declared in the closure type. The19135    //   declaration order of these members is unspecified. The type19136    //   of such a data member is the type of the corresponding19137    //   captured entity if the entity is not a reference to an19138    //   object, or the referenced type otherwise. [Note: If the19139    //   captured entity is a reference to a function, the19140    //   corresponding data member is also a reference to a19141    //   function. - end note ]19142    if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){19143      if (!RefType->getPointeeType()->isFunctionType())19144        CaptureType = RefType->getPointeeType();19145    }19146 19147    // Forbid the lambda copy-capture of autoreleasing variables.19148    if (!Invalid &&19149        CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {19150      if (BuildAndDiagnose) {19151        S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;19152        S.Diag(Var->getLocation(), diag::note_previous_decl)19153          << Var->getDeclName();19154        Invalid = true;19155      } else {19156        return false;19157      }19158    }19159 19160    // Make sure that by-copy captures are of a complete and non-abstract type.19161    if (!Invalid && BuildAndDiagnose) {19162      if (!CaptureType->isDependentType() &&19163          S.RequireCompleteSizedType(19164              Loc, CaptureType,19165              diag::err_capture_of_incomplete_or_sizeless_type,19166              Var->getDeclName()))19167        Invalid = true;19168      else if (S.RequireNonAbstractType(Loc, CaptureType,19169                                        diag::err_capture_of_abstract_type))19170        Invalid = true;19171    }19172  }19173 19174  // Compute the type of a reference to this captured variable.19175  if (ByRef)19176    DeclRefType = CaptureType.getNonReferenceType();19177  else {19178    // C++ [expr.prim.lambda]p5:19179    //   The closure type for a lambda-expression has a public inline19180    //   function call operator [...]. This function call operator is19181    //   declared const (9.3.1) if and only if the lambda-expression's19182    //   parameter-declaration-clause is not followed by mutable.19183    DeclRefType = CaptureType.getNonReferenceType();19184    bool Const = LSI->lambdaCaptureShouldBeConst();19185    // C++ [expr.prim.lambda]p10:19186    //   The type of such a data member is [...] an lvalue reference to the19187    //   referenced function type if the entity is a reference to a function.19188    //   [...]19189    if (Const && !CaptureType->isReferenceType() &&19190        !DeclRefType->isFunctionType())19191      DeclRefType.addConst();19192  }19193 19194  // Add the capture.19195  if (BuildAndDiagnose)19196    LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,19197                    Loc, EllipsisLoc, CaptureType, Invalid);19198 19199  return !Invalid;19200}19201 19202static bool canCaptureVariableByCopy(ValueDecl *Var,19203                                     const ASTContext &Context) {19204  // Offer a Copy fix even if the type is dependent.19205  if (Var->getType()->isDependentType())19206    return true;19207  QualType T = Var->getType().getNonReferenceType();19208  if (T.isTriviallyCopyableType(Context))19209    return true;19210  if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {19211 19212    if (!(RD = RD->getDefinition()))19213      return false;19214    if (RD->hasSimpleCopyConstructor())19215      return true;19216    if (RD->hasUserDeclaredCopyConstructor())19217      for (CXXConstructorDecl *Ctor : RD->ctors())19218        if (Ctor->isCopyConstructor())19219          return !Ctor->isDeleted();19220  }19221  return false;19222}19223 19224/// Create up to 4 fix-its for explicit reference and value capture of \p Var or19225/// default capture. Fixes may be omitted if they aren't allowed by the19226/// standard, for example we can't emit a default copy capture fix-it if we19227/// already explicitly copy capture capture another variable.19228static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,19229                                    ValueDecl *Var) {19230  assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);19231  // Don't offer Capture by copy of default capture by copy fixes if Var is19232  // known not to be copy constructible.19233  bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());19234 19235  SmallString<32> FixBuffer;19236  StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";19237  if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {19238    SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();19239    if (ShouldOfferCopyFix) {19240      // Offer fixes to insert an explicit capture for the variable.19241      // [] -> [VarName]19242      // [OtherCapture] -> [OtherCapture, VarName]19243      FixBuffer.assign({Separator, Var->getName()});19244      Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)19245          << Var << /*value*/ 019246          << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);19247    }19248    // As above but capture by reference.19249    FixBuffer.assign({Separator, "&", Var->getName()});19250    Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)19251        << Var << /*reference*/ 119252        << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);19253  }19254 19255  // Only try to offer default capture if there are no captures excluding this19256  // and init captures.19257  // [this]: OK.19258  // [X = Y]: OK.19259  // [&A, &B]: Don't offer.19260  // [A, B]: Don't offer.19261  if (llvm::any_of(LSI->Captures, [](Capture &C) {19262        return !C.isThisCapture() && !C.isInitCapture();19263      }))19264    return;19265 19266  // The default capture specifiers, '=' or '&', must appear first in the19267  // capture body.19268  SourceLocation DefaultInsertLoc =19269      LSI->IntroducerRange.getBegin().getLocWithOffset(1);19270 19271  if (ShouldOfferCopyFix) {19272    bool CanDefaultCopyCapture = true;19273    // [=, *this] OK since c++1719274    // [=, this] OK since c++2019275    if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)19276      CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus1719277                                  ? LSI->getCXXThisCapture().isCopyCapture()19278                                  : false;19279    // We can't use default capture by copy if any captures already specified19280    // capture by copy.19281    if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {19282          return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();19283        })) {19284      FixBuffer.assign({"=", Separator});19285      Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)19286          << /*value*/ 019287          << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);19288    }19289  }19290 19291  // We can't use default capture by reference if any captures already specified19292  // capture by reference.19293  if (llvm::none_of(LSI->Captures, [](Capture &C) {19294        return !C.isInitCapture() && C.isReferenceCapture() &&19295               !C.isThisCapture();19296      })) {19297    FixBuffer.assign({"&", Separator});19298    Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)19299        << /*reference*/ 119300        << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);19301  }19302}19303 19304bool Sema::tryCaptureVariable(19305    ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,19306    SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,19307    QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {19308  // An init-capture is notionally from the context surrounding its19309  // declaration, but its parent DC is the lambda class.19310  DeclContext *VarDC = Var->getDeclContext();19311  DeclContext *DC = CurContext;19312 19313  // Skip past RequiresExprBodys because they don't constitute function scopes.19314  while (DC->isRequiresExprBody())19315    DC = DC->getParent();19316 19317  // tryCaptureVariable is called every time a DeclRef is formed,19318  // it can therefore have non-negigible impact on performances.19319  // For local variables and when there is no capturing scope,19320  // we can bailout early.19321  if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))19322    return true;19323 19324  // Exception: Function parameters are not tied to the function's DeclContext19325  // until we enter the function definition. Capturing them anyway would result19326  // in an out-of-bounds error while traversing DC and its parents.19327  if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())19328    return true;19329 19330  const auto *VD = dyn_cast<VarDecl>(Var);19331  if (VD) {19332    if (VD->isInitCapture())19333      VarDC = VarDC->getParent();19334  } else {19335    VD = Var->getPotentiallyDecomposedVarDecl();19336  }19337  assert(VD && "Cannot capture a null variable");19338 19339  const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt19340      ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;19341  // We need to sync up the Declaration Context with the19342  // FunctionScopeIndexToStopAt19343  if (FunctionScopeIndexToStopAt) {19344    assert(!FunctionScopes.empty() && "No function scopes to stop at?");19345    unsigned FSIndex = FunctionScopes.size() - 1;19346    // When we're parsing the lambda parameter list, the current DeclContext is19347    // NOT the lambda but its parent. So move away the current LSI before19348    // aligning DC and FunctionScopeIndexToStopAt.19349    if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);19350        FSIndex && LSI && !LSI->AfterParameterList)19351      --FSIndex;19352    assert(MaxFunctionScopesIndex <= FSIndex &&19353           "FunctionScopeIndexToStopAt should be no greater than FSIndex into "19354           "FunctionScopes.");19355    while (FSIndex != MaxFunctionScopesIndex) {19356      DC = getLambdaAwareParentOfDeclContext(DC);19357      --FSIndex;19358    }19359  }19360 19361  // Capture global variables if it is required to use private copy of this19362  // variable.19363  bool IsGlobal = !VD->hasLocalStorage();19364  if (IsGlobal && !(LangOpts.OpenMP &&19365                    OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,19366                                                  MaxFunctionScopesIndex)))19367    return true;19368 19369  if (isa<VarDecl>(Var))19370    Var = cast<VarDecl>(Var->getCanonicalDecl());19371 19372  // Walk up the stack to determine whether we can capture the variable,19373  // performing the "simple" checks that don't depend on type. We stop when19374  // we've either hit the declared scope of the variable or find an existing19375  // capture of that variable.  We start from the innermost capturing-entity19376  // (the DC) and ensure that all intervening capturing-entities19377  // (blocks/lambdas etc.) between the innermost capturer and the variable`s19378  // declcontext can either capture the variable or have already captured19379  // the variable.19380  CaptureType = Var->getType();19381  DeclRefType = CaptureType.getNonReferenceType();19382  bool Nested = false;19383  bool Explicit = (Kind != TryCaptureKind::Implicit);19384  unsigned FunctionScopesIndex = MaxFunctionScopesIndex;19385  do {19386 19387    LambdaScopeInfo *LSI = nullptr;19388    if (!FunctionScopes.empty())19389      LSI = dyn_cast_or_null<LambdaScopeInfo>(19390          FunctionScopes[FunctionScopesIndex]);19391 19392    bool IsInScopeDeclarationContext =19393        !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;19394 19395    if (LSI && !LSI->AfterParameterList) {19396      // This allows capturing parameters from a default value which does not19397      // seems correct19398      if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())19399        return true;19400    }19401    // If the variable is declared in the current context, there is no need to19402    // capture it.19403    if (IsInScopeDeclarationContext &&19404        FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)19405      return true;19406 19407    // Only block literals, captured statements, and lambda expressions can19408    // capture; other scopes don't work.19409    DeclContext *ParentDC =19410        !IsInScopeDeclarationContext19411            ? DC->getParent()19412            : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,19413                                                BuildAndDiagnose, *this);19414    // We need to check for the parent *first* because, if we *have*19415    // private-captured a global variable, we need to recursively capture it in19416    // intermediate blocks, lambdas, etc.19417    if (!ParentDC) {19418      if (IsGlobal) {19419        FunctionScopesIndex = MaxFunctionScopesIndex - 1;19420        break;19421      }19422      return true;19423    }19424 19425    FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];19426    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);19427 19428    // Check whether we've already captured it.19429    if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,19430                                             DeclRefType)) {19431      CSI->getCapture(Var).markUsed(BuildAndDiagnose);19432      break;19433    }19434 19435    // When evaluating some attributes (like enable_if) we might refer to a19436    // function parameter appertaining to the same declaration as that19437    // attribute.19438    if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);19439        Parm && Parm->getDeclContext() == DC)19440      return true;19441 19442    // If we are instantiating a generic lambda call operator body,19443    // we do not want to capture new variables.  What was captured19444    // during either a lambdas transformation or initial parsing19445    // should be used.19446    if (isGenericLambdaCallOperatorSpecialization(DC)) {19447      if (BuildAndDiagnose) {19448        LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);19449        if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {19450          Diag(ExprLoc, diag::err_lambda_impcap) << Var;19451          Diag(Var->getLocation(), diag::note_previous_decl) << Var;19452          Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);19453          buildLambdaCaptureFixit(*this, LSI, Var);19454        } else19455          diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc, Var);19456      }19457      return true;19458    }19459 19460    // Try to capture variable-length arrays types.19461    if (Var->getType()->isVariablyModifiedType()) {19462      // We're going to walk down into the type and look for VLA19463      // expressions.19464      QualType QTy = Var->getType();19465      if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))19466        QTy = PVD->getOriginalType();19467      captureVariablyModifiedType(Context, QTy, CSI);19468    }19469 19470    if (getLangOpts().OpenMP) {19471      if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {19472        // OpenMP private variables should not be captured in outer scope, so19473        // just break here. Similarly, global variables that are captured in a19474        // target region should not be captured outside the scope of the region.19475        if (RSI->CapRegionKind == CR_OpenMP) {19476          // FIXME: We should support capturing structured bindings in OpenMP.19477          if (isa<BindingDecl>(Var)) {19478            if (BuildAndDiagnose) {19479              Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;19480              Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;19481            }19482            return true;19483          }19484          OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(19485              Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);19486          // If the variable is private (i.e. not captured) and has variably19487          // modified type, we still need to capture the type for correct19488          // codegen in all regions, associated with the construct. Currently,19489          // it is captured in the innermost captured region only.19490          if (IsOpenMPPrivateDecl != OMPC_unknown &&19491              Var->getType()->isVariablyModifiedType()) {19492            QualType QTy = Var->getType();19493            if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))19494              QTy = PVD->getOriginalType();19495            for (int I = 1,19496                     E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);19497                 I < E; ++I) {19498              auto *OuterRSI = cast<CapturedRegionScopeInfo>(19499                  FunctionScopes[FunctionScopesIndex - I]);19500              assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&19501                     "Wrong number of captured regions associated with the "19502                     "OpenMP construct.");19503              captureVariablyModifiedType(Context, QTy, OuterRSI);19504            }19505          }19506          bool IsTargetCap =19507              IsOpenMPPrivateDecl != OMPC_private &&19508              OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,19509                                                  RSI->OpenMPCaptureLevel);19510          // Do not capture global if it is not privatized in outer regions.19511          bool IsGlobalCap =19512              IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(19513                              Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);19514 19515          // When we detect target captures we are looking from inside the19516          // target region, therefore we need to propagate the capture from the19517          // enclosing region. Therefore, the capture is not initially nested.19518          if (IsTargetCap)19519            OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,19520                                                  RSI->OpenMPLevel);19521 19522          if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||19523              (IsGlobal && !IsGlobalCap)) {19524            Nested = !IsTargetCap;19525            bool HasConst = DeclRefType.isConstQualified();19526            DeclRefType = DeclRefType.getUnqualifiedType();19527            // Don't lose diagnostics about assignments to const.19528            if (HasConst)19529              DeclRefType.addConst();19530            CaptureType = Context.getLValueReferenceType(DeclRefType);19531            break;19532          }19533        }19534      }19535    }19536    if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {19537      // No capture-default, and this is not an explicit capture19538      // so cannot capture this variable.19539      if (BuildAndDiagnose) {19540        Diag(ExprLoc, diag::err_lambda_impcap) << Var;19541        Diag(Var->getLocation(), diag::note_previous_decl) << Var;19542        auto *LSI = cast<LambdaScopeInfo>(CSI);19543        if (LSI->Lambda) {19544          Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);19545          buildLambdaCaptureFixit(*this, LSI, Var);19546        }19547        // FIXME: If we error out because an outer lambda can not implicitly19548        // capture a variable that an inner lambda explicitly captures, we19549        // should have the inner lambda do the explicit capture - because19550        // it makes for cleaner diagnostics later.  This would purely be done19551        // so that the diagnostic does not misleadingly claim that a variable19552        // can not be captured by a lambda implicitly even though it is captured19553        // explicitly.  Suggestion:19554        //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit19555        //    at the function head19556        //  - cache the StartingDeclContext - this must be a lambda19557        //  - captureInLambda in the innermost lambda the variable.19558      }19559      return true;19560    }19561    Explicit = false;19562    FunctionScopesIndex--;19563    if (IsInScopeDeclarationContext)19564      DC = ParentDC;19565  } while (!VarDC->Equals(DC));19566 19567  // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)19568  // computing the type of the capture at each step, checking type-specific19569  // requirements, and adding captures if requested.19570  // If the variable had already been captured previously, we start capturing19571  // at the lambda nested within that one.19572  bool Invalid = false;19573  for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;19574       ++I) {19575    CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);19576 19577    // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture19578    // certain types of variables (unnamed, variably modified types etc.)19579    // so check for eligibility.19580    if (!Invalid)19581      Invalid =19582          !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);19583 19584    // After encountering an error, if we're actually supposed to capture, keep19585    // capturing in nested contexts to suppress any follow-on diagnostics.19586    if (Invalid && !BuildAndDiagnose)19587      return true;19588 19589    if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {19590      Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,19591                               DeclRefType, Nested, *this, Invalid);19592      Nested = true;19593    } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {19594      Invalid = !captureInCapturedRegion(19595          RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,19596          Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);19597      Nested = true;19598    } else {19599      LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);19600      Invalid =19601          !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,19602                           DeclRefType, Nested, Kind, EllipsisLoc,19603                           /*IsTopScope*/ I == N - 1, *this, Invalid);19604      Nested = true;19605    }19606 19607    if (Invalid && !BuildAndDiagnose)19608      return true;19609  }19610  return Invalid;19611}19612 19613bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,19614                              TryCaptureKind Kind, SourceLocation EllipsisLoc) {19615  QualType CaptureType;19616  QualType DeclRefType;19617  return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,19618                            /*BuildAndDiagnose=*/true, CaptureType,19619                            DeclRefType, nullptr);19620}19621 19622bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {19623  QualType CaptureType;19624  QualType DeclRefType;19625  return !tryCaptureVariable(19626      Var, Loc, TryCaptureKind::Implicit, SourceLocation(),19627      /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);19628}19629 19630QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {19631  assert(Var && "Null value cannot be captured");19632 19633  QualType CaptureType;19634  QualType DeclRefType;19635 19636  // Determine whether we can capture this variable.19637  if (tryCaptureVariable(Var, Loc, TryCaptureKind::Implicit, SourceLocation(),19638                         /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,19639                         nullptr))19640    return QualType();19641 19642  return DeclRefType;19643}19644 19645namespace {19646// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.19647// The produced TemplateArgumentListInfo* points to data stored within this19648// object, so should only be used in contexts where the pointer will not be19649// used after the CopiedTemplateArgs object is destroyed.19650class CopiedTemplateArgs {19651  bool HasArgs;19652  TemplateArgumentListInfo TemplateArgStorage;19653public:19654  template<typename RefExpr>19655  CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {19656    if (HasArgs)19657      E->copyTemplateArgumentsInto(TemplateArgStorage);19658  }19659  operator TemplateArgumentListInfo*()19660#ifdef __has_cpp_attribute19661#if __has_cpp_attribute(clang::lifetimebound)19662  [[clang::lifetimebound]]19663#endif19664#endif19665  {19666    return HasArgs ? &TemplateArgStorage : nullptr;19667  }19668};19669}19670 19671/// Walk the set of potential results of an expression and mark them all as19672/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.19673///19674/// \return A new expression if we found any potential results, ExprEmpty() if19675///         not, and ExprError() if we diagnosed an error.19676static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,19677                                                      NonOdrUseReason NOUR) {19678  // Per C++11 [basic.def.odr], a variable is odr-used "unless it is19679  // an object that satisfies the requirements for appearing in a19680  // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)19681  // is immediately applied."  This function handles the lvalue-to-rvalue19682  // conversion part.19683  //19684  // If we encounter a node that claims to be an odr-use but shouldn't be, we19685  // transform it into the relevant kind of non-odr-use node and rebuild the19686  // tree of nodes leading to it.19687  //19688  // This is a mini-TreeTransform that only transforms a restricted subset of19689  // nodes (and only certain operands of them).19690 19691  // Rebuild a subexpression.19692  auto Rebuild = [&](Expr *Sub) {19693    return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);19694  };19695 19696  // Check whether a potential result satisfies the requirements of NOUR.19697  auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {19698    // Any entity other than a VarDecl is always odr-used whenever it's named19699    // in a potentially-evaluated expression.19700    auto *VD = dyn_cast<VarDecl>(D);19701    if (!VD)19702      return true;19703 19704    // C++2a [basic.def.odr]p4:19705    //   A variable x whose name appears as a potentially-evalauted expression19706    //   e is odr-used by e unless19707    //   -- x is a reference that is usable in constant expressions, or19708    //   -- x is a variable of non-reference type that is usable in constant19709    //      expressions and has no mutable subobjects, and e is an element of19710    //      the set of potential results of an expression of19711    //      non-volatile-qualified non-class type to which the lvalue-to-rvalue19712    //      conversion is applied, or19713    //   -- x is a variable of non-reference type, and e is an element of the19714    //      set of potential results of a discarded-value expression to which19715    //      the lvalue-to-rvalue conversion is not applied19716    //19717    // We check the first bullet and the "potentially-evaluated" condition in19718    // BuildDeclRefExpr. We check the type requirements in the second bullet19719    // in CheckLValueToRValueConversionOperand below.19720    switch (NOUR) {19721    case NOUR_None:19722    case NOUR_Unevaluated:19723      llvm_unreachable("unexpected non-odr-use-reason");19724 19725    case NOUR_Constant:19726      // Constant references were handled when they were built.19727      if (VD->getType()->isReferenceType())19728        return true;19729      if (auto *RD = VD->getType()->getAsCXXRecordDecl())19730        if (RD->hasDefinition() && RD->hasMutableFields())19731          return true;19732      if (!VD->isUsableInConstantExpressions(S.Context))19733        return true;19734      break;19735 19736    case NOUR_Discarded:19737      if (VD->getType()->isReferenceType())19738        return true;19739      break;19740    }19741    return false;19742  };19743 19744  // Check whether this expression may be odr-used in CUDA/HIP.19745  auto MaybeCUDAODRUsed = [&]() -> bool {19746    if (!S.LangOpts.CUDA)19747      return false;19748    LambdaScopeInfo *LSI = S.getCurLambda();19749    if (!LSI)19750      return false;19751    auto *DRE = dyn_cast<DeclRefExpr>(E);19752    if (!DRE)19753      return false;19754    auto *VD = dyn_cast<VarDecl>(DRE->getDecl());19755    if (!VD)19756      return false;19757    return LSI->CUDAPotentialODRUsedVars.count(VD);19758  };19759 19760  // Mark that this expression does not constitute an odr-use.19761  auto MarkNotOdrUsed = [&] {19762    if (!MaybeCUDAODRUsed()) {19763      S.MaybeODRUseExprs.remove(E);19764      if (LambdaScopeInfo *LSI = S.getCurLambda())19765        LSI->markVariableExprAsNonODRUsed(E);19766    }19767  };19768 19769  // C++2a [basic.def.odr]p2:19770  //   The set of potential results of an expression e is defined as follows:19771  switch (E->getStmtClass()) {19772  //   -- If e is an id-expression, ...19773  case Expr::DeclRefExprClass: {19774    auto *DRE = cast<DeclRefExpr>(E);19775    if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))19776      break;19777 19778    // Rebuild as a non-odr-use DeclRefExpr.19779    MarkNotOdrUsed();19780    return DeclRefExpr::Create(19781        S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),19782        DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),19783        DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),19784        DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);19785  }19786 19787  case Expr::FunctionParmPackExprClass: {19788    auto *FPPE = cast<FunctionParmPackExpr>(E);19789    // If any of the declarations in the pack is odr-used, then the expression19790    // as a whole constitutes an odr-use.19791    for (ValueDecl *D : *FPPE)19792      if (IsPotentialResultOdrUsed(D))19793        return ExprEmpty();19794 19795    // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,19796    // nothing cares about whether we marked this as an odr-use, but it might19797    // be useful for non-compiler tools.19798    MarkNotOdrUsed();19799    break;19800  }19801 19802  //   -- If e is a subscripting operation with an array operand...19803  case Expr::ArraySubscriptExprClass: {19804    auto *ASE = cast<ArraySubscriptExpr>(E);19805    Expr *OldBase = ASE->getBase()->IgnoreImplicit();19806    if (!OldBase->getType()->isArrayType())19807      break;19808    ExprResult Base = Rebuild(OldBase);19809    if (!Base.isUsable())19810      return Base;19811    Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();19812    Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();19813    SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.19814    return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,19815                                     ASE->getRBracketLoc());19816  }19817 19818  case Expr::MemberExprClass: {19819    auto *ME = cast<MemberExpr>(E);19820    // -- If e is a class member access expression [...] naming a non-static19821    //    data member...19822    if (isa<FieldDecl>(ME->getMemberDecl())) {19823      ExprResult Base = Rebuild(ME->getBase());19824      if (!Base.isUsable())19825        return Base;19826      return MemberExpr::Create(19827          S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),19828          ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),19829          ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),19830          CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),19831          ME->getObjectKind(), ME->isNonOdrUse());19832    }19833 19834    if (ME->getMemberDecl()->isCXXInstanceMember())19835      break;19836 19837    // -- If e is a class member access expression naming a static data member,19838    //    ...19839    if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))19840      break;19841 19842    // Rebuild as a non-odr-use MemberExpr.19843    MarkNotOdrUsed();19844    return MemberExpr::Create(19845        S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),19846        ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),19847        ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),19848        ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);19849  }19850 19851  case Expr::BinaryOperatorClass: {19852    auto *BO = cast<BinaryOperator>(E);19853    Expr *LHS = BO->getLHS();19854    Expr *RHS = BO->getRHS();19855    // -- If e is a pointer-to-member expression of the form e1 .* e2 ...19856    if (BO->getOpcode() == BO_PtrMemD) {19857      ExprResult Sub = Rebuild(LHS);19858      if (!Sub.isUsable())19859        return Sub;19860      BO->setLHS(Sub.get());19861    //   -- If e is a comma expression, ...19862    } else if (BO->getOpcode() == BO_Comma) {19863      ExprResult Sub = Rebuild(RHS);19864      if (!Sub.isUsable())19865        return Sub;19866      BO->setRHS(Sub.get());19867    } else {19868      break;19869    }19870    return ExprResult(BO);19871  }19872 19873  //   -- If e has the form (e1)...19874  case Expr::ParenExprClass: {19875    auto *PE = cast<ParenExpr>(E);19876    ExprResult Sub = Rebuild(PE->getSubExpr());19877    if (!Sub.isUsable())19878      return Sub;19879    return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());19880  }19881 19882  //   -- If e is a glvalue conditional expression, ...19883  // We don't apply this to a binary conditional operator. FIXME: Should we?19884  case Expr::ConditionalOperatorClass: {19885    auto *CO = cast<ConditionalOperator>(E);19886    ExprResult LHS = Rebuild(CO->getLHS());19887    if (LHS.isInvalid())19888      return ExprError();19889    ExprResult RHS = Rebuild(CO->getRHS());19890    if (RHS.isInvalid())19891      return ExprError();19892    if (!LHS.isUsable() && !RHS.isUsable())19893      return ExprEmpty();19894    if (!LHS.isUsable())19895      LHS = CO->getLHS();19896    if (!RHS.isUsable())19897      RHS = CO->getRHS();19898    return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),19899                                CO->getCond(), LHS.get(), RHS.get());19900  }19901 19902  // [Clang extension]19903  //   -- If e has the form __extension__ e1...19904  case Expr::UnaryOperatorClass: {19905    auto *UO = cast<UnaryOperator>(E);19906    if (UO->getOpcode() != UO_Extension)19907      break;19908    ExprResult Sub = Rebuild(UO->getSubExpr());19909    if (!Sub.isUsable())19910      return Sub;19911    return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,19912                          Sub.get());19913  }19914 19915  // [Clang extension]19916  //   -- If e has the form _Generic(...), the set of potential results is the19917  //      union of the sets of potential results of the associated expressions.19918  case Expr::GenericSelectionExprClass: {19919    auto *GSE = cast<GenericSelectionExpr>(E);19920 19921    SmallVector<Expr *, 4> AssocExprs;19922    bool AnyChanged = false;19923    for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {19924      ExprResult AssocExpr = Rebuild(OrigAssocExpr);19925      if (AssocExpr.isInvalid())19926        return ExprError();19927      if (AssocExpr.isUsable()) {19928        AssocExprs.push_back(AssocExpr.get());19929        AnyChanged = true;19930      } else {19931        AssocExprs.push_back(OrigAssocExpr);19932      }19933    }19934 19935    void *ExOrTy = nullptr;19936    bool IsExpr = GSE->isExprPredicate();19937    if (IsExpr)19938      ExOrTy = GSE->getControllingExpr();19939    else19940      ExOrTy = GSE->getControllingType();19941    return AnyChanged ? S.CreateGenericSelectionExpr(19942                            GSE->getGenericLoc(), GSE->getDefaultLoc(),19943                            GSE->getRParenLoc(), IsExpr, ExOrTy,19944                            GSE->getAssocTypeSourceInfos(), AssocExprs)19945                      : ExprEmpty();19946  }19947 19948  // [Clang extension]19949  //   -- If e has the form __builtin_choose_expr(...), the set of potential19950  //      results is the union of the sets of potential results of the19951  //      second and third subexpressions.19952  case Expr::ChooseExprClass: {19953    auto *CE = cast<ChooseExpr>(E);19954 19955    ExprResult LHS = Rebuild(CE->getLHS());19956    if (LHS.isInvalid())19957      return ExprError();19958 19959    ExprResult RHS = Rebuild(CE->getLHS());19960    if (RHS.isInvalid())19961      return ExprError();19962 19963    if (!LHS.get() && !RHS.get())19964      return ExprEmpty();19965    if (!LHS.isUsable())19966      LHS = CE->getLHS();19967    if (!RHS.isUsable())19968      RHS = CE->getRHS();19969 19970    return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),19971                             RHS.get(), CE->getRParenLoc());19972  }19973 19974  // Step through non-syntactic nodes.19975  case Expr::ConstantExprClass: {19976    auto *CE = cast<ConstantExpr>(E);19977    ExprResult Sub = Rebuild(CE->getSubExpr());19978    if (!Sub.isUsable())19979      return Sub;19980    return ConstantExpr::Create(S.Context, Sub.get());19981  }19982 19983  // We could mostly rely on the recursive rebuilding to rebuild implicit19984  // casts, but not at the top level, so rebuild them here.19985  case Expr::ImplicitCastExprClass: {19986    auto *ICE = cast<ImplicitCastExpr>(E);19987    // Only step through the narrow set of cast kinds we expect to encounter.19988    // Anything else suggests we've left the region in which potential results19989    // can be found.19990    switch (ICE->getCastKind()) {19991    case CK_NoOp:19992    case CK_DerivedToBase:19993    case CK_UncheckedDerivedToBase: {19994      ExprResult Sub = Rebuild(ICE->getSubExpr());19995      if (!Sub.isUsable())19996        return Sub;19997      CXXCastPath Path(ICE->path());19998      return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),19999                                 ICE->getValueKind(), &Path);20000    }20001 20002    default:20003      break;20004    }20005    break;20006  }20007 20008  default:20009    break;20010  }20011 20012  // Can't traverse through this node. Nothing to do.20013  return ExprEmpty();20014}20015 20016ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {20017  // Check whether the operand is or contains an object of non-trivial C union20018  // type.20019  if (E->getType().isVolatileQualified() &&20020      (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||20021       E->getType().hasNonTrivialToPrimitiveCopyCUnion()))20022    checkNonTrivialCUnion(E->getType(), E->getExprLoc(),20023                          NonTrivialCUnionContext::LValueToRValueVolatile,20024                          NTCUK_Destruct | NTCUK_Copy);20025 20026  // C++2a [basic.def.odr]p4:20027  //   [...] an expression of non-volatile-qualified non-class type to which20028  //   the lvalue-to-rvalue conversion is applied [...]20029  if (E->getType().isVolatileQualified() || E->getType()->isRecordType())20030    return E;20031 20032  ExprResult Result =20033      rebuildPotentialResultsAsNonOdrUsed(*this, E, NOUR_Constant);20034  if (Result.isInvalid())20035    return ExprError();20036  return Result.get() ? Result : E;20037}20038 20039ExprResult Sema::ActOnConstantExpression(ExprResult Res) {20040  if (!Res.isUsable())20041    return Res;20042 20043  // If a constant-expression is a reference to a variable where we delay20044  // deciding whether it is an odr-use, just assume we will apply the20045  // lvalue-to-rvalue conversion.  In the one case where this doesn't happen20046  // (a non-type template argument), we have special handling anyway.20047  return CheckLValueToRValueConversionOperand(Res.get());20048}20049 20050void Sema::CleanupVarDeclMarking() {20051  // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive20052  // call.20053  MaybeODRUseExprSet LocalMaybeODRUseExprs;20054  std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);20055 20056  for (Expr *E : LocalMaybeODRUseExprs) {20057    if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {20058      MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),20059                         DRE->getLocation(), *this);20060    } else if (auto *ME = dyn_cast<MemberExpr>(E)) {20061      MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),20062                         *this);20063    } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {20064      for (ValueDecl *VD : *FP)20065        MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);20066    } else {20067      llvm_unreachable("Unexpected expression");20068    }20069  }20070 20071  assert(MaybeODRUseExprs.empty() &&20072         "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");20073}20074 20075static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,20076                                   ValueDecl *Var, Expr *E) {20077  VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();20078  if (!VD)20079    return;20080 20081  const bool RefersToEnclosingScope =20082      (SemaRef.CurContext != VD->getDeclContext() &&20083       VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());20084  if (RefersToEnclosingScope) {20085    LambdaScopeInfo *const LSI =20086        SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);20087    if (LSI && (!LSI->CallOperator ||20088                !LSI->CallOperator->Encloses(Var->getDeclContext()))) {20089      // If a variable could potentially be odr-used, defer marking it so20090      // until we finish analyzing the full expression for any20091      // lvalue-to-rvalue20092      // or discarded value conversions that would obviate odr-use.20093      // Add it to the list of potential captures that will be analyzed20094      // later (ActOnFinishFullExpr) for eventual capture and odr-use marking20095      // unless the variable is a reference that was initialized by a constant20096      // expression (this will never need to be captured or odr-used).20097      //20098      // FIXME: We can simplify this a lot after implementing P0588R1.20099      assert(E && "Capture variable should be used in an expression.");20100      if (!Var->getType()->isReferenceType() ||20101          !VD->isUsableInConstantExpressions(SemaRef.Context))20102        LSI->addPotentialCapture(E->IgnoreParens());20103    }20104  }20105}20106 20107static void DoMarkVarDeclReferenced(20108    Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,20109    llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {20110  assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||20111          isa<FunctionParmPackExpr>(E)) &&20112         "Invalid Expr argument to DoMarkVarDeclReferenced");20113  Var->setReferenced();20114 20115  if (Var->isInvalidDecl())20116    return;20117 20118  auto *MSI = Var->getMemberSpecializationInfo();20119  TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()20120                                       : Var->getTemplateSpecializationKind();20121 20122  OdrUseContext OdrUse = isOdrUseContext(SemaRef);20123  bool UsableInConstantExpr =20124      Var->mightBeUsableInConstantExpressions(SemaRef.Context);20125 20126  if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {20127    RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;20128  }20129 20130  // C++20 [expr.const]p12:20131  //   A variable [...] is needed for constant evaluation if it is [...] a20132  //   variable whose name appears as a potentially constant evaluated20133  //   expression that is either a contexpr variable or is of non-volatile20134  //   const-qualified integral type or of reference type20135  bool NeededForConstantEvaluation =20136      isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;20137 20138  bool NeedDefinition =20139      OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||20140      (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&20141       Var->getType()->isUndeducedType());20142 20143  assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&20144         "Can't instantiate a partial template specialization.");20145 20146  // If this might be a member specialization of a static data member, check20147  // the specialization is visible. We already did the checks for variable20148  // template specializations when we created them.20149  if (NeedDefinition && TSK != TSK_Undeclared &&20150      !isa<VarTemplateSpecializationDecl>(Var))20151    SemaRef.checkSpecializationVisibility(Loc, Var);20152 20153  // Perform implicit instantiation of static data members, static data member20154  // templates of class templates, and variable template specializations. Delay20155  // instantiations of variable templates, except for those that could be used20156  // in a constant expression.20157  if (NeedDefinition && isTemplateInstantiation(TSK)) {20158    // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit20159    // instantiation declaration if a variable is usable in a constant20160    // expression (among other cases).20161    bool TryInstantiating =20162        TSK == TSK_ImplicitInstantiation ||20163        (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);20164 20165    if (TryInstantiating) {20166      SourceLocation PointOfInstantiation =20167          MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();20168      bool FirstInstantiation = PointOfInstantiation.isInvalid();20169      if (FirstInstantiation) {20170        PointOfInstantiation = Loc;20171        if (MSI)20172          MSI->setPointOfInstantiation(PointOfInstantiation);20173          // FIXME: Notify listener.20174        else20175          Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);20176      }20177 20178      if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {20179        // Do not defer instantiations of variables that could be used in a20180        // constant expression.20181        // The type deduction also needs a complete initializer.20182        SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {20183          SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);20184        });20185 20186        // The size of an incomplete array type can be updated by20187        // instantiating the initializer. The DeclRefExpr's type should be20188        // updated accordingly too, or users of it would be confused!20189        if (E)20190          SemaRef.getCompletedType(E);20191 20192        // Re-set the member to trigger a recomputation of the dependence bits20193        // for the expression.20194        if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))20195          DRE->setDecl(DRE->getDecl());20196        else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))20197          ME->setMemberDecl(ME->getMemberDecl());20198      } else if (FirstInstantiation) {20199        SemaRef.PendingInstantiations20200            .push_back(std::make_pair(Var, PointOfInstantiation));20201      } else {20202        bool Inserted = false;20203        for (auto &I : SemaRef.SavedPendingInstantiations) {20204          auto Iter = llvm::find_if(20205              I, [Var](const Sema::PendingImplicitInstantiation &P) {20206                return P.first == Var;20207              });20208          if (Iter != I.end()) {20209            SemaRef.PendingInstantiations.push_back(*Iter);20210            I.erase(Iter);20211            Inserted = true;20212            break;20213          }20214        }20215 20216        // FIXME: For a specialization of a variable template, we don't20217        // distinguish between "declaration and type implicitly instantiated"20218        // and "implicit instantiation of definition requested", so we have20219        // no direct way to avoid enqueueing the pending instantiation20220        // multiple times.20221        if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)20222          SemaRef.PendingInstantiations20223            .push_back(std::make_pair(Var, PointOfInstantiation));20224      }20225    }20226  }20227 20228  // C++2a [basic.def.odr]p4:20229  //   A variable x whose name appears as a potentially-evaluated expression e20230  //   is odr-used by e unless20231  //   -- x is a reference that is usable in constant expressions20232  //   -- x is a variable of non-reference type that is usable in constant20233  //      expressions and has no mutable subobjects [FIXME], and e is an20234  //      element of the set of potential results of an expression of20235  //      non-volatile-qualified non-class type to which the lvalue-to-rvalue20236  //      conversion is applied20237  //   -- x is a variable of non-reference type, and e is an element of the set20238  //      of potential results of a discarded-value expression to which the20239  //      lvalue-to-rvalue conversion is not applied [FIXME]20240  //20241  // We check the first part of the second bullet here, and20242  // Sema::CheckLValueToRValueConversionOperand deals with the second part.20243  // FIXME: To get the third bullet right, we need to delay this even for20244  // variables that are not usable in constant expressions.20245 20246  // If we already know this isn't an odr-use, there's nothing more to do.20247  if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))20248    if (DRE->isNonOdrUse())20249      return;20250  if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))20251    if (ME->isNonOdrUse())20252      return;20253 20254  switch (OdrUse) {20255  case OdrUseContext::None:20256    // In some cases, a variable may not have been marked unevaluated, if it20257    // appears in a defaukt initializer.20258    assert((!E || isa<FunctionParmPackExpr>(E) ||20259            SemaRef.isUnevaluatedContext()) &&20260           "missing non-odr-use marking for unevaluated decl ref");20261    break;20262 20263  case OdrUseContext::FormallyOdrUsed:20264    // FIXME: Ignoring formal odr-uses results in incorrect lambda capture20265    // behavior.20266    break;20267 20268  case OdrUseContext::Used:20269    // If we might later find that this expression isn't actually an odr-use,20270    // delay the marking.20271    if (E && Var->isUsableInConstantExpressions(SemaRef.Context))20272      SemaRef.MaybeODRUseExprs.insert(E);20273    else20274      MarkVarDeclODRUsed(Var, Loc, SemaRef);20275    break;20276 20277  case OdrUseContext::Dependent:20278    // If this is a dependent context, we don't need to mark variables as20279    // odr-used, but we may still need to track them for lambda capture.20280    // FIXME: Do we also need to do this inside dependent typeid expressions20281    // (which are modeled as unevaluated at this point)?20282    DoMarkPotentialCapture(SemaRef, Loc, Var, E);20283    break;20284  }20285}20286 20287static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,20288                                        BindingDecl *BD, Expr *E) {20289  BD->setReferenced();20290 20291  if (BD->isInvalidDecl())20292    return;20293 20294  OdrUseContext OdrUse = isOdrUseContext(SemaRef);20295  if (OdrUse == OdrUseContext::Used) {20296    QualType CaptureType, DeclRefType;20297    SemaRef.tryCaptureVariable(BD, Loc, TryCaptureKind::Implicit,20298                               /*EllipsisLoc*/ SourceLocation(),20299                               /*BuildAndDiagnose*/ true, CaptureType,20300                               DeclRefType,20301                               /*FunctionScopeIndexToStopAt*/ nullptr);20302  } else if (OdrUse == OdrUseContext::Dependent) {20303    DoMarkPotentialCapture(SemaRef, Loc, BD, E);20304  }20305}20306 20307void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {20308  DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);20309}20310 20311// C++ [temp.dep.expr]p3:20312//   An id-expression is type-dependent if it contains:20313//     - an identifier associated by name lookup with an entity captured by copy20314//       in a lambda-expression that has an explicit object parameter whose type20315//       is dependent ([dcl.fct]),20316static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(20317    Sema &SemaRef, ValueDecl *D, Expr *E) {20318  auto *ID = dyn_cast<DeclRefExpr>(E);20319  if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())20320    return;20321 20322  // If any enclosing lambda with a dependent explicit object parameter either20323  // explicitly captures the variable by value, or has a capture default of '='20324  // and does not capture the variable by reference, then the type of the DRE20325  // is dependent on the type of that lambda's explicit object parameter.20326  auto IsDependent = [&]() {20327    for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {20328      auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);20329      if (!LSI)20330        continue;20331 20332      if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&20333          LSI->AfterParameterList)20334        return false;20335 20336      const auto *MD = LSI->CallOperator;20337      if (MD->getType().isNull())20338        continue;20339 20340      const auto *Ty = MD->getType()->getAs<FunctionProtoType>();20341      if (!Ty || !MD->isExplicitObjectMemberFunction() ||20342          !Ty->getParamType(0)->isDependentType())20343        continue;20344 20345      if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {20346        if (C->isCopyCapture())20347          return true;20348        continue;20349      }20350 20351      if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)20352        return true;20353    }20354    return false;20355  }();20356 20357  ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(20358      IsDependent, SemaRef.getASTContext());20359}20360 20361static void20362MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,20363                   bool MightBeOdrUse,20364                   llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {20365  if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())20366    SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);20367 20368  if (SemaRef.getLangOpts().OpenACC)20369    SemaRef.OpenACC().CheckDeclReference(Loc, E, D);20370 20371  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {20372    DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);20373    if (SemaRef.getLangOpts().CPlusPlus)20374      FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,20375                                                                       Var, E);20376    return;20377  }20378 20379  if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {20380    DoMarkBindingDeclReferenced(SemaRef, Loc, Decl, E);20381    if (SemaRef.getLangOpts().CPlusPlus)20382      FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,20383                                                                       Decl, E);20384    return;20385  }20386  SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);20387 20388  // If this is a call to a method via a cast, also mark the method in the20389  // derived class used in case codegen can devirtualize the call.20390  const MemberExpr *ME = dyn_cast<MemberExpr>(E);20391  if (!ME)20392    return;20393  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());20394  if (!MD)20395    return;20396  // Only attempt to devirtualize if this is truly a virtual call.20397  bool IsVirtualCall = MD->isVirtual() &&20398                          ME->performsVirtualDispatch(SemaRef.getLangOpts());20399  if (!IsVirtualCall)20400    return;20401 20402  // If it's possible to devirtualize the call, mark the called function20403  // referenced.20404  CXXMethodDecl *DM = MD->getDevirtualizedMethod(20405      ME->getBase(), SemaRef.getLangOpts().AppleKext);20406  if (DM)20407    SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);20408}20409 20410void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {20411  // [basic.def.odr] (CWG 1614)20412  // A function is named by an expression or conversion [...]20413  // unless it is a pure virtual function and either the expression is not an20414  // id-expression naming the function with an explicitly qualified name or20415  // the expression forms a pointer to member20416  bool OdrUse = true;20417  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))20418    if (Method->isVirtual() &&20419        !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))20420      OdrUse = false;20421 20422  if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {20423    if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&20424        !isImmediateFunctionContext() &&20425        !isCheckingDefaultArgumentOrInitializer() &&20426        FD->isImmediateFunction() && !RebuildingImmediateInvocation &&20427        !FD->isDependentContext())20428      ExprEvalContexts.back().ReferenceToConsteval.insert(E);20429  }20430  MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,20431                     RefsMinusAssignments);20432}20433 20434void Sema::MarkMemberReferenced(MemberExpr *E) {20435  // C++11 [basic.def.odr]p2:20436  //   A non-overloaded function whose name appears as a potentially-evaluated20437  //   expression or a member of a set of candidate functions, if selected by20438  //   overload resolution when referred to from a potentially-evaluated20439  //   expression, is odr-used, unless it is a pure virtual function and its20440  //   name is not explicitly qualified.20441  bool MightBeOdrUse = true;20442  if (E->performsVirtualDispatch(getLangOpts())) {20443    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))20444      if (Method->isPureVirtual())20445        MightBeOdrUse = false;20446  }20447  SourceLocation Loc =20448      E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();20449  MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,20450                     RefsMinusAssignments);20451}20452 20453void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {20454  for (ValueDecl *VD : *E)20455    MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,20456                       RefsMinusAssignments);20457}20458 20459/// Perform marking for a reference to an arbitrary declaration.  It20460/// marks the declaration referenced, and performs odr-use checking for20461/// functions and variables. This method should not be used when building a20462/// normal expression which refers to a variable.20463void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,20464                                 bool MightBeOdrUse) {20465  if (MightBeOdrUse) {20466    if (auto *VD = dyn_cast<VarDecl>(D)) {20467      MarkVariableReferenced(Loc, VD);20468      return;20469    }20470  }20471  if (auto *FD = dyn_cast<FunctionDecl>(D)) {20472    MarkFunctionReferenced(Loc, FD, MightBeOdrUse);20473    return;20474  }20475  D->setReferenced();20476}20477 20478namespace {20479  // Mark all of the declarations used by a type as referenced.20480  // FIXME: Not fully implemented yet! We need to have a better understanding20481  // of when we're entering a context we should not recurse into.20482  // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to20483  // TreeTransforms rebuilding the type in a new context. Rather than20484  // duplicating the TreeTransform logic, we should consider reusing it here.20485  // Currently that causes problems when rebuilding LambdaExprs.20486class MarkReferencedDecls : public DynamicRecursiveASTVisitor {20487  Sema &S;20488  SourceLocation Loc;20489 20490public:20491  MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}20492 20493  bool TraverseTemplateArgument(const TemplateArgument &Arg) override;20494};20495}20496 20497bool MarkReferencedDecls::TraverseTemplateArgument(20498    const TemplateArgument &Arg) {20499  {20500    // A non-type template argument is a constant-evaluated context.20501    EnterExpressionEvaluationContext Evaluated(20502        S, Sema::ExpressionEvaluationContext::ConstantEvaluated);20503    if (Arg.getKind() == TemplateArgument::Declaration) {20504      if (Decl *D = Arg.getAsDecl())20505        S.MarkAnyDeclReferenced(Loc, D, true);20506    } else if (Arg.getKind() == TemplateArgument::Expression) {20507      S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);20508    }20509  }20510 20511  return DynamicRecursiveASTVisitor::TraverseTemplateArgument(Arg);20512}20513 20514void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {20515  MarkReferencedDecls Marker(*this, Loc);20516  Marker.TraverseType(T);20517}20518 20519namespace {20520/// Helper class that marks all of the declarations referenced by20521/// potentially-evaluated subexpressions as "referenced".20522class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {20523public:20524  typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;20525  bool SkipLocalVariables;20526  ArrayRef<const Expr *> StopAt;20527 20528  EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,20529                      ArrayRef<const Expr *> StopAt)20530      : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}20531 20532  void visitUsedDecl(SourceLocation Loc, Decl *D) {20533    S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));20534  }20535 20536  void Visit(Expr *E) {20537    if (llvm::is_contained(StopAt, E))20538      return;20539    Inherited::Visit(E);20540  }20541 20542  void VisitConstantExpr(ConstantExpr *E) {20543    // Don't mark declarations within a ConstantExpression, as this expression20544    // will be evaluated and folded to a value.20545  }20546 20547  void VisitDeclRefExpr(DeclRefExpr *E) {20548    // If we were asked not to visit local variables, don't.20549    if (SkipLocalVariables) {20550      if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))20551        if (VD->hasLocalStorage())20552          return;20553    }20554 20555    // FIXME: This can trigger the instantiation of the initializer of a20556    // variable, which can cause the expression to become value-dependent20557    // or error-dependent. Do we need to propagate the new dependence bits?20558    S.MarkDeclRefReferenced(E);20559  }20560 20561  void VisitMemberExpr(MemberExpr *E) {20562    S.MarkMemberReferenced(E);20563    Visit(E->getBase());20564  }20565};20566} // namespace20567 20568void Sema::MarkDeclarationsReferencedInExpr(Expr *E,20569                                            bool SkipLocalVariables,20570                                            ArrayRef<const Expr*> StopAt) {20571  EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);20572}20573 20574/// Emit a diagnostic when statements are reachable.20575bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,20576                           const PartialDiagnostic &PD) {20577  VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;20578  // The initializer of a constexpr variable or of the first declaration of a20579  // static data member is not syntactically a constant evaluated constant,20580  // but nonetheless is always required to be a constant expression, so we20581  // can skip diagnosing.20582  if (Decl &&20583      (Decl->isConstexpr() || (Decl->isStaticDataMember() &&20584                               Decl->isFirstDecl() && !Decl->isInline())))20585    return false;20586 20587  if (Stmts.empty()) {20588    Diag(Loc, PD);20589    return true;20590  }20591 20592  if (getCurFunction()) {20593    FunctionScopes.back()->PossiblyUnreachableDiags.push_back(20594        sema::PossiblyUnreachableDiag(PD, Loc, Stmts));20595    return true;20596  }20597 20598  // For non-constexpr file-scope variables with reachability context (non-empty20599  // Stmts), build a CFG for the initializer and check whether the context in20600  // question is reachable.20601  if (Decl && Decl->isFileVarDecl()) {20602    AnalysisWarnings.registerVarDeclWarning(20603        Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));20604    return true;20605  }20606 20607  Diag(Loc, PD);20608  return true;20609}20610 20611/// Emit a diagnostic that describes an effect on the run-time behavior20612/// of the program being compiled.20613///20614/// This routine emits the given diagnostic when the code currently being20615/// type-checked is "potentially evaluated", meaning that there is a20616/// possibility that the code will actually be executable. Code in sizeof()20617/// expressions, code used only during overload resolution, etc., are not20618/// potentially evaluated. This routine will suppress such diagnostics or,20619/// in the absolutely nutty case of potentially potentially evaluated20620/// expressions (C++ typeid), queue the diagnostic to potentially emit it20621/// later.20622///20623/// This routine should be used for all diagnostics that describe the run-time20624/// behavior of a program, such as passing a non-POD value through an ellipsis.20625/// Failure to do so will likely result in spurious diagnostics or failures20626/// during overload resolution or within sizeof/alignof/typeof/typeid.20627bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,20628                               const PartialDiagnostic &PD) {20629 20630  if (ExprEvalContexts.back().isDiscardedStatementContext())20631    return false;20632 20633  switch (ExprEvalContexts.back().Context) {20634  case ExpressionEvaluationContext::Unevaluated:20635  case ExpressionEvaluationContext::UnevaluatedList:20636  case ExpressionEvaluationContext::UnevaluatedAbstract:20637  case ExpressionEvaluationContext::DiscardedStatement:20638    // The argument will never be evaluated, so don't complain.20639    break;20640 20641  case ExpressionEvaluationContext::ConstantEvaluated:20642  case ExpressionEvaluationContext::ImmediateFunctionContext:20643    // Relevant diagnostics should be produced by constant evaluation.20644    break;20645 20646  case ExpressionEvaluationContext::PotentiallyEvaluated:20647  case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:20648    return DiagIfReachable(Loc, Stmts, PD);20649  }20650 20651  return false;20652}20653 20654bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,20655                               const PartialDiagnostic &PD) {20656  return DiagRuntimeBehavior(20657      Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),20658      PD);20659}20660 20661bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,20662                               CallExpr *CE, FunctionDecl *FD) {20663  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())20664    return false;20665 20666  // If we're inside a decltype's expression, don't check for a valid return20667  // type or construct temporaries until we know whether this is the last call.20668  if (ExprEvalContexts.back().ExprContext ==20669      ExpressionEvaluationContextRecord::EK_Decltype) {20670    ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);20671    return false;20672  }20673 20674  class CallReturnIncompleteDiagnoser : public TypeDiagnoser {20675    FunctionDecl *FD;20676    CallExpr *CE;20677 20678  public:20679    CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)20680      : FD(FD), CE(CE) { }20681 20682    void diagnose(Sema &S, SourceLocation Loc, QualType T) override {20683      if (!FD) {20684        S.Diag(Loc, diag::err_call_incomplete_return)20685          << T << CE->getSourceRange();20686        return;20687      }20688 20689      S.Diag(Loc, diag::err_call_function_incomplete_return)20690          << CE->getSourceRange() << FD << T;20691      S.Diag(FD->getLocation(), diag::note_entity_declared_at)20692          << FD->getDeclName();20693    }20694  } Diagnoser(FD, CE);20695 20696  if (RequireCompleteType(Loc, ReturnType, Diagnoser))20697    return true;20698 20699  return false;20700}20701 20702// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses20703// will prevent this condition from triggering, which is what we want.20704void Sema::DiagnoseAssignmentAsCondition(Expr *E) {20705  SourceLocation Loc;20706 20707  unsigned diagnostic = diag::warn_condition_is_assignment;20708  bool IsOrAssign = false;20709 20710  if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {20711    if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)20712      return;20713 20714    IsOrAssign = Op->getOpcode() == BO_OrAssign;20715 20716    // Greylist some idioms by putting them into a warning subcategory.20717    if (ObjCMessageExpr *ME20718          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {20719      Selector Sel = ME->getSelector();20720 20721      // self = [<foo> init...]20722      if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)20723        diagnostic = diag::warn_condition_is_idiomatic_assignment;20724 20725      // <foo> = [<bar> nextObject]20726      else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")20727        diagnostic = diag::warn_condition_is_idiomatic_assignment;20728    }20729 20730    Loc = Op->getOperatorLoc();20731  } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {20732    if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)20733      return;20734 20735    IsOrAssign = Op->getOperator() == OO_PipeEqual;20736    Loc = Op->getOperatorLoc();20737  } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))20738    return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());20739  else {20740    // Not an assignment.20741    return;20742  }20743 20744  Diag(Loc, diagnostic) << E->getSourceRange();20745 20746  SourceLocation Open = E->getBeginLoc();20747  SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());20748  Diag(Loc, diag::note_condition_assign_silence)20749        << FixItHint::CreateInsertion(Open, "(")20750        << FixItHint::CreateInsertion(Close, ")");20751 20752  if (IsOrAssign)20753    Diag(Loc, diag::note_condition_or_assign_to_comparison)20754      << FixItHint::CreateReplacement(Loc, "!=");20755  else20756    Diag(Loc, diag::note_condition_assign_to_comparison)20757      << FixItHint::CreateReplacement(Loc, "==");20758}20759 20760void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {20761  // Don't warn if the parens came from a macro.20762  SourceLocation parenLoc = ParenE->getBeginLoc();20763  if (parenLoc.isInvalid() || parenLoc.isMacroID())20764    return;20765  // Don't warn for dependent expressions.20766  if (ParenE->isTypeDependent())20767    return;20768 20769  Expr *E = ParenE->IgnoreParens();20770  if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)20771    return;20772 20773  if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))20774    if (opE->getOpcode() == BO_EQ &&20775        opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)20776                                                           == Expr::MLV_Valid) {20777      SourceLocation Loc = opE->getOperatorLoc();20778 20779      Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();20780      SourceRange ParenERange = ParenE->getSourceRange();20781      Diag(Loc, diag::note_equality_comparison_silence)20782        << FixItHint::CreateRemoval(ParenERange.getBegin())20783        << FixItHint::CreateRemoval(ParenERange.getEnd());20784      Diag(Loc, diag::note_equality_comparison_to_assign)20785        << FixItHint::CreateReplacement(Loc, "=");20786    }20787}20788 20789ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,20790                                       bool IsConstexpr) {20791  DiagnoseAssignmentAsCondition(E);20792  if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))20793    DiagnoseEqualityWithExtraParens(parenE);20794 20795  ExprResult result = CheckPlaceholderExpr(E);20796  if (result.isInvalid()) return ExprError();20797  E = result.get();20798 20799  if (!E->isTypeDependent()) {20800    if (getLangOpts().CPlusPlus)20801      return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p420802 20803    ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);20804    if (ERes.isInvalid())20805      return ExprError();20806    E = ERes.get();20807 20808    QualType T = E->getType();20809    if (!T->isScalarType()) { // C99 6.8.4.1p120810      Diag(Loc, diag::err_typecheck_statement_requires_scalar)20811        << T << E->getSourceRange();20812      return ExprError();20813    }20814    CheckBoolLikeConversion(E, Loc);20815  }20816 20817  return E;20818}20819 20820Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,20821                                           Expr *SubExpr, ConditionKind CK,20822                                           bool MissingOK) {20823  // MissingOK indicates whether having no condition expression is valid20824  // (for loop) or invalid (e.g. while loop).20825  if (!SubExpr)20826    return MissingOK ? ConditionResult() : ConditionError();20827 20828  ExprResult Cond;20829  switch (CK) {20830  case ConditionKind::Boolean:20831    Cond = CheckBooleanCondition(Loc, SubExpr);20832    break;20833 20834  case ConditionKind::ConstexprIf:20835    // Note: this might produce a FullExpr20836    Cond = CheckBooleanCondition(Loc, SubExpr, true);20837    break;20838 20839  case ConditionKind::Switch:20840    Cond = CheckSwitchCondition(Loc, SubExpr);20841    break;20842  }20843  if (Cond.isInvalid()) {20844    Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),20845                              {SubExpr}, PreferredConditionType(CK));20846    if (!Cond.get())20847      return ConditionError();20848  } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))20849    Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);20850 20851  if (!Cond.isUsable())20852    return ConditionError();20853 20854  return ConditionResult(*this, nullptr, Cond,20855                         CK == ConditionKind::ConstexprIf);20856}20857 20858namespace {20859  /// A visitor for rebuilding a call to an __unknown_any expression20860  /// to have an appropriate type.20861  struct RebuildUnknownAnyFunction20862    : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {20863 20864    Sema &S;20865 20866    RebuildUnknownAnyFunction(Sema &S) : S(S) {}20867 20868    ExprResult VisitStmt(Stmt *S) {20869      llvm_unreachable("unexpected statement!");20870    }20871 20872    ExprResult VisitExpr(Expr *E) {20873      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)20874        << E->getSourceRange();20875      return ExprError();20876    }20877 20878    /// Rebuild an expression which simply semantically wraps another20879    /// expression which it shares the type and value kind of.20880    template <class T> ExprResult rebuildSugarExpr(T *E) {20881      ExprResult SubResult = Visit(E->getSubExpr());20882      if (SubResult.isInvalid()) return ExprError();20883 20884      Expr *SubExpr = SubResult.get();20885      E->setSubExpr(SubExpr);20886      E->setType(SubExpr->getType());20887      E->setValueKind(SubExpr->getValueKind());20888      assert(E->getObjectKind() == OK_Ordinary);20889      return E;20890    }20891 20892    ExprResult VisitParenExpr(ParenExpr *E) {20893      return rebuildSugarExpr(E);20894    }20895 20896    ExprResult VisitUnaryExtension(UnaryOperator *E) {20897      return rebuildSugarExpr(E);20898    }20899 20900    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {20901      ExprResult SubResult = Visit(E->getSubExpr());20902      if (SubResult.isInvalid()) return ExprError();20903 20904      Expr *SubExpr = SubResult.get();20905      E->setSubExpr(SubExpr);20906      E->setType(S.Context.getPointerType(SubExpr->getType()));20907      assert(E->isPRValue());20908      assert(E->getObjectKind() == OK_Ordinary);20909      return E;20910    }20911 20912    ExprResult resolveDecl(Expr *E, ValueDecl *VD) {20913      if (!isa<FunctionDecl>(VD)) return VisitExpr(E);20914 20915      E->setType(VD->getType());20916 20917      assert(E->isPRValue());20918      if (S.getLangOpts().CPlusPlus &&20919          !(isa<CXXMethodDecl>(VD) &&20920            cast<CXXMethodDecl>(VD)->isInstance()))20921        E->setValueKind(VK_LValue);20922 20923      return E;20924    }20925 20926    ExprResult VisitMemberExpr(MemberExpr *E) {20927      return resolveDecl(E, E->getMemberDecl());20928    }20929 20930    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {20931      return resolveDecl(E, E->getDecl());20932    }20933  };20934}20935 20936/// Given a function expression of unknown-any type, try to rebuild it20937/// to have a function type.20938static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {20939  ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);20940  if (Result.isInvalid()) return ExprError();20941  return S.DefaultFunctionArrayConversion(Result.get());20942}20943 20944namespace {20945  /// A visitor for rebuilding an expression of type __unknown_anytype20946  /// into one which resolves the type directly on the referring20947  /// expression.  Strict preservation of the original source20948  /// structure is not a goal.20949  struct RebuildUnknownAnyExpr20950    : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {20951 20952    Sema &S;20953 20954    /// The current destination type.20955    QualType DestType;20956 20957    RebuildUnknownAnyExpr(Sema &S, QualType CastType)20958      : S(S), DestType(CastType) {}20959 20960    ExprResult VisitStmt(Stmt *S) {20961      llvm_unreachable("unexpected statement!");20962    }20963 20964    ExprResult VisitExpr(Expr *E) {20965      S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)20966        << E->getSourceRange();20967      return ExprError();20968    }20969 20970    ExprResult VisitCallExpr(CallExpr *E);20971    ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);20972 20973    /// Rebuild an expression which simply semantically wraps another20974    /// expression which it shares the type and value kind of.20975    template <class T> ExprResult rebuildSugarExpr(T *E) {20976      ExprResult SubResult = Visit(E->getSubExpr());20977      if (SubResult.isInvalid()) return ExprError();20978      Expr *SubExpr = SubResult.get();20979      E->setSubExpr(SubExpr);20980      E->setType(SubExpr->getType());20981      E->setValueKind(SubExpr->getValueKind());20982      assert(E->getObjectKind() == OK_Ordinary);20983      return E;20984    }20985 20986    ExprResult VisitParenExpr(ParenExpr *E) {20987      return rebuildSugarExpr(E);20988    }20989 20990    ExprResult VisitUnaryExtension(UnaryOperator *E) {20991      return rebuildSugarExpr(E);20992    }20993 20994    ExprResult VisitUnaryAddrOf(UnaryOperator *E) {20995      const PointerType *Ptr = DestType->getAs<PointerType>();20996      if (!Ptr) {20997        S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)20998          << E->getSourceRange();20999        return ExprError();21000      }21001 21002      if (isa<CallExpr>(E->getSubExpr())) {21003        S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)21004          << E->getSourceRange();21005        return ExprError();21006      }21007 21008      assert(E->isPRValue());21009      assert(E->getObjectKind() == OK_Ordinary);21010      E->setType(DestType);21011 21012      // Build the sub-expression as if it were an object of the pointee type.21013      DestType = Ptr->getPointeeType();21014      ExprResult SubResult = Visit(E->getSubExpr());21015      if (SubResult.isInvalid()) return ExprError();21016      E->setSubExpr(SubResult.get());21017      return E;21018    }21019 21020    ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);21021 21022    ExprResult resolveDecl(Expr *E, ValueDecl *VD);21023 21024    ExprResult VisitMemberExpr(MemberExpr *E) {21025      return resolveDecl(E, E->getMemberDecl());21026    }21027 21028    ExprResult VisitDeclRefExpr(DeclRefExpr *E) {21029      return resolveDecl(E, E->getDecl());21030    }21031  };21032}21033 21034/// Rebuilds a call expression which yielded __unknown_anytype.21035ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {21036  Expr *CalleeExpr = E->getCallee();21037 21038  enum FnKind {21039    FK_MemberFunction,21040    FK_FunctionPointer,21041    FK_BlockPointer21042  };21043 21044  FnKind Kind;21045  QualType CalleeType = CalleeExpr->getType();21046  if (CalleeType == S.Context.BoundMemberTy) {21047    assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));21048    Kind = FK_MemberFunction;21049    CalleeType = Expr::findBoundMemberType(CalleeExpr);21050  } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {21051    CalleeType = Ptr->getPointeeType();21052    Kind = FK_FunctionPointer;21053  } else {21054    CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();21055    Kind = FK_BlockPointer;21056  }21057  const FunctionType *FnType = CalleeType->castAs<FunctionType>();21058 21059  // Verify that this is a legal result type of a function.21060  if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||21061      DestType->isFunctionType()) {21062    unsigned diagID = diag::err_func_returning_array_function;21063    if (Kind == FK_BlockPointer)21064      diagID = diag::err_block_returning_array_function;21065 21066    S.Diag(E->getExprLoc(), diagID)21067      << DestType->isFunctionType() << DestType;21068    return ExprError();21069  }21070 21071  // Otherwise, go ahead and set DestType as the call's result.21072  E->setType(DestType.getNonLValueExprType(S.Context));21073  E->setValueKind(Expr::getValueKindForType(DestType));21074  assert(E->getObjectKind() == OK_Ordinary);21075 21076  // Rebuild the function type, replacing the result type with DestType.21077  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);21078  if (Proto) {21079    // __unknown_anytype(...) is a special case used by the debugger when21080    // it has no idea what a function's signature is.21081    //21082    // We want to build this call essentially under the K&R21083    // unprototyped rules, but making a FunctionNoProtoType in C++21084    // would foul up all sorts of assumptions.  However, we cannot21085    // simply pass all arguments as variadic arguments, nor can we21086    // portably just call the function under a non-variadic type; see21087    // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.21088    // However, it turns out that in practice it is generally safe to21089    // call a function declared as "A foo(B,C,D);" under the prototype21090    // "A foo(B,C,D,...);".  The only known exception is with the21091    // Windows ABI, where any variadic function is implicitly cdecl21092    // regardless of its normal CC.  Therefore we change the parameter21093    // types to match the types of the arguments.21094    //21095    // This is a hack, but it is far superior to moving the21096    // corresponding target-specific code from IR-gen to Sema/AST.21097 21098    ArrayRef<QualType> ParamTypes = Proto->getParamTypes();21099    SmallVector<QualType, 8> ArgTypes;21100    if (ParamTypes.empty() && Proto->isVariadic()) { // the special case21101      ArgTypes.reserve(E->getNumArgs());21102      for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {21103        ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));21104      }21105      ParamTypes = ArgTypes;21106    }21107    DestType = S.Context.getFunctionType(DestType, ParamTypes,21108                                         Proto->getExtProtoInfo());21109  } else {21110    DestType = S.Context.getFunctionNoProtoType(DestType,21111                                                FnType->getExtInfo());21112  }21113 21114  // Rebuild the appropriate pointer-to-function type.21115  switch (Kind) {21116  case FK_MemberFunction:21117    // Nothing to do.21118    break;21119 21120  case FK_FunctionPointer:21121    DestType = S.Context.getPointerType(DestType);21122    break;21123 21124  case FK_BlockPointer:21125    DestType = S.Context.getBlockPointerType(DestType);21126    break;21127  }21128 21129  // Finally, we can recurse.21130  ExprResult CalleeResult = Visit(CalleeExpr);21131  if (!CalleeResult.isUsable()) return ExprError();21132  E->setCallee(CalleeResult.get());21133 21134  // Bind a temporary if necessary.21135  return S.MaybeBindToTemporary(E);21136}21137 21138ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {21139  // Verify that this is a legal result type of a call.21140  if (DestType->isArrayType() || DestType->isFunctionType()) {21141    S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)21142      << DestType->isFunctionType() << DestType;21143    return ExprError();21144  }21145 21146  // Rewrite the method result type if available.21147  if (ObjCMethodDecl *Method = E->getMethodDecl()) {21148    assert(Method->getReturnType() == S.Context.UnknownAnyTy);21149    Method->setReturnType(DestType);21150  }21151 21152  // Change the type of the message.21153  E->setType(DestType.getNonReferenceType());21154  E->setValueKind(Expr::getValueKindForType(DestType));21155 21156  return S.MaybeBindToTemporary(E);21157}21158 21159ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {21160  // The only case we should ever see here is a function-to-pointer decay.21161  if (E->getCastKind() == CK_FunctionToPointerDecay) {21162    assert(E->isPRValue());21163    assert(E->getObjectKind() == OK_Ordinary);21164 21165    E->setType(DestType);21166 21167    // Rebuild the sub-expression as the pointee (function) type.21168    DestType = DestType->castAs<PointerType>()->getPointeeType();21169 21170    ExprResult Result = Visit(E->getSubExpr());21171    if (!Result.isUsable()) return ExprError();21172 21173    E->setSubExpr(Result.get());21174    return E;21175  } else if (E->getCastKind() == CK_LValueToRValue) {21176    assert(E->isPRValue());21177    assert(E->getObjectKind() == OK_Ordinary);21178 21179    assert(isa<BlockPointerType>(E->getType()));21180 21181    E->setType(DestType);21182 21183    // The sub-expression has to be a lvalue reference, so rebuild it as such.21184    DestType = S.Context.getLValueReferenceType(DestType);21185 21186    ExprResult Result = Visit(E->getSubExpr());21187    if (!Result.isUsable()) return ExprError();21188 21189    E->setSubExpr(Result.get());21190    return E;21191  } else {21192    llvm_unreachable("Unhandled cast type!");21193  }21194}21195 21196ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {21197  ExprValueKind ValueKind = VK_LValue;21198  QualType Type = DestType;21199 21200  // We know how to make this work for certain kinds of decls:21201 21202  //  - functions21203  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {21204    if (const PointerType *Ptr = Type->getAs<PointerType>()) {21205      DestType = Ptr->getPointeeType();21206      ExprResult Result = resolveDecl(E, VD);21207      if (Result.isInvalid()) return ExprError();21208      return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,21209                                 VK_PRValue);21210    }21211 21212    if (!Type->isFunctionType()) {21213      S.Diag(E->getExprLoc(), diag::err_unknown_any_function)21214        << VD << E->getSourceRange();21215      return ExprError();21216    }21217    if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {21218      // We must match the FunctionDecl's type to the hack introduced in21219      // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown21220      // type. See the lengthy commentary in that routine.21221      QualType FDT = FD->getType();21222      const FunctionType *FnType = FDT->castAs<FunctionType>();21223      const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);21224      DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);21225      if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {21226        SourceLocation Loc = FD->getLocation();21227        FunctionDecl *NewFD = FunctionDecl::Create(21228            S.Context, FD->getDeclContext(), Loc, Loc,21229            FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),21230            SC_None, S.getCurFPFeatures().isFPConstrained(),21231            false /*isInlineSpecified*/, FD->hasPrototype(),21232            /*ConstexprKind*/ ConstexprSpecKind::Unspecified);21233 21234        if (FD->getQualifier())21235          NewFD->setQualifierInfo(FD->getQualifierLoc());21236 21237        SmallVector<ParmVarDecl*, 16> Params;21238        for (const auto &AI : FT->param_types()) {21239          ParmVarDecl *Param =21240            S.BuildParmVarDeclForTypedef(FD, Loc, AI);21241          Param->setScopeInfo(0, Params.size());21242          Params.push_back(Param);21243        }21244        NewFD->setParams(Params);21245        DRE->setDecl(NewFD);21246        VD = DRE->getDecl();21247      }21248    }21249 21250    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))21251      if (MD->isInstance()) {21252        ValueKind = VK_PRValue;21253        Type = S.Context.BoundMemberTy;21254      }21255 21256    // Function references aren't l-values in C.21257    if (!S.getLangOpts().CPlusPlus)21258      ValueKind = VK_PRValue;21259 21260  //  - variables21261  } else if (isa<VarDecl>(VD)) {21262    if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {21263      Type = RefTy->getPointeeType();21264    } else if (Type->isFunctionType()) {21265      S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)21266        << VD << E->getSourceRange();21267      return ExprError();21268    }21269 21270  //  - nothing else21271  } else {21272    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)21273      << VD << E->getSourceRange();21274    return ExprError();21275  }21276 21277  // Modifying the declaration like this is friendly to IR-gen but21278  // also really dangerous.21279  VD->setType(DestType);21280  E->setType(Type);21281  E->setValueKind(ValueKind);21282  return E;21283}21284 21285ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,21286                                     Expr *CastExpr, CastKind &CastKind,21287                                     ExprValueKind &VK, CXXCastPath &Path) {21288  // The type we're casting to must be either void or complete.21289  if (!CastType->isVoidType() &&21290      RequireCompleteType(TypeRange.getBegin(), CastType,21291                          diag::err_typecheck_cast_to_incomplete))21292    return ExprError();21293 21294  // Rewrite the casted expression from scratch.21295  ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);21296  if (!result.isUsable()) return ExprError();21297 21298  CastExpr = result.get();21299  VK = CastExpr->getValueKind();21300  CastKind = CK_NoOp;21301 21302  return CastExpr;21303}21304 21305ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {21306  return RebuildUnknownAnyExpr(*this, ToType).Visit(E);21307}21308 21309ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,21310                                    Expr *arg, QualType &paramType) {21311  // If the syntactic form of the argument is not an explicit cast of21312  // any sort, just do default argument promotion.21313  ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());21314  if (!castArg) {21315    ExprResult result = DefaultArgumentPromotion(arg);21316    if (result.isInvalid()) return ExprError();21317    paramType = result.get()->getType();21318    return result;21319  }21320 21321  // Otherwise, use the type that was written in the explicit cast.21322  assert(!arg->hasPlaceholderType());21323  paramType = castArg->getTypeAsWritten();21324 21325  // Copy-initialize a parameter of that type.21326  InitializedEntity entity =21327    InitializedEntity::InitializeParameter(Context, paramType,21328                                           /*consumed*/ false);21329  return PerformCopyInitialization(entity, callLoc, arg);21330}21331 21332static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {21333  Expr *orig = E;21334  unsigned diagID = diag::err_uncasted_use_of_unknown_any;21335  while (true) {21336    E = E->IgnoreParenImpCasts();21337    if (CallExpr *call = dyn_cast<CallExpr>(E)) {21338      E = call->getCallee();21339      diagID = diag::err_uncasted_call_of_unknown_any;21340    } else {21341      break;21342    }21343  }21344 21345  SourceLocation loc;21346  NamedDecl *d;21347  if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {21348    loc = ref->getLocation();21349    d = ref->getDecl();21350  } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {21351    loc = mem->getMemberLoc();21352    d = mem->getMemberDecl();21353  } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {21354    diagID = diag::err_uncasted_call_of_unknown_any;21355    loc = msg->getSelectorStartLoc();21356    d = msg->getMethodDecl();21357    if (!d) {21358      S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)21359        << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()21360        << orig->getSourceRange();21361      return ExprError();21362    }21363  } else {21364    S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)21365      << E->getSourceRange();21366    return ExprError();21367  }21368 21369  S.Diag(loc, diagID) << d << orig->getSourceRange();21370 21371  // Never recoverable.21372  return ExprError();21373}21374 21375ExprResult Sema::CheckPlaceholderExpr(Expr *E) {21376  const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();21377  if (!placeholderType) return E;21378 21379  switch (placeholderType->getKind()) {21380  case BuiltinType::UnresolvedTemplate: {21381    auto *ULE = cast<UnresolvedLookupExpr>(E);21382    const DeclarationNameInfo &NameInfo = ULE->getNameInfo();21383    // There's only one FoundDecl for UnresolvedTemplate type. See21384    // BuildTemplateIdExpr.21385    NamedDecl *Temp = *ULE->decls_begin();21386    const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);21387 21388    NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();21389    // FIXME: AssumedTemplate is not very appropriate for error recovery here,21390    // as it models only the unqualified-id case, where this case can clearly be21391    // qualified. Thus we can't just qualify an assumed template.21392    TemplateName TN;21393    if (auto *TD = dyn_cast<TemplateDecl>(Temp))21394      TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),21395                                            TemplateName(TD));21396    else21397      TN = Context.getAssumedTemplateName(NameInfo.getName());21398 21399    Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)21400        << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;21401    Diag(Temp->getLocation(), diag::note_referenced_type_template)21402        << IsTypeAliasTemplateDecl;21403 21404    TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());21405    bool HasAnyDependentTA = false;21406    for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {21407      HasAnyDependentTA |= Arg.getArgument().isDependent();21408      TAL.addArgument(Arg);21409    }21410 21411    QualType TST;21412    {21413      SFINAETrap Trap(*this);21414      TST = CheckTemplateIdType(21415          ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,21416          /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);21417    }21418    if (TST.isNull())21419      TST = Context.getTemplateSpecializationType(21420          ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),21421          /*CanonicalArgs=*/{},21422          HasAnyDependentTA ? Context.DependentTy : Context.IntTy);21423    return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},21424                              TST);21425  }21426 21427  // Overloaded expressions.21428  case BuiltinType::Overload: {21429    // Try to resolve a single function template specialization.21430    // This is obligatory.21431    ExprResult Result = E;21432    if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))21433      return Result;21434 21435    // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization21436    // leaves Result unchanged on failure.21437    Result = E;21438    if (resolveAndFixAddressOfSingleOverloadCandidate(Result))21439      return Result;21440 21441    // If that failed, try to recover with a call.21442    tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),21443                         /*complain*/ true);21444    return Result;21445  }21446 21447  // Bound member functions.21448  case BuiltinType::BoundMember: {21449    ExprResult result = E;21450    const Expr *BME = E->IgnoreParens();21451    PartialDiagnostic PD = PDiag(diag::err_bound_member_function);21452    // Try to give a nicer diagnostic if it is a bound member that we recognize.21453    if (isa<CXXPseudoDestructorExpr>(BME)) {21454      PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;21455    } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {21456      if (ME->getMemberNameInfo().getName().getNameKind() ==21457          DeclarationName::CXXDestructorName)21458        PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;21459    }21460    tryToRecoverWithCall(result, PD,21461                         /*complain*/ true);21462    return result;21463  }21464 21465  // ARC unbridged casts.21466  case BuiltinType::ARCUnbridgedCast: {21467    Expr *realCast = ObjC().stripARCUnbridgedCast(E);21468    ObjC().diagnoseARCUnbridgedCast(realCast);21469    return realCast;21470  }21471 21472  // Expressions of unknown type.21473  case BuiltinType::UnknownAny:21474    return diagnoseUnknownAnyExpr(*this, E);21475 21476  // Pseudo-objects.21477  case BuiltinType::PseudoObject:21478    return PseudoObject().checkRValue(E);21479 21480  case BuiltinType::BuiltinFn: {21481    // Accept __noop without parens by implicitly converting it to a call expr.21482    auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());21483    if (DRE) {21484      auto *FD = cast<FunctionDecl>(DRE->getDecl());21485      unsigned BuiltinID = FD->getBuiltinID();21486      if (BuiltinID == Builtin::BI__noop) {21487        E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),21488                              CK_BuiltinFnToFnPtr)21489                .get();21490        return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,21491                                VK_PRValue, SourceLocation(),21492                                FPOptionsOverride());21493      }21494 21495      if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {21496        // Any use of these other than a direct call is ill-formed as of C++20,21497        // because they are not addressable functions. In earlier language21498        // modes, warn and force an instantiation of the real body.21499        Diag(E->getBeginLoc(),21500             getLangOpts().CPlusPlus2021501                 ? diag::err_use_of_unaddressable_function21502                 : diag::warn_cxx20_compat_use_of_unaddressable_function);21503        if (FD->isImplicitlyInstantiable()) {21504          // Require a definition here because a normal attempt at21505          // instantiation for a builtin will be ignored, and we won't try21506          // again later. We assume that the definition of the template21507          // precedes this use.21508          InstantiateFunctionDefinition(E->getBeginLoc(), FD,21509                                        /*Recursive=*/false,21510                                        /*DefinitionRequired=*/true,21511                                        /*AtEndOfTU=*/false);21512        }21513        // Produce a properly-typed reference to the function.21514        CXXScopeSpec SS;21515        SS.Adopt(DRE->getQualifierLoc());21516        TemplateArgumentListInfo TemplateArgs;21517        DRE->copyTemplateArgumentsInto(TemplateArgs);21518        return BuildDeclRefExpr(21519            FD, FD->getType(), VK_LValue, DRE->getNameInfo(),21520            DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),21521            DRE->getTemplateKeywordLoc(),21522            DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);21523      }21524    }21525 21526    Diag(E->getBeginLoc(), diag::err_builtin_fn_use);21527    return ExprError();21528  }21529 21530  case BuiltinType::IncompleteMatrixIdx:21531    Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())21532             ->getRowIdx()21533             ->getBeginLoc(),21534         diag::err_matrix_incomplete_index);21535    return ExprError();21536 21537  // Expressions of unknown type.21538  case BuiltinType::ArraySection:21539    // If we've already diagnosed something on the array section type, we21540    // shouldn't need to do any further diagnostic here.21541    if (!E->containsErrors())21542      Diag(E->getBeginLoc(), diag::err_array_section_use)21543          << cast<ArraySectionExpr>(E)->isOMPArraySection();21544    return ExprError();21545 21546  // Expressions of unknown type.21547  case BuiltinType::OMPArrayShaping:21548    return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));21549 21550  case BuiltinType::OMPIterator:21551    return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));21552 21553  // Everything else should be impossible.21554#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \21555  case BuiltinType::Id:21556#include "clang/Basic/OpenCLImageTypes.def"21557#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \21558  case BuiltinType::Id:21559#include "clang/Basic/OpenCLExtensionTypes.def"21560#define SVE_TYPE(Name, Id, SingletonId) \21561  case BuiltinType::Id:21562#include "clang/Basic/AArch64ACLETypes.def"21563#define PPC_VECTOR_TYPE(Name, Id, Size) \21564  case BuiltinType::Id:21565#include "clang/Basic/PPCTypes.def"21566#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:21567#include "clang/Basic/RISCVVTypes.def"21568#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:21569#include "clang/Basic/WebAssemblyReferenceTypes.def"21570#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:21571#include "clang/Basic/AMDGPUTypes.def"21572#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:21573#include "clang/Basic/HLSLIntangibleTypes.def"21574#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:21575#define PLACEHOLDER_TYPE(Id, SingletonId)21576#include "clang/AST/BuiltinTypes.def"21577    break;21578  }21579 21580  llvm_unreachable("invalid placeholder type!");21581}21582 21583bool Sema::CheckCaseExpression(Expr *E) {21584  if (E->isTypeDependent())21585    return true;21586  if (E->isValueDependent() || E->isIntegerConstantExpr(Context))21587    return E->getType()->isIntegralOrEnumerationType();21588  return false;21589}21590 21591ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,21592                                    ArrayRef<Expr *> SubExprs, QualType T) {21593  if (!Context.getLangOpts().RecoveryAST)21594    return ExprError();21595 21596  if (isSFINAEContext())21597    return ExprError();21598 21599  if (T.isNull() || T->isUndeducedType() ||21600      !Context.getLangOpts().RecoveryASTType)21601    // We don't know the concrete type, fallback to dependent type.21602    T = Context.DependentTy;21603 21604  return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);21605}21606