-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathstructurize.rs
More file actions
1838 lines (1668 loc) · 83.2 KB
/
Copy pathstructurize.rs
File metadata and controls
1838 lines (1668 loc) · 83.2 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
//! Control-flow structurization (unstructured CFG -> structured regions).
//
// FIXME(eddyb) consider moving docs to the module level?
use crate::cf::SelectionKind;
use crate::cf::unstructured::{
ControlFlowGraph, ControlInst, ControlInstKind, IncomingEdgeCount, LoopFinder, TraversalState,
};
use crate::transform::{InnerInPlaceTransform as _, Transformed, Transformer};
use crate::{
AttrSet, Const, ConstDef, ConstKind, Context, DbgSrcLoc, EntityOrientedDenseMap, FuncDefBody,
FxIndexMap, FxIndexSet, Node, NodeDef, NodeKind, Region, RegionDef, Type, TypeKind, Value, Var,
VarDecl, VarKind, spv,
};
use itertools::{Either, Itertools};
use smallvec::SmallVec;
use std::mem;
use std::rc::Rc;
#[allow(rustdoc::private_intra_doc_links)]
/// Control-flow "structurizer", which attempts to convert as much of the CFG
/// as possible into structural control-flow (regions).
///
/// See [`StructurizeRegionState`]'s docs for more details on the algorithm.
//
// FIXME(eddyb) document this (instead of having it on `StructurizeRegionState`).
//
// NOTE(eddyb) CFG structurizer has these stages (per-region):
// 1. absorb any deferred exits that finally have 100% refcount
// 2. absorb a single backedge deferred exit to the same region
//
// What we could add is a third step, to handle irreducible controlflow:
// 3. check for groups of exits that have fully satisfied refcounts iff the
// rest of the exits in the group are all added together - if so, the group
// is *irreducible* and a single "loop header" can be created, that gets
// the group of deferred exits, and any other occurrence of the deferred
// exits (in either the original region, or amongst themselves) can be
// replaced with the "loop header" with appropriate selector inputs
//
// Sadly 3. requires a bunch of tests that are hard to craft (can rustc MIR
// even end up in the right shape?).
// OpenCL has `goto` so maybe it can also be used for this worse-than-diamond
// example: `entry -> a,b,d` `a,b -> c` `a,b,c -> d` `a,b,c,d <-> a,b,c,d`
// (the goal is avoiding a "flat group", i.e. where there is only one step
// between every exit in the group and another exit)
pub struct Structurizer<'a> {
cx: &'a Context,
/// Scrutinee type for [`SelectionKind::BoolCond`].
type_bool: Type,
/// Scrutinee value for [`SelectionKind::BoolCond`], for the "then" case.
const_true: Const,
/// Scrutinee value for [`SelectionKind::BoolCond`], for the "else" case.
const_false: Const,
func_def_body: &'a mut FuncDefBody,
// FIXME(eddyb) this feels a bit inefficient (are many-exit loops rare?).
loop_header_to_exit_targets: FxIndexMap<Region, FxIndexSet<Region>>,
// HACK(eddyb) this also tracks all of `loop_header_to_exit_targets`, as
// "false edges" from every loop header to each exit target of that loop,
// which structurizing that loop consumes to "unlock" its own exits.
incoming_edge_counts_including_loop_exits: EntityOrientedDenseMap<Region, IncomingEdgeCount>,
/// `structurize_region_state[region]` tracks `.structurize_region(region)`
/// progress/results (see also [`StructurizeRegionState`]'s docs).
//
// FIXME(eddyb) use `EntityOrientedDenseMap` (which lacks iteration by design).
structurize_region_state: FxIndexMap<Region, StructurizeRegionState>,
// FIXME(eddyb) perhaps come up with a centralized abstraction for this
// (in theory `VarDecl`s could indicate aliases, but that's a tradeoff).
var_replacements: EntityOrientedDenseMap<Var, Value>,
}
// FIXME(eddyb) maybe this should be provided by `transform`.
struct VarReplacer<'a>(&'a EntityOrientedDenseMap<Var, Value>);
impl Transformer for VarReplacer<'_> {
fn transform_value_use(&mut self, v: &Value) -> Transformed<Value> {
let mut new_v = *v;
// NOTE(eddyb) this needs to be able to apply multiple replacements,
// due to the input potentially having redundantly chained `OpPhi`s.
//
// FIXME(eddyb) union-find-style "path compression" could record the
// final value inside `self.0` while replacements are being made,
// (e.g. using the type `EntityOrientedDenseMap<Var, Cell<Value>>`?)
// to avoid going through a chain more than once (and some of these
// replacements could also be applied early).
while let Value::Var(var) = new_v {
new_v = match self.0.get(var) {
Some(&v) => v,
None => break,
};
}
(*v != new_v).then_some(new_v).map_or(Transformed::Unchanged, Transformed::Changed)
}
}
/// The state of one `.structurize_region(region)` invocation, and its result.
///
/// There is a fourth (or 0th) implicit state, which is where nothing has yet
/// observed some region, and [`Structurizer`] isn't tracking it at all.
//
// FIXME(eddyb) make the 0th state explicit and move `incoming_edge_counts` to it.
enum StructurizeRegionState {
/// Structurization is still running, and observing this is a cycle.
InProgress,
/// Structurization completed, and this region can now be claimed.
Ready {
/// Cached `region_deferred_edges[region].edge_bundle.accumulated_count`,
/// i.e. the total count of backedges (if any exist) pointing to `region`
/// from the CFG subgraph that `region` itself dominates.
///
/// Claiming a region with backedges can combine them with the bundled
/// edges coming into the CFG cycle from outside, and instead of failing
/// due to the latter not being enough to claim the region on their own,
/// actually perform loop structurization.
accumulated_backedge_count: IncomingEdgeCount,
// HACK(eddyb) the only part of a `ClaimedRegion` that is computed by
// `structurize_region` (the rest comes from `try_claim_edge_bundle`).
region_deferred_edges: DeferredEdgeBundleSet,
},
/// Region was claimed (by an [`IncomingEdgeBundle`], with the appropriate
/// total [`IncomingEdgeCount`], minus `accumulated_backedge_count`), and
/// must eventually be incorporated as part of some larger region.
Claimed,
}
/// An "(incoming) edge bundle" is a subset of the edges into a single `target`.
///
/// When `accumulated_count` reaches the total [`IncomingEdgeCount`] for `target`,
/// that [`IncomingEdgeBundle`] is said to "effectively own" its `target` (akin to
/// the more commonly used CFG domination relation, but more "incremental").
///
/// **Note**: `target` has a generic type `T` to reduce redundancy when it's
/// already implied (e.g. by the key in [`DeferredEdgeBundleSet`]'s map).
struct IncomingEdgeBundle<T> {
/// Attributes from the original [`ControlInst`]s (likely debuginfo), kept
/// when merging only when exactly identical, which can naturally be the case
/// for debuginfo (e.g. for branches from inside `if`-`else`/`switch` to a
/// common merge point, just after the whole control-flow construct).
//
// FIXME(eddyb) semantically filter these, maybe focus on debuginfo?
attrs: AttrSet,
target: T,
accumulated_count: IncomingEdgeCount,
/// The [`Value`]s that `VarKind::RegionInput { region, .. }` will get
/// on entry into `region`, through this "edge bundle".
target_inputs: SmallVec<[Value; 2]>,
}
impl<T> IncomingEdgeBundle<T> {
fn with_target<U>(self, target: U) -> IncomingEdgeBundle<U> {
let IncomingEdgeBundle { attrs, target: _, accumulated_count, target_inputs } = self;
IncomingEdgeBundle { attrs, target, accumulated_count, target_inputs }
}
}
/// A "deferred (incoming) edge bundle" is an [`IncomingEdgeBundle`] that cannot
/// be structurized immediately, but instead waits for its `accumulated_count`
/// to reach the full count of its `target`, before it can grafted into some
/// structured control-flow region.
///
/// While in the "deferred" state, its can accumulate a non-trivial `condition`,
/// every time it's propagated to an "outer" region, e.g. for this pseudocode:
/// ```text
/// if a {
/// branch => label1
/// } else {
/// if b {
/// branch => label1
/// }
/// }
/// ```
/// the deferral of branches to `label1` will result in:
/// ```text
/// label1_condition = if a {
/// true
/// } else {
/// if b {
/// true
/// } else {
/// false
/// }
/// }
/// if label1_condition {
/// branch => label1
/// }
/// ```
/// which could theoretically be simplified (after the [`Structurizer`]) to:
/// ```text
/// label1_condition = a | b
/// if label1_condition {
/// branch => label1
/// }
/// ```
///
/// **Note**: `edge_bundle.target` has a generic type `T` to reduce redundancy
/// when it's already implied (e.g. by the key in [`DeferredEdgeBundleSet`]'s map).
struct DeferredEdgeBundle<T = DeferredTarget> {
condition: LazyCond,
edge_bundle: IncomingEdgeBundle<T>,
}
impl<T> DeferredEdgeBundle<T> {
fn with_target<U>(self, target: U) -> DeferredEdgeBundle<U> {
let DeferredEdgeBundle { condition, edge_bundle } = self;
DeferredEdgeBundle { condition, edge_bundle: edge_bundle.with_target(target) }
}
}
/// A recipe for computing a control-flow-sensitive (boolean) condition [`Value`],
/// potentially requiring merging through an arbitrary number of `Select`s
/// (via per-case outputs and [`VarKind::NodeOutput`], for each `Select`).
///
/// This should largely be equivalent to eagerly generating all region outputs
/// that might be needed, and then removing the unused ones, but this way we
/// never generate unused outputs, and can potentially even optimize away some
/// redundant dataflow (e.g. `if cond { true } else { false }` is just `cond`).
#[derive(Clone)]
enum LazyCond {
// HACK(eddyb) `Undef` is used when the condition comes from e.g. a `Select`
// case that diverges and/or represents `unreachable`.
Undef,
False,
True,
Merge(Rc<LazyCondMerge>),
}
enum LazyCondMerge {
Select {
node: Node,
// FIXME(eddyb) the lowest level of `LazyCond` ends up containing only
// `LazyCond::{Undef,False,True}`, and that could more efficiently be
// expressed using e.g. bitsets, but the `Rc` in `LazyCond::Merge`
// means that this is more compact than it would otherwise be.
per_case_conds: SmallVec<[LazyCond; 4]>,
},
}
/// A target for one of the edge bundles in a [`DeferredEdgeBundleSet`], mostly
/// separate from [`Region`] to allow expressing returns as well.
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
enum DeferredTarget {
Region(Region),
/// Structured "return" out of the function (with `target_inputs` used for
/// the function body `output`s, i.e. inputs of [`ControlInstKind::Return`]).
Return,
}
/// Set of [`DeferredEdgeBundle`]s, uniquely keyed by their `target`s.
///
/// Semantically equivalent to an unordered series of conditional branches
/// to each possible `target`, which corresponds to an unenforced invariant
/// that exactly one [`DeferredEdgeBundle`] condition must be `true` at any
/// given time (the only non-trivial case, [`DeferredEdgeBundleSet::Choice`],
/// satisfies it because it's only used for merging `Select` cases, and so
/// all the conditions will end up using disjoint [`LazyCond::Merge`]s).
enum DeferredEdgeBundleSet {
Unreachable,
// NOTE(eddyb) this erases the condition (by not using `DeferredEdgeBundle`).
Always {
// HACK(eddyb) fields are split here to allow e.g. iteration.
target: DeferredTarget,
edge_bundle: IncomingEdgeBundle<()>,
},
Choice {
target_to_deferred: FxIndexMap<DeferredTarget, DeferredEdgeBundle<()>>,
},
}
impl FromIterator<DeferredEdgeBundle> for DeferredEdgeBundleSet {
fn from_iter<T: IntoIterator<Item = DeferredEdgeBundle>>(iter: T) -> Self {
let mut iter = iter.into_iter();
match iter.next() {
None => Self::Unreachable,
Some(first) => match iter.next() {
// NOTE(eddyb) this erases the condition (by not using `DeferredEdgeBundle`).
None => Self::Always {
target: first.edge_bundle.target,
edge_bundle: first.edge_bundle.with_target(()),
},
Some(second) => Self::Choice {
target_to_deferred: ([first, second].into_iter().chain(iter))
.map(|d| (d.edge_bundle.target, d.with_target(())))
.collect(),
},
},
}
}
}
impl From<FxIndexMap<DeferredTarget, DeferredEdgeBundle<()>>> for DeferredEdgeBundleSet {
fn from(target_to_deferred: FxIndexMap<DeferredTarget, DeferredEdgeBundle<()>>) -> Self {
if target_to_deferred.len() <= 1 {
target_to_deferred
.into_iter()
.map(|(target, deferred)| deferred.with_target(target))
.collect()
} else {
Self::Choice { target_to_deferred }
}
}
}
// HACK(eddyb) this API is a mess, is there an uncompromising way to clean it up?
impl DeferredEdgeBundleSet {
fn get_edge_bundle_by_target(
&self,
search_target: DeferredTarget,
) -> Option<&IncomingEdgeBundle<()>> {
match self {
DeferredEdgeBundleSet::Unreachable => None,
DeferredEdgeBundleSet::Always { target, edge_bundle } => {
(*target == search_target).then_some(edge_bundle)
}
DeferredEdgeBundleSet::Choice { target_to_deferred } => {
Some(&target_to_deferred.get(&search_target)?.edge_bundle)
}
}
}
fn get_edge_bundle_mut_by_target(
&mut self,
search_target: DeferredTarget,
) -> Option<&mut IncomingEdgeBundle<()>> {
match self {
DeferredEdgeBundleSet::Unreachable => None,
DeferredEdgeBundleSet::Always { target, edge_bundle } => {
(*target == search_target).then_some(edge_bundle)
}
DeferredEdgeBundleSet::Choice { target_to_deferred } => {
Some(&mut target_to_deferred.get_mut(&search_target)?.edge_bundle)
}
}
}
fn iter_targets_with_edge_bundle(
&self,
) -> impl Iterator<Item = (DeferredTarget, &IncomingEdgeBundle<()>)> {
match self {
DeferredEdgeBundleSet::Unreachable => Either::Left(None.into_iter()),
DeferredEdgeBundleSet::Always { target, edge_bundle } => {
Either::Left(Some((*target, edge_bundle)).into_iter())
}
DeferredEdgeBundleSet::Choice { target_to_deferred } => Either::Right(
target_to_deferred
.iter()
.map(|(&target, deferred)| (target, &deferred.edge_bundle)),
),
}
}
fn iter_targets_with_edge_bundle_mut(
&mut self,
) -> impl Iterator<Item = (DeferredTarget, &mut IncomingEdgeBundle<()>)> {
match self {
DeferredEdgeBundleSet::Unreachable => Either::Left(None.into_iter()),
DeferredEdgeBundleSet::Always { target, edge_bundle } => {
Either::Left(Some((*target, edge_bundle)).into_iter())
}
DeferredEdgeBundleSet::Choice { target_to_deferred } => Either::Right(
target_to_deferred
.iter_mut()
.map(|(&target, deferred)| (target, &mut deferred.edge_bundle)),
),
}
}
// HACK(eddyb) this only exists because of `DeferredEdgeBundleSet`'s lossy
// representation wrt conditions, so removal from a `DeferredEdgeBundleSet`
// cannot be used for e.g. `Select` iterating over per-case deferreds.
fn steal_deferred_by_target_without_removal(
&mut self,
search_target: DeferredTarget,
) -> Option<DeferredEdgeBundle<()>> {
let steal_edge_bundle = |edge_bundle: &mut IncomingEdgeBundle<()>| IncomingEdgeBundle {
attrs: edge_bundle.attrs,
target: (),
accumulated_count: edge_bundle.accumulated_count,
target_inputs: mem::take(&mut edge_bundle.target_inputs),
};
match self {
DeferredEdgeBundleSet::Unreachable => None,
DeferredEdgeBundleSet::Always { target, edge_bundle } => (*target == search_target)
.then(|| DeferredEdgeBundle {
condition: LazyCond::True,
edge_bundle: steal_edge_bundle(edge_bundle),
}),
DeferredEdgeBundleSet::Choice { target_to_deferred } => {
let DeferredEdgeBundle { condition, edge_bundle } =
target_to_deferred.get_mut(&search_target)?;
Some(DeferredEdgeBundle {
condition: mem::replace(condition, LazyCond::False),
edge_bundle: steal_edge_bundle(edge_bundle),
})
}
}
}
// NOTE(eddyb) the returned `DeferredEdgeBundleSet` exists under the assumption
// that `split_target` is not reachable from it, so this method is not suitable
// for e.g. uniformly draining `DeferredEdgeBundleSet` in a way that preserves
// conditions (but rather it's almost a kind of control-flow "slicing").
fn split_out_target(self, split_target: DeferredTarget) -> (Option<DeferredEdgeBundle>, Self) {
match self {
DeferredEdgeBundleSet::Unreachable => (None, DeferredEdgeBundleSet::Unreachable),
DeferredEdgeBundleSet::Always { target, edge_bundle } => {
if target == split_target {
(
Some(DeferredEdgeBundle {
condition: LazyCond::True,
edge_bundle: edge_bundle.with_target(target),
}),
DeferredEdgeBundleSet::Unreachable,
)
} else {
(None, DeferredEdgeBundleSet::Always { target, edge_bundle })
}
}
DeferredEdgeBundleSet::Choice { mut target_to_deferred } => {
// FIXME(eddyb) should this use `shift_remove` and/or emulate
// extra tombstones, to avoid impacting the order?
(
target_to_deferred
.swap_remove(&split_target)
.map(|d| d.with_target(split_target)),
Self::from(target_to_deferred),
)
}
}
}
// HACK(eddyb) the strange signature is overfitted to its own callsite.
fn split_out_matching<T>(
self,
mut matches: impl FnMut(DeferredEdgeBundle) -> Result<T, DeferredEdgeBundle>,
) -> (Option<T>, Self) {
match self {
DeferredEdgeBundleSet::Unreachable => (None, DeferredEdgeBundleSet::Unreachable),
DeferredEdgeBundleSet::Always { target, edge_bundle } => {
match matches(DeferredEdgeBundle {
condition: LazyCond::True,
edge_bundle: edge_bundle.with_target(target),
}) {
Ok(x) => (Some(x), DeferredEdgeBundleSet::Unreachable),
Err(new_deferred) => {
assert!(new_deferred.edge_bundle.target == target);
assert!(matches!(new_deferred.condition, LazyCond::True));
(
None,
DeferredEdgeBundleSet::Always {
target,
edge_bundle: new_deferred.edge_bundle.with_target(()),
},
)
}
}
}
DeferredEdgeBundleSet::Choice { mut target_to_deferred } => {
let mut result = None;
for (i, (&target, deferred)) in target_to_deferred.iter_mut().enumerate() {
// HACK(eddyb) "take" `deferred` so it can be passed to
// `matches` (and put back if that returned `Err`).
let taken_deferred = mem::replace(
deferred,
DeferredEdgeBundle {
condition: LazyCond::False,
edge_bundle: IncomingEdgeBundle {
attrs: Default::default(),
target: Default::default(),
accumulated_count: Default::default(),
target_inputs: Default::default(),
},
},
);
match matches(taken_deferred.with_target(target)) {
Ok(x) => {
result = Some(x);
// FIXME(eddyb) should this use `swap_remove_index`?
target_to_deferred.shift_remove_index(i).unwrap();
break;
}
// Put back the `DeferredEdgeBundle` and keep looking.
Err(new_deferred) => {
assert!(new_deferred.edge_bundle.target == target);
*deferred = new_deferred.with_target(());
}
}
}
(result, Self::from(target_to_deferred))
}
}
}
}
/// A successfully "claimed" (via `try_claim_edge_bundle`) partially structurized
/// CFG subgraph (i.e. set of [`Region`]s previously connected by CFG edges),
/// which is effectively owned by the "claimer" and **must** be used for:
/// - the whole function body (if `deferred_edges` only contains `Return`)
/// - one of the cases of a `Select` node
/// - merging into a larger region (i.e. its nearest dominator)
//
// FIXME(eddyb) consider never having to claim the function body itself,
// by wrapping the CFG in a `Node` instead.
struct ClaimedRegion {
// FIXME(eddyb) find a way to clarify that this can differ from the target
// of `try_claim_edge_bundle`, and also that `deferred_edges` are from the
// perspective of being "inside" `structured_body` (wrt hermeticity).
structured_body: Region,
/// The [`Value`]s that `VarKind::RegionInput { region: structured_body, .. }`
/// will get on entry into `structured_body`, when this region ends up
/// merged into a larger region, or as a child of a new [`Node`].
//
// FIXME(eddyb) don't replace `VarKind::RegionInput { region: structured_body, .. }`
// with `structured_body_inputs` when `structured_body` ends up a `Node` child,
// but instead make all `Region`s entirely hermetic wrt inputs.
structured_body_inputs: SmallVec<[Value; 2]>,
/// The transitive targets which couldn't be claimed into `structured_body`
/// remain as deferred exits, and will block further structurization until
/// all other edges to those same targets are gathered together.
///
/// **Note**: this will only be empty if the region can never exit,
/// i.e. it has divergent control-flow (such as an infinite loop), as any
/// control-flow path that can (eventually) return from the function, will
/// end up using a deferred target for that (see [`DeferredTarget::Return`]).
deferred_edges: DeferredEdgeBundleSet,
}
impl<'a> Structurizer<'a> {
pub fn new(cx: &'a Context, func_def_body: &'a mut FuncDefBody) -> Self {
// FIXME(eddyb) SPIR-T should have native booleans itself.
let wk = &spv::spec::Spec::get().well_known;
let type_bool = cx.intern(TypeKind::SpvInst {
spv_inst: wk.OpTypeBool.into(),
type_and_const_inputs: [].into_iter().collect(),
});
let const_true = cx.intern(ConstDef {
attrs: AttrSet::default(),
ty: type_bool,
kind: ConstKind::SpvInst {
spv_inst_and_const_inputs: Rc::new((
wk.OpConstantTrue.into(),
[].into_iter().collect(),
)),
},
});
let const_false = cx.intern(ConstDef {
attrs: AttrSet::default(),
ty: type_bool,
kind: ConstKind::SpvInst {
spv_inst_and_const_inputs: Rc::new((
wk.OpConstantFalse.into(),
[].into_iter().collect(),
)),
},
});
let (loop_header_to_exit_targets, incoming_edge_counts_including_loop_exits) =
func_def_body
.unstructured_cfg
.as_ref()
.map(|cfg| {
let loop_header_to_exit_targets =
LoopFinder::new(cfg).find_all_loops_starting_at(func_def_body.body);
let mut state = TraversalState {
incoming_edge_counts: EntityOrientedDenseMap::new(),
pre_order_visit: |_| {},
post_order_visit: |_| {},
reverse_targets: false,
};
cfg.traverse_whole_func(func_def_body, &mut state);
// HACK(eddyb) treat loop exits as "false edges", that their
// respective loop header "owns", such that structurization
// naturally stops at those loop exits, instead of continuing
// greedily into the loop exterior (producing "maximal loops").
for loop_exit_targets in loop_header_to_exit_targets.values() {
for &exit_target in loop_exit_targets {
*state
.incoming_edge_counts
.entry(exit_target)
.get_or_insert(Default::default()) += IncomingEdgeCount::ONE;
}
}
(loop_header_to_exit_targets, state.incoming_edge_counts)
})
.unwrap_or_default();
Self {
cx,
type_bool,
const_true,
const_false,
func_def_body,
loop_header_to_exit_targets,
incoming_edge_counts_including_loop_exits,
structurize_region_state: FxIndexMap::default(),
var_replacements: EntityOrientedDenseMap::new(),
}
}
pub fn structurize_func(mut self) {
// Don't even try to re-structurize functions.
if self.func_def_body.unstructured_cfg.is_none() {
return;
}
// FIXME(eddyb) it might work much better to have the unstructured CFG
// wrapped in a `Node` inside the function body, instead.
let func_body_deferred_edges = {
let func_entry_pseudo_edge = {
let target = self.func_def_body.body;
move || IncomingEdgeBundle {
attrs: Default::default(),
target,
accumulated_count: IncomingEdgeCount::ONE,
target_inputs: [].into_iter().collect(),
}
};
// HACK(eddyb) it's easier to assume the function never loops back
// to its body, than fix up the broken CFG if that never happens.
if self.incoming_edge_counts_including_loop_exits[func_entry_pseudo_edge().target]
!= func_entry_pseudo_edge().accumulated_count
{
// FIXME(eddyb) find a way to attach (diagnostic) attributes
// to a `FuncDefBody`, would be useful to have that here.
return;
}
let ClaimedRegion { structured_body, structured_body_inputs, deferred_edges } =
self.try_claim_edge_bundle(func_entry_pseudo_edge()).ok().unwrap();
assert!(structured_body == func_entry_pseudo_edge().target);
assert!(structured_body_inputs == func_entry_pseudo_edge().target_inputs);
deferred_edges
};
match func_body_deferred_edges {
// FIXME(eddyb) also support structured return when the whole body
// is divergent, by generating undef constants (needs access to the
// whole `FuncDecl`, not just `FuncDefBody`, to get the right types).
DeferredEdgeBundleSet::Unreachable => {
// HACK(eddyb) replace the CFG with one that only contains an
// `Unreachable` terminator for the body, comparable to what
// `rebuild_cfg_from_unclaimed_region_deferred_edges` would do
// in the general case (but special-cased because this is very
// close to being structurizable, just needs a bit of plumbing).
let mut control_inst_on_exit_from = EntityOrientedDenseMap::new();
control_inst_on_exit_from.insert(
self.func_def_body.body,
ControlInst {
attrs: AttrSet::default(),
kind: ControlInstKind::Unreachable,
inputs: [].into_iter().collect(),
targets: [].into_iter().collect(),
target_inputs: FxIndexMap::default(),
},
);
self.func_def_body.unstructured_cfg = Some(ControlFlowGraph {
control_inst_on_exit_from,
loop_merge_to_loop_header: Default::default(),
});
}
// Structured return, the function is fully structurized.
DeferredEdgeBundleSet::Always { target: DeferredTarget::Return, edge_bundle } => {
let body_def = self.func_def_body.at_mut_body().def();
body_def.outputs = edge_bundle.target_inputs;
self.func_def_body.unstructured_cfg = None;
}
_ => {
// Repair all the regions that remain unclaimed, including the body.
let structurize_region_state =
mem::take(&mut self.structurize_region_state).into_iter().chain([(
self.func_def_body.body,
StructurizeRegionState::Ready {
accumulated_backedge_count: IncomingEdgeCount::default(),
region_deferred_edges: func_body_deferred_edges,
},
)]);
for (target, state) in structurize_region_state {
if let StructurizeRegionState::Ready { region_deferred_edges, .. } = state {
self.rebuild_cfg_from_unclaimed_region_deferred_edges(
target,
region_deferred_edges,
);
}
}
}
}
// The last step of structurization is applying replacements accumulated
// while structurizing (i.e. `var_replacements`).
//
// FIXME(eddyb) obsolete this by fully taking advantage of hermeticity,
// and only replacing `VarKind::RegionInput { region, .. }` within
// `region`'s children, shallowly, whenever `region` gets claimed.
self.func_def_body.inner_in_place_transform_with(&mut VarReplacer(&self.var_replacements));
}
fn try_claim_edge_bundle(
&mut self,
edge_bundle: IncomingEdgeBundle<Region>,
) -> Result<ClaimedRegion, IncomingEdgeBundle<Region>> {
let target = edge_bundle.target;
// Always attempt structurization before checking the `IncomingEdgeCount`,
// to be able to make use of backedges (if any were found).
if self.structurize_region_state.get(&target).is_none() {
self.structurize_region(target);
}
let backedge_count = match self.structurize_region_state[&target] {
// This `try_claim_edge_bundle` call is itself a backedge, and it's
// coherent to not let any of them claim the loop itself, and only
// allow claiming the whole loop (if successfully structurized).
StructurizeRegionState::InProgress => IncomingEdgeCount::default(),
StructurizeRegionState::Ready { accumulated_backedge_count, .. } => {
accumulated_backedge_count
}
StructurizeRegionState::Claimed => {
unreachable!("cfg::Structurizer::try_claim_edge_bundle: already claimed");
}
};
if self.incoming_edge_counts_including_loop_exits[target]
!= edge_bundle.accumulated_count + backedge_count
{
return Err(edge_bundle);
}
let state =
self.structurize_region_state.insert(target, StructurizeRegionState::Claimed).unwrap();
let mut deferred_edges = match state {
StructurizeRegionState::InProgress => unreachable!(
"cfg::Structurizer::try_claim_edge_bundle: cyclic calls \
should not get this far"
),
StructurizeRegionState::Ready { region_deferred_edges, .. } => region_deferred_edges,
StructurizeRegionState::Claimed => {
// Handled above.
unreachable!()
}
};
let mut backedge = None;
if backedge_count != IncomingEdgeCount::default() {
(backedge, deferred_edges) =
deferred_edges.split_out_target(DeferredTarget::Region(target));
}
// If the target contains any backedge to itself, that's a loop, with:
// * entry: `edge_bundle` (unconditional, i.e. `do`-`while`-like)
// * body: `target`
// * repeat ("continue") edge: `backedge` (with its `condition`)
// * exit ("break") edges: `deferred_edges`
let structured_body = if let Some(backedge) = backedge {
let DeferredEdgeBundle { condition: repeat_condition, edge_bundle: backedge } =
backedge;
let body = target;
// HACK(eddyb) due to `Loop` `Node`s not being hermetic on
// the output side yet (i.e. they still have SSA-like semantics),
// it gets wrapped in a `Region`, which can be as hermetic as
// the loop body itself was originally.
// NOTE(eddyb) both input declarations and the child `Loop` node are
// added later down below, after the `Loop` node is created.
let wrapper_region = self.func_def_body.regions.define(self.cx, RegionDef::default());
// Any loop body region inputs, which must receive values from both
// the loop entry and the backedge, become explicit "loop state",
// starting as `initial_inputs` and being replaced with body outputs
// after every loop iteration.
//
// FIXME(eddyb) `Loop` `Node`s should be changed to be hermetic
// and have the loop state be output from the whole node itself,
// for any outside uses of values defined within the loop body.
let body_def = &mut self.func_def_body.regions[body];
let original_body_input_vars = mem::take(&mut body_def.inputs);
assert!(body_def.outputs.is_empty());
// HACK(eddyb) some dataflow through the loop body is redundant,
// and can be lifted out of it, but the worst part is that applying
// the replacement requires leaving alone all the non-redundant
// `body` region inputs at the same time, and it's not really
// feasible to move `body`'s children into a new region without
// wasting it completely (i.e. can't swap with `wrapper_region`).
let mut initial_inputs = SmallVec::<[_; 2]>::new();
// FIXME(eddyb) optimize this (also, maybe it's worth introducing
// a high-level `retain` for `body_def.inputs`, also updating decls).
for (original_body_input_var, mut backedge_value) in
original_body_input_vars.into_iter().zip_eq(backedge.target_inputs)
{
VarReplacer(&self.var_replacements)
.transform_value_use(&backedge_value)
.apply_to(&mut backedge_value);
// FIXME(eddyb) this fully duplicates attributes, could be messy?
let input_var_decl = self.func_def_body.vars[original_body_input_var].clone();
let wrapper_region_input_vars =
&mut self.func_def_body.regions[wrapper_region].inputs;
let wrapper_region_input_decl = VarDecl {
def_parent: Either::Left(wrapper_region),
def_idx: wrapper_region_input_vars.len().try_into().unwrap(),
..input_var_decl.clone()
};
if backedge_value == Value::Var(original_body_input_var) {
// Move this redundant input to `wrapper_region`, instead of
// allocating a new `Var`, to avoid wasting the now-unused
// `original_body_input_var` (which would've also needed a
// `var_replacements` entry, mapping it to the new `Var`).
self.func_def_body.vars[original_body_input_var] = wrapper_region_input_decl;
wrapper_region_input_vars.push(original_body_input_var);
} else {
let wrapper_region_input_var =
self.func_def_body.vars.define(self.cx, wrapper_region_input_decl);
wrapper_region_input_vars.push(wrapper_region_input_var);
initial_inputs.push(Value::Var(wrapper_region_input_var));
let body_def = &mut self.func_def_body.regions[body];
self.func_def_body.vars[original_body_input_var] = VarDecl {
def_parent: Either::Left(body),
def_idx: body_def.inputs.len().try_into().unwrap(),
..input_var_decl
};
body_def.inputs.push(original_body_input_var);
body_def.outputs.push(backedge_value);
}
}
let body_def = &mut self.func_def_body.regions[body];
assert_eq!(initial_inputs.len(), body_def.inputs.len());
assert_eq!(body_def.outputs.len(), body_def.inputs.len());
let repeat_condition = self.materialize_lazy_cond(&repeat_condition);
let loop_node = self.func_def_body.nodes.define(
self.cx,
NodeDef {
// FIXME(eddyb) could it be possible to synthesize attrs
// from `ControlInst`s' attrs and/or `OpLoopMerge`'s?
attrs: AttrSet::default(),
kind: NodeKind::Loop { repeat_condition },
inputs: initial_inputs,
child_regions: [body].into_iter().collect(),
outputs: [].into_iter().collect(),
}
.into(),
);
self.func_def_body.regions[wrapper_region]
.children
.insert_last(loop_node, &mut self.func_def_body.nodes);
// HACK(eddyb) we've treated loop exits as extra "false edges", so
// here they have to be added to the loop (potentially unlocking
// structurization to the outside of the loop, in the caller).
if let Some(exit_targets) = self.loop_header_to_exit_targets.get(&target) {
for &exit_target in exit_targets {
// FIXME(eddyb) what if this is `None`, is that impossible?
if let Some(exit_edge_bundle) = deferred_edges
.get_edge_bundle_mut_by_target(DeferredTarget::Region(exit_target))
{
exit_edge_bundle.accumulated_count += IncomingEdgeCount::ONE;
}
}
}
wrapper_region
} else {
target
};
let IncomingEdgeBundle { attrs, target: _, accumulated_count: _, target_inputs } =
edge_bundle;
// FIXME(eddyb) this loses `attrs`.
let _ = attrs;
Ok(ClaimedRegion { structured_body, structured_body_inputs: target_inputs, deferred_edges })
}
/// Structurize `region` by absorbing into it the entire CFG subgraph which
/// it dominates (and deferring any other edges to the rest of the CFG).
///
/// The output of this process is stored in, and any other bookkeeping is
/// done through, `self.structurize_region_state[region]`.
///
/// See also [`StructurizeRegionState`]'s docs.
fn structurize_region(&mut self, region: Region) {
{
let old_state =
self.structurize_region_state.insert(region, StructurizeRegionState::InProgress);
if let Some(old_state) = old_state {
unreachable!(
"cfg::Structurizer::structurize_region: \
already {}, when attempting to start structurization",
match old_state {
StructurizeRegionState::InProgress => "in progress (cycle detected)",
StructurizeRegionState::Ready { .. } => "completed",
StructurizeRegionState::Claimed => "claimed",
}
);
}
}
let control_inst_on_exit = self
.func_def_body
.unstructured_cfg
.as_mut()
.unwrap()
.control_inst_on_exit_from
.remove(region)
.expect(
"cfg::Structurizer::structurize_region: missing \
`ControlInst` (CFG wasn't unstructured in the first place?)",
);
// Start with the concatenation of `region` and `control_inst_on_exit`,
// always appending `Node`s (including the children of entire
// `ClaimedRegion`s) to `region`'s definition itself.
let mut deferred_edges = {
let ControlInst { attrs, kind, inputs, targets, target_inputs } = control_inst_on_exit;
let target_regions: SmallVec<[_; 8]> = targets
.iter()
.map(|&target| {
self.try_claim_edge_bundle(IncomingEdgeBundle {
attrs: if targets.len() == 1 { attrs } else { AttrSet::default() },
target,
accumulated_count: IncomingEdgeCount::ONE,
target_inputs: target_inputs.get(&target).cloned().unwrap_or_default(),
})
.map_err(|edge_bundle| {
// HACK(eddyb) special-case "shared `unreachable`" to
// always inline it and avoid awkward "merges".
// FIXME(eddyb) should this be in a separate CFG pass?
// (i.e. is there a risk of other logic needing this?)
let target_is_trivial_unreachable =
match self.structurize_region_state.get(&edge_bundle.target) {
Some(StructurizeRegionState::Ready {
region_deferred_edges: DeferredEdgeBundleSet::Unreachable,
..
}) => {
// FIXME(eddyb) DRY this "is empty region" check.
self.func_def_body
.at(edge_bundle.target)
.at_children()
.into_iter()
.next()
.is_none()
}
_ => false,
};
if target_is_trivial_unreachable {
DeferredEdgeBundleSet::Unreachable
} else {
DeferredEdgeBundleSet::Always {
target: DeferredTarget::Region(edge_bundle.target),
edge_bundle: edge_bundle.with_target(()),
}
}
})
})