Search code examples
c++gccg++gnuinteger-overflow

"-ftrapv" and "-fwrapv": Which is better for efficiency?


From GNU's website:

  • -ftrapv

    This option generates traps for signed overflow on addition, subtraction, multiplication operations.

  • -fwrapv

This option instructs the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation. This flag enables some optimizations and disables others.

https://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Code-Gen-Options.html

I have two questions:

  1. Which of these options is better for performance?
  2. What what does it mean when the -ftrapv definition says it generates "traps?" Does this mean exceptions? (I'm guessing no, but it's worth asking.)

Solution

  • The whole point of both of these options is to give the optimiser less leeway than it normally has. Therefore, unless you encounter a bug in the optimiser, the fastest should be to use neither, where the optimiser assumes your code doesn't have any overflows and doesn't emit code to handle overflows.

    What what does it mean when the -ftrapv definition says it generates "traps?" Does this mean exceptions?

    It doesn't mean a C++ exception. It's target-dependent, but assuming x86, it means the GCC runtime libraries cause SIGABRT to be raised that will normally abort your program. On other platforms, it might use special CPU instructions that cause a hardware exception. It's mainly useful for debugging purposes and perhaps in a few cases for safety, where the risk of continuing after overflow is greater than the risk of the program suddenly terminating.