Debian Codegraph @

src/nouveau/compiler/nak/liveness.rs

raw
1 // Copyright © 2022 Collabora, Ltd.
2 // SPDX-License-Identifier: MIT
3
4 use crate::ir::*;
5
6 use compiler::bitset::BitSet;
7 use compiler::dataflow::BackwardDataflow;
8 use rustc_hash::{FxHashMap, FxHashSet};
9 use std::cmp::{max, min, Ord, Ordering};
10
11 #[derive(Clone, Default)]
12 pub struct LiveSet {
13 live: PerRegFile<u32>,
14 set: FxHashSet<SSAValue>,
15 }
16
17 impl LiveSet {
18 pub fn new() -> LiveSet {
19 Default::default()
20 }
21
22 pub fn clear(&mut self) {
23 self.live = Default::default();
24 self.set.clear();
25 }
26
27 pub fn contains(&self, ssa: &SSAValue) -> bool {
28 self.set.contains(ssa)
29 }
30
31 pub fn count(&self, file: RegFile) -> u32 {
32 self.live[file]
33 }
34
35 pub fn insert(&mut self, ssa: SSAValue) -> bool {
36 if self.set.insert(ssa) {
37 self.live[ssa.file()] += 1;
38 true
39 } else {
40 false
41 }
42 }
43
44 pub fn iter(&self) -> impl Iterator<Item = &SSAValue> {
45 self.set.iter()
46 }
47
48 pub fn remove(&mut self, ssa: &SSAValue) -> bool {
49 if self.set.remove(ssa) {
50 self.live[ssa.file()] -= 1;
51 true
52 } else {
53 false
54 }
55 }
56
57 pub fn insert_instr_top_down<L: BlockLiveness>(
58 &mut self,
59 ip: usize,
60 instr: &Instr,
61 bl: &L,
62 ) -> PerRegFile<u32> {
63 // Vector destinations go live before sources are killed. Even
64 // in the case where the destination is immediately killed, it
65 // still may contribute to pressure temporarily.
66 for dst in instr.dsts() {
67 if let Dst::SSA(vec) = dst {
68 if vec.comps() > 1 {
69 for ssa in vec.iter() {
70 self.insert(*ssa);
71 }
72 }
73 }
74 }
75
76 let after_dsts_live = self.live;
77
78 instr.for_each_ssa_use(|ssa| {
79 if !bl.is_live_after_ip(ssa, ip) {
80 self.remove(ssa);
81 }
82 });
83
84 // Scalar destinations are allocated last
85 for dst in instr.dsts() {
86 if let Dst::SSA(vec) = dst {
87 if vec.comps() == 1 {
88 self.insert(vec[0]);
89 }
90 }
91 }
92
93 let max_live = PerRegFile::new_with(|file| {
94 max(self.live[file], after_dsts_live[file])
95 });
96
97 // It's possible (but unlikely) that a destination is immediately
98 // killed. Remove any which are killed by this instruction.
99 instr.for_each_ssa_def(|ssa| {
100 debug_assert!(self.contains(ssa));
101 if !bl.is_live_after_ip(ssa, ip) {
102 self.remove(ssa);
103 }
104 });
105
106 max_live
107 }
108 }
109
110 impl FromIterator<SSAValue> for LiveSet {
111 fn from_iter<T: IntoIterator<Item = SSAValue>>(iter: T) -> Self {
112 let mut set = LiveSet::new();
113 let iter = iter.into_iter();
114 set.set.reserve(iter.size_hint().0);
115 for ssa in iter {
116 set.insert(ssa);
117 }
118 set
119 }
120 }
121
122 impl Extend<SSAValue> for LiveSet {
123 fn extend<T: IntoIterator<Item = SSAValue>>(&mut self, iter: T) {
124 let iter = iter.into_iter();
125 self.set.reserve(iter.size_hint().0);
126 for ssa in iter {
127 self.insert(ssa);
128 }
129 }
130 }
131
132 pub trait BlockLiveness {
133 /// Returns true if @val is still live after @ip
134 fn is_live_after_ip(&self, val: &SSAValue, ip: usize) -> bool;
135
136 /// Returns true if @val is live-in to this block
137 fn is_live_in(&self, val: &SSAValue) -> bool;
138
139 /// Returns true if @val is live-out of this block
140 fn is_live_out(&self, val: &SSAValue) -> bool;
141
142 fn get_instr_pressure(&self, ip: usize, instr: &Instr) -> PerRegFile<u8> {
143 let mut live = PerRegFile::new_with(|_| 0_i8);
144
145 // Vector destinations go live before sources are killed.
146 for dst in instr.dsts() {
147 if let Dst::SSA(vec) = dst {
148 if vec.comps() > 1 {
149 for ssa in vec.iter() {
150 live[ssa.file()] += 1;
151 }
152 }
153 }
154 }
155
156 // This is the first high point
157 let vec_dst_live = live;
158
159 // Use a hash set because sources may occur more than once
160 let mut killed: FxHashSet<_> = Default::default();
161 instr.for_each_ssa_use(|ssa| {
162 if !self.is_live_after_ip(ssa, ip) {
163 killed.insert(*ssa);
164 }
165 });
166 for ssa in killed.drain() {
167 live[ssa.file()] -= 1;
168 }
169
170 // Scalar destinations are allocated last
171 for dst in instr.dsts() {
172 if let Dst::SSA(vec) = dst {
173 if vec.comps() == 1 {
174 live[vec[0].file()] += 1;
175 }
176 }
177 }
178
179 PerRegFile::new_with(|file| {
180 max(0, max(vec_dst_live[file], live[file]))
181 .try_into()
182 .unwrap()
183 })
184 }
185 }
186
187 pub trait Liveness {
188 type PerBlock: BlockLiveness;
189
190 fn block_live(&self, idx: usize) -> &Self::PerBlock;
191
192 fn calc_max_live(&self, f: &Function) -> PerRegFile<u32> {
193 let mut max_live: PerRegFile<u32> = Default::default();
194 let mut block_live_out: Vec<LiveSet> = Vec::new();
195
196 for (bb_idx, bb) in f.blocks.iter().enumerate() {
197 let bl = self.block_live(bb_idx);
198
199 let mut live = LiveSet::new();
200
201 // Predecessors are added block order so we can just grab the first
202 // one (if any) and it will be a block we've processed.
203 if let Some(pred_idx) = f.blocks.pred_indices(bb_idx).first() {
204 let pred_out = &block_live_out[*pred_idx];
205 for ssa in pred_out.iter() {
206 if bl.is_live_in(ssa) {
207 live.insert(*ssa);
208 }
209 }
210 }
211
212 for (ip, instr) in bb.instrs.iter().enumerate() {
213 let live_at_instr = live.insert_instr_top_down(ip, instr, bl);
214 max_live = PerRegFile::new_with(|file| {
215 max(max_live[file], live_at_instr[file])
216 });
217
218 if let Op::RegOut(reg_out) = &instr.op {
219 // This should be the last instruction. Everything should
220 // be dead once we've processed it.
221 debug_assert!(live.count(RegFile::GPR) == 0);
222 let num_gprs_out = reg_out.srcs.len().try_into().unwrap();
223 max_live[RegFile::GPR] =
224 max(max_live[RegFile::GPR], num_gprs_out);
225 }
226 }
227
228 assert!(block_live_out.len() == bb_idx);
229 block_live_out.push(live);
230 }
231
232 max_live
233 }
234 }
235
236 #[derive(Default)]
237 pub struct SimpleBlockLiveness {
238 defs: BitSet<SSAValue>,
239 uses: BitSet<SSAValue>,
240 last_use: FxHashMap<SSAValue, usize>,
241 live_in: BitSet<SSAValue>,
242 live_out: BitSet<SSAValue>,
243 }
244
245 impl SimpleBlockLiveness {
246 fn new() -> Self {
247 Default::default()
248 }
249
250 fn add_def(&mut self, ssa: SSAValue) {
251 self.defs.insert(ssa);
252 }
253
254 fn add_use(&mut self, ssa: SSAValue, ip: usize) {
255 self.uses.insert(ssa);
256 self.last_use.insert(ssa, ip);
257 }
258 }
259
260 impl BlockLiveness for SimpleBlockLiveness {
261 fn is_live_after_ip(&self, val: &SSAValue, ip: usize) -> bool {
262 if self.live_out.contains(*val) {
263 true
264 } else if let Some(last_use_ip) = self.last_use.get(val) {
265 *last_use_ip > ip
266 } else {
267 false
268 }
269 }
270
271 fn is_live_in(&self, val: &SSAValue) -> bool {
272 self.live_in.contains(*val)
273 }
274
275 fn is_live_out(&self, val: &SSAValue) -> bool {
276 self.live_out.contains(*val)
277 }
278 }
279
280 pub struct SimpleLiveness {
281 ssa_block_ip: FxHashMap<SSAValue, (usize, usize)>,
282 blocks: Vec<SimpleBlockLiveness>,
283 }
284
285 impl SimpleLiveness {
286 pub fn for_function(func: &Function) -> SimpleLiveness {
287 let mut l = SimpleLiveness {
288 ssa_block_ip: Default::default(),
289 blocks: Vec::new(),
290 };
291
292 for (bi, b) in func.blocks.iter().enumerate() {
293 let mut bl = SimpleBlockLiveness::new();
294
295 for (ip, instr) in b.instrs.iter().enumerate() {
296 instr.for_each_ssa_use(|ssa| {
297 bl.add_use(*ssa, ip);
298 });
299 instr.for_each_ssa_def(|ssa| {
300 l.ssa_block_ip.insert(*ssa, (bi, ip));
301 bl.add_def(*ssa);
302 });
303 }
304
305 l.blocks.push(bl);
306 }
307 assert!(l.blocks.len() == func.blocks.len());
308
309 let mut live_in: Vec<BitSet<SSAValue>> =
310 (0..func.blocks.len()).map(|_| Default::default()).collect();
311 let mut live_out: Vec<BitSet<SSAValue>> =
312 (0..func.blocks.len()).map(|_| Default::default()).collect();
313 BackwardDataflow {
314 cfg: &func.blocks,
315 block_in: &mut live_in[..],
316 block_out: &mut live_out[..],
317 transfer: |block_idx, _, live_in, live_out| {
318 let bl = &l.blocks[block_idx];
319 live_in.union_with(
320 (live_out.s(..) | bl.uses.s(..)) - bl.defs.s(..),
321 )
322 },
323 join: |live_out, succ_live_in| {
324 *live_out |= succ_live_in.s(..);
325 },
326 }
327 .solve();
328
329 for ((bl, b_live_in), b_live_out) in l
330 .blocks
331 .iter_mut()
332 .zip(live_in.into_iter())
333 .zip(live_out.into_iter())
334 {
335 bl.live_in = b_live_in;
336 bl.live_out = b_live_out;
337 }
338
339 l
340 }
341 }
342
343 impl SimpleLiveness {
344 pub fn def_block_ip(&self, ssa: &SSAValue) -> (usize, usize) {
345 *self.ssa_block_ip.get(ssa).unwrap()
346 }
347
348 pub fn interferes(&self, a: &SSAValue, b: &SSAValue) -> bool {
349 let (ab, ai) = self.def_block_ip(a);
350 let (bb, bi) = self.def_block_ip(b);
351
352 match ab.cmp(&bb).then(ai.cmp(&bi)) {
353 Ordering::Equal => true,
354 Ordering::Less => self.block_live(bb).is_live_after_ip(a, bi),
355 Ordering::Greater => self.block_live(ab).is_live_after_ip(b, ai),
356 }
357 }
358 }
359
360 impl Liveness for SimpleLiveness {
361 type PerBlock = SimpleBlockLiveness;
362
363 fn block_live(&self, idx: usize) -> &SimpleBlockLiveness {
364 &self.blocks[idx]
365 }
366 }
367
368 struct SSAUseDef {
369 defined: bool,
370 uses: Vec<usize>,
371 }
372
373 impl SSAUseDef {
374 fn add_def(&mut self) {
375 self.defined = true;
376 }
377
378 fn add_in_block_use(&mut self, use_ip: usize) {
379 self.uses.push(use_ip);
380 }
381
382 fn add_successor_use(
383 &mut self,
384 num_block_instrs: usize,
385 use_ip: usize,
386 ) -> bool {
387 // IPs are relative to the start of their block
388 let use_ip = num_block_instrs + use_ip;
389
390 if let Some(last_use_ip) = self.uses.last_mut() {
391 if *last_use_ip < num_block_instrs {
392 // We've never seen a successor use before
393 self.uses.push(use_ip);
394 true
395 } else if *last_use_ip > use_ip {
396 // Otherwise, we want the minimum next use
397 *last_use_ip = use_ip;
398 true
399 } else {
400 false
401 }
402 } else {
403 self.uses.push(use_ip);
404 true
405 }
406 }
407 }
408
409 pub struct NextUseBlockLiveness {
410 num_instrs: usize,
411 ssa_map: FxHashMap<SSAValue, SSAUseDef>,
412 }
413
414 impl NextUseBlockLiveness {
415 fn new(num_instrs: usize) -> Self {
416 Self {
417 num_instrs: num_instrs,
418 ssa_map: Default::default(),
419 }
420 }
421
422 fn entry_mut(&mut self, ssa: SSAValue) -> &mut SSAUseDef {
423 self.ssa_map.entry(ssa).or_insert_with(|| SSAUseDef {
424 defined: false,
425 uses: Vec::new(),
426 })
427 }
428
429 fn add_def(&mut self, ssa: SSAValue) {
430 self.entry_mut(ssa).add_def();
431 }
432
433 fn add_use(&mut self, ssa: SSAValue, ip: usize) {
434 self.entry_mut(ssa).add_in_block_use(ip);
435 }
436
437 /// Returns an iterator over all the values which are live-in to this block
438 pub fn iter_live_in(&self) -> impl Iterator<Item = &SSAValue> {
439 self.ssa_map.iter().filter_map(|(ssa, entry)| {
440 if entry.defined || entry.uses.is_empty() {
441 None
442 } else {
443 Some(ssa)
444 }
445 })
446 }
447
448 /// Returns the IP of the first use of @val
449 ///
450 /// The returned IP is relative to the start of this block. If the next use
451 /// is in some successor block, the returned IP is relative to the start of
452 /// this block. If @val is not used in this block and is not live-out, None
453 /// is returned.
454 pub fn first_use(&self, val: &SSAValue) -> Option<usize> {
455 if let Some(entry) = self.ssa_map.get(val) {
456 entry.uses.first().cloned()
457 } else {
458 None
459 }
460 }
461
462 /// Returns the IP of the first use of @val which is greater than or equal
463 /// to @ip
464 ///
465 /// All IPs are relative to the start of the block. If the next use is some
466 /// successor block, the returned IP is relative to the start of this block.
467 pub fn next_use_after_or_at_ip(
468 &self,
469 val: &SSAValue,
470 ip: usize,
471 ) -> Option<usize> {
472 if let Some(entry) = self.ssa_map.get(val) {
473 let i = entry.uses.partition_point(|u| *u < ip);
474 if i < entry.uses.len() {
475 Some(entry.uses[i])
476 } else {
477 None
478 }
479 } else {
480 None
481 }
482 }
483 }
484
485 impl BlockLiveness for NextUseBlockLiveness {
486 fn is_live_after_ip(&self, val: &SSAValue, ip: usize) -> bool {
487 if let Some(entry) = self.ssa_map.get(val) {
488 if let Some(last_use_ip) = entry.uses.last() {
489 *last_use_ip > ip
490 } else {
491 false
492 }
493 } else {
494 false
495 }
496 }
497
498 fn is_live_in(&self, val: &SSAValue) -> bool {
499 if let Some(entry) = self.ssa_map.get(val) {
500 !entry.defined && !entry.uses.is_empty()
501 } else {
502 false
503 }
504 }
505
506 fn is_live_out(&self, val: &SSAValue) -> bool {
507 if let Some(entry) = self.ssa_map.get(val) {
508 if let Some(last_use_ip) = entry.uses.last() {
509 *last_use_ip >= self.num_instrs
510 } else {
511 false
512 }
513 } else {
514 false
515 }
516 }
517 }
518
519 /// An implementation of Liveness that tracks next-use IPs for each SSAValue
520 ///
521 /// Along with the usual liveness information, this tracks next-use IPs for each
522 /// SSAValue. Cross-block next-use IPs computed are as per the global next-use
523 /// distance algorithm described in "Register Spilling and Live-Range Splitting
524 /// for SSA-Form Programs" by Braun and Hack.
525 pub struct NextUseLiveness {
526 blocks: Vec<NextUseBlockLiveness>,
527 }
528
529 impl NextUseLiveness {
530 pub fn for_function(
531 func: &Function,
532 files: &RegFileSet,
533 ) -> NextUseLiveness {
534 let mut blocks = Vec::new();
535 for (bi, b) in func.blocks.iter().enumerate() {
536 let mut bl = NextUseBlockLiveness::new(b.instrs.len());
537
538 for (ip, instr) in b.instrs.iter().enumerate() {
539 instr.for_each_ssa_use(|ssa| {
540 if files.contains(ssa.file()) {
541 bl.add_use(*ssa, ip);
542 }
543 });
544
545 instr.for_each_ssa_def(|ssa| {
546 if files.contains(ssa.file()) {
547 bl.add_def(*ssa);
548 }
549 });
550 }
551
552 debug_assert!(bi == blocks.len());
553 blocks.push(bl);
554 }
555
556 let mut live_out: Vec<FxHashMap<SSAValue, usize>> =
557 (0..func.blocks.len()).map(|_| Default::default()).collect();
558 BackwardDataflow {
559 cfg: &func.blocks,
560 block_in: &mut blocks[..],
561 block_out: &mut live_out[..],
562 transfer: |_block_idx, _block, live_in, live_out| {
563 let num_instrs = live_in.num_instrs;
564 let mut changed = false;
565
566 for (&ssa, &first_use_ip) in live_out.iter() {
567 changed |= live_in
568 .entry_mut(ssa)
569 .add_successor_use(num_instrs, first_use_ip);
570 }
571 changed
572 },
573 join: |live_out, succ_live_in| {
574 if live_out.capacity() == 0 {
575 live_out.reserve(succ_live_in.ssa_map.len());
576 }
577
578 for (&ssa, entry) in succ_live_in.ssa_map.iter() {
579 if entry.defined {
580 continue;
581 }
582
583 let Some(&first_use_ip) = entry.uses.first() else {
584 continue;
585 };
586
587 live_out
588 .entry(ssa)
589 .and_modify(|val| *val = min(*val, first_use_ip))
590 .or_insert(first_use_ip);
591 }
592 },
593 }
594 .solve();
595
596 NextUseLiveness { blocks }
597 }
598 }
599
600 impl Liveness for NextUseLiveness {
601 type PerBlock = NextUseBlockLiveness;
602
603 fn block_live(&self, idx: usize) -> &NextUseBlockLiveness {
604 &self.blocks[idx]
605 }
606 }