Inline assembly without inputs considered const/pure?

Andrew Haley aph@redhat.com
Thu Feb 25 16:22:00 GMT 2016


On 02/25/2016 04:03 PM, Matthias Pfaller wrote:
> On 02/25/2016 04:40 PM, Andrew Haley wrote:
>> On 02/25/2016 03:36 PM, Matthias Pfaller wrote:
>>> When gcc decides to inline mrsbasepri it will again be free to CSE the
>>> mrs instructions :-(. Is it really just me having run into this problem?
>>> How do other people solve the problem that __asm__ without input is
>>> handled like a __attribute((const)) function?
>>
>> Either with a memoryclobber, or make it volatile, or both.
> 
> I have a memoryclobber, but that's output and doesn't help for input.
> And marking it volatile will avoid deleting it in all cases. But I want
> to get it deleted when I don't need the return value.

This works for me:

extern volatile int poo;

static __inline__ unsigned long long rdtsc(void)
{
  unsigned hi, lo;
  __asm__ ("rdtscp" : "=a"(lo), "=d"(hi) : "m"(poo) : "rcx");
  return ( (unsigned long long)lo)|( ((unsigned long long)hi) <<32 );
}

long bar (int counts) {
  long result = 0;
  for (int i = 0; i < counts; i++)
    result += rdtsc();
  return result;
}

All you need is an externally visible memory effect.
The asm doesn't actually modify poo, but GCC doesn't know that.

.L3:
#APP
# 8 "z.c" 1
        rdtscp
# 0 "" 2
#NO_APP
        salq    $32, %rdx
        movl    %eax, %eax
        addl    $1, %esi
        orq     %rdx, %rax
        addq    %rax, %r8
        cmpl    %esi, %edi
        jne     .L3


Andrew.



More information about the Gcc-help mailing list