简体   繁体   中英

Skipping instruction in ARM assembly

Im not experienced in writing Assembly at all, so I have this rather easy to answer question I guess.

Having this simple loop:

mov r0,#3
loop:
   do some instructions
   ...
   last-instruction

subs r0,r0,#1
bne loop
afterloop:

If I understand well, this loop should decrease from 3 to 0 and stop (correct me if Im wrong).

However,in the last iteration when r0 == 0 I want to skip the last-instruction and step out of the loop. I presume there has to be some cmp if r0 equals 0 then jump to afterloop . But I guess there might be some easier way to achieve this.

EDIT: One more question - what if there's more instructions to be skipped?

In C it would look like this:

int i = 3;
while (1) {
  foo();

  if (i == 0) break;
  skipped_func();
  --i;
}

Unless the last instruction depends on r0 and/or modifies the CPSR, move the subs line one step before the last instruction and make the last instruction conditional with a NE condition. Like this:

mov r0,#3
loop:
   do some instructions
   ...


    subs r0,r0,#1
    last-instructionNE
bne loop
afterloop:

If the last instruction is a mov , make it a movne . If a str , make it a strne . And so forth.

This won't work if the last instruction already has an "s" postfix - modifies the flags. If it does, it'll ruin the zero flag and the bne won't work as expected. Also, if the last instruction relies on the value of r0 before the decrease, it also has to execute before the subs .

On ARM, unlike Intel, almost every instruction can be made conditional, not just B(ranch). Unless it's actually Thumb.

EDIT re: edit: you can make more than one instruction conditional that way. Alternatively, you can also replicate the same logic with jumps. Like this:

mov r0,#3
loop:
   do some instructions
   ...
    subs r0,r0,#1
    bz afterloop

   last-instructions
b loop
afterloop:

This is decidedly the "Intelish" style of assembly. Some claim it's easier to understand. For 2-3 conditional lines, I wouldn't bother. For 10+, I would. In the middle there's a gray zone. :)

Bz and be are synonyms. The logic is clearer this way - you're implicitly comparing r0 to 0.

In this scenario, last instructions can ruin the flags all they want. Reading from r0 would still give you the already-decreased value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM