diff options
author | Kartik Agaram <vc@akkartik.com> | 2018-09-07 22:13:10 -0700 |
---|---|---|
committer | Kartik Agaram <vc@akkartik.com> | 2018-09-07 22:19:13 -0700 |
commit | e07a3f2886b117970b3cd58f7cd6806cbfe5cc4a (patch) | |
tree | 6fcddb741f3b15eaa7892b5ce0468a6f3695005a /subx/apps/factorial.subx | |
parent | 608a7fa8d0faf9a3e3d182d9eabe969804443aab (diff) | |
download | mu-e07a3f2886b117970b3cd58f7cd6806cbfe5cc4a.tar.gz |
4537
Streamline the factorial function; we don't need to save a stack variable into a register before operating on it. All instructions can take a stack variable directly. In the process we found two bugs: a) Opcode f7 was not implemented correctly. It was internally consistent but I'd never validated it against a natively running program. Turns out it encodes multiple instructions, not just 'not'. b) The way we look up imm32 operands was sometimes reading them before disp8/disp32 operands.
Diffstat (limited to 'subx/apps/factorial.subx')
-rw-r--r-- | subx/apps/factorial.subx | 8 |
1 files changed, 3 insertions, 5 deletions
diff --git a/subx/apps/factorial.subx b/subx/apps/factorial.subx index c531041b..76594623 100644 --- a/subx/apps/factorial.subx +++ b/subx/apps/factorial.subx @@ -32,15 +32,13 @@ # factorial(n) factorial: - # initialize n - 8b/copy 1/mod/*+disp8 4/rm32/sib 4/base/ESP 4/index/none 2/r32/EDX 4/disp8 . # copy *(ESP+4) to EDX # initialize EAX to 1 (base case) b8/copy . . . . . . . 1/imm32 # copy 1 to EAX # if (n <= 1) jump exit - 81 7/subop/compare 3/mod/direct 2/rm32/EDX . . . . . 1/imm32 # compare EDX with 1 + 81 7/subop/compare 1/mod/*+disp8 4/rm32/sib 4/base/ESP 4/index/none . . 4/disp8 1/imm32 # compare *(ESP+4) with 1 7e/jump-if-<= . . . . . . $factorial:exit/disp8 # jump if <= to $factorial:exit # EBX: n-1 - 89/copy 3/mod/direct 3/rm32/EBX . . . 2/r32/EDX . . # copy EDX to EBX + 8b/copy 1/mod/*+disp8 4/rm32/sib 4/base/ESP 4/index/none 3/r32/EBX 4/disp8 . # copy *(ESP+4) to EBX 81 5/subop/subtract 3/mod/direct 3/rm32/EBX . . . . . 1/imm32 # subtract 1 from EBX # prepare call 55/push . . . . . . . . # push EBP @@ -56,7 +54,7 @@ factorial: # refresh n 8b/copy 1/mod/*+disp8 4/rm32/sib 4/base/ESP 4/index/none 2/r32/EDX 4/disp8 . # copy *(ESP+4) to EDX # return n * factorial(n-1) - 0f af/multiply 3/mod/direct 2/rm32/EDX . . . 0/r32/EAX . . # multiply EDX (n) into EAX (factorial(n-1)) + f7 4/subop/multiply 1/mod/*+disp8 4/rm32/sib 4/base/ESP 4/index/none 4/disp8 . # multiply *(ESP+4) (n) into EAX (factorial(n-1)) # TODO: check for overflow $factorial:exit: c3/return |