简体   繁体   中英

BL instruction ARM - How does it work

I am learning ARM Assembly, and I am stuck on something right now.

I know about the Link Register, which if I'm not wrong holds the address to return to when a function call completes.

So if we have something like that (taken from the ARM documentation):

0 | here
1 |   B there
2 |   
3 |   CMP R1, #0
4 |   BEQ anotherfunc
5 |
6 |   BL sub+rom ;  Call subroutine at computed address.

So, if we think of the column at the left as addresses of each instruction, then after the B there at address 1, the Link Register holds the value of 1 right?

Then the program goes to the method there and then it uses the value of the Link Register to know where to return.

If we skip to address 6 now, where I am stuck, we know what BL copies the address of the next instruction into lr (r14, the link register).

So now it would copy the address of sub which is a subroutine (what is a subroutine??) + rom (which is a number?) or the address of sub+rom (I don't know what this could be).

But in general, when would we need BL? Why do we want it in the example above? Can someone give me an example where we would really need it?

Thanks!

It seems there is a bit of confusion. Here is an explanation :

The B instruction will branch. It jumps to another instruction, and there is no return expected. The Link Register (LR) is not touched.

The BL instruction will branch, but also link. LR will be loaded with the address of the instruction after BL in memory, not the instruction executed after BL . It will then be possible to return from the branch using LR.

Example :

start:
01:  MOV r0, r2     ; some instruction
02:  B there        ; go there and never return !

there:
11:  MOV r1, r0         ; some instruction
12:  BL some_function   ; go to some_function, but hope to return !
                        ; this BL will load 13 into LR
13:  MOV r5, r0
14:  BL some_function   ; this BL will load 15 into LR
15:  MOV r6, r0


some_function:
     MOV r0, #3
     B LR               ; here, we go back to where we were before

If you want to call another function inside a function, LR will be overwritten, so you won't be able to return. The common solution is to save LR on the stack with PUSH {LR} , and restore it before returning with POP {LR} . You can even restore and return in a single POP {PC} : this will restore the value of LR, but in the program counter, effectively returning of the function.

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