Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using condition flags as GNU C inline asm outputs

I'm working on some code where it would be highly desirable to take condition-flags output from an inline asm block and use that as a condition to branch on in the calling C code. I don't want to store the flags (that would be useless and inefficient; there are already more efficient ways to achieve the result) but use the flags directly. Is there any way to achieve this with GNU C inline asm constraints? I'm interested in approaches that would work for multiple instruction set architectures, with the intent of using it with the condition flags produced by the architecture's LL/SC style atomics. Of course another obvious usage case (separate from what I'm doing) would be to allow the outer C code to branch on the result of the carry flag from an operation in inline asm.

like image 369
R.. GitHub STOP HELPING ICE Avatar asked May 19 '15 00:05

R.. GitHub STOP HELPING ICE


1 Answers

Starting with GCC6 on x86 you can actually use "=@ccCOND" as output (where COND is any valid x86 condition code).

Example originally from here, cleaned up by David's suggestions:

int variable_test_bit(long n, volatile const unsigned long *addr)
{
    int oldbit;
    asm volatile("bt %[value],%[bit]"
                 : "=@ccc" (oldbit)
                 : [value] "m" (*addr), [bit] "Jr" (n));
    return oldbit;
}

Before using this, you should test if __GCC_ASM_FLAG_OUTPUTS__ is defined.

Documentation at https://gcc.gnu.org.

like image 188
chtz Avatar answered Nov 11 '22 18:11

chtz