on-line compiler bug ?

17 Feb 2017

Using the mbed online compiler (for various boards), the following program produces "bad" code (result is not what is reported on linux C and on teensy)

#include "mbed.h"
 
#define BUFSIZE 16384

uint8_t buf[BUFSIZE] __attribute__((aligned(4)));

// bit bang crc32
uint32_t crcbb(uint8_t *address, int bytes) { 
    uint32_t crc = 0xFFFFFFFF;
    int count1 = 0;
    int count2 = 0;

    /* Calculates the CRC-32 polynomial on the multicast group address. */
    for (count1 = 0; count1 < bytes; count1++)
    {
        /*volatile*/  uint8_t c = address[count1];  // volatile for compiler bug ??
        for (count2 = 0; count2 < 8; count2++)
        {
            if ((c ^ crc) & 1)
            {
                crc >>= 1;
                c >>= 1;
                crc ^= 0xEDB88320;
            }
            else
            {
                crc >>= 1;
                c >>= 1;
            }
        }
    }
    return ~crc;
}

main() {
        uint32_t i;
        for (int i=0; i<BUFSIZE; i++)  buf[i] = (i+1) & 0xff;
        i=crcbb(buf,BUFSIZE);
        printf("bit bang 0x%08x    ?=0x1271457f\n",i);
}

I got it to work by adding volatile to the declaration of c. (Seems like I have seen this before, but i couldn't find a post). Compiling with #pragma O2 works without volatile (as does O0 O1, but not O3)