Search code examples
lc3

Can BR replace JSR to a certain extent?(LC-3)


I think that if I put the address of the instruction following BR into R7 and then jump to the address of of the subroutine.Is it just JSR to some extent?I'd like to ask what's the difference between BR and JSR that makes them distinct.


Solution

  • I'd like to ask what's the difference between BR and JSR that makes them distinct.

    JSR sets R7 to point to the instruction after JSR. That is what makes BR different from JSR.

    (There is another minor difference. JSR has a much longer range, because it uses an 11 bit offset instead of a 9 bit offset, which lets it reach labels that are 4 times further.)

    Can BR replace JSR to a certain extent?

    Yes. If you couldn't use JSR for some reason, you could work around it by using BR instead.

    Here's how you could call a subroutine using JSR:

    main         JSR subroutine
                 ; back from subroutine
    
    subroutine   ; do something
                 ; ...
                 RET
    

    Here's the equivalent code using BR/LEA:

    main         LEA R7, return
                 BR subroutine
    return       ; back from subroutine
    
    subroutine   ; do something
                 ; ...
                 RET
    

    (Note: this is not precisely equivalent, because LEA sets the CC register, and JSR does not.)