[flang-commits] [flang] [clang-tools-extra] [lld] [clang] [libcxx] [lldb] [compiler-rt] [mlir] [llvm] [libc++][numeric] P0543R3: Saturation arithmetic (PR #77967)
Nikolas Klauser via flang-commits
flang-commits at lists.llvm.org
Sun Jan 14 03:24:08 PST 2024
================
@@ -0,0 +1,130 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20, c++23
+
+// <numeric>
+
+// template<class T>
+// constexpr T div_sat(T x, T y) noexcept; // freestanding
+
+#include <cassert>
+#include <concepts>
+#include <limits>
+#include <numeric>
+
+#include "check_constexpr.h"
+
+template <typename IntegerT>
+constexpr bool test_signed() {
+ constexpr auto minVal = std::numeric_limits<IntegerT>::min();
+ constexpr auto maxVal = std::numeric_limits<IntegerT>::max();
+
+ static_assert(noexcept(std::div_sat(minVal, maxVal)));
+
+ // No saturation
+ {
+ std::same_as<IntegerT> decltype(auto) quot = std::div_sat(IntegerT{3}, IntegerT{4});
+ assert(quot == IntegerT{0});
+ }
+
+ {
+ std::same_as<IntegerT> decltype(auto) quot = std::div_sat(maxVal, minVal);
+ assert(quot == (maxVal / minVal));
+ }
+
+ {
+ std::same_as<IntegerT> decltype(auto) quot = std::div_sat(minVal, maxVal);
+ assert(quot == (minVal / maxVal));
+ }
+
+ // Saturation - max only
+ {
+ std::same_as<IntegerT> decltype(auto) quot = std::div_sat(minVal, IntegerT{-1});
+ assert(quot == maxVal);
+ }
+
+ return true;
+}
+
+template <typename IntegerT>
+constexpr bool test_unsigned() {
+ constexpr auto minVal = std::numeric_limits<IntegerT>::min();
+ constexpr auto maxVal = std::numeric_limits<IntegerT>::max();
+
+ static_assert(noexcept(std::div_sat(minVal, maxVal)));
+
+ // No saturation
+ {
+ std::same_as<IntegerT> decltype(auto) quot = std::div_sat(IntegerT{3}, IntegerT{4});
+ assert(quot == IntegerT{0});
+ }
+
+ {
+ std::same_as<IntegerT> decltype(auto) quot = std::div_sat(minVal, maxVal);
+ assert(quot == (minVal / maxVal));
+ }
+
+ // Unsigned integer devision never overflow
+
+ return true;
+}
+
+template <typename IntegerT>
+void test_constexpr() {
+ TEST_EXPRESSION_CONSTEXPR(std::div_sat(IntegerT{90}, IntegerT{84}));
+ TEST_EXPRESSION_NOT_CONSTEXPR(std::div_sat(IntegerT{90}, IntegerT{0}));
----------------
philnik777 wrote:
We don't want to test the compiler in our tests. There is no need to check that division by zero results in an expression that's not constant AFAICT. The check for the `constexpr` expression can simply be tested by putting it into a scope that is forced to be constant evaluated.
https://github.com/llvm/llvm-project/pull/77967
More information about the flang-commits
mailing list