loda-lang / loda-cpp

Runtime and miner for the LODA language written in C++
https://loda-lang.org/
Apache License 2.0
21 stars 1 forks source link

Instruction `lps` shorthand of `L-oo-P S-ubtract` - for faster loops #219

Closed neoneye closed 1 year ago

neoneye commented 1 year ago

Problem

This is a popular pattern

lpb $0
  ; do things N+1 times and undos the last time
  sub $0,1
lpe

It has the shortcoming that an extra iteration gets executed and then reverted in the last step when $0 no longer changes.

Memory management overhead. The ability to revert back to the previous state, requires a memory shapshot of the previous state. When reaching the end then restore from the previous snapshot.

Step overhead. For a tiny loop body, then it's not a big a problem. For a loop body that is expensive to perform, containing a seq instruction or a nested loop, then there are lots of steps being wasted.

Proposal

Eliminate the expensive "restore to previous snapshot" mechanism.

The lps combines lpb and sub and looks like this:

lps $0
  ; do things N times
lpe

Same code in C

while (x > 0) {
    // do things N times
    x -= 1;
}     

Here the lps $0 does a subtract until reaching 0 or negative.

If the initial value of $0 is zero or negative, then the loop body is not executed.

If the loop body changes the $0 value, then the loop stops, similar to the break command.

If the loop body sets the $0 to zero or a negative value, then the loop stops, similar to the break command in C.

ckrause commented 1 year ago

The performance impact of the "restore to previous snapshot" mechanism is definitely relevant. In loda-cpp we use incremental evaluation for simple loops. This is even much faster than the proposed mechanism.

I think there are conceptual issues with the proposal. If you use lps $0, is $0 implicitely decremented? If yes, what it is also modified inside the loop? If not, how can the loop counter be accessed inside the loop? Related implementation question: where would you store the loop counter if it it outside of LODA's memory?