[Clang][Sema] Do not evaluate value-dependent immediate invocations
authorEvgeny Shulgin <izaronplatz@gmail.com>
Fri, 25 Feb 2022 15:55:08 +0000 (16:55 +0100)
committerCorentin Jabot <corentinjabot@gmail.com>
Fri, 25 Feb 2022 16:23:36 +0000 (17:23 +0100)
Value-dependent ConstantExprs are not meant to be evaluated.
There is an assert in Expr::EvaluateAsConstantExpr that ensures this condition.
But before this patch the method was called without prior check.

Fixes https://github.com/llvm/llvm-project/issues/52768

Reviewed By: erichkeane

Differential Revision: https://reviews.llvm.org/D119375

clang/lib/Sema/SemaExpr.cpp
clang/test/SemaCXX/cxx2a-consteval.cpp

index 454e21e..b24caa5 100644 (file)
@@ -16817,7 +16817,10 @@ ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
       ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
                                    getASTContext()),
       /*IsImmediateInvocation*/ true);
-  ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
+  /// Value-dependent constant expressions should not be immediately
+  /// evaluated until they are instantiated.
+  if (!Res->isValueDependent())
+    ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
   return Res;
 }
 
index e909f2f..941d47d 100644 (file)
@@ -613,6 +613,32 @@ static_assert(is_same<long, T>::value);
 
 } // namespace unevaluated
 
+namespace value_dependent {
+
+consteval int foo(int x) {
+  return x;
+}
+
+template <int X> constexpr int bar() {
+  // Previously this call was rejected as value-dependent constant expressions
+  // can't be immediately evaluated. Now we show that we don't immediately
+  // evaluate them until they are instantiated.
+  return foo(X);
+}
+
+template <typename T> constexpr int baz() {
+  constexpr int t = sizeof(T);
+  // Previously this call was rejected as `t` is value-dependent and its value
+  // is unknown until the function is instantiated. Now we show that we don't
+  // reject such calls.
+  return foo(t);
+}
+
+static_assert(bar<15>() == 15);
+static_assert(baz<int>() == sizeof(int));
+
+} // namespace value_dependent
+
 namespace PR50779 {
 struct derp {
   int b = 0;