0

Using bison to generate assembly code for a simple calculator, but I can't figure out exactly what my bug is here, all the answers seem to be one multiplication off...

global intpow
intpow:
    push    ebp
    mov     ebp,esp
    mov     ecx,[ebp+8]
    mov     eax,[ebp+12]

loop:
    cmp     eax,1
    jle     finish
    dec     eax
    imul    ecx,ecx
    jmp     loop

finish:
    mov     eax,ecx
    mov     esp,ebp
    pop     ebp
    ret

Here's the code in my .y file when I identify an exponent call:

exp '^' exp        { $$ = pow ($1, $3);
          printf("call\tintpow\n");
          printf("push\tDWORD eax\n");
}

Is the assembly wrong? The .y? Both?

SetSlapShot
  • 1,298
  • 1
  • 21
  • 48
  • I suggest you employ rubber duck debugging and comment each line of assembly with what you believe it is doing. – Jens Björnhager Sep 19 '12 at 05:04
  • 3
    `imul ecx, ecx` will overwrite the original value with the multiplied result. The second iteration of the loop will compute `(y * y) * (y * y)` instead of `(y * y) * y`, and so on. – DCoder Sep 19 '12 at 05:06
  • Instead of a power function you've written [a tetration function](http://en.wikipedia.org/wiki/Tetration), which is same as [Knuth's double-arrow function](http://en.wikipedia.org/wiki/Knuth's_up-arrow_notation). It's valid code, only for different purpose. – nrz Sep 19 '12 at 05:43
  • 1
    What you are calculating is x^(2^y). – Gunther Piez Sep 19 '12 at 08:28

1 Answers1

1

(Comments converted to an Answer)

@DCoder wrote:

imul ecx, ecx will overwrite the original value with the multiplied result. The second iteration of the loop will compute (y * y) * (y * y) instead of (y * y) * y, and so on.

@nrz wrote:

nstead of a power function you've written a tetration function, which is same as Knuth's double-arrow function. It's valid code, only for different purpose.

@hirschhornsalz wrote:

What you are calculating is x^(2^y).

Community
  • 1
  • 1
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129