From 0c6cf984c91c642482bc00d7968094050a05aa7c Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Mon, 13 May 2024 10:26:13 +0200 Subject: [PATCH] merge instructions --- src/ram.py | 33 +++++++++++++++++++++++++++++++++ src/ram.y | 2 +- src/test.asm | 9 +++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/src/ram.py b/src/ram.py index 12640f5..1e51a66 100644 --- a/src/ram.py +++ b/src/ram.py @@ -185,3 +185,36 @@ class Ram(object): for instr in new_instr: print(instr) self.instr = new_instr + + def predecessors(self, node): + graph_edges = self.generate_graph() + return [edge[0] for edge in graph_edges if edge[1] == node] + + def merge_instructions(self): + for (n,instr) in enumerate(self.instr): + if instr['op'] == Ram.op and (instr['args'][0] == 'ADD' or instr['args'][0] == 'MULT'): + registry = instr['args'][3] + op = instr['args'][0] + if (instr['args'][1] == registry and instr['args'][2][0] == 'value') or (instr['args'][2] == registry and instr['args'][1][0] == 'value'): + predecessors = self.predecessors(n) + if len(predecessors) == 1: + predecessor_instr = self.instr[predecessors[0]] + if predecessor_instr['op'] == Ram.op: + if op == predecessor_instr['args'][0] and predecessor_instr['args'][1][0] == 'value' and predecessor_instr['args'][2][0] == 'value' and predecessor_instr['args'][3] == registry: + if op == 'ADD': + value_int = predecessor_instr['args'][1][1] + predecessor_instr['args'][2][1] + if instr['args'][1][0] == 'value': + value_int += instr['args'][1][1] + else: + value_int += instr['args'][2][1] + self.instr[n] = {"op": Ram.op, "args": (op, ('value', value_int), ('value', 0), registry)} + elif op == 'MULT': + value_int = predecessor_instr['args'][1][1] * predecessor_instr['args'][2][1] + if instr['args'][1][0] == 'value': + value_int *= instr['args'][1][1] + else: + value_int *= instr['args'][2][1] + self.instr[n] = {"op": Ram.op, "args": (op, ('value', value_int), ('value', 1), registry)} + self.instr.pop(predecessors[0]) + for instr in self.instr: + print(instr) diff --git a/src/ram.y b/src/ram.y index f356dc5..075e565 100644 --- a/src/ram.y +++ b/src/ram.y @@ -128,7 +128,7 @@ int main() { fprintf(stderr, "Error creating file machine.py\n"); return 1; } else { - fprintf(file, "from ram import *\n\n%s\nram = Ram(instructions, input_registers)\nram.remove_unreachable_instr()\nram.execute()\nprint(\"Result:\", ram.output_registers)\n", result); + fprintf(file, "from ram import *\n\n%s\nram = Ram(instructions, input_registers)\nram.remove_unreachable_instr()\nprint()\nram.merge_instructions()\nram.execute()\nprint(\"Result:\", ram.output_registers)\n", result); fclose(file); } return 0; diff --git a/src/test.asm b/src/test.asm index a403cfa..c41634e 100644 --- a/src/test.asm +++ b/src/test.asm @@ -1,7 +1,16 @@ (10,5,1,2,4) + ADD(i0 ,1 ,r0) SUB(i1,3,r1) +ADD(6, 4, r0) +ADD(8, r0, r0) +ADD(r0, 0, o3) + +MULT(2, 3, r0) +MULT(2, r0, r0) +ADD(r0, 0, o4) + JUMP(2) DIV(10,2,r1) // unreachable