This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Array references in inline assembler


On Fri, Jul 17, 2009 at 03:45:15PM -0400, Peter Hurley wrote:
> What memory reference syntax is used to refer to the nth element of an array
> in inline assembler?  For example, the following x86 example doesn't
> assemble:
> 
> void test()
> {
>    unsigned _tmp[8];
>    __asm__ (
>       "movl %%edi, 12(%0)"	// generates movl %edi, 12(-40(%ebp))
>       : "=m" (_tmp) : :
>    );
> }
> 
> The following is kind of a workaround (ok for 1 reference):

Note, you should not be using "m", because the compiler will optimize the
addresses.  I would suggest:

void test()
{
  unsigned _tmp[8];
  __asm__ volatile ("movl %%edi, 12(%1)" : "=m" (_tmp) : "r" (_tmp) : "memory");
}

The volatile tells the compiler not to move the asm around.  The "memory" part
says that you are modifying memory in an unspecified fashion.  You may or may
not need these, but in doing something like you are doing, it is probably
safest to do both.


The "=m" (_tmp) tells the compiler that it will be modifying memory as an
output.

The "r" (_tmp) tells the compiler to load up the address of _tmp into a
register (assuming _tmp is an array).

> void test2()
> {
>    unsigned _tmp[8];
>    __asm__ (
>       "movl %%edi, %0"	// generates movl %edi, -28(%ebp)
>       : "=m" (_tmp[3]) : :
>    );
> }
> 
> But somewhat onerous and error-prone for several references:
> 
> void test3()
> {
>    unsigned _tmp[8];
>    __asm__ (
>       "movl %%edi, %0      \n\t"
>       "movl %%esi, %1      \n\t"
>       "movl %%ebp, %2      \n\t"
>       "movl %%ebx, %3      \n\t"
>       "movl %%edx, %4      \n\t"
>       "movl %%ecx, %5      \n\t"
>       "movl %%eax, %6      \n\t"
>       : "=m" (_tmp[0]), "=m" (_tmp[1]), "=m" (_tmp[2]),
>         "=m" (_tmp[4]), "=m" (_tmp[5]), "=m" (_tmp[6]),
>         "=m" (_tmp[7]
>       : :
>    );
> }

Yep.

> On a separate note, is there any plan to implement __attribute__(__naked__)
> for x86?  Restarting a processor exception is wicked tricky without being
> able to alter the stack frame directly...

Well if you need it badly, perhaps you should contribute patches to add it.

-- 
Michael Meissner, IBM
4 Technology Place Drive, MS 2203A, Westford, MA, 01886, USA
meissner@linux.vnet.ibm.com


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]