Reputation: 1
in instructions like shift, add, increment we always check the result and if the result is zero we indicate that in a flag. in what instances we use this zero flag? what is the use of this zero flag?
Upvotes: 0
Views: 1956
Reputation: 62096
We use these flags for two main purposes:
Not all CPUs have flags that describe ALU operation results in terms of zero, negative, unsigned overflow/underflow (or, alternatively, carry/borrow), signed overflow, parity and others.
MIPS CPUs don't have such flags for integer and bitwise operations. The have conditional branches that can branch on conditions such as:
If a different kind of comparison is needed that isn't supported by those branches, there are special instructions for that. They set the result to 0 or 1 and then a conditional branch can use that as its input.
Carry and overflow are a bit tricky on MIPS processors. They need to be obtained through multiple instructions.
Upvotes: 2
Reputation: 18523
In general, the flags of a CPU are used to perform conditional operations.
(An exception is the carry flag which is both used for conditional operations and for "carry in" in operations like add-with-carry or subtract-with-borrow.)
On ARM CPUs you can perform any instruction based on the zero flag: The instruction ldmeqda
for example will do the same as the instruction ldmda
if the zero flag is set; it will do nothing when the zero flag is clear.
Typically you perform a subtraction (using the cmp
instruction) first to compare two numbers. The zero flag is set if both numbers are equal. The next instruction(s) shall only be executed if the two numbers are (not) equal, so you execute the instructions based on the state of the zero flag.
(The instruction cmp
performs a subtraction and discards the result! This means that this instruction is only setting the flags based on the result of a subtraction. This is useful when CoMParing two numbers; this is why the instruction is named cmp
.)
On most other CPUs that have flags (not all CPUs have them) you can only do jumps (branches) based on the states of the flags.
What you do is you jump over the instructions not to be executed if the flag has the wrong state.
Example (x86):
someloop:
mov eax, [esi]
add esi, 20
add eax, 1234
# The zero flag will be set if the result is 0
# The next instruction will jump if the zero flag is set
jz skipif
# We only get here if the zero flag is clear
# This corresponds to "if(eax!=0)" in C
mov [esi-10],bl
skipif:
dec edx
# The zero flag is set if edx is not 0
# Jump back to "someloop" if this is the case
# This corresponds to a "do { ... } while((--edx)!=0);"
# loop in C
jnz someloop
Upvotes: 1