Compare and jump instruction as one instruction

2019-08-03 22:03发布

问题:

Is there a way I can compare and jump in one instruction:

C code:
1. while(i<10)
2. {i++}

Assembly code: (eax=0)(ecx=10)

  1. .while:
  2. cmp eax, ecx
  3. jge .endofwhile
  4. add eax, 1
  5. jmp .while
  6. .endofwhile:

Is there a way i can do line 2 and 3 in one instruction?

回答1:

Yes, you can have the test and branch treated as a single instruction, and the way to do this is to write them as two instructions like you did, to use a modern Intel processor and to follow a few simple rules (the branch instruction must be contained in the same 16-bytes line of code that the test instruction ends, the two instructions must not be separated by any other instruction, …).

The mechanism is called macro-fusion. More detailed information including the precise conditions in which macro-fusion apply is available from Agner Fog's manual, page 82.



回答2:

Is there a way i can do line 2 and 3 in one instruction?

If you're allowed to change your C code to count backwards:

1. i = 10;
2. while(--i >= 0);

Then you can use the (single) LOOP opcode.

LOOP is an old instruction though, so it may be deprecated on newer (Pentium++) CPUs: where by "deprecated" I mean, "still supported, but slower than using more primitive opcodes like the ones given in Pascal's answer."



标签: assembly nasm