when does avr-gcc use instructions like SWAP, BST, ROL?

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

On browsing through the AVR instruction manual, I see several interesting and useful instructions that don't map readily to any simple C code. I'm curious if and when avr-gcc would use these instructions, or do programmers need to use inline assembly to take advantage of them?

 

SWAP - swap nibbles

// swap nibbles in uint8_t variable x
uint8_t temp = x;
x <<= 1;
x <<= 1;
x <<= 1;
x <<= 1;
temp >>= 1;
temp >>= 1;
temp >>= 1;
temp >>= 1;
x |= temp;

 

ROL - rotate left through carry

// rotate left through carry uint8_t variable x
if (x & 0x80) {
    x <<= 1;
    x |= 1;
}
else {
    x << = 1;
}

 

BST - bit storage from register to T

BLD - bit load from T to register

// copy bit 3 of uint8_t variable x to bit 6 of uint8_t variable y
if (x & 8)
    y |= 0x40;
else
    y &= ~0x40;

// assembly code version
BST Rx,3
BLD Ry,6

 

even basic branching functions like BRCS - branch if carry set , in some contexts

// shift left uint8_t variable x, call a function if the bit just shifted out was 1
if (x & 0x80) {
    x = x << 1;
    MyFunc();
}
else {
    x = x << 1;
}

// assembly code version
LSL Rd
BRCS MyFunc

I'm unsure if avr-gcc is smart enough to recognize these kinds of coding constructs and use the more efficient assembly instructions.

Last Edited: Thu. Dec 16, 2021 - 06:20 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm not sure that swap is used by the compiler, but ROL is used for shifts on a uint16_t and bigger

 

BLD and BST is used by the compiler (but there will be situations where it's not where it could benefit).

 

I personally prefer to have T as a global control flag so the compiler stayed away from T or at least restored if changed.

 

I just checked a program

swap not used

rol not used in the program 

bst was used in the div lib together with brtc (not bld). 

add:

One should remember that the AVR don't have a special ROL instruction because it's the same as adc a register with itself. 

Last Edited: Thu. Dec 16, 2021 - 10:28 PM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I've noticed GCC uses swap for certain bit shifts, say by a fixed 4 or 5 bits.