contiki-ng / mspsim

Official MSPSim git repository
BSD 3-Clause "New" or "Revised" License
66 stars 83 forks source link

SUB Instruction Status Flag Interpretation #34

Open caioso opened 10 years ago

caioso commented 10 years ago

Hello guys! Today I was debugging a little software with MSPSIM and I really got stuck while trying to understand the effects of the status flags after subtraction operations with the simulator. I was performing a set of operations right in the registers (R4 and R14) and the two following operations were performed in a row:

SUB.B #0x0002, R14; R14 was loaded with 0x0000 -> Expected Status Flags: SR: -N-- SUB.B #0x0002, R4; R4 was loaded with 0x00FF -> Expected Status Flags: SR: -N-C

Results: R14 -> 0x00FE; R4 -> 0x00FD

The simulator successfully stores the correct results at the registers however, when performing these operations, I've noticed that it sets the Carry bit as a result of the first instruction which I believe may lead to unexpected behaviors. This is so, because a SUB instruction is performed by MSP430 CPU as a sum of the two's complement representation of the source, with the destination (and storing the result at the destination afterwards), like this: dst <- dst + [not(src) + 1]. Taking this into account, I believe that a carry (borrow) can't be generated as result of the first subtraction. I'll try to demonstrate below:

2'b                 ->   0 0 0 0   0 0 1 0 
One's Complement    ->   1 1 1 1   1 1 0 1 

                                       1 <-----Carry
Two's Complement    ->   1 1 1 1   1 1 0 1 
                       + 0 0 0 0   0 0 0 1 
                         -----------------
                         1 1 1 1   1 1 1 0 <-- 0x00FE

Subtraction         ->   0 0 0 0   0 0 0 0
                       + 1 1 1 1   1 1 1 0
                         -----------------
                         1 1 1 1   1 1 1 0 <-- 0x00FE (namely -2)

At the cluttered diagram I've shown above, neither the 'Two's complement' operation nor the sum itself generates a carry out and thus the status bit could not be set. I'm not sure if my assumptions are correct, so I'd really appreciate a little help to understand what's happening on these bit operations. Remember that I'm performing byte-wise operations and I've not yet tested the same code with word-size operands. Thank you very much!

*PS: I don't know if this is the best place to ask such kind of question but I couldn't manage to find other place ;)