Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should carry flag be set in assembly language

Tags:

c

assembly

arm

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.

like image 599
Summer_More_More_Tea Avatar asked May 18 '10 07:05

Summer_More_More_Tea


2 Answers

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;
like image 22
AProgrammer Avatar answered Sep 23 '22 12:09

AProgrammer


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).

like image 146
Paul R Avatar answered Sep 23 '22 12:09

Paul R