Why doesn't my conditional Branch and Link Statement work?

444 views Asked by At

I am relatively new to the world of ARM so I apologize if I am missing something obvious. For some context, this code is being executed on a microcontroller based on the ARM Cortex-M4F.

When running this code I expected the branch & links with conditional statements to be run if certain conditions were met duh. But, what actually happens is that after the first compare, regardless of the state of the PSR flags, both KURUMA and SHUKAKU are branched to.

Now I have been able to get the correct conditional branches to work, if I remove the link part of the branch & link command.

How do I get the branch & link to work with a conditional statement, that is actually dependent on the PSR flags?

Thank you

    .text
    .align 2
    .global main
;
; ------------------------------

main:

    MOV R1, #5
    MOV R0, #1

    BL MATATBI
    NOP
    B main

MATATBI:
    PUSH{LR}
    CMPS R1, R0;
    BLHI KURUMA; branch & link if R1 is higher, unsigned,[C=1, Z=0] than r0 to kuruma
    NOP
    CMPS R1, R0;
    BLLO SHUKAKU; branch & link if R1 is lower, unsigned,[C=0] than r0 to shukaku
    NOP
    POP{LR}
    BX LR

KURUMA:
    ADD R1, #7
    BX LR

SHUKAKU:
    SUB R1, #4
    BX LR
hang_forever:
        nop
      B   hang_forever
;
; ------------------------------

    .end

; ------------------------------------------------------------```
1

There are 1 answers

1
Brighton Sikarskie On

The issue is with the BL (Branch and Link) instructions (BLHI and BLLO). These are intended to perform a function call only if certain conditions are met (based on the PSR (Program Status Register) flags set by the CMPS instruction).

Unlike the BHI and BLO, BL instructions will always execute the branch and update the LR (Link Register) regardless of the condition. This means that in your code both KURUMA and SHUKAKU are being called unconditionally. You need to seperate these instructions to make sure they only occur when the conditions are actually met.

MATATBI:
    PUSH {LR}
    CMPS R1, R0
    BHI KURUMA_COND
    BLO SHUKAKU_COND
    POP {LR}
    BX LR

KURUMA_COND:
    BL KURUMA
    B EXIT_MATATBI

SHUKAKU_COND:
    BL SHUKAKU
    B EXIT_MATATBI

EXIT_MATATBI:
    POP {LR}
    BX LR

KURUMA:
    ADD R1, #7
    BX LR

SHUKAKU:
    SUB R1, #4
    BX LR