Author Topic: Keil studio Cortex-m0 LDR PC-relative instruction with offset  (Read 616 times)

0 Members and 1 Guest are viewing this topic.

Offline liudrTopic starter

  • Contributor
  • Posts: 36
  • Country: us
Keil studio Cortex-m0 LDR PC-relative instruction with offset
« on: January 04, 2026, 04:16:16 am »
I'm trying to get this to work:

Code: [Select]
__main
; Testing LDR instructions
LDR R0, =myData ;
LDR R1, [R0] ; Load myData's value to R1 using the address loaded into R0 by the previous instruction.
LDR R2, myData ; Directly load myData value to R2, using PC-relative reference.
LDR R2, myData+4; Directly load content stored at myData+4 to R2, using PC-relative reference.
B .
myData
DCD 0xFEDCBA98, 0x76543210

The above code is testing a few ways to load a value 0xFEDCBA98 into a register, all using PC-relative LDR. They all assemble and run correctly except for the last one, where I wanted to load the next value defined under the label myData. I tried a few ways to express the +4 offset including adding PC into the instruction or using [PC,#( myData -(.+4))]. As soon as I added PC, Keil refused to assemble, even if I just did LDR R2,[PC,#16] which is what the previous instruction assembles into or #18, which I think is the correct offset. Anyway, the error message is:

"main.s", line 24: Error: A1875E: Register Rn must be from R0 to R7 in this instruction

So, it seems that Keil either has a different way to use PC-relative or doesn't support a developer to use it. If it's you, would you define another label for the next 4 bytes of data?
 

Offline liudrTopic starter

  • Contributor
  • Posts: 36
  • Country: us
Re: Keil studio Cortex-m0 LDR PC-relative instruction with offset
« Reply #1 on: January 04, 2026, 05:23:31 am »
OK, I found my own issues. I didn't put align 4 before myData. And Keil studio's error message is no help. That R0-R7 error is just wrong. It should say myData lacks 4-byte alignment or something like that.

So the solution is:

Code: [Select]
__main
; Testing LDR instructions
LDR R2, myData ; Directly load myData value to R2, using PC-relative reference.
LDR R4, myData+4; Directly load content stored at myData+4 to R4, using PC-relative reference with a simple offset expression, without mentioning PC.
B .
align 4
myData
DCD 0xFEDCBA98, 0x76543210

Do NOT use [PC,#imm] ! Because Cortex-m0 only uses 16-bit Thumb instructions and the #imm are 4-byte aligned. You'll run into trouble assembling the instruction if it's not 4-byte aligned.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf