CMP setting N flag when it shouldn't?

Discuss technical or other issues relating to programming the Nintendo Entertainment System, Famicom, or compatible systems.

Moderator: Moderators

supercat
Posts: 161
Joined: Thu Apr 18, 2019 9:13 am

Re: CMP setting N flag when it shouldn't?

Post by supercat »

tepples wrote:
rainwarrior wrote:Though honestly, this entire problem only happens with division.
That and the general trend of newer versions of C and C++ compilers becoming more pedantic about treating signed overflow and other undefined behaviors as an excuse to make unexpectedly aggressive optimizations. Raymond Chen has referred to this aggression as "time travel". Unsigned addition, subtraction, and multiplication, on the other hand, are carefully defined to wrap around modulo [type]_MAX + 1.
Time travel would be fine if it were limited to things which have no causal relationship. For example, given

Code: Select all

#include <math.h>
volatile int x,y;

void test(long long temp)
{
  while(temp & 1234)
    temp = 123456789123456789*sin(temp);
  if (x) y=temp;
}
I would not think it unreasonable for a compiler to perform the read of "x" before performing the computations involving "temp" and skip those computations if x yields zero, even if the loop would never have exited.

Unfortunately, "modern" compilers use Undefined Behavior not only as an excuse to engage in time travel, but also to negate the laws of causality. For example, given:

Code: Select all

unsigned mul_mod_65536(unsigned short x, unsigned short y)
{ return x*y & 0xFFFF; }

volatile unsigned q;
unsigned test(unsigned short x)
{
    unsigned sum=0;
    x|=0x8000;
    for (int i=0x8000; i<=x; i++)
    {
        q=mul_mod_65536(65535,i);
        sum++;
    }
    return sum;
}
When targeting platforms where "int" is 32 bits, gcc will generate code for "test" which always writes 32768 to "q" and returns 1, ignoring the value of "x".
Post Reply