BL instruction ARM - How does it work

走远了吗. 提交于 2020-01-03 01:21:05

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/34091898/bl-instruction-arm-how-does-it-work

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