generate dependency graph and remove dead instructions

This commit is contained in:
Sam Hadow 2024-03-30 22:42:03 +01:00
parent 39c5e930ca
commit 5f5ce35a08

View File

@ -97,6 +97,49 @@ class Ram(object):
print(*self.instr[self.current]['args'])
self.instr[self.current]['op'](self, *self.instr[self.current]['args'])
def generate_graph(self):
graph_edges = []
n_instr = len(self.instr)
for (n,instr) in enumerate(self.instr):
if ((instr['op'] == Ram.op) and (n<n_instr-1)):
graph_edges.append((n, n+1))
elif (instr['args'][0] == 'JUMP'):
dest = n+instr['args'][1]
if dest<n_instr:
graph_edges.append((n, dest))
elif ((instr['args'][0] == 'JL') or (instr['args'][0] == 'JE')):
if (n<n_instr-1):
graph_edges.append((n, n+1))
graph_edges.append((n, n+instr['args'][1]))
return graph_edges
def accessible_instr(self):
graph_edges = self.generate_graph()
accessible_from_instr = dict()
for edge in graph_edges:
accessible_from_instr.setdefault(edge[0], []).append(edge[1])
waitlist = [0]
accessible = []
while len(waitlist)>0:
current = waitlist.pop()
accessible.append(current)
try:
temp = accessible_from_instr[current]
except KeyError: # no node reachable from this node
pass
for elem in temp:
if elem not in accessible and elem not in waitlist:
waitlist.append(elem)
return sorted(accessible)
def remove_unreachable_instr(self):
accessible = self.accessible_instr()
new_instr = [instr for (i,instr) in enumerate(self.instr) if i in accessible]
for instr in new_instr:
print(instr)
self.instr = new_instr
### example