sy2002 / QNICE-FPGA

QNICE-FPGA is a 16-bit computer system for recreational programming built as a fully-fledged System-on-a-Chip in portable VHDL.
http://qnice-fpga.com
Other
69 stars 15 forks source link

Check, if you need to clear X at the beginning of MTH$RAND #171

Closed sy2002 closed 3 years ago

sy2002 commented 3 years ago

Just being paranoid :-) Here is a question for you:

Do you need to clear the X flag at the beginning of MTH$RAND?

I am asking, because of this code snippet (but I need to admit that I did not understand, how the whole function works):

                ; We multiply R5 by 2 and add bit 15 of R1.
                ; At the same time we clear bit 15 of R1.
                SHL     1, R1                   ; Move bit 15 to carry (and X into bit 0)
                ADDC    R5, R5                  ; Note: This also clears carry
                SHR     1, R1                   ; Move zero back into bit 15 (and bit 0 to X)

The very first time, the code flow reaches SHL 1, R1, the X flag is undefined as far as I have seen that. From the second iteration on, X is filled by the SHR 1, R1

MJoergen commented 3 years ago

Thank you for asking!

The way this sequence of instructions is intended is that upon entry X is undefined. After SHL 1, R1, this undefined X-value gets copied into bit 0 of R1. The second instruction ADDC R5, R5 does not change that, and the third instruction SHR 1, R1 moves bit 0 of R1 back into the X-register. The X-register is therefore still undefined (but unchanged from before this sequence!).

In other words, bit 0 of R1 will temporarily (for the duration of these few instructions) contain an undefined value in bit 0. But after the sequence, all bits in R1 should be well-defined.

I have at least convinced myself that this sequence of instructions is correct! If I've convinced you too, then you may close this issue.

sy2002 commented 3 years ago

Thanks for taking the time to explain it to me. Got it now. 👍 Closing.