3 ms·
I won't be able to use them in portable code anytime soon, but the new feature here that most interests me is __builtin_add_overflow, __builtin_sub_overflow and
by ploxiln 12y ago
I won't be able to use them in portable code anytime soon, but the new feature here that most interests me is __builtin_add_overflow, __builtin_sub_overflow and __builtin_mul_overflow
"These builtins have two integral arguments (which don't need to have the same type), the arguments are extended to infinite precision signed type, +, - or * is performed on those, and the result is stored in an integer variable pointed to by the last argument. If the stored value is equal to the infinite precision result, the built-in functions return false, otherwise true. The type of the integer variable that will hold the result can be different from the types of the first two arguments."
Handling all possible integer overflow with plain C is annoyingly tricky and for some critical paths in-efficient. These built-ins can often do a conditional jump based on the overflow bit in the flags register.
- mikeash 12y agoSounds useful for wrappers, where you could conditionally compile to use either these builtins, or the annoying, potentially slow, portable versions.
- cremno 12y agoSadly clang (the origin of those built-in functions) doesn't implement the type-generic ones and GCC doesn't implement __has_builtin yet.
- Someone 12y agoThat may be sooner than you think, depending on what you mean by portable. I think these functions originated as non-generic versions in clang (http://clang.llvm.org/docs/LanguageExtensions.html#builtin-functions http://clang.llvm.org/docs/LanguageExtensions.html#builtin-f...). gcc copied them and now added generic variants. I think it is likely that clang will now copy gcc and add the generic variants. Edit: here is the request for gcc to copy clang: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59708 https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59708 (nice discussion about the need to have builtins for overflow detection) And here is a request for clang to copy gcc's generic versions: https://llvm.org/bugs/show_bug.cgi?id=21716 https://llvm.org/bugs/show_bug.cgi?id=21716
- madez 12y agoThis is a good example of how competition is contribution.
- yuhong 12y agoThere is also _addcarry_u32 and _subcarry_u32
- rurban 12y agoI use them for some time now with +#if (defined(__clang__) && ((__clang_major__ > 3) \ + || (__clang_major__ == 3 && __clang_minor__ >= 4))) \ + || (defined(__GNUC__) && __GNUC__ >= 5)