[flang] Complete refactor of Fold() - checkpoint

Original-commit: flang-compiler/f18@5061171268ef6a4552aa365642d3f5ad120f871f
Reviewed-on: https://github.com/flang-compiler/f18/pull/219
Tree-same-pre-rewrite: false
diff --git a/flang/lib/evaluate/intrinsics.cc b/flang/lib/evaluate/intrinsics.cc
index 486ea4b..872b46f 100644
--- a/flang/lib/evaluate/intrinsics.cc
+++ b/flang/lib/evaluate/intrinsics.cc
@@ -14,6 +14,7 @@
 
 #include "intrinsics.h"
 #include "expression.h"
+#include "tools.h"
 #include "type.h"
 #include "../common/enum-set.h"
 #include "../common/fortran.h"
@@ -1057,15 +1058,12 @@
       CHECK(kindDummyArg != nullptr);
       CHECK(result.categorySet == CategorySet{resultType->category});
       if (kindArg != nullptr) {
-        if (auto *jExpr{std::get_if<Expr<SomeInteger>>(&kindArg->value->u)}) {
-          CHECK(jExpr->Rank() == 0);
-          if (auto value{jExpr->ScalarValue()}) {
-            if (auto code{value->ToInt64()}) {
-              if (IsValidKindOfIntrinsicType(resultType->category, *code)) {
-                resultType->kind = *code;
-                break;
-              }
-            }
+        auto &expr{*kindArg->value};
+        CHECK(expr.Rank() == 0);
+        if (auto code{ToInt64(expr)}) {
+          if (IsValidKindOfIntrinsicType(resultType->category, *code)) {
+            resultType->kind = *code;
+            break;
           }
         }
         messages.Say("'kind=' argument must be a constant scalar integer "