-
Notifications
You must be signed in to change notification settings - Fork 0
/
optimizer.py
640 lines (420 loc) · 15.1 KB
/
optimizer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
#!/usr/bin/env python
# coding: utf-8
# In[26]:
import os
from pprint import pprint
import networkx as nx
import matplotlib.pyplot as plt
quads = open('quads.txt', 'r').readlines()
quads = [i.strip().split('\t') for i in quads]
start, end = 0, len(quads)
for idx, i in enumerate(quads):
if '--All Quads--' in i[0]:
start=idx
if '------------------------------------' in i[0]:
end = idx
quads = quads[start+1:end]
blocks = [[]]
next_block = [[]]
functions = {}
skip_f = False
idx = -1
returnto = []
labels = {}
mode="read" #read
# for i in quads:
# print(i)
function_trig = []
# print("\n\nFLow graph")
while idx<len(quads):
# print(idx, quads[idx])
idx+=1
if idx>=len(quads):
break
ith_quad = quads[idx]
if 'BeginF' == ith_quad[1]:
functions[ith_quad[2]] = idx
skip_f = True
if 'EndF' == ith_quad[1]:
# print("Return to", returnto)
if skip_f:
skip_f = False
continue
else:
idx = returnto.pop()
blocks[-1].append(ith_quad)
blocks.append([])
continue
if skip_f:
continue
if 'Label' == ith_quad[1]:
if len(blocks[-1]) != 0:
blocks.append([])
labels[ith_quad[-1]] = len(blocks)-1
if 'If False' == ith_quad[1] or 'goto' == ith_quad[1]:
blocks[-1].append(ith_quad)
blocks.append([])
continue
blocks[-1].append(ith_quad)
if 'Call' == ith_quad[1]:
if ith_quad[2] not in function_trig:
function_trig.append(ith_quad[2])
else:
continue
if len(blocks[-1]) != 0:
blocks.append([])
returnto.append(idx)
fname = ith_quad[2]
blocks[-1].append(quads[functions[fname]])
idx = functions[fname]
shift=0
for idx, block in enumerate(blocks):
if len(block) == 0:
blocks.pop(idx-shift)
shift+=1
# In[27]:
blocks
# In[28]:
from pyvis.network import Network
plt.rcParams["figure.figsize"] = (28,28)
import networkx as nx
connections = []
edge = []
edge_labels = []
G = nx.DiGraph()
block_names = []
for idx, i in enumerate(blocks):
# block_names.append(f"Block {idx}:\n"+'\n'.join([str(j) for j in i]))
block_names.append(f"Block {idx}")
G.add_node(block_names[-1])
for idx, (b_name, code_) in enumerate(zip(block_names, blocks)):
if 'goto' in code_[-1][1]:
l = code_[-1][-1]
G.add_edge(block_names[idx], block_names[labels[l]], label="goto")
edge.append((block_names[idx], block_names[labels[l]]))
edge_labels.append("goto")
continue
if 'If False' in code_[-1][1]:
l = code_[-1][-1]
G.add_edge(block_names[idx], block_names[labels[l]], label="If False")
edge.append((block_names[idx], block_names[labels[l]]))
edge_labels.append("If False")
if idx+1<len(block_names):
G.add_edge(block_names[idx], block_names[idx+1], label="next")
edge.append((block_names[idx], block_names[idx+1]))
edge_labels.append("next")
# for i, j in zip(block_names, blocks):
# #pprint(i)
# print("==============")
# In[29]:
# nx.draw_networkx(G, with_labels=True, node_shape="s", node_color="none", bbox=dict(facecolor="skyblue", edgecolor='black', boxstyle='round'), font_size=10, alpha=1, width=2.)
pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
nx.draw_networkx_nodes(G, pos, node_size=20000, alpha=0.3, node_shape="s")
# nx.draw_networkx_labels(G, pos, font_size=10, font_family="sans-serif")
# nx.draw_networkx_edges(G, pos, width=2)
# nx.draw_networkx_edge_labels(G, pos, font_size=10)
nx.draw_networkx_labels(G, pos, font_size=20, font_family="sans-serif")
nx.draw_networkx_edges(G, pos, width=2)
nx.draw_networkx_edge_labels(G, pos, font_size=15)
# nx.draw_networkx(G, with_labels=True, node_shape="s", node_color="none", bbox=dict(facecolor="skyblue", edgecolor='black', boxstyle='round'), font_size=10, alpha=1, width=2.)
#plt.show()
# In[30]:
from pyvis.network import Network
plt.rcParams["figure.figsize"] = (20,20)
import networkx as nx
connections = []
edge = []
edge_labels = []
G = nx.DiGraph()
block_names = []
for idx, i in enumerate(blocks):
block_names.append(f"Block {idx}:\n"+'\n'.join([str(j) for j in i]))
# block_names.append(f"Block {idx}")
G.add_node(block_names[-1])
for idx, (b_name, code_) in enumerate(zip(block_names, blocks)):
if 'goto' in code_[-1][1]:
l = code_[-1][-1]
G.add_edge(block_names[idx], block_names[labels[l]], label="goto")
edge.append((block_names[idx], block_names[labels[l]]))
edge_labels.append("goto")
continue
if 'If False' in code_[-1][1]:
l = code_[-1][-1]
G.add_edge(block_names[idx], block_names[labels[l]], label="If False")
edge.append((block_names[idx], block_names[labels[l]]))
edge_labels.append("If False")
if idx+1<len(block_names):
G.add_edge(block_names[idx], block_names[idx+1], label="next")
edge.append((block_names[idx], block_names[idx+1]))
edge_labels.append("next")
# for i, j in zip(block_names, blocks):
# #pprint(i)
# print("==============")
# In[31]:
# nx.draw_networkx(G, with_labels=True, node_shape="s", node_color="none", bbox=dict(facecolor="skyblue", edgecolor='black', boxstyle='round'), font_size=10, alpha=1, width=2.)
pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
nx.draw_networkx_nodes(G, pos, node_size=20000, alpha=0.3, node_shape="s")
nx.draw_networkx_labels(G, pos, font_size=10, font_family="sans-serif")
nx.draw_networkx_edges(G, pos, width=2)
nx.draw_networkx_edge_labels(G, pos, font_size=12)
# nx.draw_networkx(G, with_labels=True, node_shape="s", node_color="none", bbox=dict(facecolor="skyblue", edgecolor='black', boxstyle='round'), font_size=10, alpha=1, width=2.)
#plt.show()
# In[32]:
class ICG:
def __init__(self, l) -> None:
self.l = l
self.lineno = l[0]
self.op = l[1]
l[2:] = [None if i=='-' else (i.strip() if i!=None else None) for i in l[2:]]
self.op1 = l[2]
self.op2 = l[3]
self.result = l[4]
def __repr__(self) -> str:
return f"{self.l[0]}: {self.op}, {self.op1}, {self.op2}, {self.result}"
block1 = [ICG(i) for i in blocks[0]]
# In[33]:
blocks
# In[34]:
block1 = [ICG(i) for i in blocks[0]]
block1
# In[35]:
def plot_DAG(block1):
nodes = []
for i in block1:
nodes.append(i.op1)
nodes.append(i.op2)
nodes.append(i.result)
nodes = list(set(nodes))
nodes.remove(None)
# print(nodes)
G = nx.DiGraph()
for i in nodes:
G.add_node(i)
for i in block1:
if i.result:
if i.op == "goto":
G.add_edge(i.result, i.result, label=i.op)
continue
if i.op1:
G.add_edge(i.op1, i.result, label=i.op)
if i.op2:
G.add_edge(i.op2, i.result, label=i.op)
elif i.op == 'Print':
G.add_edge(i.op1, i.op, label=i.op)
# nx.draw_networkx(G, with_labels=True, node_shape="s", node_color="none", bbox=dict(facecolor="skyblue", edgecolor='black', boxstyle='round'), font_size=10, alpha=1, width=2.)
pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
nx.draw_networkx_nodes(G, pos, node_size=5000, alpha=0.3, node_shape="s")
nx.draw_networkx_labels(G, pos, font_size=20, font_family="sans-serif")
nx.draw_networkx_edges(G, pos, width=2)
nx.draw_networkx_edge_labels(G, pos, font_size=20)
# nx.draw_networkx(G, with_labels=True, node_shape="s", node_color="none", bbox=dict(facecolor="skyblue", edgecolor='black', boxstyle='round'), font_size=10, alpha=1, width=2.)
#plt.show()
plot_DAG(block1)
# In[36]:
block1
# In[37]:
def check_str(a):
return (a[0]=='"' and a[-1]=='"') or (a=='True' or a=='False')
def constant_propagation_replace(block1, idx, term, value):
for i in range(idx, len(block1)):
if block1[i].op1 == term:
# print("Replacing", block1[i], "with", value)
block1[i].op1 = value
if block1[i].op2 == term:
# print("Replacing", block1[i], "with", value)
block1[i].op2 = value
if block1[i].result == term: ## if term is result of any operation, then stop replacing
break
return block1
def constant_propagation(block1):
for idx, i in enumerate(block1):
if i.result !=None:
if i.op2 == None and i.op1 is not None :
if i.op1.isdigit() or check_str(i.op1):
block1 = constant_propagation_replace(block1, idx+1, i.result, i.op1)
continue
elif i.op1 == None and i.op2 is not None:
if i.op2.isdigit() or check_str(i.op2):
block1 = constant_propagation_replace(block1, idx+1, i.result, i.op1)
continue
elif i.op1 == None and i.op2 == None:
continue
return block1
def constant_folding(block1):
for idx, i in enumerate(block1):
if i.op1 != None and i.op2 != None:
if (i.op1.isdigit() or check_str(i.op1)) and (i.op2.isdigit() or check_str(i.op2)):
# print("Constant folding", i)
block1[idx] = ICG([i.lineno, "=", str(eval(f"{i.op1} {i.op} {i.op2}")), None, i.result])
return block1
# In[38]:
block1 = constant_propagation(block1)
plot_DAG(block1)
block1 = constant_folding(block1)
# #pprint(block1)
plot_DAG(block1)
# In[39]:
def tot_repr(tot_icg):
return '\n'.join(['\n'.join([j.__repr__() for j in i]) for i in tot_icg])
tot_icg = []
for i in blocks:
tot_icg.append([ICG(j) for j in i])
from copy import deepcopy
before_copy = deepcopy(tot_icg)
while True:
for i in range(len(tot_icg)):
tot_icg[i] = constant_folding(tot_icg[i])
tot_icg[i] = constant_propagation(tot_icg[i])
#pprint(tot_icg)
plot_DAG(tot_icg[0])
if tot_repr(tot_icg) == tot_repr(before_copy):
break
before_copy = deepcopy(tot_icg)
# In[40]:
#pprint(tot_icg), plot_DAG(tot_icg[0])
# In[41]:
def deadcodeeliminations(blocks):
in_use = {}
for idx, block in enumerate(blocks):
for idx_l, linel in enumerate(block):
if linel.op1:
if not linel.op1.isdigit() or (linel.op1[0]=='"' and linel.op1[-1]=='"'):
in_use[linel.op1] = True
if linel.op2:
if not linel.op2.isdigit() or (linel.op2[0]=='"' and linel.op2[-1]=='"'):
in_use[linel.op2] = True
if linel.result and linel.op == '=':
if not linel.result.isdigit() or (linel.result[0]=='"' and linel.result[-1]=='"'):
in_use[linel.result] = False
else:
continue
blocks[idx] = block
#pprint(in_use)
for idx, block in enumerate(blocks):
offset = 0
for idx_l, linel in enumerate(block):
if linel.op=="Label" or linel.op=="goto" or linel.op=="If False" or linel.op=="BeginF" or linel.op=="EndF":
continue
if linel.result:
if linel.result in in_use:
if not in_use[linel.result]:
block.pop(idx_l-offset)
offset+=1
return blocks
before_copy = deepcopy(tot_icg)
while True:
tot_icg = deadcodeeliminations(tot_icg)
for i in range(len(tot_icg)):
tot_icg[i] = constant_folding(tot_icg[i])
tot_icg[i] = constant_propagation(tot_icg[i])
if tot_repr(tot_icg) == tot_repr(before_copy):
break
else:
before_copy = deepcopy(tot_icg)
#pprint(tot_icg)
plot_DAG(tot_icg[0])
# In[42]:
#pprint(tot_icg)
# In[43]:
for i in tot_icg:
#pprint(i)
plot_DAG(i)
# In[44]:
blocks
# In[45]:
#pprint(tot_icg)
# In[46]:
def remove_unreachable(tot_icg):
reachable = {}
for idx, block in enumerate(tot_icg):
for idx_l, linel in enumerate(block):
if linel.op == 'goto':
reachable[linel.result] = True
if linel.op == 'If False':
reachable[linel.result] = True
print(reachable)
offset = 0
for idx, block in enumerate(tot_icg):
if block[0].op == 'Label':
if block[-1].result not in reachable:
tot_icg.pop(idx-offset)
offset+=1
return tot_icg
def peephole(tot_icg):
tot_icg = remove_unreachable(tot_icg)
for idx, block in enumerate(tot_icg):
offset = 0
for idx_l, linel in enumerate(block):
if linel.op == 'If False':
if linel.op1 in ['True', 'False']:
if linel.op1 == 'False':
block[idx_l] = ICG([linel.lineno, 'goto', linel.result, None, None])
else:
block.pop(idx_l-offset)
offset+=1
tot_icg = remove_unreachable(tot_icg)
return tot_icg
# In[47]:
tot_icg = peephole(tot_icg)
tot_icg
# In[48]:
plt.rcParams["figure.figsize"] = (10,10)
for i in tot_icg:
#pprint(i)
plot_DAG(i)
# In[49]:
icg_tolist = []
for i in tot_icg:
temp = []
for j in i:
temp.append([j.op, j.op1, j.op2, j.result])
for _i in range(len(temp[-1])):
if temp[-1][_i] == None:
temp[-1][_i] = '-'
icg_tolist.append(temp)
blocks = icg_tolist
blocks
# In[50]:
from pyvis.network import Network
plt.rcParams["figure.figsize"] = (10,10)
import networkx as nx
connections = []
edge = []
edge_labels = []
G = nx.DiGraph()
block_names = []
for idx, i in enumerate(blocks):
block_names.append(f"Block {idx}:\n"+'\n'.join([str(j) for j in i]))
# block_names.append(f"Block {idx}")
G.add_node(block_names[-1])
for idx, (b_name, code_) in enumerate(zip(block_names, blocks)):
if 'goto' in code_[-1][1]:
l = code_[-1][-1]
G.add_edge(block_names[idx], block_names[labels[l]], label="goto")
edge.append((block_names[idx], block_names[labels[l]]))
edge_labels.append("goto")
continue
if 'If False' in code_[-1][1]:
l = code_[-1][-1]
G.add_edge(block_names[idx], block_names[labels[l]], label="If False")
edge.append((block_names[idx], block_names[labels[l]]))
edge_labels.append("If False")
if idx+1<len(block_names):
G.add_edge(block_names[idx], block_names[idx+1], label="next")
edge.append((block_names[idx], block_names[idx+1]))
edge_labels.append("next")
# for i, j in zip(block_names, blocks):
# #pprint(i)
# print("==============")
# nx.draw_networkx(G, with_labels=True, node_shape="s", node_color="none", bbox=dict(facecolor="skyblue", edgecolor='black', boxstyle='round'), font_size=10, alpha=1, width=2.)
pos = nx.nx_agraph.graphviz_layout(G, prog='dot')
nx.draw_networkx_nodes(G, pos, node_size=20000, alpha=0.3, node_shape="s")
nx.draw_networkx_labels(G, pos, font_size=10, font_family="sans-serif")
nx.draw_networkx_edges(G, pos, width=2)
nx.draw_networkx_edge_labels(G, pos, font_size=12)
# nx.draw_networkx(G, with_labels=True, node_shape="s", node_color="none", bbox=dict(facecolor="skyblue", edgecolor='black', boxstyle='round'), font_size=10, alpha=1, width=2.)
#plt.show()
print("-----------After all optimization: Code propagation, folding, peephole----------------");
for i in icg_tolist:
for j in i:
print('\t'.join(j))