| 1 | // Copyright 2010-2022 Chris Spiegel. |
| 2 | // |
| 3 | // SPDX-License-Identifier: MIT |
| 4 | |
| 5 | #include "branch.h" |
| 6 | #include "memory.h" |
| 7 | #include "process.h" |
| 8 | #include "stack.h" |
| 9 | #include "types.h" |
| 10 | #include "util.h" |
| 11 | |
| 12 | void branch_if(bool do_branch) |
| 13 | { |
| 14 | uint8_t branch = byte(pc++); |
| 15 | |
| 16 | if (!do_branch) { |
| 17 | branch ^= 0x80; |
| 18 | } |
| 19 | |
| 20 | uint16_t offset = branch & 0x3f; |
| 21 | |
| 22 | if ((branch & 0x40) == 0) { |
| 23 | offset = (offset << 8) | byte(pc++); |
| 24 | |
| 25 | // Get the sign right. |
| 26 | if ((offset & 0x2000) == 0x2000) { |
| 27 | offset |= 0xc000; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | if ((branch & 0x80) == 0x80) { |
| 32 | if (offset > 1) { |
| 33 | pc += as_signed(offset) - 2; |
| 34 | ZASSERT(pc < memory_size, "branch to invalid address 0x%lx", static_cast<unsigned long>(pc)); |
| 35 | } else { |
| 36 | do_return(offset); |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | void zjump() |
| 42 | { |
| 43 | // -= 2 because pc has been advanced past the jump instruction. |
| 44 | pc += as_signed(zargs[0]); |
| 45 | pc -= 2; |
| 46 | |
| 47 | ZASSERT(pc < memory_size, "@jump to invalid address 0x%lx", static_cast<unsigned long>(pc)); |
| 48 | } |
| 49 | |
| 50 | void zjz() |
| 51 | { |
| 52 | branch_if(zargs[0] == 0); |
| 53 | } |
| 54 | |
| 55 | void zje() |
| 56 | { |
| 57 | if (znargs == 1) { |
| 58 | branch_if(false); |
| 59 | } else if (znargs == 2) { |
| 60 | branch_if(zargs[0] == zargs[1]); |
| 61 | } else if (znargs == 3) { |
| 62 | branch_if(zargs[0] == zargs[1] || zargs[0] == zargs[2]); |
| 63 | } else { |
| 64 | branch_if(zargs[0] == zargs[1] || zargs[0] == zargs[2] || zargs[0] == zargs[3]); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | void zjl() |
| 69 | { |
| 70 | branch_if(as_signed(zargs[0]) < as_signed(zargs[1])); |
| 71 | } |
| 72 | |
| 73 | void zjg() |
| 74 | { |
| 75 | branch_if(as_signed(zargs[0]) > as_signed(zargs[1])); |
| 76 | } |