Search code examples
cgccwhile-loopinline-assemblycontinue

``continue`` breaks label placement


This works just fine:

#include <stdio.h>

int main(){
    volatile int abort_counter = 0;
    volatile int i = 0;
    while (i < 100000000) {
        __asm__ ("xbegin ABORT");
        i++;
        __asm__ ("xend");
        __asm__ ("ABORT:");
        ++abort_counter;
    }

    printf("%d\n", i);
    printf("nof abort-retries: %d\n",abort_counter-i);
    return 0;
}

However, what I originally wrote was

#include <stdio.h>

int main(){
    volatile int abort_counter = 0;
    volatile int i = 0;
    while (i < 100000000) {
        __asm__ ("xbegin ABORT");
        i++;
        __asm__ ("xend");
        continue;
        __asm__ ("ABORT:");
        ++abort_counter;
    }

    printf("%d\n", i);
    printf("nof abort-retries: %d\n",abort_counter);
    return 0;
}

but this led to

/tmp/cchmn6a6.o: In function `main':
rtm_simple.c:(.text+0x1a): undefined reference to `ABORT'
collect2: error: ld returned 1 exit status

Why?

(Compiled with gcc rtm_simple.c -o rtm_simple.)


Solution

  • You might be able to trick it:

            continue;
            reachable:
            __asm__ ("ABORT:");
            ++abort_counter;
        }
    
        printf("%d\n", i);
        printf("nof abort-retries: %d\n",abort_counter);
        if (abort_counter < 0) goto reachable;
        return 0;
    }
    

    The goto with the label tells gcc that the code is reachable, and abort_counter being volatile should prevent gcc from being able to optimize the goto away.