1

SPARC assembly has a cmp instruction, which compares two numbers (using subtraction, if I understand correctly). It also has subcc, addcc, andcc, and others. What is the difference between comparing two numbers using cmp and setting condition codes after performing a calculation? I'm having trouble wrapping my mind around the concept.

Brian Knoblauch
  • 20,639
  • 15
  • 57
  • 92
vaindil
  • 7,536
  • 21
  • 68
  • 127

1 Answers1

2

What is the difference between comparing two numbers using cmp and setting condition codes after performing a calculation?

Generally (e.g. on x86 or 68000 type processors), cmp only sets the status flags, without modifying the operands or storing the result anywhere.

sub etc. are also changing the destination operands (they need to store the result somewhere ), which is not necessary when doing comparison operations.

In essence, cmp is a sub operation where the result is simply discarded (probably saving instruction cycles). When doing comparisons, you do not need the result, you only need to know whether the result is zero or not, and whether it is negative or not.

On SPARC, in particular, cmp is a "synthetic instruction" provided for better readability which is eventually converted by the assembler into a subcc instruction. See "Synthetic instructions" at http://moss.csc.ncsu.edu/~mueller/codeopt/codeopt00/notes/sparc.html.

So, cmp %reg1,%reg2 is converted to subcc %reg1,%reg2,%g0 by the assembler. This subtracts the two registers, and effectively also discards the result by storing it into register %g0. %g0 is a register which always returns 0 when read, and does not change when being written to. So, on an instruction level, there is no difference at all between cmp and subcc (in other words, SPARC does not have a separate cmp instruction, but uses subcc with a special destination register for comparison).

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
  • I expect cmp is subcc with g0 as the target register so the result doesn't overwrite any value register only the hardwired zero register. I doubt it saves any cycles unless the implementation was quite unusual. – cb88 Mar 21 '13 at 12:39
  • Isn't that is what I basically said in case of SPARC (`cmp` converted to `subcc`)? – Andreas Fester Mar 21 '13 at 13:01
  • Yes but you only what as far as what occurs not how it occurs. Althouth the linked text does cover it it takes awhile to get to that part. Understanding the use of g0 is helpful as well as how synthetic instructions can be constructed. Also when you consider how cmp is implemented it probably does NOT save instruction cycles rather it makes them faster by making the instruction set simpler. – cb88 Mar 21 '13 at 14:13
  • Valid statement :) I have updated the answer, hope it is a bit clearer now – Andreas Fester Mar 21 '13 at 14:27