Repository navigation
Expand file tree
/
Copy pathStructurizer.cpp
More file actions
2743 lines (2562 loc) · 119 KB
/
Copy pathStructurizer.cpp
File metadata and controls
2743 lines (2562 loc) · 119 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
#include "ControlFlow/Structurizer.hpp"
#include "ControlFlow/ControlFlowHelpers.hpp"
#include <algorithm>
#include <bit>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <functional>
#include <iterator>
#include <map>
#include <optional>
#include <stdexcept>
namespace ShaderRecompiler {
namespace {
std::vector<std::uint32_t> allBlockIds(std::uint32_t count) {
std::vector<std::uint32_t> ids;
ids.reserve(count);
for (std::uint32_t i = 0; i < count; ++i) {
ids.push_back(i);
}
return ids;
}
std::vector<std::uint32_t> reversePostOrder(const ControlFlowGraph& graph);
std::vector<std::uint32_t> analysisOrder(const ControlFlowGraph& graph, bool successorsFirst) {
const auto count = static_cast<std::uint32_t>(graph.blocks.size());
std::vector<std::uint32_t> order;
std::vector<bool> placed(count, false);
if (graph.entryBlock < count) {
order = reversePostOrder(graph);
if (successorsFirst) {
std::reverse(order.begin(), order.end());
}
for (const auto id : order) {
placed[id] = true;
}
}
for (std::uint32_t id = 0; id < count; ++id) {
if (!placed[id]) {
order.push_back(id);
}
}
return order;
}
bool inPlaceIntersections() {
static const bool enabled = std::getenv("APS5_NO_PERF_DOM_INTERSECTION") == nullptr;
return enabled;
}
bool dominatorTrees() {
static const bool enabled = std::getenv("APS5_NO_PERF_DOMINATOR_TREE") == nullptr;
return enabled;
}
template <typename IncomingOf>
bool assignTreeDominators(std::vector<BasicBlock>& blocks, const std::vector<std::uint32_t>& roots, IncomingOf incomingOf, std::vector<std::uint32_t> BasicBlock::*sets, std::uint32_t BasicBlock::*parent = nullptr) {
const auto count = static_cast<std::uint32_t>(blocks.size());
const auto virtualRoot = count;
std::vector<bool> isRoot(count, false);
std::vector<std::vector<std::uint32_t>> outgoing(count + 1u);
for (const auto root : roots) {
isRoot[root] = true;
outgoing[virtualRoot].push_back(root);
}
for (std::uint32_t id = 0; id < count; ++id) {
if (isRoot[id]) continue;
for (const auto from : incomingOf(id)) outgoing[from].push_back(id);
}
std::vector<std::uint32_t> postOrder(count + 1u, InvalidControlFlowId);
std::vector<std::uint32_t> order;
order.reserve(count + 1u);
std::vector<std::pair<std::uint32_t, std::size_t>> stack = {{virtualRoot, 0u}};
postOrder[virtualRoot] = 0;
while (!stack.empty()) {
auto& [node, next] = stack.back();
if (next < outgoing[node].size()) {
const auto target = outgoing[node][next++];
if (postOrder[target] == InvalidControlFlowId) {
postOrder[target] = 0;
stack.emplace_back(target, 0u);
}
continue;
}
postOrder[node] = static_cast<std::uint32_t>(order.size());
order.push_back(node);
stack.pop_back();
}
if (order.size() != count + 1u) {
return false;
}
std::vector<std::uint32_t> immediate(count + 1u, InvalidControlFlowId);
immediate[virtualRoot] = virtualRoot;
const auto intersect = [&](std::uint32_t first, std::uint32_t second) {
while (first != second) {
while (postOrder[first] < postOrder[second]) first = immediate[first];
while (postOrder[second] < postOrder[first]) second = immediate[second];
}
return first;
};
for (bool changed = true; changed;) {
changed = false;
for (auto position = order.size() - 1u; position-- > 0u;) {
const auto node = order[position];
auto next = isRoot[node] ? virtualRoot : InvalidControlFlowId;
if (!isRoot[node]) {
for (const auto from : incomingOf(node)) {
if (immediate[from] != InvalidControlFlowId) next = next == InvalidControlFlowId ? from : intersect(from, next);
}
}
if (immediate[node] != next) {
immediate[node] = next;
changed = true;
}
}
}
for (auto position = order.size() - 1u; position-- > 0u;) {
const auto node = order[position];
auto& set = blocks[node].*sets;
if (immediate[node] == virtualRoot) set.clear();
else set = blocks[immediate[node]].*sets;
set.insert(std::upper_bound(set.begin(), set.end(), node), node);
if (parent != nullptr) blocks[node].*parent = immediate[node] == virtualRoot ? node : immediate[node];
}
return true;
}
struct BlockSet {
std::vector<std::uint64_t> words;
static std::size_t wordCount(std::uint32_t count) {
return (static_cast<std::size_t>(count) + 63u) / 64u;
}
static BlockSet filled(std::uint32_t count, std::uint64_t fill) {
BlockSet set;
set.words.assign(wordCount(count), fill);
return set;
}
static BlockSet none(std::uint32_t count) {
return filled(count, 0);
}
static BlockSet all(std::uint32_t count) {
auto set = filled(count, ~std::uint64_t{0});
if (const auto tail = count % 64u) set.words.back() &= (std::uint64_t{1} << tail) - 1u;
return set;
}
static BlockSet only(std::uint32_t count, std::uint32_t id) {
auto set = none(count);
set.add(id);
return set;
}
static BlockSet fromIds(std::uint32_t count, const std::vector<std::uint32_t>& ids) {
auto set = none(count);
for (const auto id : ids) set.add(id);
return set;
}
void add(std::uint32_t id) {
words[static_cast<std::size_t>(id) / 64u] |= std::uint64_t{1} << (id % 64u);
}
bool has(std::uint32_t id) const {
return (words[static_cast<std::size_t>(id) / 64u] >> (id % 64u) & 1u) != 0u;
}
void intersect(const BlockSet& other) {
for (std::size_t i = 0; i < words.size(); ++i) words[i] &= other.words[i];
}
bool operator==(const BlockSet& other) const {
return words == other.words;
}
std::vector<std::uint32_t> ids() const {
std::vector<std::uint32_t> out;
for (std::size_t word = 0; word < words.size(); ++word) {
auto bits = words[word];
while (bits != 0) {
const auto bit = static_cast<std::uint32_t>(std::countr_zero(bits));
out.push_back(static_cast<std::uint32_t>(word * 64u) + bit);
bits &= bits - 1u;
}
}
return out;
}
};
bool replaceSet(BlockSet& destination, BlockSet&& next) {
if (next == destination) return false;
destination = std::move(next);
return true;
}
std::vector<std::vector<std::uint32_t>> analysisVectors(const std::vector<BlockSet>& sets) {
std::vector<std::vector<std::uint32_t>> vectors(sets.size());
for (std::size_t i = 0; i < sets.size(); ++i) vectors[i] = sets[i].ids();
return vectors;
}
void intersectAnalysisSet(std::vector<std::uint32_t>& values, const std::vector<std::uint32_t>& other) {
if (!inPlaceIntersections()) {
values = intersectSorted(values, other);
return;
}
std::size_t left = 0;
std::size_t right = 0;
std::size_t count = 0;
while (left < values.size() && right < other.size()) {
if (values[left] < other[right]) {
++left;
} else if (other[right] < values[left]) {
++right;
} else {
values[count++] = values[left++];
++right;
}
}
values.resize(count);
}
void replaceAnalysisSet(std::vector<std::uint32_t>& destination, std::vector<std::uint32_t>&& values) {
if (inPlaceIntersections() && values.capacity() - values.size() > values.size()) {
std::vector<std::uint32_t>(values).swap(values);
}
destination = std::move(values);
}
void addSortedUnique(std::vector<std::uint32_t>& values, std::uint32_t value) {
const auto position = std::lower_bound(values.begin(), values.end(), value);
if (position == values.end() || *position != value) {
values.insert(position, value);
}
}
bool containsSorted(const std::vector<std::uint32_t>& values, std::uint32_t value) {
return std::binary_search(values.begin(), values.end(), value);
}
bool replaceValue(std::vector<std::uint32_t>& values, std::uint32_t oldValue, std::uint32_t newValue) {
bool changed = false;
for (auto& value : values) {
if (value == oldValue) {
value = newValue;
changed = true;
}
}
if (changed) {
sortUnique(values);
}
return changed;
}
bool removeValue(std::vector<std::uint32_t>& values, std::uint32_t value) {
const auto oldSize = values.size();
values.erase(std::remove(values.begin(), values.end(), value), values.end());
return values.size() != oldSize;
}
bool replaceTerminatorTarget(Terminator& terminator, std::uint32_t oldValue, std::uint32_t newValue) {
bool changed = false;
if (terminator.trueBlock == oldValue) {
terminator.trueBlock = newValue;
changed = true;
}
if (terminator.falseBlock == oldValue) {
terminator.falseBlock = newValue;
changed = true;
}
return changed;
}
std::vector<std::uint32_t> applyBlockOrder(ControlFlowGraph& graph, std::vector<BasicBlock> blocks) {
std::vector<std::uint32_t> idMap(blocks.size(), InvalidControlFlowId);
for (std::uint32_t i = 0; i < blocks.size(); ++i) {
idMap[blocks[i].id] = i;
}
graph.blocks = std::move(blocks);
graph.entryBlock = remapId(graph.entryBlock, idMap);
for (auto& block : graph.blocks) {
block.id = remapId(block.id, idMap);
block.immediatePostDominator = remapId(block.immediatePostDominator, idMap);
remapIds(block.predecessors, idMap);
remapIds(block.successors, idMap);
remapIds(block.dominators, idMap);
remapIds(block.postDominators, idMap);
block.terminator.trueBlock = remapId(block.terminator.trueBlock, idMap);
block.terminator.falseBlock = remapId(block.terminator.falseBlock, idMap);
block.terminator.mergeBlock = remapId(block.terminator.mergeBlock, idMap);
block.terminator.continueBlock = remapId(block.terminator.continueBlock, idMap);
for (auto& target : block.terminator.indirectTargets) {
target = remapId(target, idMap);
}
for (auto& target : block.terminator.indirectSelectorTargets) {
target = remapId(target, idMap);
}
}
return idMap;
}
std::uint32_t moveBlockBefore(ControlFlowGraph& graph, std::uint32_t blockId, std::uint32_t beforeId) {
if (blockId == beforeId || blockId >= graph.blocks.size() || beforeId >= graph.blocks.size()) {
return blockId;
}
const auto blockPos = blockId;
const auto beforePos = beforeId;
std::vector<BasicBlock> oldBlocks = std::move(graph.blocks);
std::vector<BasicBlock> newBlocks;
newBlocks.reserve(oldBlocks.size());
for (std::uint32_t i = 0; i < oldBlocks.size(); ++i) {
if (i == beforePos) {
newBlocks.push_back(std::move(oldBlocks[blockPos]));
}
if (i != blockPos) {
newBlocks.push_back(std::move(oldBlocks[i]));
}
}
const auto idMap = applyBlockOrder(graph, std::move(newBlocks));
return remapId(blockId, idMap);
}
std::vector<std::uint32_t> dominatedBlocks(const ControlFlowGraph& graph, std::uint32_t headerBlock, std::uint32_t stopBlock = InvalidControlFlowId) {
std::vector<std::uint32_t> blocks;
if (headerBlock == stopBlock || !graph.Dominates(headerBlock, headerBlock)) {
return blocks;
}
std::vector<std::uint32_t> stack = {headerBlock};
std::vector<bool> visited(graph.blocks.size());
while (!stack.empty()) {
const auto blockId = stack.back();
stack.pop_back();
if (blockId >= visited.size()) {
visited.resize(blockId + 1);
}
if (visited[blockId]) {
continue;
}
const auto& block = graph.FindBlock(blockId);
visited[blockId] = true;
blocks.push_back(blockId);
for (const auto successor : block.successors) {
if (successor != stopBlock && (successor >= visited.size() || !visited[successor]) && graph.Dominates(headerBlock, successor)) {
stack.push_back(successor);
}
}
}
sortUnique(blocks);
return blocks;
}
std::uint32_t appendSyntheticBranchBlock(ControlFlowGraph& graph, std::uint32_t target) {
const auto& targetBlock = graph.FindBlock(target);
BasicBlock block;
block.id = static_cast<std::uint32_t>(graph.blocks.size());
block.startProgramCounter = targetBlock.startProgramCounter;
block.endProgramCounter = block.startProgramCounter;
block.instructionBegin = targetBlock.instructionBegin;
block.instructionEnd = block.instructionBegin;
block.successors = {target};
block.terminator.kind = TerminatorKind::Branch;
block.terminator.condition = BranchCondition::Always;
block.terminator.trueBlock = target;
graph.blocks.push_back(std::move(block));
return graph.blocks.back().id;
}
bool isolateSemanticLoopHeader(ControlFlowGraph& graph, std::uint32_t oldHeader, const std::function<void(ControlFlowGraph&)>& recompute) {
const auto& header = graph.FindBlock(oldHeader);
if (header.instructionBegin == header.instructionEnd) {
return false;
}
const auto predecessors = header.predecessors;
const auto newHeader = appendSyntheticBranchBlock(graph, oldHeader);
for (const auto predecessor : predecessors) {
auto& block = graph.FindBlock(predecessor);
replaceValue(block.successors, oldHeader, newHeader);
replaceTerminatorTarget(block.terminator, oldHeader, newHeader);
}
if (graph.entryBlock == oldHeader) {
graph.entryBlock = newHeader;
}
moveBlockBefore(graph, newHeader, oldHeader);
rebuildPredecessors(graph);
recompute(graph);
return true;
}
const NaturalLoop* findInnermostContainingLoop(const ControlFlowGraph& graph, std::uint32_t blockId) {
const NaturalLoop* innermost = nullptr;
for (const auto& loop : graph.naturalLoops) {
if (containsSorted(loop.blocks, blockId) && (innermost == nullptr || loop.blocks.size() < innermost->blocks.size())) {
innermost = &loop;
}
}
return innermost;
}
bool isInsideLoopConstruct(const ControlFlowGraph& graph, const NaturalLoop& loop, std::uint32_t blockId) {
return blockId != InvalidControlFlowId && blockId != loop.mergeBlock && blockId != loop.continueBlock && graph.Dominates(loop.headerBlock, blockId) && !graph.Dominates(loop.mergeBlock, blockId);
}
bool isLoopControlGateway(const ControlFlowGraph& graph, const NaturalLoop& loop, std::uint32_t blockId) {
const auto& block = graph.FindBlock(blockId);
if (block.terminator.kind != TerminatorKind::ConditionalBranch) {
return false;
}
const auto isControlTarget = [&](std::uint32_t target) {
return target == loop.mergeBlock || target == loop.continueBlock;
};
return isControlTarget(block.terminator.trueBlock) && isControlTarget(block.terminator.falseBlock);
}
bool hasLinearPathToTerminal(const ControlFlowGraph& graph, std::uint32_t start) {
std::vector<bool> visited(graph.blocks.size(), false);
for (auto blockId = start;;) {
if (visited[blockId]) {
return false;
}
const auto& block = graph.FindBlock(blockId);
if (block.successors.empty()) {
return true;
}
if (block.successors.size() != 1) {
return false;
}
visited[blockId] = true;
blockId = block.successors.front();
}
}
bool isEnclosingLinearExit(const ControlFlowGraph& graph, std::uint32_t header, std::uint32_t blockId) {
if (!hasLinearPathToTerminal(graph, blockId)) {
return false;
}
const BasicBlock* block = &graph.FindBlock(blockId);
while (graph.Dominates(header, block->id) && block->successors.size() == 1u) {
block = &graph.FindBlock(block->successors.front());
}
if (graph.Dominates(header, block->id) || block->predecessors.empty()) {
return false;
}
return std::all_of(block->predecessors.begin(), block->predecessors.end(), [&](std::uint32_t predecessor) {
return graph.Dominates(header, predecessor) || graph.Dominates(predecessor, header);
});
}
bool canReachBefore(const ControlFlowGraph& graph, std::uint32_t start, std::uint32_t target, std::uint32_t stop) {
std::vector<std::uint32_t> pending = {start};
std::vector<bool> visited(graph.blocks.size(), false);
while (!pending.empty()) {
const auto blockId = pending.back();
pending.pop_back();
if (blockId == target) {
return true;
}
if (blockId == stop || visited[blockId]) {
continue;
}
visited[blockId] = true;
const auto& block = graph.FindBlock(blockId);
pending.insert(pending.end(), block.successors.begin(), block.successors.end());
}
return false;
}
bool reachesWithinIteration(const ControlFlowGraph& graph, const NaturalLoop& loop, std::uint32_t start, std::uint32_t target) {
if (start == target) return true;
if (start == loop.continueBlock || start == loop.mergeBlock) return false;
std::vector<std::uint32_t> pending = {start};
std::vector<bool> visited(graph.blocks.size(), false);
while (!pending.empty()) {
const auto blockId = pending.back();
pending.pop_back();
if (blockId == target) {
return true;
}
if (blockId == loop.continueBlock || blockId == loop.mergeBlock || visited[blockId]) {
continue;
}
visited[blockId] = true;
const auto& block = graph.FindBlock(blockId);
pending.insert(pending.end(), block.successors.begin(), block.successors.end());
}
return false;
}
std::uint32_t joinWithinIteration(const ControlFlowGraph& graph, const NaturalLoop& loop, std::uint32_t trueTarget, std::uint32_t falseTarget, std::uint32_t globalMerge) {
std::vector<bool> reached(graph.blocks.size(), false);
std::vector<std::uint32_t> pending = {trueTarget, falseTarget};
while (!pending.empty()) {
const auto blockId = pending.back();
pending.pop_back();
if (blockId == globalMerge || reached[blockId] || !isInsideLoopConstruct(graph, loop, blockId)) {
continue;
}
reached[blockId] = true;
const auto& successors = graph.FindBlock(blockId).successors;
pending.insert(pending.end(), successors.begin(), successors.end());
}
std::vector<bool> joins(graph.blocks.size(), false);
std::vector<std::uint32_t> joining = {globalMerge};
joins[globalMerge] = true;
for (std::size_t index = 0; index < joining.size(); ++index) {
for (const auto predecessor : graph.FindBlock(joining[index]).predecessors) {
if (reached[predecessor] && !joins[predecessor]) {
joins[predecessor] = true;
joining.push_back(predecessor);
}
}
}
sortUnique(joining);
if (!joins[trueTarget] || !joins[falseTarget]) {
return globalMerge;
}
const auto count = static_cast<std::uint32_t>(graph.blocks.size());
std::vector<std::vector<std::uint32_t>> postDominators(count);
const auto order = analysisOrder(graph, true);
if (inPlaceIntersections()) {
const auto universe = BlockSet::fromIds(count, joining);
std::vector<BlockSet> sets(count, BlockSet::none(count));
for (const auto blockId : joining) sets[blockId] = blockId == globalMerge ? BlockSet::only(count, globalMerge) : universe;
for (bool changed = true; changed;) {
changed = false;
for (const auto blockId : order) {
if (!joins[blockId] || blockId == globalMerge) continue;
auto next = universe;
for (const auto successor : graph.FindBlock(blockId).successors) {
if (joins[successor]) next.intersect(sets[successor]);
}
next.add(blockId);
changed = replaceSet(sets[blockId], std::move(next)) || changed;
}
}
postDominators = analysisVectors(sets);
} else {
for (const auto blockId : joining) postDominators[blockId] = blockId == globalMerge ? std::vector<std::uint32_t>{globalMerge} : joining;
for (bool changed = true; changed;) {
changed = false;
for (const auto blockId : order) {
if (!joins[blockId] || blockId == globalMerge) continue;
auto next = joining;
for (const auto successor : graph.FindBlock(blockId).successors) {
if (joins[successor]) next = intersectSorted(next, postDominators[successor]);
}
addSortedUnique(next, blockId);
if (next != postDominators[blockId]) {
postDominators[blockId] = std::move(next);
changed = true;
}
}
}
}
const auto common = intersectSorted(postDominators[trueTarget], postDominators[falseTarget]);
const auto merge = std::find_if(common.begin(), common.end(), [&](std::uint32_t candidate) {
return std::all_of(common.begin(), common.end(), [&](std::uint32_t other) { return contains(postDominators[candidate], other); });
});
return merge == common.end() ? globalMerge : *merge;
}
std::vector<std::uint32_t> linearTail(const ControlFlowGraph& graph, std::uint32_t start) {
std::vector<std::uint32_t> tail;
for (auto blockId = start; !contains(tail, blockId);) {
tail.push_back(blockId);
const auto& block = graph.FindBlock(blockId);
if (block.successors.size() != 1u) {
break;
}
blockId = block.successors.front();
}
return tail;
}
std::uint32_t mergeBesideReturns(const ControlFlowGraph& graph, const BasicBlock& header) {
const auto reach = [&](std::uint32_t start) {
std::vector<std::uint32_t> reached;
std::vector<std::uint32_t> pending = {start};
while (!pending.empty()) {
const auto blockId = pending.back();
pending.pop_back();
if (blockId == header.id || contains(reached, blockId)) {
continue;
}
reached.push_back(blockId);
const auto& successors = graph.FindBlock(blockId).successors;
pending.insert(pending.end(), successors.begin(), successors.end());
}
sortUnique(reached);
return reached;
};
const auto trueReach = reach(header.terminator.trueBlock);
const auto falseReach = reach(header.terminator.falseBlock);
if (intersectSorted(trueReach, falseReach).empty()) {
const auto returnsWithin = [&](const std::vector<std::uint32_t>& reached) {
return std::all_of(reached.begin(), reached.end(), [&](std::uint32_t blockId) { return graph.Dominates(header.id, blockId); });
};
if (returnsWithin(trueReach) && graph.Dominates(header.id, header.terminator.falseBlock)) {
return header.terminator.falseBlock;
}
if (returnsWithin(falseReach) && graph.Dominates(header.id, header.terminator.trueBlock)) {
return header.terminator.trueBlock;
}
}
const auto count = static_cast<std::uint32_t>(graph.blocks.size());
enum class Returning : std::uint8_t { Unknown, Visiting, No, Yes };
std::vector<Returning> returning(count, Returning::Unknown);
const auto returns = [&](std::uint32_t start) {
std::vector<std::uint32_t> pending{start};
while (!pending.empty()) {
const auto blockId = pending.back();
const auto& block = graph.FindBlock(blockId);
if (returning[blockId] == Returning::Unknown) {
if (block.predecessors.size() == 1u && graph.Dominates(header.id, blockId)) {
returning[blockId] = Returning::Visiting;
std::copy_if(block.successors.begin(), block.successors.end(), std::back_inserter(pending), [&](std::uint32_t successor) { return returning[successor] == Returning::Unknown; });
continue;
}
returning[blockId] = Returning::No;
} else if (returning[blockId] == Returning::Visiting) {
const bool privateReturn = std::all_of(block.successors.begin(), block.successors.end(), [&](std::uint32_t successor) { return returning[successor] == Returning::Yes; });
returning[blockId] = privateReturn ? Returning::Yes : Returning::No;
}
pending.pop_back();
}
return returning[start] == Returning::Yes;
};
std::vector<std::vector<std::uint32_t>> kept(count);
for (const auto& block : graph.blocks) {
for (const auto successor : block.successors) {
if (!returns(successor)) kept[block.id].push_back(successor);
}
}
const auto order = analysisOrder(graph, true);
std::vector<std::vector<std::uint32_t>> postDominators;
if (inPlaceIntersections()) {
std::vector<BlockSet> sets(count, BlockSet::all(count));
for (const auto& block : graph.blocks) {
if (kept[block.id].empty()) sets[block.id] = BlockSet::only(count, block.id);
}
for (bool changed = true; changed;) {
changed = false;
for (const auto blockId : order) {
const auto& block = graph.blocks[blockId];
if (kept[block.id].empty()) continue;
auto next = sets[kept[block.id].front()];
for (std::size_t i = 1; i < kept[block.id].size(); ++i) next.intersect(sets[kept[block.id][i]]);
next.add(block.id);
changed = replaceSet(sets[block.id], std::move(next)) || changed;
}
}
postDominators = analysisVectors(sets);
} else {
postDominators.assign(count, allBlockIds(count));
for (const auto& block : graph.blocks) {
if (kept[block.id].empty()) postDominators[block.id] = {block.id};
}
for (bool changed = true; changed;) {
changed = false;
for (const auto blockId : order) {
const auto& block = graph.blocks[blockId];
if (kept[block.id].empty()) continue;
auto next = postDominators[kept[block.id].front()];
for (std::size_t i = 1; i < kept[block.id].size(); ++i) intersectAnalysisSet(next, postDominators[kept[block.id][i]]);
addSortedUnique(next, block.id);
if (next != postDominators[block.id]) {
replaceAnalysisSet(postDominators[block.id], std::move(next));
changed = true;
}
}
}
}
const auto common = intersectSorted(postDominators[header.terminator.trueBlock], postDominators[header.terminator.falseBlock]);
const auto merge = std::find_if(common.begin(), common.end(), [&](std::uint32_t candidate) {
return std::all_of(common.begin(), common.end(), [&](std::uint32_t other) { return contains(postDominators[candidate], other); });
});
if (merge == common.end() || *merge == header.id) {
return InvalidControlFlowId;
}
const auto inConstruct = [&](std::uint32_t blockId) {
return blockId != *merge && graph.Dominates(header.id, blockId) && !graph.Dominates(*merge, blockId);
};
for (const auto& block : graph.blocks) {
if (block.id == header.id || !inConstruct(block.id)) {
continue;
}
for (const auto successor : block.successors) {
if (successor != *merge && !inConstruct(successor)) {
return InvalidControlFlowId;
}
}
}
if (canReachBefore(graph, *merge, header.id, InvalidControlFlowId)) {
return InvalidControlFlowId;
}
for (const auto& block : graph.blocks) {
if (block.id != header.id && inConstruct(block.id) && canReachBefore(graph, *merge, block.id, header.id)) {
return InvalidControlFlowId;
}
}
return *merge;
}
std::uint32_t iterationSelectionMerge(const ControlFlowGraph& graph, const NaturalLoop& loop, const BasicBlock& header, std::uint32_t join) {
const auto count = static_cast<std::uint32_t>(graph.blocks.size());
static const bool reuse = std::getenv("APS5_NO_PERF_ITERATION_SELECTION") == nullptr;
const auto escapes = [&](std::uint32_t blockId) { return blockId == loop.continueBlock || blockId == loop.mergeBlock; };
std::vector<bool> joins(count, false);
std::vector<std::uint32_t> pending = {join};
joins[join] = true;
while (!pending.empty()) {
const auto blockId = pending.back();
pending.pop_back();
for (const auto predecessor : graph.FindBlock(blockId).predecessors) {
if (!joins[predecessor] && !escapes(predecessor)) {
joins[predecessor] = true;
pending.push_back(predecessor);
}
}
}
const auto trueTarget = header.terminator.trueBlock;
const auto falseTarget = header.terminator.falseBlock;
if (!joins[trueTarget] || !joins[falseTarget]) {
return InvalidControlFlowId;
}
const auto order = analysisOrder(graph, true);
std::vector<std::vector<std::uint32_t>> postDominators;
if (reuse && inPlaceIntersections()) {
std::vector<BlockSet> sets(count, BlockSet::all(count));
sets[join] = BlockSet::only(count, join);
for (bool changed = true; changed;) {
changed = false;
for (const auto blockId : order) {
const auto& block = graph.blocks[blockId];
if (!joins[block.id] || block.id == join) continue;
bool seeded = false;
auto next = BlockSet::none(count);
for (const auto successor : block.successors) {
if (!joins[successor]) continue;
if (!seeded) {
next = sets[successor];
seeded = true;
} else {
next.intersect(sets[successor]);
}
}
if (!seeded) next = BlockSet::all(count);
next.add(block.id);
changed = replaceSet(sets[block.id], std::move(next)) || changed;
}
}
postDominators = analysisVectors(sets);
} else {
postDominators.assign(count, allBlockIds(count));
postDominators[join] = {join};
for (bool changed = true; changed;) {
changed = false;
for (const auto blockId : order) {
const auto& block = graph.blocks[blockId];
if (!joins[block.id] || block.id == join) continue;
bool seeded = !reuse;
auto next = seeded ? allBlockIds(count) : std::vector<std::uint32_t>{};
for (const auto successor : block.successors) {
if (joins[successor]) {
if (!seeded) {
next = postDominators[successor];
seeded = true;
} else if (reuse) {
intersectAnalysisSet(next, postDominators[successor]);
} else {
next = intersectSorted(next, postDominators[successor]);
}
}
}
if (!seeded) next = allBlockIds(count);
if (reuse) addSortedUnique(next, block.id);
else {
addUnique(next, block.id);
sortUnique(next);
}
if (next != postDominators[block.id]) {
if (reuse) replaceAnalysisSet(postDominators[block.id], std::move(next));
else postDominators[block.id] = std::move(next);
changed = true;
}
}
}
}
const auto common = intersectSorted(postDominators[trueTarget], postDominators[falseTarget]);
const auto merge = std::find_if(common.begin(), common.end(), [&](std::uint32_t candidate) {
return std::all_of(common.begin(), common.end(), [&](std::uint32_t other) { return contains(postDominators[candidate], other); });
});
if (merge == common.end() || *merge == join || *merge == header.id || !graph.Dominates(header.id, *merge) || !isInsideLoopConstruct(graph, loop, *merge)) {
return InvalidControlFlowId;
}
return *merge;
}
std::uint32_t findSelectionMerge(const ControlFlowGraph& graph, const BasicBlock& block, bool routeLeavingExits = false, bool routeSharedExits = false) {
const auto globalMerge = graph.FindNearestCommonPostDominator(block.terminator.trueBlock, block.terminator.falseBlock);
const auto* loop = findInnermostContainingLoop(graph, block.id);
const auto trueTarget = block.terminator.trueBlock;
const auto falseTarget = block.terminator.falseBlock;
if (loop == nullptr) {
const bool globalMergeIsExit = globalMerge == InvalidControlFlowId || graph.FindBlock(globalMerge).successors.empty();
if (globalMergeIsExit) {
const bool falseReachesTrue = canReachBefore(graph, falseTarget, trueTarget, globalMerge);
const bool trueReachesFalse = canReachBefore(graph, trueTarget, falseTarget, globalMerge);
if (falseReachesTrue != trueReachesFalse) {
return falseReachesTrue ? trueTarget : falseTarget;
}
if (globalMerge == InvalidControlFlowId) {
if (isEnclosingLinearExit(graph, block.id, trueTarget)) {
return trueTarget;
}
if (isEnclosingLinearExit(graph, block.id, falseTarget)) {
return falseTarget;
}
if (graph.Dominates(block.id, falseTarget) && hasLinearPathToTerminal(graph, trueTarget)) {
return falseTarget;
}
if (graph.Dominates(block.id, trueTarget) && hasLinearPathToTerminal(graph, falseTarget)) {
return trueTarget;
}
return mergeBesideReturns(graph, block);
}
}
return globalMerge;
}
if (routeSharedExits && reachesWithinIteration(graph, *loop, trueTarget, loop->continueBlock) && reachesWithinIteration(graph, *loop, falseTarget, loop->continueBlock)) {
return joinWithinIteration(graph, *loop, trueTarget, falseTarget, loop->continueBlock);
}
if (isLoopControlGateway(graph, *loop, trueTarget) && graph.Dominates(block.id, trueTarget) && isInsideLoopConstruct(graph, *loop, falseTarget)) {
return trueTarget;
}
if (isLoopControlGateway(graph, *loop, falseTarget) && graph.Dominates(block.id, falseTarget) && isInsideLoopConstruct(graph, *loop, trueTarget)) {
return falseTarget;
}
const auto joinsAt = [&](std::uint32_t join, std::uint32_t other) {
const auto& arm = graph.FindBlock(other);
const bool armLeavesOrJoins = arm.terminator.kind == TerminatorKind::ConditionalBranch && arm.predecessors.size() == 1u && std::all_of(arm.successors.begin(), arm.successors.end(), [&](std::uint32_t successor) {
return successor == join || successor == loop->continueBlock || successor == loop->mergeBlock;
});
return armLeavesOrJoins && isInsideLoopConstruct(graph, *loop, other) && isInsideLoopConstruct(graph, *loop, join) && graph.Dominates(block.id, join);
};
if (joinsAt(trueTarget, falseTarget)) {
return trueTarget;
}
if (joinsAt(falseTarget, trueTarget)) {
return falseTarget;
}
if (globalMerge != InvalidControlFlowId) {
const bool trueJoins = reachesWithinIteration(graph, *loop, trueTarget, globalMerge);
const bool falseJoins = reachesWithinIteration(graph, *loop, falseTarget, globalMerge);
if (trueJoins != falseJoins) {
return trueJoins ? trueTarget : falseTarget;
}
const auto escapesAround = [&](std::uint32_t arm) {
return canReachBefore(graph, arm, loop->continueBlock, globalMerge) || canReachBefore(graph, arm, loop->mergeBlock, globalMerge);
};
if (trueJoins && !graph.Dominates(block.id, globalMerge) && (escapesAround(trueTarget) || escapesAround(falseTarget))) {
if (const auto merge = iterationSelectionMerge(graph, *loop, block, globalMerge); merge != InvalidControlFlowId) {
return merge;
}
}
}
return globalMerge;
}
bool isInnermostLoopControlConditional(const ControlFlowGraph& graph, const BasicBlock& block) {
if (block.terminator.kind != TerminatorKind::ConditionalBranch) {
return false;
}
const auto* loop = findInnermostContainingLoop(graph, block.id);
if (loop == nullptr || loop->mergeBlock == InvalidControlFlowId || loop->continueBlock == InvalidControlFlowId) {
return false;
}
const auto trueTarget = block.terminator.trueBlock;
const auto falseTarget = block.terminator.falseBlock;
if (block.id == loop->continueBlock) {
const auto isRepeatTarget = [&](std::uint32_t target) {
return target == loop->headerBlock || target == loop->mergeBlock;
};
return isRepeatTarget(trueTarget) && isRepeatTarget(falseTarget);
}
const bool trueInBody = containsSorted(loop->blocks, trueTarget);
const bool falseInBody = containsSorted(loop->blocks, falseTarget);
if (trueInBody != falseInBody) {
return true;
}
const auto isControlTarget = [&](std::uint32_t target) {
return target == loop->mergeBlock || target == loop->continueBlock;
};
return (isControlTarget(trueTarget) && (isControlTarget(falseTarget) || isInsideLoopConstruct(graph, *loop, falseTarget))) || (isControlTarget(falseTarget) && isInsideLoopConstruct(graph, *loop, trueTarget));
}
std::uint32_t exitTailSelectionMerge(const ControlFlowGraph& graph, const BasicBlock& block, bool privateTail) {
if (block.terminator.kind != TerminatorKind::ConditionalBranch) {
return InvalidControlFlowId;
}
const auto* loop = findInnermostContainingLoop(graph, block.id);
if (loop == nullptr || loop->mergeBlock == InvalidControlFlowId || loop->continueBlock == InvalidControlFlowId || block.id == loop->continueBlock) {
return InvalidControlFlowId;
}
const auto trueTarget = block.terminator.trueBlock;
const auto falseTarget = block.terminator.falseBlock;
const bool trueInBody = containsSorted(loop->blocks, trueTarget);
if (trueInBody == containsSorted(loop->blocks, falseTarget)) {
return InvalidControlFlowId;
}
const auto body = trueInBody ? trueTarget : falseTarget;
const auto tail = trueInBody ? falseTarget : trueTarget;
if (tail == loop->mergeBlock || tail == loop->continueBlock || body == loop->continueBlock || !isInsideLoopConstruct(graph, *loop, tail) || !graph.Dominates(block.id, body) || !graph.Dominates(block.id, tail) || (privateTail && reachesWithinIteration(graph, *loop, body, tail))) {
return InvalidControlFlowId;
}
std::vector<std::uint32_t> pending{tail};
std::vector<std::uint32_t> seen;
while (!pending.empty()) {
const auto blockId = pending.back();
pending.pop_back();
if (contains(seen, blockId)) {
continue;
}
seen.push_back(blockId);
for (const auto successor : graph.FindBlock(blockId).successors) {
if (successor == loop->mergeBlock) {
continue;
}
if (containsSorted(loop->blocks, successor) || !graph.Dominates(tail, successor) || !isInsideLoopConstruct(graph, *loop, successor)) {
return InvalidControlFlowId;
}
pending.push_back(successor);
}
}
return body;
}
bool isStructuredLoopExit(const ControlFlowGraph& graph, const BasicBlock& block, bool privateTail) {
if (!isInnermostLoopControlConditional(graph, block)) {
return false;
}
if (!privateTail) {
return true;
}
const auto* loop = findInnermostContainingLoop(graph, block.id);
const auto isControlTarget = [&](std::uint32_t target) {
return target == loop->mergeBlock || target == loop->continueBlock || (block.id == loop->continueBlock && target == loop->headerBlock);
};
return isControlTarget(block.terminator.trueBlock) || isControlTarget(block.terminator.falseBlock) || exitTailSelectionMerge(graph, block, true) != InvalidControlFlowId;
}
bool mergeLeavesContainingLoop(const ControlFlowGraph& graph, std::uint32_t header, std::uint32_t merge) {
for (const auto& loop : graph.naturalLoops) {
if (loop.headerBlock != header && isInsideLoopConstruct(graph, loop, header) && !isInsideLoopConstruct(graph, loop, merge)) {
return true;
}
}
return false;
}
template <typename InConstruct>
bool splitSharedMergeBlock(ControlFlowGraph& graph, std::uint32_t merge, InConstruct inConstruct, bool forceSplit = false) {
if (merge == InvalidControlFlowId || merge >= graph.blocks.size() || inConstruct(merge)) {
return false;
}
const auto& mergeBlock = graph.FindBlock(merge);
std::vector<std::uint32_t> constructPredecessors;
bool hasExternalPredecessor = false;
for (const auto predecessor : mergeBlock.predecessors) {
if (inConstruct(predecessor)) {
addUnique(constructPredecessors, predecessor);
} else {
hasExternalPredecessor = true;
}
}
if (constructPredecessors.empty() || (!forceSplit && !hasExternalPredecessor)) {
return false;
}
const auto syntheticMerge = appendSyntheticBranchBlock(graph, merge);
auto& syntheticBlock = graph.FindBlock(syntheticMerge);