Conditional Execution for “And” in ARM syntax

こ雲淡風輕ζ 提交于 2020-01-06 04:12:29

问题


I'm trying to get a grip on conditional execution within ARM programming.

So I kind of understand a situation like this:

if ( (R0 != 5) || (R2 != R3) ) ; != means not equal,  || mean OR 
{  
R4-- ; // R4 = R4 - 1 
}

And the ARM version of this would be:

CMP   R0, 5
CMPEQ R2, R3
SUBNE R4, R4, 1

I was curious how ARM knows that that is an "OR" (||). So it does two compares. But what happens if both compares aren't correct. Is that what NE does? What happens if they were different (like example below).

So lets say the code is this:

if ( (R0 > 5) && (R2 != R3) ) ; != means not equal,  && mean AND 
{  
R4-- ; // R4 = R4 - 1 
}

How would you write this with conditional instructions in ARM?

Thanks!


回答1:


This is some simple logic that seems counter intuitive for the 'OR' case. The 'AND' is simpler in my opinion. The key is that the 2nd condition should only be evaluated if the first passed for 'AND'. For the 'OR' case it is the opposite. You short circuit the logic and don't bother to execute the 2nd condition.


Here are the steps for the 'AND' case,

  1. test cc1
  2. if cc1 test cc2
  3. execute if cc2

If 'cc1 == cc2' and the first is false then step 2 doesn't execute and hence not 3 as well.


To take your example,

if((R0 > 5) && (R2 != R3)) R4--; 

It would translate as,

TST   R2, R3     ; step 1 as (R2 != R3)
MSREQ CPSR_f,#3<<30 ; set N and Z flags  (also APSR_nz)
CMPNE R0, #5     ; step 2 as (R0 > 5)
SUBPL R4, #1     ; step 3

Care must be taken to ensure that the first test in step 1 does not influence the execution of step 3. Tests can be re-ordered for the 'AND' condition as both must be tested.

See:
Dave space on conditional execution
HeyRick on status register




回答2:


So I think I have found a solution for my problem.. For those that may also need this help. I had a Professor help me out luckily.

So lets say the code is:

if ( (R0 > 5) && (R2 != R3) ) ; != means not equal,  && mean AND 
{  
R4-- ; // R4 = R4 - 1 
}

ARM conditional solution could be:

CMP   R0, #5
BLE   Somewhere
CMP   R2, R3
SUBNE R4, #1
Somewhere:

Somewhere is there to branch away from the next compare because since its an "&&" and it has failed, you want to make sure that you don't keep going in the if statement.

BLE stands for branch if less than or equal



来源:https://stackoverflow.com/questions/39823486/conditional-execution-for-and-in-arm-syntax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!