3 ms·
My assembler is very rusty, couldn't compilers check the carry flag on i386 after a math operation that could potentially overflow, and handle the trapping in s
by perlgeek 12y ago
My assembler is very rusty, couldn't compilers check the carry flag on i386 after a math operation that could potentially overflow, and handle the trapping in software?
- danbruc 12y agoOf course and this is what actually happens if you enable overflow checking but it comes at a price - if your code is correct you will never need the checks but you will execute them every time.
- throwawayaway 12y agohere's the best guide i could find on enabling those checks in gcc. it is unclear whether they take advantage of the carry bits, do you have a source for that information? http://www.pixelbeat.org/programming/gcc/integer_overflow.html http://www.pixelbeat.org/programming/gcc/integer_overflow.ht...
- danbruc 12y agoYou can see the implementation in GCC here [1], for example addition starting on line 74. What machine code gets emitted for that obviously depends on the target architecture but it is reasonable to assume that the optimizer recognizes these patterns and uses hardware flags where available. [1] https://github.com/mirrors/gcc/blob/master/libgcc/libgcc2.c https://github.com/mirrors/gcc/blob/master/libgcc/libgcc2.c
- throwawayaway 12y agolooking over it again, it seems like quite a leap for the optimiser to do that, i have my doubts.
- throwawayaway 12y agohttp://www.emulators.com/docs/LazyOverflowDetect_Final.pdf http://www.emulators.com/docs/LazyOverflowDetect_Final.pdf This paper seems to imply that that high level languages can't access the carry bit, yet C#'s checked mechanism uses it. I've been using -ftrapv with gcc for a long time, from here: https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options. From the code you posted, and the assembly[1] emitted in the pdf above I can't see the optimiser taking advantage of the carry bit. No mention of CF, OF: [1] lea ebx, DWORD PTR [edi+eax] cmp ebx, edi jae SHORT $LN4@unsigned_c cmp ebx, eax jae SHORT $LN4@unsigned_c mov ecx, 1 jmp SHORT $LN5@unsigned_c xor ecx, ecx The gcc flag ftapv only works for signed integers, not clear what the carry bit behaviour is for unsigned integers.