-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOptimize.cpp
More file actions
1469 lines (1264 loc) · 57.1 KB
/
Copy pathOptimize.cpp
File metadata and controls
1469 lines (1264 loc) · 57.1 KB
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
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Attempts to reduces the number of lines of code in a TM by looking
* for patterns commonly produced by the code generators for Call/Done
* and for Set/Load.
*
* This optimizer works as follows.
*
* * For each label consisting just of an unconditional Goto, replace all
* Gotos to that label with Gotos to the target label.
*
* * Remove all (non-Start) labels that have nothing pointing into them.
*
* * Reorder the code so that Gotos that are the only way to reach
* specific labels are removed, along with the target label.
*
* * Remove all Gotos that go directly to the next line.
*
* * Group all consecutive labels together into a single label.
*
* * Remove any Move Lefts immediately followed by Remove Rights
* or vice-versa.
*
* * Repeat the above until no improvements can be made.
*
* * Replace all label names with (hopefully!) shorter ones.
*
* These are all syntactic simplifications; no attempt is made at
* semantic improvements (e.g. looking for unnecessary moves / writes
* or combining different code paths together).
*/
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <iomanip>
#include <queue>
#include <set>
#include <sstream>
#include <optional>
#include "Turing/StrUtils/StrUtils.h"
#include "Turing/Turing.h"
using namespace std;
namespace {
/* Lists all errors found in the program. */
void showErrorsIn(const Turing::Program& program) {
cout << "Errors found in program:" << endl;
for (size_t i = 0; i < program.numLines(); i++) {
auto error = program.errorAtLine(i);
if (error != "") {
cout << setw(6) << i << " " << program.line(i) << endl;
cout << " " << error << endl;
}
}
}
/* Finds all Goto labels. */
set<string> usedLabelsIn(const Turing::Program& program) {
set<string> result = { "Start" }; // Start is always used
for (size_t i = 0; i < program.numLines(); i++) {
if (auto statement = program.statement(i)) {
class LabelFinder: public Turing::Calculator<set<string>> {
public:
set<string> handle(Turing::Goto& g) override {
return { g.label() };
}
set<string> handle(Turing::If& i, const set<string>& nested) override {
return nested;
}
};
auto labels = LabelFinder().calculate(*statement);
result.insert(labels.begin(), labels.end());
}
}
return result;
}
Turing::Program removeUnusedLabelsFrom(const Turing::Program& p) {
auto labels = usedLabelsIn(p);
stringstream builder;
for (size_t i = 0; i < p.numLines(); i++) {
auto label = dynamic_pointer_cast<Turing::Label>(p.statement(i));
/* Output this line UNLESS it's an unused label (i.e. not a label or
* is used) OR has no statement.
*/
if (p.statement(i) && (!label || labels.contains(label->label()))) {
builder << p.line(i) << '\n';
}
}
return Turing::Program(builder);
}
/* A basic block in the program. This consists of a maximal region of
* contiguous straight-line code.
*/
struct BasicBlock {
/* Range of lines from the original program. */
size_t firstLine = 0xBADBADBADU, lastLine = 0xBADBADBADU;
/* In and out arrows in the control-flow graph. */
set<BasicBlock*> in, out;
/* "Pinning" information. A basic block can be pinned
* to the block before or after it if it continues to
* those blocks via fallthrough. When moving blocks
* around, we have to treat pinned blocks as a unit.
*
* Each block stores the BB that is pinned before
* and after it, which could be nullptr if it isn't
* pinned on each side.
*/
BasicBlock* pinnedBefore = nullptr;
BasicBlock* pinnedAfter = nullptr;
/* Whether this basic block terminates in an unconditional
* Goto statement. This is used by the optimizer to reorder
* blocks and eliminate Gotos and labels.
*/
bool endsInGoto = false;
/* Whether this basic block begins with a label. This is used
* by the optimizer to reorder blocks and eliminate Gotos and
* labels.
*/
bool startsWithLabel = false;
bool isStartLabel = false;
/* The "chain" that this basic block belongs to. */
struct Chain* chain = nullptr;
};
/* A "chain" in the program. A chain consists of a maximal region
* of pinned blocks in a row.
*/
struct Chain {
deque<BasicBlock*> bbs;
};
/* Returns whether the given statement is a label. */
bool isLabel(const shared_ptr<Turing::Statement>& statement) {
return dynamic_pointer_cast<Turing::Label>(statement) != nullptr;
}
/* Returns whether the given statement contains a Goto. */
bool containsGoto(shared_ptr<Turing::Statement> statement) {
/* Peek into If statements. */
if (auto i = dynamic_pointer_cast<Turing::If>(statement)) {
statement = i->stmt();
}
return dynamic_pointer_cast<Turing::Goto>(statement) != nullptr;
}
/* Returns whether the given statement contains a Return. */
bool containsReturn(shared_ptr<Turing::Statement> statement) {
/* Peek into If statements. */
if (auto i = dynamic_pointer_cast<Turing::If>(statement)) {
statement = i->stmt();
}
return dynamic_pointer_cast<Turing::Return>(statement) != nullptr;
}
/* Given a line in a program, outputs the line numbers of its successors. */
set<size_t> successorsOf(const Turing::Program& program, size_t line) {
class SuccessorFinder: public Turing::Calculator<set<size_t>> {
public:
SuccessorFinder(const Turing::Program& program, size_t line) : program(program), line(line) {
// Handled in initialization line
}
/* Most statements fall through to the next line. */
set<size_t> handle(Turing::Label&) override {
return nextLine();
}
set<size_t> handle(Turing::Move&) override {
return nextLine();
}
set<size_t> handle(Turing::Write&) override {
return nextLine();
}
/* Return statements have no successors. */
set<size_t> handle(Turing::Return&) override {
return { };
}
/* Conditionals can either go to the next line or wherever their
* nested statements go.
*/
set<size_t> handle(Turing::If&, const set<size_t>& nestedTargets) override {
auto result = nestedTargets;
auto next = nextLine();
result.insert(next.begin(), next.end());
return result;
}
/* Gotos go where their labels are. */
set<size_t> handle(Turing::Goto& g) override {
return { program.lineForLabel(g.label()) };
}
private:
const Turing::Program& program;
size_t line;
/* Finds the next line after the given one. */
set<size_t> nextLine() const {
return line + 1 < program.numLines()? set<size_t>{ line + 1 } : set<size_t>{ };
}
};
return SuccessorFinder(program, line).calculate(*program.statement(line));
}
/* Basic blocks, keyed by their starting lines. */
map<size_t, BasicBlock*> basicBlocksIn(const Turing::Program& program) {
map<size_t, BasicBlock*> result;
/* Worklist algorithm; we're doing a BFS over the program looking
* for reachability. As we do, we assemble the basic blocks.
*/
auto startLine = program.lineForLabel("Start");
queue<size_t> worklist;
worklist.push(startLine);
result[startLine] = new BasicBlock { startLine, startLine };
/* Standard BFS. */
while (!worklist.empty()) {
/* Grab the current line. */
size_t startLine = worklist.front();
worklist.pop();
/* Keep stepping forward until we have a reason not to. */
auto* bb = result[startLine];
for (size_t line = startLine; line < program.numLines(); line++) {
/* If this line is a label and isn't the very first line in the
* BB, we've gone too far.
*/
if (line != startLine && isLabel(program.statement(line))) {
break;
}
/* Otherwise, this line is part of the BB. Pessimistically assume
* it's the last line.
*/
bb->lastLine = line;
/* The basic block will continue onward to the next line unless any of
* the following conditions hold:
*
* 1. The current line is a Goto or contains a Goto.
* 2. The current line is a Return or contains a Return.
*/
if (containsGoto(program.statement(line)) ||
containsReturn(program.statement(line))) {
break;
}
}
/* Now, wire the appropriate links to other blocks. */
for (size_t successor: successorsOf(program, bb->lastLine)) {
auto* targetBB = result[successor];
/* If we've never seen this BB before, we need to enqueue it into our BFS
* worklist. If we have seen it before, all we're doing is updating its
* information.
*/
if (!targetBB) {
result[successor] = new BasicBlock{ successor, successor };
targetBB = result[successor];
worklist.push(successor);
}
/* Update predecessor/successor information. */
targetBB->in.insert(bb);
bb->out.insert(targetBB);
}
/* Look at the very last instruction of the current basic block. If it's
* not a Goto or Return, then we are pinned to whatever block comes after us.
*
* Edge case: The very last line of the program can't pin to the nothing
* that comes after it.
*/
if (typeid(*program.statement(bb->lastLine)) != typeid(Turing::Goto) &&
typeid(*program.statement(bb->lastLine)) != typeid(Turing::Return) &&
bb->lastLine + 1 != program.numLines()) {
auto* successor = result.at(bb->lastLine + 1);
bb->pinnedAfter = successor;
successor->pinnedBefore = bb;
}
/* If our very last line is an unconditional Goto, remember that for later. */
if (typeid(*program.statement(bb->lastLine)) == typeid(Turing::Goto)) {
bb->endsInGoto = true;
}
/* If our very first line is a label, remember that for later. */
if (typeid(*program.statement(bb->firstLine)) == typeid(Turing::Label)) {
bb->startsWithLabel = true;
}
/* If we're the start label, remember that for later. */
if (program.lineForLabel("Start") == bb->firstLine) {
bb->isStartLabel = true;
}
}
return result;
}
[[ maybe_unused ]] void printBBs(const map<size_t, BasicBlock*>& bbs, const Turing::Program& program) {
for (auto [line, bb]: bbs) {
cout << "Basic block starting on line " << line << ": " << endl;
for (size_t i = bb->firstLine; i <= bb->lastLine; i++) {
cout << " " << setw(6) << i << " " << program.line(i) << endl;
}
cout << " ----" << endl;
cout << " IN: ";
for (auto* in: bb->in) {
cout << in->firstLine << " ";
}
cout << endl;
cout << " OUT: ";
for (auto* out: bb->out) {
cout << out->firstLine << " ";
}
cout << endl;
if (bb->pinnedBefore) {
cout << " Pinned above to BB " << bb->pinnedBefore->firstLine << endl;
}
if (bb->pinnedAfter) {
cout << " Pinned below to BB " << bb->pinnedAfter->firstLine << endl;
}
if (bb->endsInGoto) {
cout << " Block ends with Goto." << endl;
}
if (bb->startsWithLabel) {
cout << " Block starts with a label." << endl;
}
cout << endl;
}
}
/* Given a basic block, returns the basic block at the top of its pin chain. */
BasicBlock* topOfPinChain(BasicBlock* bb) {
while (bb->pinnedBefore) bb = bb->pinnedBefore;
return bb;
}
/* Utility to get a nice printed version of a BB's line range. */
[[ maybe_unused ]] string spanOf(BasicBlock* bb) {
ostringstream builder;
builder << bb->firstLine << " - "
<< bb->lastLine;
return builder.str();
}
/* Utility to get a nice printed version of a chain's line range. */
[[ maybe_unused ]] string spanOf(Chain* chain) {
ostringstream builder;
builder << chain->bbs.front()->firstLine << " - "
<< chain->bbs.back()->lastLine;
return builder.str();
}
/* Computes the chains associated with each BB by following up and down the
* pin links.
*/
void determineChainsIn(const map<size_t, BasicBlock*>& bbs, const Turing::Program& program) {
/* Standard BFS. We use the first entry in the chain as the element of the
* visited set.
*/
queue<BasicBlock*> worklist;
worklist.push(topOfPinChain(bbs.at(program.lineForLabel("Start"))));
set<BasicBlock*> visited = { worklist.front() };
while (!worklist.empty()) {
auto* bb = worklist.front();
worklist.pop();
/* Form the chain one link at a time. */
auto* chain = new Chain;
for (auto* curr = bb; curr != nullptr; curr = curr->pinnedAfter) {
curr->chain = chain;
chain->bbs.push_back(curr);
/* Add successors to the worklist. */
for (auto* successor: curr->out) {
auto* top = topOfPinChain(successor);
if (!visited.contains(top)) {
visited.insert(top);
worklist.push(top);
}
}
}
}
}
[[ maybe_unused ]] void printChains(const map<size_t, BasicBlock*>& bbs,
const Turing::Program& program) {
set<Chain*> used;
for (auto [ _, bb ]: bbs) {
if (!used.contains(bb->chain)) {
used.insert(bb->chain);
cout << "Next chain: " << endl;
for (size_t i = bb->chain->bbs.front()->firstLine; i <= bb->chain->bbs.back()->lastLine; i++) {
cout << setw(6) << i << " " << program.line(i) << endl;
}
}
}
}
/* Returns the predecessor chain, if any, in the context of the Goto/Label elimination
* optimization. The predecessor, if one exists, is the chain that ends with a Goto,
* has indegree one, and jumps to the label at the top of this chain.
*/
Chain* predecessorOf(Chain* chain) {
/* Look at the basic block at the front of the chain. */
auto* firstBB = chain->bbs.front();
if (firstBB->startsWithLabel && firstBB->in.size() == 1) {
/* See which BB points at us. */
auto* inBB = *firstBB->in.begin();
/* If the BB ends in a Goto, it's also definitionally the
* end of a chain because there's no fallthrough.
*/
if (inBB->endsInGoto) return inBB->chain;
}
/* Nope, has no predecessor. */
return nullptr;
}
/* Returns the successor chain, if any, in the context of the Goto/Label elimination
* optimization. The successor, if one exists, is the chain that starts with a label,
* has indegree 1, and is pointed at by an unconditional Goto at the end of this
* chain.
*/
Chain* successorOf(Chain* chain) {
/* Look at the last BB in the chain. */
auto* lastBB = chain->bbs.back();
if (lastBB->endsInGoto) {
/* Now see where we go. */
auto* outBB = *lastBB->out.begin();
/* If it has indegree one, it's our successor. */
if (outBB->in.size() == 1) return outBB->chain;
}
/* Nope, no successor. */
return nullptr;
}
/* A major optimization pass that reorders the code to put labels only reached
* by a single Goto right after that Goto. A side-effect of this optimization
* is that we eliminate all unreachable code.
*/
Turing::Program reorderCode(const Turing::Program& program) {
stringstream builder;
/* Find the basic blocks in this program. */
auto bbs = basicBlocksIn(program);
/* Determine the chains for each (reachable) basic block. */
determineChainsIn(bbs, program);
/* We can visit the basic blocks in any order as long as we don't repeat any
* chains. The BB we initiate from is not necessarily going to be the first BB
* that's emitted.
*/
set<Chain*> used;
for (auto [_, bb]: bbs) {
/* See if we need to process this chain. */
auto* chain = bb->chain;
if (!chain) {
continue;
}
if (used.contains(chain)) {
continue;
}
/* Here's how the optimization works. We are looking for chains where
* the end of one chain is an unconditional Goto and the start of the
* destination chain is a label that has indegree one. This means that
* the Goto from the destination chain, and the label, can (likely) be
* eliminated by reordering the chains so that the second chain starts
* where the first one ends. We then drop the label and the Goto, saving
* two lines.
*
* The graph structure of the chains is a digraph where each node has
* indegree at most one and outdegree at most one. Why? Because
*
* INDEGREE AT MOST ONE: Each edge corresponds to something that
* occurs when the start of the basic block is a label of indegree
* one. Therefore, there can be at most one incoming edge.
*
* OUTDEGREE AT MOST ONE: Each edge originates at an unconditional
* Goto, which can only go to one spot.
*
* This partitions the chains into paths and cycles. Paths are easy to
* output: you just start at the beginning of the path and lay things
* out until you get to the end. Cycles are a bit trickier because the
* naive approach would run into an infinite loop trying to lay out
* blocks before other blocks. (Ask me how I learned that! >_<)
*
* Thus in the cycle case, we simply cut the cycle at some arbitrary
* point and leave the very first label and very last Goto unmodified.
*
* We also need to be careful not to accidentally remove the Start
* label. That one has to remain there.
*/
/* Order of the chains that need to be emitted. */
deque<Chain*> toOutput = { chain };
bool hasLoop = false;
/* Walk backwards from this point. We will either hit a cycle or
* we will find a node of indegree 0.
*/
for (auto* curr = chain; (curr = predecessorOf(curr)); ) {
/* We'll hit a loop if we return to our starting chain. */
if (curr == toOutput.back()) {
hasLoop = true;
break;
}
/* Otherwise prepend this to our list. */
toOutput.push_front(curr);
}
/* If we didn't hit a cycle, walk forwards until we reach a chain
* with no successor.
*/
if (!hasLoop) for (auto* curr = chain; (curr = successorOf(curr)); ) {
toOutput.push_back(curr);
}
/* Now, render these from top to bottom. If there's a loop, don't
* apply the optimization to the first label and last Goto.
*/
for (auto* chain: toOutput) {
for (auto* bb: chain->bbs) {
size_t start = bb->firstLine;
/* Retain the first label in the chain, as we still need that
* as a Goto target. (Otherwise, we would have something before us.)
* Otherwise skip the label at the start of the chain.
*
* Oh... and never remove Start!
*/
if (bb == chain->bbs.front() && chain != toOutput.front() && !bb->isStartLabel) {
start++;
}
size_t end = bb->lastLine;
/* Retain the last Goto in the chain, as otherwise the chain
* would have continued.
*/
if (bb == chain->bbs.back() && chain != toOutput.back()) {
end--;
}
/* Output the line. */
for (size_t line = start; line <= end; line++) {
builder << program.line(line) << '\n';
}
}
/* Remember that we output this so that we don't do it again. */
used.insert(chain);
}
}
return Turing::Program(builder);
}
/* Remove any Gotos that jump to the next line. */
Turing::Program removeUnneededGotos(const Turing::Program& program) {
stringstream builder;
/* Remove any line that's a Goto that points to the next line. */
for (size_t i = 0; i < program.numLines(); i++) {
bool writeLine = true;
if (auto g = dynamic_pointer_cast<Turing::Goto>(program.statement(i))) {
/* No need for a Goto that just goes to the next line. */
if (program.lineForLabel(g->label()) == i + 1) {
writeLine = false;
}
}
if (writeLine) builder << program.line(i) << '\n';
}
return Turing::Program(builder);
}
/* Calculator that rewrites programs by deleting labels whose new names don't
* match their old names and that rewrites Goto targets.
*/
class Rewriter: public Turing::Calculator<Turing::Statement*> {
public:
Rewriter(const map<string, string>& newNames): newNames(newNames) {
}
/* Moves are unchanged. */
Turing::Statement* handle(Turing::Move& m) override {
return &m;
}
/* Writes are unchanged. */
Turing::Statement* handle(Turing::Write& w) override {
return &w;
}
/* Returns are unmodified. */
Turing::Statement* handle(Turing::Return& r) override {
return &r;
}
/* Gotos use the new target. */
Turing::Statement* handle(Turing::Goto& g) override {
return new Turing::Goto(newNames.at(g.label()));
}
/* Labels that map to new names get dropped; labels that keep
* their name are retained.
*/
Turing::Statement* handle(Turing::Label& l) override {
return newNames.at(l.label()) == l.label()? &l : nullptr;
}
/* If statements use the translated nested statement. */
Turing::Statement* handle(Turing::If& i, Turing::Statement* const & nested) override {
return new Turing::If(i.isNegated(), i.ch(), shared_ptr<Turing::Statement>(nested));
}
private:
const map<string, string>& newNames;
};
/* Symbol to text representation. */
string symbolToString(char32_t ch) {
if (ch == Turing::kBlankSymbol) {
return "Blank";
} else if (ch == '\n') {
return "'\\n'";
} else if (ch == '\t') {
return "'\\t'";
} else if (ch == '\'') {
return "'\\''";
} else if (ch == '\\') {
return "'\\\\'";
} else {
return "\'" + string(1, ch) + "\'";
}
}
/* Calculator that converts statements to strings. */
class StatementToString: public Turing::Calculator<string> {
public:
string handle(Turing::Label& l) override {
return l.label() + ":";
}
string handle(Turing::Move& m) override {
return "Move " + string(m.direction() == Turing::Direction::LEFT? "Left" : "Right");
}
string handle(Turing::Return& r) override {
return "Return " + string(r.isAccepting()? "True" : "False");
}
string handle(Turing::Goto& g) override {
return "Goto " + g.label();
}
string handle(Turing::Write& w) override {
return "Write " + symbolToString(w.ch());
}
string handle(Turing::If& w, const string& nested) override {
return "If " + string(w.isNegated()? "Not " : "") + symbolToString(w.ch()) + " " + nested;
}
};
/* Look for consecutive labels and replace them with one unified label.
* This requires two passes: one to figure out where those labels are and
* rename them, and then one to rewrite the labels.
*/
Turing::Program removeConsecutiveLabels(const Turing::Program& program) {
map<string, string> newNames; // Old name -> New name
/* Phase 1: Assign new names to the labels. */
for (size_t i = 0; i < program.numLines(); ) {
/* If it's a label, scan forward while we're finding more labels. */
if (auto l = dynamic_pointer_cast<Turing::Label>(program.statement(i))) {
set<string> groupNames = { l->label() };
/* Find all consecutive labels. */
size_t lastLabel = i + 1;
for (; lastLabel < program.numLines(); lastLabel++) {
if (auto l2 = dynamic_pointer_cast<Turing::Label>(program.statement(lastLabel))) {
groupNames.insert(l2->label());
} else break;
}
/* Pick a unified name for all the labels. If any of them are Start use that; else
* just pick the first.
*/
string newName = (groupNames.contains("Start")? "Start" : *groupNames.begin());
for (string name: groupNames) {
newNames[name] = newName;
}
/* Advance forward. */
i = lastLabel;
} else i++;
}
/* Phase 2: Rewrite the program by removing duplicate labels and changing Goto
* targets.
*/
stringstream builder;
for (size_t i = 0; i < program.numLines(); i++) {
if (auto* result = Rewriter(newNames).calculate(*program.statement(i))) {
builder << StatementToString().calculate(*result) << '\n';
}
}
return Turing::Program(builder);
}
/* Look for consecutive Writes and remove all but the last of them. */
Turing::Program removeConsecutiveWrites(const Turing::Program& program) {
stringstream builder;
for (size_t i = 0; i < program.numLines(); ) {
/* If it's a Write, scan forward while we're finding more Writes. */
if (auto w = dynamic_pointer_cast<Turing::Write>(program.statement(i))) {
size_t lastWrite = i + 1;
for (; lastWrite < program.numLines(); lastWrite++) {
if (!dynamic_pointer_cast<Turing::Write>(program.statement(lastWrite))) break;
}
/* Only output the last write. */
builder << program.line(lastWrite - 1) << '\n';
/* Advance forward. */
i = lastWrite;
}
/* Write everything else unmodified. */
else {
builder << program.line(i) << '\n';
i++;
}
}
return Turing::Program(builder);
}
/* Command-line args telling us what to do. */
struct Arguments {
bool simplifyNames = true;
};
Arguments parseArguments(int argc, const char* argv[]) {
/* We either take no args or the arg --keep-names. */
if (argc == 1) return {};
if (argc == 2 && argv[1] == string("--keep-names")) return { false };
cout << "Usage: optimize [--keep-names]" << endl;
exit(-1);
}
/* Calculator that rewrites programs by renaming labels. */
class Renamer: public Turing::Calculator<Turing::Statement*> {
public:
Renamer(const map<string, string>& newNames): newNames(newNames) {
}
/* Moves are unchanged. */
Turing::Statement* handle(Turing::Move& m) override {
return &m;
}
/* Writes are unchanged. */
Turing::Statement* handle(Turing::Write& w) override {
return &w;
}
/* Returns are unmodified. */
Turing::Statement* handle(Turing::Return& r) override {
return &r;
}
/* Gotos use the new target. */
Turing::Statement* handle(Turing::Goto& g) override {
return new Turing::Goto(newNames.at(g.label()));
}
/* Labels that map to new names get dropped; labels that keep
* their name are retained.
*/
Turing::Statement* handle(Turing::Label& l) override {
return new Turing::Label(newNames.at(l.label()));
}
/* If statements use the translated nested statement. */
Turing::Statement* handle(Turing::If& i, Turing::Statement* const & nested) override {
return new Turing::If(i.isNegated(), i.ch(), shared_ptr<Turing::Statement>(nested));
}
private:
const map<string, string>& newNames;
};
/* Calculator that rewrites programs by rewriting Gotos while preserving label names. */
class GotoTranslator: public Turing::Calculator<Turing::Statement*> {
public:
GotoTranslator(const map<string, string>& newNames): newNames(newNames) {
}
/* Moves are unchanged. */
Turing::Statement* handle(Turing::Move& m) override {
return &m;
}
/* Writes are unchanged. */
Turing::Statement* handle(Turing::Write& w) override {
return &w;
}
/* Returns are unmodified. */
Turing::Statement* handle(Turing::Return& r) override {
return &r;
}
/* Gotos use the new target. */
Turing::Statement* handle(Turing::Goto& g) override {
return new Turing::Goto(newNames.at(g.label()));
}
/* Labels that map to new names get dropped; labels that keep
* their name are retained.
*/
Turing::Statement* handle(Turing::Label& l) override {
return &l;
}
/* If statements use the translated nested statement. */
Turing::Statement* handle(Turing::If& i, Turing::Statement* const & nested) override {
return new Turing::If(i.isNegated(), i.ch(), shared_ptr<Turing::Statement>(nested));
}
private:
const map<string, string>& newNames;
};
/* Returns the set of all legal characters that can be in a label. */
string legalLabelValues() {
static string result = [] {
string result;
for (int i = 0; i < 128; i++) {
if (isalnum(i) || i == '_') {
result += i;
}
}
return result;
} ();
return result;
}
/* Given a base-63 string, advances to the next one. */
string nextLabel(string input) {
string chars = legalLabelValues();
for (size_t i = 0; i < input.size(); i++) {
/* Increment this digit. If no overflow, we're done. */
size_t value = chars.find(input[i]);
if (value + 1 != chars.size()) {
input[i] = chars[value + 1];
return input;
}
/* Otherwise there is overflow. That's fine. */
input[i] = chars[0];
}
/* If we're here, we need another digit. */
return input + chars[0];
}
/* Replaces all non-Start label names with something shorter. */
Turing::Program simplifyNames(const Turing::Program& program) {
map<string, string> newNames = { { "Start", "Start" } };
/* Phase 1: Come up with new names for all the labels. */
string label(1, legalLabelValues()[0]);
for (size_t i = 0; i < program.numLines(); i++) {
if (auto l = dynamic_pointer_cast<Turing::Label>(program.statement(i))) {
if (l->label() != "Start") {
/* Prepend an underscore to each label to ensure it's syntactically
* valid.
*/
newNames[l->label()] = "_" + label;
label = nextLabel(label);
}
}
}
/* Phase 2: Translate all labels. */
stringstream builder;
for (size_t i = 0; i < program.numLines(); i++) {
builder << StatementToString().calculate(*Renamer(newNames).calculate(*program.statement(i))) << '\n';
}
return Turing::Program(builder);
}
/* If we see 'Move Left' followed by 'Move Right' or vice-versa, we should output neither. */
Turing::Program removeUselessMoves(const Turing::Program& program) {
stringstream builder;
for (size_t i = 0; i + 1 < program.numLines(); i++) {
/* See if this and the next line are moves. */
auto m1 = dynamic_pointer_cast<Turing::Move>(program.statement(i));
auto m2 = dynamic_pointer_cast<Turing::Move>(program.statement(i + 1));
/* If so, see if they go in opposite directions. */
if (m1 && m2 && m1->direction() != m2->direction()) {
/* Don't output this line. Also, skip the next line. */
i++;
}
/* Otherwise output as usual. */
else {
builder << program.line(i) << '\n';
}
}
/* Always output the last line. */
builder << program.line(program.numLines() - 1) << '\n';
return Turing::Program(builder);
}
/* Look for labels of the following form:
*
* Label:
* Goto OtherLabel
*
* Anything that points to Label should instead point to where OtherLabel
* points. Moreover, this can be chained, so anything jumping to Label
* should instead go where OtherLabel ultimately points.
*/
Turing::Program bypassUnnecessaryLabels(const Turing::Program& program) {
/* Map from labels to their ultimate replacements. Labels that don't
* meet the criteria here will be replaced by themselves.
*/
map<string, string> newNames;
for (size_t i = 0; i < program.numLines(); i++) {
if (auto l = dynamic_pointer_cast<Turing::Label>(program.statement(i))) {
/* Default to the label replacing itself. */
newNames[l->label()] = l->label();
/* See if there's a line after us and whether it's a goto. */
if (i + 1 != program.numLines()) {
if (auto g = dynamic_pointer_cast<Turing::Goto>(program.statement(i + 1))) {
/* Our new target is that target. */
newNames[l->label()] = g->label();
}
}
}
}
/* Compress all chains. This is basically a union-find "path compression"
* step.
*/
function<string (string)> compress = [&](string label) {
if (label == newNames[label]) return label;
return newNames[label] = compress(newNames[label]);
};
for (auto [ label, _ ]: newNames) {
compress(label);