Why is the .NET Native compilation cycle in reverse order?

I am working on optimization methods performed by the .NET Native compiler. I created a sample loop:

for (int i = 0; i < 100; i++) { Function(); } 

And I compiled it with Native. Then I .dll result file with machine code inside the IDA. As a result, I have:

IDA output

(I deleted some unnecessary lines, so don't worry that the address lines are inconsistent)

I understand that add esi, 0FFFFFFFFh really means subtract one from esi and alter Zero Flag if needed , so we can go to the beginning if zero has not yet been reached.

What I don’t understand is why the compiler reversed the loop?

I came to the conclusion that

 LOOP: add esi, 0FFFFFFFFh jnz LOOP 

just faster than for example

 LOOP: inc esi cmp esi, 064h jl LOOP 

But is this really because of this, and is the speed difference really significant?

+6
source share
2 answers

inc may be slower than add due to a partial flag update . Moreover, add affects the zero flag, so you do not need to use another cmp statement. Just jump straight.

This is one known type of cycle optimization.

reverse . Reversing the loop overrides the order in which values ​​are assigned to the index variable. This is a subtle optimization that can help eliminate dependencies and thus enable other optimizations. In addition, some architectures use assembly-level loop constructs that count only in one direction (for example, decrement-jump-if-not-zero (DJNZ)).

You can see the result for other compilers here .

+4
source

Your conclusion is correct: the inverted loop will be aimed at 0 (the loop will end when the register value reaches 0 ), so Add set the zero flag used in the conditional branch.

Thus, you do not need dedicated Cmp , which leads to: 1) size optimization 2) it is also faster (output from the decision of the compiler programmers and another answer ).

This is a fairly common assembler trick to target loop 0 . I am surprised that you understand assembler, but do not know (ask) about it.

+2
source

Source: https://habr.com/ru/post/1246477/


All Articles