C Language gcc Inline assembly in macros


We can put assembly instructions inside a macro and use the macro like you would call a function.

#define mov(x,y) \
{ \
    __asm__ ("l.cmov %0,%1,%2" : "=r" (x) : "r" (y), "r" (0x0000000F)); \

/// some definition and assignment
unsigned char sbox[size][size];
unsigned char sbox[size][size];

mov(state[0][1], sbox[si][sj]);

Using inline assembly instructions embedded in C code can improve the run time of a program. This is very helpful in time critical situations like cryptographic algorithms such as AES. For example, for a simple shift operation that is needed in the AES algorithm, we can substitute a direct Rotate Right assembly instruction with C shift operator >>.

In an implementation of 'AES256', in 'AddRoundKey()' function we have some statements like this:

unsigned int w;          // 32-bit
unsigned char subkey[4]; // 8-bit, 4*8 = 32 

subkey[0] = w >> 24;     // hold 8 bit, MSB, leftmost group of 8-bits 
subkey[1] = w >> 16;     // hold 8 bit, second group of 8-bit from left    
subkey[2] = w >> 8;      // hold 8 bit, second group of 8-bit from right
subkey[3] = w;           // hold 8 bit, LSB, rightmost group of 8-bits

/// subkey <- w

They simply assign the bit value of w to subkey array.

We can change three shift + assign and one assign C expression with only one assembly Rotate Right operation.

__asm__ ("l.ror  %0,%1,%2" : "=r" (* (unsigned int *) subkey)  : "r" (w), "r" (0x10));

The final result is exactly same.