M. Chen
M. Chen

Reputation: 213

assembly language code doesn't add correctly

I am trying to write an assembly language code that multiples a number by 2(without using multiplication) and print it out, but my assembly code is not working- it is printing 0 when it should be printing 20. I checked and I did initialize the %r10 to 10, but then after I copied %r10 to %r11 value of %r10 just becomes an unrelated number (582). Can someone help point out what I am doing wrong and how should I implement it? Thank you!

    .section .rodata
sOutputFmt: .string "%ld\n"
    .section .text
    .globl main
main:
    subq $8,%rsp
    movq $10,%r10
    
    movq %r11,%r10
    
    addq %r11,%r10
    addq %r11,%r10

    movq $sOutputFmt,%rdi
    movq %r10,%rsi
    call printf
    
    addq $8,%rsp
    ret

Upvotes: 1

Views: 182

Answers (1)

paxdiablo
paxdiablo

Reputation: 881323

movq $10,  %r10
movq %r11, %r10

AT&T syntax (as opposed to Intel syntax) has the source first then the destination. So the first line above correctly loads 10 into r10, then the second loads whatever was in r11 (probably zero based on your results) into r10, overwriting it.

If you want r11 to end up double r10, the sequence would be something like:

movq %r10, %r11  ; r11 <- r10
addq %r10, %r11  ; r11 <- r11 + r10

Notice there's a mov and a single add there. Your original code has a mov followed by two add instructions, meaning you would end up multiplying by three rather than two.

Upvotes: 2

Related Questions