How do I store or load by byte unit into memory when using “riscv32-unknown-elf-gcc”?

1.1k views Asked by At

I want to operate memory load or store in BYTE (8-bit) or HALF WORD (16-bit) unit.

So I made the C code as below and compiled it using "riscv32-unknown-elf-gcc".

void fun3 (void) {
    char i,j;
    i = (char)*(volatile unsigned int *) 0xf10007f8;
    j = (char)*(volatile unsigned int *) 0xf10007f4;
    *(volatile unsigned int *) 0xf10007f0 = (char) i+j;
    *(volatile unsigned int *) 0xf10007fc = (int ) 0x4;
}

I compiled it as follows and the de-asm code of the function is as follows.

riscv32-unknown-elf-gcc -march=rv32im -mabi=ilp32 -nostartfiles -nostdlib -Os   -x c  -Wl,-T,/work/test5.x -o test5.o test5.c
riscv32-unknown-elf-objdump -d -t test5.o > test5_Os.dump


f100006c <fun3>:
f100006c:   f1000737            lui a4,0xf1000
f1000070:   7f872783            lw  a5,2040(a4) # f10007f8 <__global_pointer$+0xffffeef0>
f1000074:   7f472683            lw  a3,2036(a4)
f1000078:   0ff7f793            andi    a5,a5,255
f100007c:   0ff6f693            andi    a3,a3,255
f1000080:   00d787b3            add a5,a5,a3
f1000084:   7ef72823            sw  a5,2032(a4)
f1000088:   00400793            li  a5,4
f100008c:   7ef72e23            sw  a5,2044(a4)
f1000090:   00008067            ret

I want to convert "lw" and "sw" to "lb" and "sb" in the assembler code above.

If you know, please answer.

1

There are 1 answers

1
yflelion On BEST ANSWER

If you remplace :

i = (char)*(volatile unsigned int *) 0xf10007f8;
j = (char)*(volatile unsigned int *) 0xf10007f4;
*(volatile unsigned int *) 0xf10007f0 = (char) i+j;

with :

i = *(char*) 0xf10007f8;
j = *(char*) 0xf10007f4;
*(char *) 0xf10007f0 = i+j;

The compiler will generate load and store bytes.
The fact is with your code you are telling him to load a word because you are using an unsigned int pointer, and cast the result to a char so it is normal he will use lw. The same for the store, you are using an unsigned int pointer.