0

I've only seen BLT Loop which is a comparison between the index of a for loop and the loop upper bound. So if the index is less than the bound, then branch to Loop. But how would I manage to achieve the same functionality using BGT? Would I instead say BGT Exit? So if the index is greater than the bound, then exit the loop? Would that ensure the loop keeps looping as long as the index is NOT greater than the bound? Also, for Exit, do I need to write anything after it? Or is just "Exit: " fine?

Mike Tero
  • 1
  • 1
  • 1
  • You could count a negative number up towards zero, or `cmp r1, r0` / `bge .looptop` instead of `cmp r0, r1` / `blt .looptop` if you're counting up to a bound (and thus need a cmp anyway instead of just `subs r0,#1`). Or maybe offset something by 1 so you can `bgt` instead of `bge`. Yes you *could* just use an `if (r0>r1) goto exit`, but that's obviously less efficient if you then also need an unconditional branch (`b`) at the bottom of the loop. ([Why are loops always compiled into "do...while" style (tail jump)?](https://stackoverflow.com/q/47783926)). Why do want to use `bgt` anyway? – Peter Cordes Feb 09 '22 at 05:15
  • Oh, so basically just invert the comparison so instead of (index - loop bound) then check if less than 0, you do (loop bound - index) and check if that's greater than 0, and if it is, go to the loop again? Also, could you explain in what scenario you would need an unconditional branch at the bottom of the loop? Is it to Exit? How would that work? Thanks! – Mike Tero Feb 09 '22 at 06:04
  • I'd basically never use an unconditional branch at the bottom of a loop, that's dumb and inefficient vs. rotating the loop (if necessary) so a conditional branch can be the loop branch, like I explained in the answer I linked. As for the other stuff, see Aki's answer. – Peter Cordes Feb 09 '22 at 06:06

1 Answers1

1

The inverse of BLT is BGE, not BGT. Note the equality. BGE or BGT would make sense if the index was decreasing, as in for (int i = 7; i >=0; --i).

In incremented loop one can skip out of the loop with BGE/BGT, but then one would need an additional jump back to the loop beginning.

loop_begin:
     add r0, r0, #1
     cmp r0, r1
     b.ge out
     b loop_begin
out:

It's anyway typical that a regular loop for (int i = 0; i < N; i++) is converted by a compiler to the decremented version (when the iteration count can be computed), producing

 cmp r0, 0  // assume r0 == N
 b.le  out  // need to skip the branch if N<=0
 loop_begin:
    subs r0, r0, #1  // decrement and compare to zero
    b.gt loop_begin
 out:

If possible, one should try to formulate the loops to the form do { } while (--i), executing at least one iteration.

loop_begin:
  subs r0, r0, #1  // decrement and compare to zero
  b.gt loop_begin
Aki Suihkonen
  • 19,144
  • 1
  • 36
  • 57