Search code examples
assemblyarm

ARM assembly,remain the same r2 by using ldr after loops


I'm new to arm assembly language. I was trying to keep loading r2 with the same value for r0 after ending the loop. However, when I run the code ldr r2,[fp,#4] by second times, the value is changed. What should I do to fix it so that I can ldr r2 with the same value as r0?

.syntax unified
.global main
.type main, %function


main:
  ldr r1, =storage
  @ your code starts here
  bl addvalue

initial_pointer:
addvalue:
   stmdb sp!,{fp,lr}
   add fp,sp,#4
   sub sp,#4
   str r0,[fp,#-8]
   ldr r0,[r1],4
   str r0,[sp,4]! @provide r0 to next branch
   bl get_loop
   add sp,#4
   add sp,#4
   ldmia sp!,{fp,lr}
   bx lr
get_loop:
  stmdb sp!,{fp,lr}
  add fp,sp,#4
  sub sp,#4
  ldr r2,[fp,#4] @load r2 with the value of r0
  bl loop
  add sp,4
  ldmia sp!,{fp,lr}
  bx lr
loop:
   cmp r2,0 @loop control
   beq get_loop
   sub r2,1
   b loop
   
  b main





.size main, .-main
.data
storage:
  .word 5, 3, 2, 1

Solution

  • However, when I run the code ldr r2,[fp,#4] by second times, the value is changed

    Because fp is changed, so you are reading different memory address

      stmdb sp!,{fp,lr}  # sp is changed here by 2regs * 4Bytes = 8Bytes
      add fp,sp,#4       # fp = sp from previous iteration - 8 + 4