C: How to check the overflow flag?
I've read that on amd64 arch. there is an integer overflow flag. Is it possible to examine that flag inside a C program, to check for addition/subtraction overflow? Also, does Linux have some kind of API relating to that?
|
http://www.fefe.de/intof.html
"Issue 2" on this page seems to answer the question quite well: Quote:
|
Hmm, thanks for the info, although I must admit I am hesitant to accept that answer. It seems like, in a language that accepts inline assembly, there must be a way. I'll explore this some more when I get more knowledgeable about assembly.
|
Quote:
But you can code both the add or subtract and the overflow check together in one chunk of inline asm. |
Quote:
AFAIK, adding two unsigned will always allow you to detect if there was overflow by comparing if the resulting value is less than either of the arguments (note the keyword is unsigned), but it requires separate unsigned storage. Additionally, it should be easy to tell a compliant C compiler (for instance, gcc) not to throw away "always true" checks, by saying that they're not always true via the volatile keyword. I believe the following C code is portable, correct, compliant, and complete to demonstrate, but if I've violated something, INSERT DISCLAIMER HERE. Code:
#include <assert.h> |
Quote:
Quote:
But also the add or subtract itself might be recoded in some way that doesn't effect the overflow flag (such as an LEA instruction). Quote:
|
I have a draft of C99 that states (in section 3.4.3) that integer overflow is an undefined behavior. Furthermore, I know that there are multiple ways of representing integer signs in various architectures. Therefore, checking the result of an addition for an invalid sign change is not portable across architectures.
Of course, checking an overflow flag is not portable either, but my thought was to do some conditional compiling, using the fastest and simplest check method available for each arch. @johnsfine: You wouldn't happen to know what that inline asm would look like, perchance? |
Quote:
This, to my knowledeg, is a compiler guarantee that it won't reorder the assembly around the inlined asm. YMMV, and it's true that it isn't portable to other compilers. I'm not sure if it will or will not optimize the surrounding code. My gut says that it shouldn't, but then again my gut is large and filled with beer. Quote:
|
After reading the GCC-Inline-Assembly-HOWTO <http://ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html>, and spending some more time in the AMD64 APM, I was able to figure this out. (Or, at least one solution):
Code:
$ cat test.c Code:
$ gcc -O2 test.c -o test So, anyway, if you think that was a helpful solution, feel free to give me a few rep points. :) |
All times are GMT -5. The time now is 07:44 PM. |