0

The task for me is to use cmov in assembly to implement the C code snippets, how can I jump to stop after every operation without using any jmp command? I am confused

C code:

if (x > y){
    z = x - y;
}else if (y > x){
    z = y - x;
}else{
    z = 0;
}

Assembly:

cmpl %eax, %ebx
cmovll %eax, %ecx    # x > y, z = x
subl %ebx, %ecx      # z = x - y

cmpl %eax, %ebx 
cmovgl %ebx, %ecx   # y > x, z = y
subl %eax, %ecx     # z = y - x

cmpl %eax, %ebx 
cmovel $0, %ecx     # z = 0
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Hant
  • 1
  • 2
  • You don't need to jump because the other conditions then evaluate to false so you can fall through them. Basically you could rewrite the code without the `else` just like `if (x > y) z = x - y; if (y > x) z = y - x; if (x == y) z = 0;` – Jester Apr 14 '20 at 18:22
  • I think I didn't make it clear. So I need a way to directly stop the operation after one is done, in order to avoid falling through all the subtractions – Hant Apr 14 '20 at 18:24
  • 1
    I have just told you you don't need to do that because the other conditions evaluate to false so you **can** fall through them. – Jester Apr 14 '20 at 18:25
  • the c code is not allowed to change, I can only modify the assembly :-( – Hant Apr 14 '20 at 18:25
  • so nothing add between? – Hant Apr 14 '20 at 18:27
  • 1
    You don't need to modify the C code. I just showed that it is equivalent to that code. If any one of the conditions is true, no other can be true. Your assembly is broken though but not for this reason. – Jester Apr 14 '20 at 18:32
  • 1
    You only need two `cmov` instructions, and `cmov` with an immediate source isn't encodeable. Actually only one `cmov` because `x-y = y-x = 0` in the case where they're neither > nor <. This just calculates the absolute difference `z = abs(x-y)` without overflow. Or for unsigned? You don't say whether x and y are `int` or `unsigned`. – Peter Cordes Apr 14 '20 at 19:54

0 Answers0