Override substitution type range failures in IR

This validation should only trigger failure for when running without
the dawn pipeline (ie tint end2end tests). Some code was moved to the
utility library to avoid excessive duplication of source [1].


[1]
https://source.chromium.org/chromium/chromium/src/+/main:third_party/dawn/src/dawn/native/Pipeline.cpp;l=135?q=pipeline.cpp&ss=chromium

Bug: 397479777
Change-Id: I62b6c1c1de61b1833eca818128436a48ee6d4e98
Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/226994
Commit-Queue: Peter McNeeley <petermcneeley@google.com>
Reviewed-by: dan sinclair <dsinclair@chromium.org>
diff --git a/src/dawn/common/Numeric.h b/src/dawn/common/Numeric.h
index 38633bd..4488136 100644
--- a/src/dawn/common/Numeric.h
+++ b/src/dawn/common/Numeric.h
@@ -65,20 +65,6 @@
     return static_cast<Dst>(value);
 }
 
-template <typename T>
-bool IsDoubleValueRepresentable(double value) {
-    if constexpr (std::is_same_v<T, float> || std::is_integral_v<T>) {
-        // Following WebIDL 3.3.6.[EnforceRange] for integral
-        // Following WebIDL 3.2.5.float for float
-        // TODO(crbug.com/1396194): now follows what blink does but may need revisit.
-        constexpr double kLowest = static_cast<double>(std::numeric_limits<T>::lowest());
-        constexpr double kMax = static_cast<double>(std::numeric_limits<T>::max());
-        return kLowest <= value && value <= kMax;
-    } else {
-        static_assert(std::is_same_v<T, float> || std::is_integral_v<T>, "Unsupported type");
-    }
-}
-
 // Returns if two inclusive integral ranges [x0, x1] and [y0, y1] have overlap.
 template <typename T>
 bool RangesOverlap(T x0, T x1, T y0, T y1) {
diff --git a/src/dawn/native/Pipeline.cpp b/src/dawn/native/Pipeline.cpp
index 46c7e36..43c170e 100644
--- a/src/dawn/native/Pipeline.cpp
+++ b/src/dawn/native/Pipeline.cpp
@@ -40,14 +40,7 @@
 #include "dawn/native/ObjectContentHasher.h"
 #include "dawn/native/PipelineLayout.h"
 #include "dawn/native/ShaderModule.h"
-
-namespace {
-bool IsDoubleValueRepresentableAsF16(double value) {
-    constexpr double kLowestF16 = -65504.0;
-    constexpr double kMaxF16 = 65504.0;
-    return kLowestF16 <= value && value <= kMaxF16;
-}
-}  // namespace
+#include "src/utils/numeric.h"
 
 namespace dawn::native {
 ResultOrError<ShaderModuleEntryPoint> ValidateProgrammableStage(DeviceBase* device,
diff --git a/src/tint/lang/core/ir/transform/substitute_overrides.cc b/src/tint/lang/core/ir/transform/substitute_overrides.cc
index 2923c25..c4168bd 100644
--- a/src/tint/lang/core/ir/transform/substitute_overrides.cc
+++ b/src/tint/lang/core/ir/transform/substitute_overrides.cc
@@ -27,10 +27,12 @@
 
 #include "src/tint/lang/core/ir/transform/substitute_overrides.h"
 
+#include <cstdint>
 #include <functional>
 #include <utility>
 
 #include "src/tint/lang/core/binary_op.h"
+#include "src/tint/lang/core/fluent_types.h"
 #include "src/tint/lang/core/ir/binary.h"
 #include "src/tint/lang/core/ir/builder.h"
 #include "src/tint/lang/core/ir/const_param_validator.h"
@@ -46,6 +48,7 @@
 #include "src/tint/lang/core/ir/validator.h"
 #include "src/tint/lang/core/ir/value.h"
 #include "src/tint/utils/result/result.h"
+#include "src/utils/numeric.h"
 
 using namespace tint::core::fluent_types;     // NOLINT
 using namespace tint::core::number_suffixes;  // NOLINT
@@ -96,6 +99,33 @@
             // Check if the user provided an override for the given ID.
             auto iter = cfg.map.find(override->OverrideId());
             if (iter != cfg.map.end()) {
+                bool substitution_representation_valid = tint::Switch(
+                    override->Result(0)->Type(),  //
+                    [&](const core::type::Bool*) { return true; },
+                    [&](const core::type::I32*) {
+                        return dawn::IsDoubleValueRepresentable<int32_t>(iter->second);
+                    },
+                    [&](const core::type::U32*) {
+                        return dawn::IsDoubleValueRepresentable<uint32_t>(iter->second);
+                    },
+                    [&](const core::type::F32*) {
+                        return dawn::IsDoubleValueRepresentable<float>(iter->second);
+                    },
+                    [&](const core::type::F16*) {
+                        return dawn::IsDoubleValueRepresentableAsF16(iter->second);
+                    },
+                    TINT_ICE_ON_NO_MATCH);
+
+                if (!substitution_representation_valid) {
+                    diag::Diagnostic error{};
+                    error.severity = diag::Severity::Error;
+                    error.source = ir.SourceOf(override);
+                    error << "Pipeline overridable constant " << iter->first.value
+                          << " with value (" << iter->second << ")  is not representable in type ("
+                          << override->Result(0)->Type()->FriendlyName() << ")";
+                    return Failure(error);
+                }
+
                 auto* replacement = CreateConstant(override->Result(0)->Type(), iter->second);
                 override->SetInitializer(replacement);
             }
diff --git a/src/tint/lang/core/ir/transform/substitute_overrides_test.cc b/src/tint/lang/core/ir/transform/substitute_overrides_test.cc
index c13ce75..65a2f10 100644
--- a/src/tint/lang/core/ir/transform/substitute_overrides_test.cc
+++ b/src/tint/lang/core/ir/transform/substitute_overrides_test.cc
@@ -1574,5 +1574,93 @@
     EXPECT_EQ(expect, str());
 }
 
+TEST_F(IR_SubstituteOverridesTest, OverrideInvalidRepresentationU32) {
+    b.Append(mod.root_block, [&] {
+        auto* x = b.Override("x", ty.u32());
+        x->SetOverrideId({2});
+    });
+    auto* src = R"(
+$B1: {  # root
+  %x:u32 = override @id(2)
+}
+
+)";
+    EXPECT_EQ(src, str());
+
+    SubstituteOverridesConfig cfg{};
+    cfg.map[OverrideId{2}] = -100.0;
+    auto result = RunWithFailure(SubstituteOverrides, cfg);
+    ASSERT_NE(result, Success);
+    EXPECT_EQ(
+        result.Failure().reason.Str(),
+        R"(error: Pipeline overridable constant 2 with value (-100.0)  is not representable in type (u32))");
+}
+
+TEST_F(IR_SubstituteOverridesTest, OverrideInvalidRepresentationI32) {
+    b.Append(mod.root_block, [&] {
+        auto* x = b.Override("x", ty.i32());
+        x->SetOverrideId({2});
+    });
+    auto* src = R"(
+$B1: {  # root
+  %x:i32 = override @id(2)
+}
+
+)";
+    EXPECT_EQ(src, str());
+
+    SubstituteOverridesConfig cfg{};
+    cfg.map[OverrideId{2}] = 8'000'000'000.0;
+    auto result = RunWithFailure(SubstituteOverrides, cfg);
+    ASSERT_NE(result, Success);
+    EXPECT_EQ(
+        result.Failure().reason.Str(),
+        R"(error: Pipeline overridable constant 2 with value (8000000000.0)  is not representable in type (i32))");
+}
+
+TEST_F(IR_SubstituteOverridesTest, OverrideInvalidRepresentationF32) {
+    b.Append(mod.root_block, [&] {
+        auto* x = b.Override("x", ty.f32());
+        x->SetOverrideId({2});
+    });
+    auto* src = R"(
+$B1: {  # root
+  %x:f32 = override @id(2)
+}
+
+)";
+    EXPECT_EQ(src, str());
+
+    SubstituteOverridesConfig cfg{};
+    cfg.map[OverrideId{2}] = 3.14e40;
+    auto result = RunWithFailure(SubstituteOverrides, cfg);
+    ASSERT_NE(result, Success);
+    EXPECT_EQ(
+        result.Failure().reason.Str(),
+        R"(error: Pipeline overridable constant 2 with value (31399999999999998802000170346751583059968.0)  is not representable in type (f32))");
+}
+
+TEST_F(IR_SubstituteOverridesTest, OverrideInvalidRepresentationF16) {
+    b.Append(mod.root_block, [&] {
+        auto* x = b.Override("x", ty.f16());
+        x->SetOverrideId({2});
+    });
+    auto* src = R"(
+$B1: {  # root
+  %x:f16 = override @id(2)
+}
+
+)";
+    EXPECT_EQ(src, str());
+
+    SubstituteOverridesConfig cfg{};
+    cfg.map[OverrideId{2}] = 65505;
+    auto result = RunWithFailure(SubstituteOverrides, cfg);
+    ASSERT_NE(result, Success);
+    EXPECT_EQ(
+        result.Failure().reason.Str(),
+        R"(error: Pipeline overridable constant 2 with value (65505.0)  is not representable in type (f16))");
+}
+
 }  // namespace
 }  // namespace tint::core::ir::transform
diff --git a/src/utils/BUILD.bazel b/src/utils/BUILD.bazel
index 23139e0..d559500 100644
--- a/src/utils/BUILD.bazel
+++ b/src/utils/BUILD.bazel
@@ -31,6 +31,7 @@
   name = "utils",
   hdrs = [
     "compiler.h",
+    "numeric.h",
   ],
   srcs = [
     "placeholder.cc",
diff --git a/src/utils/BUILD.gn b/src/utils/BUILD.gn
index 8ed9784..3de8f1b 100644
--- a/src/utils/BUILD.gn
+++ b/src/utils/BUILD.gn
@@ -38,6 +38,7 @@
 static_library("utils") {
   sources = [
     "compiler.h",
+    "numeric.h",
     "placeholder.cc",
   ]
 
diff --git a/src/utils/CMakeLists.txt b/src/utils/CMakeLists.txt
index 5e177b4..9cdd2e9 100644
--- a/src/utils/CMakeLists.txt
+++ b/src/utils/CMakeLists.txt
@@ -27,6 +27,7 @@
 
 set(private_headers
     "compiler.h"
+    "numeric.h"
 )
 
 set(sources
diff --git a/src/utils/numeric.h b/src/utils/numeric.h
new file mode 100644
index 0000000..a0015fa
--- /dev/null
+++ b/src/utils/numeric.h
@@ -0,0 +1,56 @@
+// Copyright 2025 The Dawn & Tint Authors
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice, this
+//    list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright notice,
+//    this list of conditions and the following disclaimer in the documentation
+//    and/or other materials provided with the distribution.
+//
+// 3. Neither the name of the copyright holder nor the names of its
+//    contributors may be used to endorse or promote products derived from
+//    this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef SRC_UTILS_NUMERIC_H_
+#define SRC_UTILS_NUMERIC_H_
+
+#include <limits>
+#include <type_traits>
+
+namespace dawn {
+template <typename T>
+bool inline IsDoubleValueRepresentable(double value) {
+    if constexpr (std::is_same_v<T, float> || std::is_integral_v<T>) {
+        // Following WebIDL 3.3.6.[EnforceRange] for integral
+        // Following WebIDL 3.2.5.float for float
+        // TODO(crbug.com/1396194): now follows what blink does but may need revisit.
+        constexpr double kLowest = static_cast<double>(std::numeric_limits<T>::lowest());
+        constexpr double kMax = static_cast<double>(std::numeric_limits<T>::max());
+        return kLowest <= value && value <= kMax;
+    } else {
+        static_assert(std::is_same_v<T, float> || std::is_integral_v<T>, "Unsupported type");
+    }
+}
+
+inline bool IsDoubleValueRepresentableAsF16(double value) {
+    constexpr double kLowestF16 = -65504.0;
+    constexpr double kMaxF16 = 65504.0;
+    return kLowestF16 <= value && value <= kMaxF16;
+}
+}  // namespace dawn
+
+#endif  // SRC_UTILS_NUMERIC_H_