Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions .clang-tidy
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,12 @@ Checks: >-
readability-identifier-naming
WarningsAsErrors: '*'
HeaderFilterRegex: '(gecode|test|examples|tools)/'
ExcludeHeaderFilterRegex: 'gecode/third-party/|gecode/flatzinc/(parser\.tab\.(cpp|hpp)|lexer\.yy\.cpp)$'
ExcludeHeaderFilterRegex: 'gecode/flatzinc/(parser\.tab\.(cpp|hpp)|lexer\.yy\.cpp)$'
FormatStyle: file

CheckOptions:
# Explicit discards document intentional ownership handoffs.
bugprone-unused-return-value.AllowCastToVoid: true
# Shallow handles stay passed by value: a copy duplicates a few pointers or
# ids, with no reference count or allocation. See docs/code-style.md.
performance-unnecessary-value-param.AllowedTypes: '^Gecode::Float::ScaleView$'
readability-identifier-naming.FunctionCase: lower_case
readability-identifier-naming.MethodCase: lower_case
readability-identifier-naming.VariableCase: lower_case
Expand Down
3 changes: 1 addition & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -920,7 +920,7 @@ foreach(input ${GECODE_DOC_SOURCE_INPUTS})
endif()
endforeach()
list(APPEND GECODE_DOC_HELPER_INPUTS ${GECODE_VAR_TYPE_HPP} ${GECODE_VAR_IMP_HPP})
list(FILTER GECODE_DOC_HELPER_INPUTS EXCLUDE REGEX "/gecode/(third-party|gist/standalone-example|flatzinc/exampleplugin)/")
list(FILTER GECODE_DOC_HELPER_INPUTS EXCLUDE REGEX "/gecode/(gist/standalone-example|flatzinc/exampleplugin)/")
list(FILTER GECODE_DOC_HELPER_INPUTS EXCLUDE REGEX "/gecode/flatzinc/(parser\\.tab|lexer\\.)")
list(REMOVE_DUPLICATES GECODE_DOC_HELPER_INPUTS)

Expand Down Expand Up @@ -1650,7 +1650,6 @@ if(GECODE_INSTALL)
FILES_MATCHING
PATTERN "**.hh"
PATTERN "**.hpp"
PATTERN "LICENSE_1_0.txt"
PATTERN "mznlib" EXCLUDE
PATTERN "flatzinc/registry-internal.hh" EXCLUDE
PATTERN "flatzinc/blackbox.hh" EXCLUDE
Expand Down
60 changes: 60 additions & 0 deletions changelog.in
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,66 @@ make the set variables empty. Debug builds aborted with failed assertions.
Element over set variables, rel with union or disjoint union and a constant
set, and weights also post nothing for empty arrays.

[ENTRY]
Module: float
What: bug
Rank: major
[DESCRIPTION]
Keep directed rounding sound under compiler optimization. Float::Rounding
and FloatVal arithmetic could return a bound on the wrong side of the exact
result: optimizers folded constants in round-to-nearest, shared one square
root or quotient between both bounds, and fused the negated multiplication,
even in Clang Debug builds. Each operand and result now passes through an
optimization barrier, so neither Gecode nor applications need floating-point
compiler flags.
[MORE]
The barrier is an empty volatile asm statement with GCC and Clang, and a
volatile store and reload with other compilers. Integer rounding uses floor
and ceil, which do not depend on the rounding mode. The even-root bounds of
pow and nroot use the same rounding operations.

[ENTRY]
Module: float
What: change
Rank: major
[DESCRIPTION]
Implement interval arithmetic in Gecode itself, as the new type
Float::Interval with its free functions in namespace Gecode::Float. Gecode
no longer contains, or installs, its renamed copy of the Boost interval
library and Boost's LICENSE_1_0.txt, and it takes on no external dependency in
their place. Bounds, comparison results, and search behave exactly as
before. The empty-interval exception is still a std::runtime_error, but its
message is now "Gecode::Float::Interval: empty interval".
[MORE]
The interval code is Gecode code under Gecode's MIT license.

[ENTRY]
Module: float
What: change
Rank: major
[DESCRIPTION]
Make Float::RoundingBase and Float::Rounding plain Gecode classes. Their
arithmetic members are unchanged. RoundingBase no longer derives from a Boost
rounding class: init, upward, downward, and to_nearest are now protected,
and toward_zero, get_rounding_mode, set_rounding_mode, to_int, conv_down,
conv_up, force_rounding, and rounding_mode are gone. Rounding is a scope that
saves the caller's rounding mode and restores it; it cannot be copied and no
longer has the mode member or unprotected_rounding typedef of Boost's
save_state. The typedef RoundingControl is gone, FloatVal::FloatValImpType is
now Float::Interval, and FloatVal's protected typedefs R and P are gone.

[ENTRY]
Module: float
What: change
Rank: major
[DESCRIPTION]
Make FloatVal trivially copyable. Its layout is unchanged, but on AArch64 and
SysV x86-64 it is now passed and returned by value in registers instead of
through memory. A program built against older headers must be rebuilt: the
symbol names are unchanged, so the dynamic linker does not catch the
mismatch. Two exported functions take a FloatVal by value and are affected:
FloatValArgs::create and Float::Linear::post.

[ENTRY]
Module: search
What: bug
Expand Down
1 change: 1 addition & 0 deletions cmake/GecodeSources.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,7 @@ set(GECODE_TEST_SOURCES
test/float/basic.cpp
test/float/channel.cpp
test/float/dom.cpp
test/float/interval.cpp
test/float/linear.cpp
test/float/mm-lin.cpp
test/float/rel.cpp
Expand Down
10 changes: 4 additions & 6 deletions docs/code-style.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Use clang-format **22** for first-party C and C++ sources. `.clang-format`
defines the exact formatting; `.editorconfig` supplies the matching editor
defaults. Keep upstream third-party files in their original style.
defaults.

## Formatting

Expand Down Expand Up @@ -130,14 +130,12 @@ on), the variable arrays and `ViewArray`, the open variable and view lists,
with no reference count or allocation, and Gecode code relies on their value
semantics. Keep them so: define no copy member, move member, or destructor
for a handle that only copies its members, or default it on its first
declaration. `test/array.cpp` asserts the property. The check's
`AllowedTypes` lists only `Float::ScaleView`, a view that is not trivially
copyable because its `FloatVal` member is not. Owned and reference-counted
declaration. `test/array.cpp` asserts the property. Owned and reference-counted
types are not exempt: `SharedHandle` types such as `IntSet`, `TupleSet`,
`DFA`, `Rnd`, `Action`, and `CHB`, `SharedArray`, the `*Args` arrays, `REG`,
strings, and callbacks. Their copies touch a reference count or allocate, so
they follow the rule above. `FloatVal` is not exempt either: it is two
doubles, not a handle.
they follow the rule above. `FloatVal` is trivially copyable, so the check
does not report it, but it is two doubles, not a handle: pass it by `const&`.

Special members follow the rule of zero: a class whose members copy, move,
and destroy themselves declares no copy member, move member, or destructor.
Expand Down
1 change: 0 additions & 1 deletion doxygen/doxygen.conf.in
Original file line number Diff line number Diff line change
Expand Up @@ -520,7 +520,6 @@ EXCLUDE_PATTERNS = \
*.svn/* \
*moc_* \
*gecode/gist/standalone-example/* \
*gecode/third-party/* \
*gecode/flatzinc/exampleplugin/* \
*gecode/flatzinc/parser.tab.* *gecode/flatzinc/lexer.*

Expand Down
131 changes: 109 additions & 22 deletions gecode/float.hh
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,12 @@
#ifndef GECODE_FLOAT_HH
#define GECODE_FLOAT_HH

#include <cfenv>
#include <climits>
#include <cfloat>
#include <cmath>
#include <iostream>
#include <limits>

#include <functional>

Expand Down Expand Up @@ -68,8 +71,21 @@

#endif

// Include interval implementation
#include <gecode/third-party/boost/numeric/interval.hpp>
/*
* Configure rounding control
*
*/

// cl.exe on x86 and x64 sets the rounding mode with _control87. clang-cl
// defines __x86_64__ and uses <cfenv> like every other compiler.
#if defined(_MSC_VER) && !defined(__x86_64__) && (defined(_M_X64) || defined(_M_IX86))
#define GECODE_FLOAT_MODE_CONTROL87
#include <float.h>
#endif
// MSVC on x64, or on x86 with SSE, sets the direction in every operation.
#if defined(_MSC_VER) && (defined(_M_X64) || (defined(_M_IX86_FP) && (_M_IX86_FP > 0)))
#define GECODE_FLOAT_DIRECTED_PER_OPERATION
#endif

/**
* \namespace Gecode::Float
Expand Down Expand Up @@ -127,21 +143,79 @@ namespace Gecode {

namespace Gecode { namespace Float {

/*
* All compilers, MSVC included, keep upward mode between calls. The
* downward operations negate an operand, which negate_opaque in
* rounded_arith.hpp keeps from being folded into the rounded operation.
*
*/
/// Rounding operations that keep upward mode between calls
typedef gecode_boost::numeric::interval_lib::rounded_arith_opp<FloatNum> RoundingControl;

/**
* \brief Floating point rounding operations without state saving
*
* Every lower bound is rounded toward \f$-\infty\f$ and every upper bound
* toward \f$+\infty\f$, also when the compiler optimizes and when the
* operands are compile-time constants.
*
* Neither Gecode nor applications need floating-point compiler flags or
* pragmas for this: no `-frounding-math`, `-ffp-model=strict`,
* `/fp:strict`, or `#pragma STDC FENV_ACCESS`. Compilers assume
* round-to-nearest without them, so each operand and each result of the
* arithmetic operations passes through barrier(). With GCC and Clang the
* barrier is an empty `__asm__ __volatile__` statement with the value as a
* floating-point register operand (`"+w"` on AArch64, `"+x"` on x86-64).
* Other compilers, including MSVC, use a volatile store and reload. The
* barrier hides the value from the optimizer, so constants are not
* folded, one result is not shared between the two directions, a negation
* is not fused into the operation, and no operation moves across a
* rounding-mode change. This relies on GCC and Clang keeping volatile
* `asm` statements, and every compiler keeping volatile accesses, in
* order with the opaque calls that change the mode (`fesetround` or
* `_control87`). IEEE binary64 arithmetic in SSE2 or AArch64 registers is
* assumed; x87 arithmetic and `-ffast-math` are not supported.
*
* The rounding mode is read and set with `std::fegetround` and
* `std::fesetround`. Under GECODE_FLOAT_MODE_CONTROL87 (cl.exe on x86 and
* x64) it is read and set with `_control87`, which also masks all
* floating-point exceptions while Gecode sets a mode and, on x86, selects
* 64-bit precision and affine infinity; restoring a mode writes back the
* caller's bits. Without GECODE_FLOAT_DIRECTED_PER_OPERATION, the mode
* stays upward between operations. An upper bound is computed directly,
* and a lower bound as the negated upper bound of the negated operation;
* sqrt_down() and median() switch the mode and switch back to upward.
* With it (MSVC on x64, or on x86 with SSE), each operation sets its own
* direction. int_down() and int_up() use `std::floor` and `std::ceil`,
* which do not depend on the mode.
*
* The test Float::Arithmetic::DirectedRounding checks the bounds with
* literal and runtime operands under every caller mode.
*
* \ingroup TaskModelFloatVars
*/
class RoundingBase : public RoundingControl {
class RoundingBase {
protected:
/// \name Rounding mode control
//@{
#ifdef GECODE_FLOAT_MODE_CONTROL87
/// Floating-point control word, as returned by `_control87`
typedef unsigned int Mode;
#else
/// Rounding mode, one of the `FE_*` values of `<cfenv>`
typedef int Mode;
#endif
/// Return the current rounding mode
static Mode current_mode(void);
/// Restore mode \a m, as returned by current_mode()
static void restore_mode(Mode m);
/// Round toward \f$+\infty\f$
static void upward(void);
/// Round toward \f$-\infty\f$
static void downward(void);
/// Round to nearest
static void to_nearest(void);
/// Set the mode that the arithmetic operations expect between calls
static void init(void);
//@}

private:
/// Return \a x unchanged, hidden from the optimizer (see the class comment)
static FloatNum barrier(FloatNum x);
/// Return the midpoint of \a x and \a y, rounded to nearest
static FloatNum nearest_median(FloatNum x, FloatNum y);

public:
/// \name Arithmetic operations
//@{
Expand Down Expand Up @@ -257,17 +331,35 @@ namespace Gecode { namespace Float {
};

/**
* \brief Floating point rounding policy that restores the caller's mode
* \brief Scope of floating point rounding operations
*
* Saves the mode before initializing rounding operations and restores it
* on destruction. Nested policies restore the enclosing policy's mode.
* Saves the caller's rounding mode and initializes the rounding
* operations on construction, and restores the saved mode on destruction,
* also when an operation throws. Nested scopes restore the enclosing
* scope's mode. A copy would restore the mode a second time, so a scope
* cannot be copied.
* \ingroup TaskModelFloatVars
*/
class Rounding : public gecode_boost::numeric::interval_lib::save_state<RoundingBase> {};
class Rounding : public RoundingBase {
private:
/// The caller's rounding mode
Mode saved;

public:
/// Save the caller's mode and initialize the rounding operations
Rounding(void);
/// Restore the caller's mode
~Rounding(void);
/// A scope cannot be copied
Rounding(const Rounding&) = delete;
/// A scope cannot be assigned
Rounding& operator=(const Rounding&) = delete;
};

}} // namespace Gecode::Float

#include <gecode/float/rounding.hpp>
#include <gecode/float/interval.hpp>

namespace Gecode { namespace Float {

Expand Down Expand Up @@ -403,13 +495,8 @@ namespace Gecode {
friend FloatVal Float::hull(const FloatNum& x, const FloatNum& y);

protected:
/// Used rounding policies
typedef Float::Rounding R;
/// Used checking policy
typedef gecode_boost::numeric::interval_lib::checking_strict<FloatNum> P;
/// Implementation type for float value
typedef gecode_boost::numeric::interval<FloatNum, gecode_boost::numeric::interval_lib::policies<R, P>>
FloatValImpType;
typedef Float::Interval FloatValImpType;
/// Implementation of float value
FloatValImpType x;
/// Initialize from implementation \a i
Expand Down
4 changes: 1 addition & 3 deletions gecode/float/arithmetic/pow-nroot.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ namespace Gecode { namespace Float { namespace Arithmetic {
/// Return a downward-rounded positive integer power
forceinline FloatNum
positive_pow_down(FloatNum x, int n) {
typedef gecode_boost::numeric::interval_lib::rounded_arith_std<FloatNum> DirectRoundingBase;
typedef gecode_boost::numeric::interval_lib::save_state<DirectRoundingBase> DirectRounding;
DirectRounding r;
Rounding r;
FloatNum y = 1.0;
while (n > 0) {
if ((n & 1) != 0)
Expand Down
Loading
Loading