This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug middle-end/59538] Optimization of -O2 or higher creates incorrect code in loop


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59538

--- Comment #7 from Andrew Pinski <pinskia at gcc dot gnu.org> ---
Try:
//  GCC Bug - bug.c
//  Created by Arsham Skrenes on 2013-12-17

#include <stdio.h>
#include <sys/time.h>

// Find the NTH prime number SAMPLES times
#define NTH     10000
#define SAMPLES 5

int main(void)
{
    struct timeval t1, t2, t3;
    int i, sample;
    volatile int keeparound;
    printf("Generating %d samples...\n", SAMPLES);

    // i = prime candidate; check = test number (naive algorithm)
    for (sample = 0; sample < SAMPLES; sample++)
    {
        int count = 2, check;
        gettimeofday(&t1, NULL);
        for (i = 3; count <= NTH; i++)
        {
            for (check = 2; check <= i - 1; check++)
            {
                if (i%check == 0)
                    break;
            }
            if (check == i)
            {
                // found a prime number
                count++;
            }
        }
        gettimeofday(&t2, NULL);

        // calculate primes/second for this sample
        timersub(&t2, &t1, &t3);
        printf("It took %f seconds to find the %dth prime number.\n",
               (double)t3.tv_usec / 1000000 + t3.tv_sec,
               NTH);
    }

    // If you uncomment the following line, or compile this code with flag -O1
    // or less, it will work correctly...
    //printf("The %dth prime number is %d\n", NTH, i-1);
        keeparound = i - 1;

    return 0;
}

Which will keep around the final i and not cause any optimizations to happen
(well GCC might change around the loop to figure out i only once but that
optimization is not done currently but could be in the future).


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]