GCC extended asm, structural offset element offset

I am trying to write a small part of my code in extended asm (x86-64 target) in the GCC style, and I am having problems coding for structural offsets.

I have struct s with an element size_t a[] , a pointer to such a structure and an index, both of which are generated inside the asm block.

Now I need to access this element in asm

 asm ( "mov %[displ](%[s], %[index], 8), %%rbx" : [s] "+r" (s) , [index] "+r" (i) : "memory", "cc", "rax", "rbx" ); 

How can I encode displ into asm block? Passing offsetof(struct s, a) as an immediate prefix using $ and generates an invalid assembly.

 asm ( "mov %[displ](%[s], %[index], 8), %%rbx" : [s] "+r" (s) , [index] "+r" (i) : [displ] "i" (offsetof(struct s, a)) : "memory", "cc", "rax", "rbx" ); 
+6
source share
2 answers

In fact, this is possible using the operand modifier %c... :

 #include <stddef.h> #include <stdint.h> struct s { int a, b; }; int foo (struct s *s, int i) { int r; asm ( "movl %c[displ](%[s],%[index],8), %[r]\n\t" : [r] "=r" (r) : [s] "r" (s) , [index] "r" ((uintptr_t)i), [displ] "e" (offsetof(struct s, b)) : ); return r; } 

Thank you, thank you, thank you for being here . There is a gcc mailing list citing this; keywords are "output substitution."
Stackoverflow port message What does the% c value mean for GCC inline assembler code? also contains explanations about %c in particular.

+7
source

Your only option is to use Intel syntax. GCC, of ​​course, can generate insn as mov off(base, index, scale) , but it does it at the level of integer RTL MEM expressions, i.e. It does not have an offset, base, etc., As separate operands.

So, Intel syntax, compile the following with gcc -c -masm=intel xc :

 #include <stddef.h> struct s { int a, b; }; int foo (struct s *s, int i) { int r; asm ( "mov %[r], dword ptr [%[s]+%[index]*8 + %[displ]] " : [r] "=r" (r) : [s] "r" (s) , [index] "r" (i), [displ] "e" (offsetof(struct s, b)) : ); return r; } 
+2
source

All Articles