I'm puzzled by this problem when writting an ARM assembly simulator in C. I've found some similar questions in the forum, but none of them explain how to set the carry flag just using the relationship between two operands and the result.
Any reply is appreciated. Thanks in advance.
Regard.
You have to check the reference manual for the processor to know which instructions set the carry flags and in which way. I don't know enough about ARM, but I've seen some variations in other processors:
some instructions which logically generates a carry may not set the carry flag
some instructions may use the carry flag with as some additional implicit operand or result without having a connection with addition/subtraction
after a subtraction, processors vary in which condition the carry flag is set (i.e some do it in the same way as after the addition of an inversed second operand, the other set it to the negation of that)
If what you want is a way to see if a carry should be generated for an addition in C, here are two ways (the first is straight from definition, the second comes from wrap around behavior of unsigned):
unsigned w1, w2, result;
int carry;
carry = w1 > UINT_MAX-w2;
result = w1 + w2;
carry = result < w1;
The carry flag gets set in the normal way, e.g. as the result of an addition which generates a carry. You can then use an ADC
(add with carry) instruction to propagate this carry into a high order word, e.g. when doing a 64 bit add:
ADDS r4, r0, r2 ; add least significant words
ADC r5, r1, r3 ; add most significant words with carry
In this example the 64 bit value in r4:r5 is equal to the sum of the 64-bit values in r0:r1 and r2:r3.
On early versions of ARM you could set the carry flag explicitly like this:
ORRS R15,R15,#&20000000
or like this:
TEQP R15,#&20000000
See this tutorial for more info: http://www.peter-cockerell.net/aalp/html/ch-3.html
Apparently newer versions of ARM have moved the carry flag to a different register (see comments below).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With