Strange behaviour with assembly program

Hi All,

I’m doing some assembly programming and i’m running into some strange behaviour. I’ve tried to isolate it from the rest of the program, so here is a demo program. It may seem a bit odd but it’s just to trigger the behaviour:

        .text
        .section .rodata
        .align  1

formatstring:
        .string "s5 value: %d\n"

        .align  1
        .globl  main
        .type   main, @function

main:
        addi sp,sp,-16
        sd ra,0(sp)
        sd s5,8(sp)

        li s5,2
        li t0,-3

        slli t0,t0,3
        srli t0,t0,3

        add s5,s5,t0

        bltz s5,skip

        la a0,formatstring
        mv a1,s5
        call printf@plt

skip:

        ld ra,0(sp)
        ld s5,8(sp)
        addi sp,sp,16
        li a0,0
        jr ra

I just compile with gcc and run in qemu or on the unmatched, both give the same result.

The output is:
s5 value: -1
Which is strange, because bltz should branch if s5 is lower than zero, and it should skip the call to printf, so there should be no output at all.
The trigger seems to be the logical shifts, if i remove those things work as expected.

Does anyone understand where this comes from? Since both qemu and the unmatched have the same behaviour i guess i’m doing something wrong, but i can’t see what :slight_smile:

Thanks in advance.

I’m assuming you are using a riscv64 toolchain. Change the %d to 0x%lx and I get
s5 value: 0x1fffffffffffffff
The value is positive, but %d only prints the lower 32 bits of the value which looks like a negative number.

1 Like

Thanks for your answer @jimw.
I’m indeed using either gcc natively on the unmatched or cross compiling on my x86 desktop.
I’ve changed srli for srai and now i get the result i was expecting :slight_smile: