Debian Codegraph @

src/nouveau/compiler/nak/spill_values.rs

raw
1 // Copyright © 2023 Collabora, Ltd.
2 // SPDX-License-Identifier: MIT
3
4 use crate::api::{GetDebugFlags, DEBUG};
5 use crate::const_tracker::ConstTracker;
6 use crate::ir::*;
7 use crate::liveness::{
8 BlockLiveness, LiveSet, Liveness, NextUseBlockLiveness, NextUseLiveness,
9 };
10
11 use compiler::bitset::BitSet;
12 use rustc_hash::{FxHashMap, FxHashSet};
13 use std::cell::RefCell;
14 use std::cmp::{max, Ordering, Reverse};
15 use std::collections::BinaryHeap;
16
17 #[derive(Default)]
18 struct PhiDstMap {
19 phi_ssa: FxHashMap<Phi, SSAValue>,
20 ssa_phi: FxHashMap<SSAValue, Phi>,
21 }
22
23 impl PhiDstMap {
24 fn new() -> PhiDstMap {
25 Default::default()
26 }
27
28 fn add_phi_dst(&mut self, phi: Phi, dst: &Dst) {
29 let vec = dst.as_ssa().expect("Not an SSA destination");
30 debug_assert!(vec.comps() == 1);
31 self.phi_ssa.insert(phi, vec[0]);
32 self.ssa_phi.insert(vec[0], phi);
33 }
34
35 pub fn from_block(block: &BasicBlock) -> PhiDstMap {
36 let mut map = PhiDstMap::new();
37 if let Some(op) = block.phi_dsts() {
38 for (idx, dst) in op.dsts.iter() {
39 map.add_phi_dst(*idx, dst);
40 }
41 }
42 map
43 }
44
45 fn get_phi(&self, ssa: &SSAValue) -> Option<&Phi> {
46 self.ssa_phi.get(ssa)
47 }
48
49 fn get_dst_ssa(&self, phi: &Phi) -> Option<&SSAValue> {
50 self.phi_ssa.get(phi)
51 }
52 }
53
54 #[derive(Default)]
55 struct PhiSrcMap {
56 src_phi: FxHashMap<SSAValue, Phi>,
57 }
58
59 impl PhiSrcMap {
60 fn new() -> PhiSrcMap {
61 Default::default()
62 }
63
64 fn add_phi_src(&mut self, phi: Phi, src: &Src) {
65 debug_assert!(src.is_unmodified());
66 let vec = src.src_ref.as_ssa().expect("Not an SSA source");
67 debug_assert!(vec.comps() == 1);
68 self.src_phi.insert(vec[0], phi);
69 }
70
71 pub fn from_block(block: &BasicBlock) -> PhiSrcMap {
72 let mut map = PhiSrcMap::new();
73 if let Some(op) = block.phi_srcs() {
74 for (phi, src) in op.srcs.iter() {
75 map.add_phi_src(*phi, src);
76 }
77 }
78 map
79 }
80
81 pub fn get_phi(&self, ssa: &SSAValue) -> Option<&Phi> {
82 self.src_phi.get(ssa)
83 }
84 }
85
86 trait Spill {
87 fn spill_file(&self, file: RegFile) -> RegFile;
88 fn spill(&mut self, dst: SSAValue, src: Src) -> Instr;
89 fn fill(&mut self, dst: Dst, src: SSAValue) -> Instr;
90 }
91
92 struct SpillUniform<'a> {
93 info: &'a mut ShaderInfo,
94 }
95
96 impl<'a> SpillUniform<'a> {
97 fn new(info: &'a mut ShaderInfo) -> Self {
98 Self { info }
99 }
100 }
101
102 impl Spill for SpillUniform<'_> {
103 fn spill_file(&self, file: RegFile) -> RegFile {
104 debug_assert!(file.is_uniform());
105 file.to_warp()
106 }
107
108 fn spill(&mut self, dst: SSAValue, src: Src) -> Instr {
109 self.info.num_spills_to_reg += 1;
110 Instr::new(OpCopy {
111 dst: dst.into(),
112 src: src,
113 })
114 }
115
116 fn fill(&mut self, dst: Dst, src: SSAValue) -> Instr {
117 self.info.num_fills_from_reg += 1;
118 Instr::new(OpR2UR {
119 dst: dst,
120 src: src.into(),
121 })
122 }
123 }
124
125 struct SpillPred<'a> {
126 info: &'a mut ShaderInfo,
127 }
128
129 impl<'a> SpillPred<'a> {
130 fn new(info: &'a mut ShaderInfo) -> Self {
131 Self { info }
132 }
133 }
134
135 impl Spill for SpillPred<'_> {
136 fn spill_file(&self, file: RegFile) -> RegFile {
137 match file {
138 RegFile::Pred => RegFile::GPR,
139 RegFile::UPred => RegFile::UGPR,
140 _ => panic!("Unsupported register file"),
141 }
142 }
143
144 fn spill(&mut self, dst: SSAValue, src: Src) -> Instr {
145 assert!(matches!(dst.file(), RegFile::GPR | RegFile::UGPR));
146 self.info.num_spills_to_reg += 1;
147 if let Some(b) = src.as_bool() {
148 let u32_src = Src::from(if b { !0 } else { 0 });
149 Instr::new(OpCopy {
150 dst: dst.into(),
151 src: u32_src,
152 })
153 } else {
154 Instr::new(OpSel {
155 dst: dst.into(),
156 cond: src.bnot(),
157 srcs: [0.into(), (!0).into()],
158 })
159 }
160 }
161
162 fn fill(&mut self, dst: Dst, src: SSAValue) -> Instr {
163 assert!(matches!(src.file(), RegFile::GPR | RegFile::UGPR));
164 self.info.num_fills_from_reg += 1;
165 Instr::new(OpISetP {
166 dst: dst,
167 set_op: PredSetOp::And,
168 cmp_op: IntCmpOp::Ne,
169 cmp_type: IntCmpType::U32,
170 ex: false,
171 srcs: [0.into(), src.into()],
172 accum: true.into(),
173 low_cmp: true.into(),
174 })
175 }
176 }
177
178 struct SpillBar<'a> {
179 info: &'a mut ShaderInfo,
180 }
181
182 impl<'a> SpillBar<'a> {
183 fn new(info: &'a mut ShaderInfo) -> Self {
184 Self { info }
185 }
186 }
187
188 impl Spill for SpillBar<'_> {
189 fn spill_file(&self, file: RegFile) -> RegFile {
190 assert!(file == RegFile::Bar);
191 RegFile::GPR
192 }
193
194 fn spill(&mut self, dst: SSAValue, src: Src) -> Instr {
195 assert!(dst.file() == RegFile::GPR);
196 self.info.num_spills_to_reg += 1;
197 Instr::new(OpBMov {
198 dst: dst.into(),
199 src: src,
200 clear: false,
201 })
202 }
203
204 fn fill(&mut self, dst: Dst, src: SSAValue) -> Instr {
205 assert!(src.file() == RegFile::GPR);
206 self.info.num_fills_from_reg += 1;
207 Instr::new(OpBMov {
208 dst: dst,
209 src: src.into(),
210 clear: false,
211 })
212 }
213 }
214
215 struct SpillGPR<'a> {
216 info: &'a mut ShaderInfo,
217 }
218
219 impl<'a> SpillGPR<'a> {
220 fn new(info: &'a mut ShaderInfo) -> Self {
221 Self { info }
222 }
223 }
224
225 impl Spill for SpillGPR<'_> {
226 fn spill_file(&self, file: RegFile) -> RegFile {
227 assert!(file == RegFile::GPR);
228 RegFile::Mem
229 }
230
231 fn spill(&mut self, dst: SSAValue, src: Src) -> Instr {
232 assert!(dst.file() == RegFile::Mem);
233 self.info.num_spills_to_mem += 1;
234 if let Some(ssa) = src.as_ssa() {
235 assert!(ssa.file() == RegFile::GPR);
236 Instr::new(OpCopy {
237 dst: dst.into(),
238 src: src,
239 })
240 } else {
241 // We use parallel copies for spilling non-GPR things to Mem
242 let mut pcopy = OpParCopy::new();
243 pcopy.push(dst.into(), src);
244 Instr::new(pcopy)
245 }
246 }
247
248 fn fill(&mut self, dst: Dst, src: SSAValue) -> Instr {
249 assert!(src.file() == RegFile::Mem);
250 self.info.num_fills_from_mem += 1;
251 Instr::new(OpCopy {
252 dst: dst,
253 src: src.into(),
254 })
255 }
256 }
257
258 #[derive(Eq, PartialEq)]
259 struct SSANextUse {
260 ssa: SSAValue,
261 next_use: usize,
262 }
263
264 impl SSANextUse {
265 fn new(ssa: SSAValue, next_use: usize) -> SSANextUse {
266 SSANextUse {
267 ssa: ssa,
268 next_use: next_use,
269 }
270 }
271 }
272
273 impl Ord for SSANextUse {
274 fn cmp(&self, other: &Self) -> Ordering {
275 self.next_use
276 .cmp(&other.next_use)
277 .then_with(|| self.ssa.idx().cmp(&other.ssa.idx()))
278 }
279 }
280
281 impl PartialOrd for SSANextUse {
282 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
283 Some(self.cmp(other))
284 }
285 }
286
287 struct SpillCache<'a, S: Spill> {
288 alloc: &'a mut SSAValueAllocator,
289 spill: S,
290 const_tracker: ConstTracker,
291 val_spill: FxHashMap<SSAValue, SSAValue>,
292 }
293
294 impl<'a, S: Spill> SpillCache<'a, S> {
295 fn new(alloc: &'a mut SSAValueAllocator, spill: S) -> SpillCache<'a, S> {
296 SpillCache {
297 alloc: alloc,
298 spill: spill,
299 const_tracker: ConstTracker::new(),
300 val_spill: Default::default(),
301 }
302 }
303
304 fn add_copy_if_const(&mut self, op: &OpCopy) {
305 self.const_tracker.add_copy(op);
306 }
307
308 fn is_const(&self, ssa: &SSAValue) -> bool {
309 self.const_tracker.contains(ssa)
310 }
311
312 fn spill_file(&self, file: RegFile) -> RegFile {
313 self.spill.spill_file(file)
314 }
315
316 fn get_spill(&mut self, ssa: SSAValue) -> SSAValue {
317 *self.val_spill.entry(ssa).or_insert_with(|| {
318 self.alloc.alloc(self.spill.spill_file(ssa.file()))
319 })
320 }
321
322 fn spill_src(&mut self, ssa: SSAValue, src: Src) -> Instr {
323 let dst = self.get_spill(ssa);
324 self.spill.spill(dst, src)
325 }
326
327 fn spill(&mut self, ssa: SSAValue) -> Instr {
328 if let Some(c) = self.const_tracker.get(&ssa) {
329 self.spill_src(ssa, c.clone().into())
330 } else {
331 self.spill_src(ssa, ssa.into())
332 }
333 }
334
335 fn fill_dst(&mut self, dst: Dst, ssa: SSAValue) -> Instr {
336 let src = self.get_spill(ssa);
337 self.spill.fill(dst, src)
338 }
339
340 fn fill(&mut self, ssa: SSAValue) -> Instr {
341 if let Some(c) = self.const_tracker.get(&ssa) {
342 Instr::new(OpCopy {
343 dst: ssa.into(),
344 src: c.clone().into(),
345 })
346 } else {
347 self.fill_dst(ssa.into(), ssa)
348 }
349 }
350 }
351
352 struct SpillChooser<'a> {
353 bl: &'a NextUseBlockLiveness,
354 pinned: &'a FxHashSet<SSAValue>,
355 ip: usize,
356 count: usize,
357 spills: BinaryHeap<Reverse<SSANextUse>>,
358 min_next_use: usize,
359 }
360
361 struct SpillChoiceIter {
362 spills: BinaryHeap<Reverse<SSANextUse>>,
363 }
364
365 impl<'a> SpillChooser<'a> {
366 pub fn new(
367 bl: &'a NextUseBlockLiveness,
368 pinned: &'a FxHashSet<SSAValue>,
369 ip: usize,
370 count: usize,
371 ) -> Self {
372 Self {
373 bl: bl,
374 pinned: pinned,
375 ip: ip,
376 count: count,
377 spills: BinaryHeap::new(),
378 min_next_use: ip + 1,
379 }
380 }
381
382 pub fn add_candidate(&mut self, ssa: SSAValue) {
383 // Don't spill anything that's pinned
384 if self.pinned.contains(&ssa) {
385 return;
386 }
387
388 // Ignore anything used sonner than spill options we've already
389 // rejected.
390 let next_use = self.bl.next_use_after_or_at_ip(&ssa, self.ip).unwrap();
391 if next_use < self.min_next_use {
392 return;
393 }
394
395 self.spills.push(Reverse(SSANextUse::new(ssa, next_use)));
396
397 if self.spills.len() > self.count {
398 // Because we reversed the heap, pop actually removes the
399 // one with the lowest next_use which is what we want here.
400 let old = self.spills.pop().unwrap();
401 debug_assert!(self.spills.len() == self.count);
402 self.min_next_use = max(self.min_next_use, old.0.next_use);
403 }
404 }
405 }
406
407 impl IntoIterator for SpillChooser<'_> {
408 type Item = SSAValue;
409 type IntoIter = SpillChoiceIter;
410
411 fn into_iter(self) -> SpillChoiceIter {
412 SpillChoiceIter {
413 spills: self.spills,
414 }
415 }
416 }
417
418 impl Iterator for SpillChoiceIter {
419 type Item = SSAValue;
420
421 fn size_hint(&self) -> (usize, Option<usize>) {
422 let len = self.spills.len();
423 (len, Some(len))
424 }
425
426 fn next(&mut self) -> Option<SSAValue> {
427 self.spills.pop().map(|x| x.0.ssa)
428 }
429 }
430
431 #[derive(Clone)]
432 struct SSAState {
433 // The set of variables which currently exist in registers
434 w: LiveSet,
435 // The set of variables which have already been spilled. These don't need
436 // to be spilled again.
437 s: FxHashSet<SSAValue>,
438 // The set of pinned variables
439 p: FxHashSet<SSAValue>,
440 }
441
442 fn spill_values<S: Spill>(
443 func: &mut Function,
444 file: RegFile,
445 limit: u32,
446 spill: S,
447 ) {
448 let files = RegFileSet::from_iter([file]);
449 let live = NextUseLiveness::for_function(func, &files);
450 let blocks = &mut func.blocks;
451
452 // Record the set of SSA values used within each loop
453 let mut phi_dst_maps = Vec::new();
454 let mut phi_src_maps = Vec::new();
455 let mut loop_uses = FxHashMap::default();
456 for b_idx in 0..blocks.len() {
457 phi_dst_maps.push(PhiDstMap::from_block(&blocks[b_idx]));
458 phi_src_maps.push(PhiSrcMap::from_block(&blocks[b_idx]));
459
460 if let Some(lh_idx) = blocks.loop_header_index(b_idx) {
461 let uses = loop_uses
462 .entry(lh_idx)
463 .or_insert_with(|| RefCell::new(Default::default()));
464 let uses: &mut FxHashSet<_> = uses.get_mut();
465
466 for instr in &blocks[b_idx].instrs {
467 instr.for_each_ssa_use(|ssa| {
468 if ssa.file() == file {
469 uses.insert(*ssa);
470 }
471 });
472 }
473 }
474 }
475
476 if !loop_uses.is_empty() {
477 // The previous loop only added values to the uses set for the
478 // inner-most loop. Propagate from inner loops to outer loops.
479 for b_idx in (0..blocks.len()).rev() {
480 let Some(uses) = loop_uses.get(&b_idx) else {
481 continue;
482 };
483 let uses = uses.borrow();
484
485 let Some(dom) = blocks.dom_parent_index(b_idx) else {
486 continue;
487 };
488
489 let Some(dom_lh_idx) = blocks.loop_header_index(dom) else {
490 continue;
491 };
492
493 let mut parent_uses =
494 loop_uses.get(&dom_lh_idx).unwrap().borrow_mut();
495 for ssa in uses.iter() {
496 parent_uses.insert(*ssa);
497 }
498 }
499 }
500
501 let mut spill = SpillCache::new(&mut func.ssa_alloc, spill);
502 let mut spilled_phis: BitSet<Phi> = BitSet::new();
503
504 let mut ssa_state_in: Vec<SSAState> = Vec::new();
505 let mut ssa_state_out: Vec<SSAState> = Vec::new();
506
507 for b_idx in 0..blocks.len() {
508 let bl = live.block_live(b_idx);
509
510 let preds = blocks.pred_indices(b_idx).to_vec();
511 let w = if preds.is_empty() {
512 // This is the start block so we start with nothing in
513 // registers.
514 LiveSet::new()
515 } else if preds.len() == 1 {
516 // If we only have one predecessor then it can't possibly be a
517 // loop header and we can just copy the predecessor's w.
518 assert!(!blocks.is_loop_header(b_idx));
519 assert!(preds[0] < b_idx);
520 let p_w = &ssa_state_out[preds[0]].w;
521 LiveSet::from_iter(
522 p_w.iter().filter(|ssa| bl.is_live_in(ssa)).cloned(),
523 )
524 } else if !blocks[b_idx].uniform && file.is_uniform() {
525 // If this is a non-uniform block, then we can't spill or fill any
526 // uniform registers. The good news is that none of our non-uniform
527 // predecessors could spill, either, so we know that everything that
528 // was resident coming in will fit in the register file.
529 let mut w = LiveSet::new();
530 for p_idx in &preds {
531 if *p_idx < b_idx {
532 let p_w = &ssa_state_out[*p_idx].w;
533 w.extend(
534 p_w.iter().filter(|ssa| bl.is_live_in(ssa)).cloned(),
535 );
536 }
537 }
538 debug_assert!(w.count(file) <= limit);
539 w
540 } else if blocks.is_loop_header(b_idx) {
541 let mut i_b: FxHashSet<SSAValue> =
542 FxHashSet::from_iter(bl.iter_live_in().cloned());
543
544 if let Some(phi) = blocks[b_idx].phi_dsts() {
545 for (_, dst) in phi.dsts.iter() {
546 if let Dst::SSA(vec) = dst {
547 assert!(vec.comps() == 1);
548 let ssa = vec[0];
549 if ssa.file() == file {
550 i_b.insert(ssa);
551 }
552 }
553 }
554 }
555
556 let lu = loop_uses.get(&b_idx).unwrap().borrow();
557 let mut w = LiveSet::new();
558
559 let mut some = BinaryHeap::new();
560 for ssa in i_b.iter() {
561 if lu.contains(ssa) {
562 let next_use = bl.first_use(ssa).unwrap();
563 some.push(Reverse(SSANextUse::new(*ssa, next_use)));
564 }
565 }
566 while w.count(file) < limit {
567 let Some(entry) = some.pop() else {
568 break;
569 };
570 w.insert(entry.0.ssa);
571 }
572
573 // If we still have room, consider values which aren't used
574 // inside the loop.
575 if w.count(file) < limit {
576 for ssa in i_b.iter() {
577 debug_assert!(ssa.file() == file);
578 if !lu.contains(ssa) {
579 let next_use = bl.first_use(ssa).unwrap();
580 some.push(Reverse(SSANextUse::new(*ssa, next_use)));
581 }
582 }
583
584 while w.count(file) < limit {
585 let Some(entry) = some.pop() else {
586 break;
587 };
588 w.insert(entry.0.ssa);
589 }
590 }
591
592 w
593 } else {
594 let phi_dst_map = &phi_dst_maps[b_idx];
595
596 struct SSAPredInfo {
597 num_preds: usize,
598 next_use: usize,
599 }
600 let mut live: FxHashMap<SSAValue, SSAPredInfo> = Default::default();
601
602 for p_idx in &preds {
603 let phi_src_map = &phi_src_maps[*p_idx];
604
605 for mut ssa in ssa_state_out[*p_idx].w.iter().cloned() {
606 if let Some(phi) = phi_src_map.get_phi(&ssa) {
607 ssa = *phi_dst_map.get_dst_ssa(phi).unwrap();
608 }
609
610 if let Some(next_use) = bl.first_use(&ssa) {
611 live.entry(ssa)
612 .and_modify(|e| e.num_preds += 1)
613 .or_insert_with(|| SSAPredInfo {
614 num_preds: 1,
615 next_use: next_use,
616 });
617 }
618 }
619 }
620
621 let mut w = LiveSet::new();
622 let mut some = BinaryHeap::new();
623
624 for (ssa, info) in live.drain() {
625 if info.num_preds == preds.len() {
626 // This one is in all the input sets
627 w.insert(ssa);
628 } else {
629 some.push(Reverse(SSANextUse::new(ssa, info.next_use)));
630 }
631 }
632 while w.count(file) < limit {
633 let Some(entry) = some.pop() else {
634 break;
635 };
636 let ssa = entry.0.ssa;
637 assert!(ssa.file() == file);
638 w.insert(ssa);
639 }
640
641 w
642 };
643
644 let s = if preds.is_empty() {
645 Default::default()
646 } else if preds.len() == 1 {
647 let p_s = &ssa_state_out[preds[0]].s;
648 FxHashSet::from_iter(
649 p_s.iter().filter(|ssa| bl.is_live_in(ssa)).cloned(),
650 )
651 } else {
652 let mut s: FxHashSet<_> = Default::default();
653 for p_idx in &preds {
654 if *p_idx >= b_idx {
655 continue;
656 }
657
658 // We diverge a bit from Braun and Hack here. They assume that
659 // S is is a subset of W which is clearly bogus. Instead, we
660 // take the union of all forward edge predecessor S_out and
661 // intersect with live-in for the current block.
662 for ssa in ssa_state_out[*p_idx].s.iter() {
663 if bl.is_live_in(ssa) {
664 s.insert(*ssa);
665 }
666 }
667 }
668
669 // The loop header heuristic sometimes drops stuff from W that has
670 // never been spilled so we need to make sure everything live-in
671 // which isn't in W is included in the spill set so that it gets
672 // properly spilled when we spill across CF edges.
673 if blocks.is_loop_header(b_idx) {
674 for ssa in bl.iter_live_in() {
675 if !w.contains(ssa) {
676 s.insert(*ssa);
677 }
678 }
679 }
680
681 s
682 };
683
684 let mut p: FxHashSet<_> = Default::default();
685 for p_idx in &preds {
686 if *p_idx < b_idx {
687 let p_p = &ssa_state_out[*p_idx].p;
688 p.extend(p_p.iter().filter(|ssa| bl.is_live_in(ssa)).cloned());
689 }
690 }
691
692 for ssa in bl.iter_live_in() {
693 debug_assert!(
694 w.contains(ssa) || s.contains(ssa) || spill.is_const(ssa)
695 );
696 }
697
698 let mut b = SSAState { w: w, s: s, p: p };
699
700 assert!(ssa_state_in.len() == b_idx);
701 ssa_state_in.push(b.clone());
702
703 let bb = &mut blocks[b_idx];
704
705 let mut instrs = Vec::new();
706 for (ip, mut instr) in bb.instrs.drain(..).enumerate() {
707 if let Op::Copy(op) = &instr.op {
708 spill.add_copy_if_const(op);
709 }
710
711 match &mut instr.op {
712 Op::PhiDsts(op) => {
713 // For phis, anything that is not in W needs to be spilled
714 // by setting the destination to some spill value.
715 for (phi, dst) in op.dsts.iter_mut() {
716 let vec = dst.as_ssa().unwrap();
717 debug_assert!(vec.comps() == 1);
718 let ssa = &vec[0];
719
720 if ssa.file() == file && !b.w.contains(ssa) {
721 spilled_phis.insert(*phi);
722 b.s.insert(*ssa);
723 *dst = spill.get_spill(*ssa).into();
724 }
725 }
726 }
727 Op::PhiSrcs(_) => {
728 // We handle phi sources later. For now, leave them be.
729 }
730 Op::ParCopy(pcopy) => {
731 let mut num_w_dsts = 0_u32;
732 for (dst, src) in pcopy.dsts_srcs.iter_mut() {
733 let dst_vec = dst.as_ssa().unwrap();
734 debug_assert!(dst_vec.comps() == 1);
735 let dst_ssa = &dst_vec[0];
736
737 debug_assert!(src.is_unmodified());
738 let Some(src_vec) = src.src_ref.as_ssa() else {
739 continue;
740 };
741 debug_assert!(src_vec.comps() == 1);
742 let src_ssa = &src_vec[0];
743
744 debug_assert!(dst_ssa.file() == src_ssa.file());
745 if src_ssa.file() != file {
746 continue;
747 }
748
749 // If it's not resident, rewrite to just move from one
750 // spill to another, assuming that copying in spill
751 // space is efficient
752 if b.w.contains(src_ssa) {
753 num_w_dsts += 1;
754 } else {
755 if b.s.insert(*src_ssa) {
756 assert!(spill.is_const(src_ssa));
757 instrs.push(spill.spill(*src_ssa));
758 }
759 b.s.insert(*dst_ssa);
760 *src = spill.get_spill(*src_ssa).into();
761 *dst = spill.get_spill(*dst_ssa).into();
762 }
763 }
764
765 // We can now assume that a source is in W if and only if
766 // the file matches. Remove all killed sources from W.
767 for (_, src) in pcopy.dsts_srcs.iter() {
768 let Some(src_vec) = src.src_ref.as_ssa() else {
769 continue;
770 };
771 let src_ssa = &src_vec[0];
772 if !bl.is_live_after_ip(src_ssa, ip) {
773 b.w.remove(src_ssa);
774 }
775 }
776
777 let rel_limit = limit - b.w.count(file);
778 if num_w_dsts > rel_limit {
779 // We can't spill uniform registers in a non-uniform
780 // block
781 assert!(bb.uniform || !file.is_uniform());
782
783 let count = num_w_dsts - rel_limit;
784 let count = count.try_into().unwrap();
785
786 let mut spills = SpillChooser::new(bl, &b.p, ip, count);
787 for (dst, _) in pcopy.dsts_srcs.iter() {
788 let dst_ssa = &dst.as_ssa().unwrap()[0];
789 if dst_ssa.file() == file {
790 spills.add_candidate(*dst_ssa);
791 }
792 }
793
794 let spills: FxHashSet<SSAValue> =
795 FxHashSet::from_iter(spills);
796
797 for (dst, src) in pcopy.dsts_srcs.iter_mut() {
798 let dst_ssa = &dst.as_ssa().unwrap()[0];
799 let src_ssa = &src.src_ref.as_ssa().unwrap()[0];
800 if spills.contains(dst_ssa) {
801 if b.s.insert(*src_ssa) {
802 if DEBUG.annotate() {
803 instrs.push(Instr::new(OpAnnotate {
804 annotation:
805 "generated by spill_values"
806 .into(),
807 }));
808 }
809 instrs.push(spill.spill(*src_ssa));
810 }
811 b.s.insert(*dst_ssa);
812 *src = spill.get_spill(*src_ssa).into();
813 *dst = spill.get_spill(*dst_ssa).into();
814 }
815 }
816 }
817
818 for (dst, _) in pcopy.dsts_srcs.iter() {
819 let dst_ssa = &dst.as_ssa().unwrap()[0];
820 if dst_ssa.file() == file {
821 b.w.insert(*dst_ssa);
822 }
823 }
824 }
825 _ => {
826 if file == RegFile::UGPR && !bb.uniform {
827 // We can't spill UGPRs in a non-uniform block.
828 // Instead, we depend on two facts:
829 //
830 // 1. Uniform instructions are not allowed in
831 // non-uniform blocks
832 //
833 // 2. Non-uniform instructions can always accept a wave
834 // register in leu of a uniform register
835 //
836 debug_assert!(spill.spill_file(file) == RegFile::GPR);
837 instr.for_each_ssa_use_mut(|ssa| {
838 if ssa.file() == file && !b.w.contains(ssa) {
839 if b.s.insert(*ssa) {
840 assert!(spill.is_const(ssa));
841 instrs.push(spill.spill(*ssa));
842 }
843 *ssa = spill.get_spill(*ssa);
844 }
845 });
846 } else if file == RegFile::UPred && !bb.uniform {
847 // We can't spill UPreds in a non-uniform block.
848 // Instead, we depend on two facts:
849 //
850 // 1. Uniform instructions are not allowed in
851 // non-uniform blocks
852 //
853 // 2. Non-uniform instructions can always accept a wave
854 // register in leu of a uniform register
855 //
856 // 3. We can un-spill from a UGPR directly to a Pred
857 //
858 // This also shouldn't come up that often in practice
859 // so it's okay to un-spill every time on the spot.
860 //
861 instr.for_each_ssa_use_mut(|ssa| {
862 if ssa.file() == file && !b.w.contains(ssa) {
863 if DEBUG.annotate() {
864 instrs.push(Instr::new(OpAnnotate {
865 annotation: "generated by spill_values"
866 .into(),
867 }));
868 }
869 let tmp = spill.alloc.alloc(RegFile::Pred);
870 instrs.push(spill.fill_dst(tmp.into(), *ssa));
871 *ssa = tmp;
872 }
873 });
874 } else {
875 // First compute fills even though those have to come
876 // after spills.
877 let mut fills = Vec::new();
878 instr.for_each_ssa_use(|ssa| {
879 if ssa.file() == file && !b.w.contains(ssa) {
880 debug_assert!(
881 b.s.contains(ssa) || spill.is_const(ssa)
882 );
883 debug_assert!(bb.uniform || !ssa.is_uniform());
884 fills.push(spill.fill(*ssa));
885 b.w.insert(*ssa);
886 }
887 });
888
889 let rel_pressure =
890 bl.get_instr_pressure(ip, &instr)[file];
891 let abs_pressure =
892 b.w.count(file) + u32::from(rel_pressure);
893
894 if abs_pressure > limit {
895 let count = abs_pressure - limit;
896 let count = count.try_into().unwrap();
897
898 let mut spills =
899 SpillChooser::new(bl, &b.p, ip, count);
900 for ssa in b.w.iter() {
901 spills.add_candidate(*ssa);
902 }
903
904 for ssa in spills {
905 debug_assert!(ssa.file() == file);
906 b.w.remove(&ssa);
907 if !spill.is_const(&ssa) {
908 if DEBUG.annotate() {
909 instrs.push(Instr::new(OpAnnotate {
910 annotation:
911 "generated by spill_values"
912 .into(),
913 }));
914 }
915 instrs.push(spill.spill(ssa));
916 b.s.insert(ssa);
917 }
918 }
919 }
920
921 if DEBUG.annotate() {
922 instrs.push(Instr::new(OpAnnotate {
923 annotation: "generated by spill_values".into(),
924 }));
925 }
926 instrs.append(&mut fills);
927
928 instr.for_each_ssa_use(|ssa| {
929 if ssa.file() == file {
930 debug_assert!(b.w.contains(ssa));
931 }
932 });
933
934 b.w.insert_instr_top_down(ip, &instr, bl);
935 }
936 }
937 }
938
939 // OpPin takes the normal spilling path but we want to also mark any
940 // of its destination SSA values as pinned.
941 if matches!(&instr.op, Op::Pin(_)) {
942 instr.for_each_ssa_def(|ssa| {
943 b.p.insert(*ssa);
944 });
945 }
946
947 instrs.push(instr);
948 }
949 bb.instrs = instrs;
950
951 assert!(ssa_state_out.len() == b_idx);
952 ssa_state_out.push(b);
953 }
954
955 // Now that everthing is spilled, we handle phi sources and connect the
956 // blocks by adding spills and fills as needed along edges.
957 for p_idx in 0..blocks.len() {
958 let succ = blocks.succ_indices(p_idx);
959 if succ.len() != 1 {
960 // We don't have any critical edges
961 for s_idx in succ {
962 debug_assert!(blocks.pred_indices(*s_idx).len() == 1);
963 }
964 continue;
965 }
966 let s_idx = succ[0];
967
968 let pb = &mut blocks[p_idx];
969 let p_out = &ssa_state_out[p_idx];
970 let s_in = &ssa_state_in[s_idx];
971 let phi_dst_map = &phi_dst_maps[s_idx];
972
973 let mut spills = Vec::new();
974 let mut fills = Vec::new();
975
976 if let Some(op) = pb.phi_srcs_mut() {
977 for (phi, src) in op.srcs.iter_mut() {
978 debug_assert!(src.is_unmodified());
979 let vec = src.src_ref.as_ssa().unwrap();
980 debug_assert!(vec.comps() == 1);
981 let ssa = &vec[0];
982
983 if ssa.file() != file {
984 continue;
985 }
986
987 if spilled_phis.contains(*phi) {
988 if !p_out.s.contains(ssa) {
989 spills.push(*ssa);
990 }
991 *src = spill.get_spill(*ssa).into();
992 } else {
993 if !p_out.w.contains(ssa) {
994 fills.push(*ssa);
995 }
996 }
997 }
998 }
999
1000 for ssa in s_in.s.iter() {
1001 if !p_out.s.contains(ssa) {
1002 assert!(p_out.w.contains(ssa) || spill.is_const(ssa));
1003 spills.push(*ssa);
1004 }
1005 }
1006
1007 for ssa in s_in.w.iter() {
1008 if phi_dst_map.get_phi(ssa).is_some() {
1009 continue;
1010 }
1011
1012 if !p_out.w.contains(ssa) {
1013 fills.push(*ssa);
1014 }
1015 }
1016
1017 if spills.is_empty() && fills.is_empty() {
1018 continue;
1019 }
1020
1021 // Sort to ensure stability of the algorithm
1022 spills.sort_by_key(|ssa| ssa.idx());
1023 fills.sort_by_key(|ssa| ssa.idx());
1024
1025 let mut instrs = Vec::new();
1026 for ssa in spills {
1027 instrs.push(spill.spill(ssa));
1028 }
1029 for ssa in fills {
1030 debug_assert!(pb.uniform || !ssa.is_uniform());
1031 instrs.push(spill.fill(ssa));
1032 }
1033
1034 // Insert spills and fills right after the phi (if any)
1035 let ip = pb
1036 .phi_srcs_ip()
1037 .or_else(|| pb.branch_ip())
1038 .unwrap_or(pb.instrs.len());
1039 pb.instrs.splice(ip..ip, instrs.into_iter());
1040 }
1041 }
1042
1043 impl Function {
1044 /// Spill values from @file to fit within @limit registers
1045 ///
1046 /// This pass assumes that the function is already in CSSA form. See
1047 /// @to_cssa for more details.
1048 ///
1049 /// The algorithm implemented here is roughly based on "Register Spilling
1050 /// and Live-Range Splitting for SSA-Form Programs" by Braun and Hack. The
1051 /// primary contributions of the Braun and Hack paper are the global
1052 /// next-use distances which are implemented by @NextUseLiveness and a
1053 /// heuristic for computing spill sets at block boundaries. The paper
1054 /// describes two sets:
1055 ///
1056 /// - W, the set of variables currently resident
1057 ///
1058 /// - S, the set of variables which have been spilled
1059 ///
1060 /// These sets are tracked as we walk instructions and \[un\]spill values to
1061 /// satisfy the given limit. When spills are required we spill the value
1062 /// with the nighest next-use IP. At block boundaries, Braun and Hack
1063 /// describe a heuristic for determining the starting W and S sets based on
1064 /// the W and S from the end of each of the forward edge predecessor blocks.
1065 ///
1066 /// What Braun and Hack do not describe is how to handle phis and parallel
1067 /// copies. Because we assume the function is already in CSSA form, we can
1068 /// use a fairly simple algorithm. On the first pass, we ignore phi sources
1069 /// and assign phi destinations based on W at the start of the block. If
1070 /// the phi destination is in W, we leave it alone. If it is not in W, then
1071 /// we allocate a new spill value and assign it to the phi destination. In
1072 /// a second pass, we handle phi sources based on the destination. If the
1073 /// destination is in W, we leave it alone. If the destination is spilled,
1074 /// we read from the spill value corresponding to the source, spilling first
1075 /// if needed. In the second pass, we also handle spilling across blocks as
1076 /// needed for values that do not pass through a phi.
1077 ///
1078 /// A special case is also required for parallel copies because they can
1079 /// have an unbounded number of destinations. For any source values not in
1080 /// W, we allocate a spill value for the destination and copy in the spill
1081 /// register file. For any sources which are in W, we try to leave as much
1082 /// in W as possible. However, since source values may not be killed by the
1083 /// copy and because one source value may be copied to arbitrarily many
1084 /// destinations, that is not always possible. Whenever we need to spill
1085 /// values, we spill according to the highest next-use of the destination
1086 /// and we spill the source first and then parallel copy the source into a
1087 /// spilled destination value.
1088 ///
1089 /// This all assumes that it's better to copy in spill space than to unspill
1090 /// just for the sake of a parallel copy. While this may not be true in
1091 /// general, especially not when spilling to memory, the register allocator
1092 /// is good at eliding unnecessary copies.
1093 pub fn spill_values(
1094 &mut self,
1095 file: RegFile,
1096 limit: u32,
1097 info: &mut ShaderInfo,
1098 ) {
1099 match file {
1100 RegFile::GPR => {
1101 let spill = SpillGPR::new(info);
1102 spill_values(self, file, limit, spill);
1103 }
1104 RegFile::UGPR => {
1105 let spill = SpillUniform::new(info);
1106 spill_values(self, file, limit, spill);
1107 }
1108 RegFile::Pred => {
1109 let spill = SpillPred::new(info);
1110 spill_values(self, file, limit, spill);
1111 }
1112 RegFile::UPred => {
1113 let spill = SpillPred::new(info);
1114 spill_values(self, file, limit, spill);
1115 }
1116 RegFile::Bar => {
1117 let spill = SpillBar::new(info);
1118 spill_values(self, file, limit, spill);
1119 }
1120 _ => panic!("Don't know how to spill {} registers", file),
1121 }
1122
1123 self.repair_ssa();
1124 self.opt_dce();
1125
1126 if DEBUG.print() {
1127 eprintln!("NAK IR after spilling {}:\n{}", file, self);
1128 }
1129 }
1130 }