This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Safe integer overflows in C++


Hello,

I'm writing a library in C++ for decimal fixed-point arithmetic. Basically,
any suitable decimal fraction q is scaled by 10^k with k selected in such a
way that q * 10^k is an integral value stored in std::int64_t. This allows me
to perform basic arithmetic operations on such scaled fractions using
integral arithmetic only, which results in extremely fast code. Performance
is of crucial importance here and the values rarely exceed the
capacity of std::int64_t
so I can't use GMP or similar libraries.

However, signed overflows are considered UB in C and C++, so my library
doesn't need to be portable beyond the "sane" platform set -- U2, 2^n encodings
with 32- and 64-bit fundamental types. I know that GCC does a lot to detect
overflow-related errors, as they are mostly bugs. But in this case I
know exactly
what's happening under the hood, so assuming the above caveats, the question
is how to perform overflowing integral arithmetic in GCC more or less
safely, e.g.:

std::int64_t x = ..., y = ...;
std::int64_t z = x + y; // may overflow!

if (overflow) {

    // enter slow correction path

} else {

    // fast path
}

and how to detect that addition/subtraction has overflowed.
Are there any pragmas or built-ins related to the above issue?

As a last resort I can use GCC inline assembly, but since the set of
target platforms is relatively big (x86, x86, SPARC, POWER, Itanium),
I'd rather want to use a semi-portable gnu++0x-based solution.

    Best regards,
    Piotr Wyderski


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]