I can't understand some instructions in ARM: SBC, RSC

6.4k views Asked by At

I don't understand SBC and RSC ARM instructions

I know that both deal with the carry flag (C)

I think it makes sense adding the result with the carry (ADC) like:

ADC r1, r2, r3   @ r1 = r2 + r3 + Carry 

But subtracting/reverse subtracting with the carry... I can't understand what is happening :(

Can you guys give me an example using SBC and RSC?

2

There are 2 answers

1
Notlikethat On BEST ANSWER

Given two's complement, subtraction can just be transformed into addition:

z = y - x
  = y + (-x)
  = y + ~x + 1

which makes it easier to consider how the carry flag is set in that situation, i.e. by subs:

   z = 0 - 0
     = 0 + ffffffff + 1
 C:z = 1:00000000        // no borrow, C = 1

   z = 0 - 1
     = 0 + fffffffe + 1
 C:z = 0:ffffffff        // borrow, C = 0

Hence why the value of the C flag is nB ("not borrow"), so sbc as "subtract with carry" means "subtract with not borrow", or in other words:

z = y + ~x + C           // i.e. adc with the second operand inverted
  = y - (x - 1) - (~C + 1)
  = y - x - ~C
8
Sean On

I have come across this little oddity myself. I think it important to note that Thumb only has 2 fields for SUBS instructions so any logic using 3 fields cannot be carried out in 1 instruction.

I had an inner-loop for which the C flag would be appropriately set for an ADCS but not for an SBCS.

Thumb was designed to produce smaller compiled C so I can only presume that their is some logic but speed is not addressed AT ALL.

Along with the RORS Rd,Rs instruction format, the SBCS has me baffled. On the plus side, the fact that you can setup the bottom 8 registers and jump to a specified address makes it possible to produce very fast switch statements.