merge instructions

This commit is contained in:
Sam Hadow 2024-05-13 10:26:13 +02:00
parent f2204df7d7
commit 0c6cf984c9
3 changed files with 43 additions and 1 deletions

View File

@ -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)

View File

@ -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;

View File

@ -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