Debian Codegraph @

src/nouveau/compiler/nak/calc_instr_deps.rs

raw
1 // Copyright © 2022 Collabora, Ltd.
2 // SPDX-License-Identifier: MIT
3
4 use crate::api::{GetDebugFlags, DEBUG};
5 use crate::ir::*;
6 use crate::opt_instr_sched_common::estimate_block_weight;
7 use crate::reg_tracker::{RegRefIterable, RegTracker, SparseRegTracker};
8
9 use compiler::dataflow::{BackwardDataflow, ForwardDataflow};
10 use rustc_hash::{FxHashMap, FxHashSet};
11 use std::cmp::max;
12 use std::hash::Hash;
13 use std::ops::Range;
14 use std::slice;
15
16 #[derive(Clone)]
17 enum RegUse<T: Clone> {
18 None,
19 Write(T),
20 Reads(Vec<T>),
21 }
22
23 impl<T: Clone> RegUse<T> {
24 pub fn deps(&self) -> &[T] {
25 match self {
26 RegUse::None => &[],
27 RegUse::Write(dep) => slice::from_ref(dep),
28 RegUse::Reads(deps) => &deps[..],
29 }
30 }
31
32 pub fn clear(&mut self) -> Self {
33 std::mem::replace(self, RegUse::None)
34 }
35
36 pub fn clear_write(&mut self) -> Self {
37 if matches!(self, RegUse::Write(_)) {
38 std::mem::replace(self, RegUse::None)
39 } else {
40 RegUse::None
41 }
42 }
43
44 pub fn add_read(&mut self, dep: T) -> Self {
45 match self {
46 RegUse::None => {
47 *self = RegUse::Reads(vec![dep]);
48 RegUse::None
49 }
50 RegUse::Write(_) => {
51 std::mem::replace(self, RegUse::Reads(vec![dep]))
52 }
53 RegUse::Reads(reads) => {
54 reads.push(dep);
55 RegUse::None
56 }
57 }
58 }
59
60 pub fn set_write(&mut self, dep: T) -> Self {
61 std::mem::replace(self, RegUse::Write(dep))
62 }
63 }
64
65 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
66 enum RegReadWrite {
67 Read,
68 Write,
69 }
70
71 /// Maps each register read/write to a value
72 /// a register can have multiple reads AND multiple writes at the same
73 /// point in time if it comes from a merge.
74 /// For edits inside a CFG block, a RegUseMap will never contain multiple
75 /// writes.
76 ///
77 /// We need to track multiple reads as we don't know which one can cause
78 /// the highest latency for the interfering instruction (in RaW). For the
79 /// same reason we might need to track both reads and writes in the case of
80 /// a CFG block with multiple successors.
81 /// We cannot flush writes after a read operation since we can still
82 /// encounter other, slower reads that could interfere with the write.
83 #[derive(Clone, PartialEq, Eq, Default)]
84 struct RegUseMap<K: Hash + Eq, V> {
85 map: FxHashMap<(RegReadWrite, K), V>,
86 }
87
88 impl<K, V> RegUseMap<K, V>
89 where
90 K: Copy + Default + Hash + Eq,
91 V: Clone,
92 {
93 pub fn add_read(&mut self, k: K, v: V) {
94 self.map.insert((RegReadWrite::Read, k), v);
95 }
96
97 pub fn set_write(&mut self, k: K, v: V) {
98 // Writes wait on all previous Reads and writes
99 self.map.clear();
100 self.map.insert((RegReadWrite::Write, k), v);
101 }
102
103 pub fn iter_reads(&self) -> impl Iterator<Item = (&K, &V)> {
104 self.map
105 .iter()
106 .filter(|(k, _v)| k.0 == RegReadWrite::Read)
107 .map(|(k, v)| (&k.1, v))
108 }
109
110 pub fn iter_writes(&self) -> impl Iterator<Item = (&K, &V)> {
111 self.map
112 .iter()
113 .filter(|(k, _v)| k.0 == RegReadWrite::Write)
114 .map(|(k, v)| (&k.1, v))
115 }
116
117 /// Merge two instances using a custom merger for value conflicts
118 pub fn merge_with(
119 &mut self,
120 other: &Self,
121 mut merger: impl FnMut(&V, &V) -> V,
122 ) {
123 use std::collections::hash_map::Entry;
124 for (k, v) in other.map.iter() {
125 match self.map.entry(*k) {
126 Entry::Vacant(vacant_entry) => {
127 vacant_entry.insert(v.clone());
128 }
129 Entry::Occupied(mut occupied_entry) => {
130 let orig = occupied_entry.get_mut();
131 *orig = merger(orig, v);
132 }
133 }
134 }
135 }
136 }
137
138 struct DepNode {
139 read_dep: Option<usize>,
140 first_wait: Option<(usize, usize)>,
141 }
142
143 struct DepGraph {
144 deps: Vec<DepNode>,
145 instr_deps: FxHashMap<(usize, usize), (usize, usize)>,
146 instr_waits: FxHashMap<(usize, usize), Vec<usize>>,
147 active: FxHashSet<usize>,
148 }
149
150 impl DepGraph {
151 pub fn new() -> Self {
152 Self {
153 deps: Vec::new(),
154 instr_deps: Default::default(),
155 instr_waits: Default::default(),
156 active: Default::default(),
157 }
158 }
159
160 fn add_new_dep(&mut self, read_dep: Option<usize>) -> usize {
161 let dep = self.deps.len();
162 self.deps.push(DepNode {
163 read_dep: read_dep,
164 first_wait: None,
165 });
166 dep
167 }
168
169 pub fn add_instr(&mut self, block_idx: usize, ip: usize) -> (usize, usize) {
170 let rd = self.add_new_dep(None);
171 let wr = self.add_new_dep(Some(rd));
172 self.instr_deps.insert((block_idx, ip), (rd, wr));
173 (rd, wr)
174 }
175
176 pub fn add_signal(&mut self, dep: usize) {
177 self.active.insert(dep);
178 }
179
180 pub fn add_waits(
181 &mut self,
182 block_idx: usize,
183 ip: usize,
184 mut waits: Vec<usize>,
185 ) {
186 for dep in &waits {
187 // A wait on a write automatically waits on the read. By removing
188 // it from the active set here we ensure that we don't record any
189 // duplicate write/read waits in the retain below.
190 if let Some(rd) = &self.deps[*dep].read_dep {
191 self.active.remove(rd);
192 }
193 }
194
195 waits.retain(|dep| {
196 let node = &mut self.deps[*dep];
197 if let Some(wait) = node.first_wait {
198 // Someone has already waited on this dep
199 debug_assert!(!self.active.contains(dep));
200 debug_assert!((block_idx, ip) >= wait);
201 false
202 } else if !self.active.contains(dep) {
203 // Even if it doesn't have a use, it may still be deactivated.
204 // This can happen if we depend the the destination before any
205 // of its sources.
206 false
207 } else {
208 self.deps[*dep].first_wait = Some((block_idx, ip));
209 self.active.remove(dep);
210 true
211 }
212 });
213
214 // Sort for stability. The list of waits may come from a HashSet (see
215 // add_barrier()) and so it's not guaranteed stable across Rust
216 // versions. This also ensures that everything always waits on oldest
217 // dependencies first.
218 waits.sort();
219
220 let _old = self.instr_waits.insert((block_idx, ip), waits);
221 debug_assert!(_old.is_none());
222 }
223
224 pub fn add_barrier(&mut self, block_idx: usize, ip: usize) {
225 let waits = self.active.iter().cloned().collect();
226 self.add_waits(block_idx, ip, waits);
227 debug_assert!(self.active.is_empty());
228 }
229
230 pub fn dep_is_waited_after(
231 &self,
232 dep: usize,
233 block_idx: usize,
234 ip: usize,
235 ) -> bool {
236 if let Some(wait) = self.deps[dep].first_wait {
237 wait > (block_idx, ip)
238 } else {
239 false
240 }
241 }
242
243 pub fn get_instr_deps(
244 &self,
245 block_idx: usize,
246 ip: usize,
247 ) -> (usize, usize) {
248 *self.instr_deps.get(&(block_idx, ip)).unwrap()
249 }
250
251 pub fn get_instr_waits(&self, block_idx: usize, ip: usize) -> &[usize] {
252 if let Some(waits) = self.instr_waits.get(&(block_idx, ip)) {
253 &waits[..]
254 } else {
255 &[]
256 }
257 }
258 }
259
260 struct BarAlloc {
261 num_bars: u8,
262 bar_dep: [usize; 6],
263 }
264
265 impl BarAlloc {
266 pub fn new() -> BarAlloc {
267 BarAlloc {
268 num_bars: 6,
269 bar_dep: [usize::MAX; 6],
270 }
271 }
272
273 pub fn bar_is_free(&self, bar: u8) -> bool {
274 debug_assert!(bar < self.num_bars);
275 self.bar_dep[usize::from(bar)] == usize::MAX
276 }
277
278 pub fn set_bar_dep(&mut self, bar: u8, dep: usize) {
279 debug_assert!(self.bar_is_free(bar));
280 self.bar_dep[usize::from(bar)] = dep;
281 }
282
283 pub fn free_bar(&mut self, bar: u8) {
284 debug_assert!(!self.bar_is_free(bar));
285 self.bar_dep[usize::from(bar)] = usize::MAX;
286 }
287
288 pub fn try_find_free_bar(&self) -> Option<u8> {
289 (0..self.num_bars).find(|&bar| self.bar_is_free(bar))
290 }
291
292 pub fn free_some_bar(&mut self) -> u8 {
293 // Get the oldest by looking for the one with the smallest dep
294 let mut bar = 0;
295 for b in 1..self.num_bars {
296 if self.bar_dep[usize::from(b)] < self.bar_dep[usize::from(bar)] {
297 bar = b;
298 }
299 }
300 self.free_bar(bar);
301 bar
302 }
303
304 pub fn get_bar_for_dep(&self, dep: usize) -> Option<u8> {
305 (0..self.num_bars).find(|&bar| self.bar_dep[usize::from(bar)] == dep)
306 }
307 }
308
309 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
310 struct TexQueueSimulationEntry {
311 min_pos: u8,
312 }
313
314 impl TexQueueSimulationEntry {
315 const INVALID: Self = TexQueueSimulationEntry { min_pos: u8::MAX };
316
317 // First element on the queue
318 const FIRST: Self = TexQueueSimulationEntry { min_pos: 0 };
319
320 fn is_valid(&self) -> bool {
321 if *self == Self::INVALID {
322 false
323 } else {
324 debug_assert!(self.min_pos <= OpTexDepBar::MAX_TEXTURES_LEFT);
325 true
326 }
327 }
328
329 fn push(&mut self) {
330 if self.is_valid() {
331 self.min_pos += 1;
332 }
333 }
334
335 fn flush_after(&mut self, pos: u8) -> bool {
336 if self.min_pos < pos {
337 true
338 } else {
339 // This entry is either invalid or higher than the cull level
340 *self = Self::INVALID;
341 false
342 }
343 }
344
345 fn merge(&mut self, other: &Self) {
346 self.min_pos = self.min_pos.min(other.min_pos);
347 }
348 }
349
350 /// Simulate the state of a register in the queue, in buckets of 4
351 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
352 struct TexQueueSimulationBucket {
353 entries: [TexQueueSimulationEntry; 4],
354 }
355
356 impl TexQueueSimulationBucket {
357 const EMPTY: Self = TexQueueSimulationBucket {
358 entries: [TexQueueSimulationEntry::INVALID; 4],
359 };
360
361 fn min_queue_position(&self, range: Range<usize>) -> Option<u8> {
362 self.entries[range]
363 .iter()
364 .filter(|x| x.is_valid())
365 .map(|x| x.min_pos)
366 .min()
367 }
368
369 fn set_as_first(&mut self, range: Range<usize>) {
370 for i in range {
371 debug_assert!(!self.entries[i].is_valid());
372 self.entries[i] = TexQueueSimulationEntry::FIRST;
373 }
374 }
375
376 fn push(&mut self) {
377 for entry in &mut self.entries {
378 entry.push();
379 }
380 }
381
382 fn flush_after(&mut self, pos: u8) -> bool {
383 debug_assert!(pos <= OpTexDepBar::MAX_TEXTURES_LEFT);
384
385 let mut retain = false;
386 for x in &mut self.entries {
387 retain |= x.flush_after(pos);
388 }
389 retain
390 }
391
392 fn merge(&mut self, other: &Self) {
393 for (x, y) in self.entries.iter_mut().zip(other.entries.iter()) {
394 x.merge(y);
395 }
396 }
397 }
398
399 /// This state simulates the texture queue for each destination.
400 ///
401 /// For example, at the start the queue is always empty, but if we encounter a
402 /// tex operation that writes in r4..r8, that is pushed on the queue at
403 /// position 0. If we encounter another tex operation that only writes r5,
404 /// that will be pushed at position 0 and the old tex instruction will be in
405 /// position 1. This data-structure keeps track of the position of the queue
406 /// for each destination register present in the queue, push operations
407 /// correspond to new texture instructions, while flush operations correspond to
408 /// the usage of registers which may still be on the queue.
409 ///
410 /// Since all Kepler texture operations use at most 4 registers, and many
411 /// instruction use more than one destination at a time, we group registers in
412 /// buckets of 4. With this optimization each RegRef only accesses a single
413 /// bucket.
414 #[derive(Debug, Clone, PartialEq, Eq)]
415 pub struct TexQueueSimulationState {
416 /// Min position of the destination register in the queue,
417 /// in buckets of 4 (indexed by register_index / 4).
418 queue_pos: FxHashMap<u8, TexQueueSimulationBucket>,
419 /// Max length of the queue, needed to check for overflows
420 max_queue_len: u8,
421 }
422
423 impl TexQueueSimulationState {
424 pub fn new() -> Self {
425 TexQueueSimulationState {
426 queue_pos: Default::default(),
427 max_queue_len: 0,
428 }
429 }
430
431 /// Translate from RegRef to bucket_index + bucket_range
432 #[inline]
433 fn reg_ref_to_coords(reg: RegRef) -> (u8, Range<usize>) {
434 debug_assert!(reg.base_idx() <= u8::MAX.into());
435 let idx = reg.base_idx() as u8 / 4;
436 let sub = (reg.base_idx() % 4) as usize;
437
438 let range = sub..(sub + reg.comps() as usize);
439 assert!(range.end <= 4);
440 (idx, range)
441 }
442
443 fn min_queue_position(&self, reg: RegRef) -> Option<u8> {
444 let (idx, range) = Self::reg_ref_to_coords(reg);
445
446 self.queue_pos
447 .get(&idx)
448 .and_then(|x| x.min_queue_position(range))
449 }
450
451 fn is_queue_full(&self) -> bool {
452 // MAX_TEXTURES_LEFT describes the maximum number encodable
453 // in the texdepbar, but the queue must have an element more.
454 self.max_queue_len > OpTexDepBar::MAX_TEXTURES_LEFT
455 }
456
457 /// Flush every element whose position >= pos
458 ///
459 /// Effectively simulates the execution of a `texdepbar pos`
460 fn flush_after(&mut self, pos: u8) {
461 self.max_queue_len = self.max_queue_len.min(pos);
462 self.queue_pos.retain(|_, v| v.flush_after(pos));
463 }
464
465 pub fn push(&mut self, reg: RegRef) -> Option<u8> {
466 // Assert we are not on the queue
467 debug_assert!(self.min_queue_position(reg).is_none());
468
469 // Check that the push operation does not overflow the queue,
470 // if it does, we must insert a barrier
471 let mut tex_bar = None;
472 if self.is_queue_full() {
473 // The queue is full, there are 64 in-flight tex-ops.
474 // make space by making removing 1 texture.
475 tex_bar = Some(OpTexDepBar::MAX_TEXTURES_LEFT);
476 self.flush_after(OpTexDepBar::MAX_TEXTURES_LEFT);
477 // Now the queue is not full anymore
478 debug_assert!(!self.is_queue_full());
479 }
480
481 self.max_queue_len += 1;
482 // Every entry is pushed by 1
483 for x in self.queue_pos.values_mut() {
484 x.push();
485 }
486
487 // Put us on the queue as first
488 let (idx, range) = Self::reg_ref_to_coords(reg);
489 self.queue_pos
490 .entry(idx)
491 .or_insert(TexQueueSimulationBucket::EMPTY)
492 .set_as_first(range);
493
494 tex_bar
495 }
496
497 pub fn flush(&mut self, reg: RegRef) -> Option<u8> {
498 let queue_pos = self.min_queue_position(reg);
499
500 let Some(queue_pos) = queue_pos else {
501 return None; // Not in queue
502 };
503
504 // Cut the queue
505 self.flush_after(queue_pos);
506 debug_assert!(self.min_queue_position(reg).is_none());
507
508 Some(queue_pos)
509 }
510
511 pub fn merge(&mut self, other: &Self) {
512 self.max_queue_len = self.max_queue_len.max(other.max_queue_len);
513 for (key, y) in other.queue_pos.iter() {
514 let x = self
515 .queue_pos
516 .entry(*key)
517 .or_insert(TexQueueSimulationBucket::EMPTY);
518 x.merge(y);
519 }
520 }
521
522 /// Simulates the execution of an instruction and returns the
523 /// barrier level needed.
524 pub fn visit_instr(&mut self, instr: &Instr) -> Option<u8> {
525 // Flush register reads and writes
526 // (avoid write-after-write and read-after-write hazards)
527 // Compute the minimum required flush level (for barriers)
528 let flush_level = if !self.queue_pos.is_empty() {
529 let src_refs =
530 instr.srcs().iter().filter_map(|x| x.src_ref.as_reg());
531 let dst_refs = instr.dsts().iter().filter_map(|x| x.as_reg());
532
533 src_refs
534 .chain(dst_refs)
535 .filter_map(|reg_ref| self.flush(*reg_ref))
536 .reduce(|a, b| a.min(b))
537 } else {
538 // The queue is empty, no need to check the instruction
539 None
540 };
541
542 // Push registers (if we are a tex instruction)
543 // We might need to insert a barrier if the queue is full
544 let push_level = if instr_needs_texbar(instr) {
545 let dst = instr.dsts()[0].as_reg().unwrap();
546 self.push(*dst)
547 } else {
548 None
549 };
550
551 // If the flush needs a barrier, the queue will not be full,
552 // therefore the push will not need a barrier.
553 debug_assert!(flush_level.is_none() || push_level.is_none());
554 flush_level.or(push_level)
555 }
556 }
557
558 fn instr_needs_texbar(instr: &Instr) -> bool {
559 matches!(
560 instr.op,
561 Op::Tex(_)
562 | Op::Tld(_)
563 | Op::Tmml(_)
564 | Op::Tld4(_)
565 | Op::Txd(_)
566 | Op::Txq(_)
567 )
568 }
569
570 /// Hardware has a FIFO queue of texture that are still fetching,
571 /// when the oldest tex finishes executing, it's written to the reg,
572 /// removed from the queue and it begins executing the new one.
573 /// The problem arises when a texture is read while it is still being fetched
574 /// to avoid it, we have a `texdepbar {i}` instruction that stalls until
575 /// the texture fetch queue has at most {i} elements.
576 /// e.g. the most simple solution is to have texdepbar 0 after each texture
577 /// instruction, but this would stall the pipeline until the texture fetch
578 /// finishes executing.
579 /// This algorithm inserts `texdepbar` at each use of the texture results,
580 /// simulating the texture queue execution.
581 ///
582 /// Note that the texture queue has for each entry (texture data, register output)
583 /// and each register can be on the queue only once (we don't want to have multiple texture
584 /// operations in-flight that write to the same registers).
585 /// This can lead to a neat algorithm:
586 /// instead of tracking the queue directly, which can exponentially explode in complexity,
587 /// track the position of each register, which needs at most 255/63 positions.
588 /// For branches the state is duplicated in each basic block,
589 /// for joins instead we want to keep both the minimum position of each
590 /// entry and the maximum length og the queue to avoid overflows.
591 ///
592 /// TODO: IF this pass is too slow, there are still optimizations left:
593 /// - Our data-flow computes barrier levels and discards them,
594 /// but since most CFG blocks do not need recomputation, we could save
595 /// the barrier levels in a vec and save a pass later.
596 /// - Instead of pushing by 1 each element in the queue on a `push` op,
597 /// we could keep track of an in-flight range and use a wrapping timestamp
598 /// this improves performance but needs careful implementation to avoid bugs
599 fn insert_texture_barriers(f: &mut Function, sm: &ShaderModelInfo) {
600 assert!(sm.is_kepler()); // Only kepler has texture barriers!
601
602 let mut state_in: Vec<_> = (0..f.blocks.len())
603 .map(|_| TexQueueSimulationState::new())
604 .collect();
605 let mut state_out: Vec<_> = (0..f.blocks.len())
606 .map(|_| TexQueueSimulationState::new())
607 .collect();
608 ForwardDataflow {
609 cfg: &f.blocks,
610 block_in: &mut state_in[..],
611 block_out: &mut state_out[..],
612 transfer: |_block_idx, block, sim_out, sim_in| {
613 let mut sim = sim_in.clone();
614
615 for instr in block.instrs.iter() {
616 // Ignore the barrier, we will recompute this later
617 let _bar = sim.visit_instr(instr);
618 }
619
620 if *sim_out == sim {
621 false
622 } else {
623 *sim_out = sim;
624 true
625 }
626 },
627 join: |sim_in, pred_sim_out| {
628 sim_in.merge(pred_sim_out);
629 },
630 }
631 .solve();
632
633 for (block, mut sim) in f.blocks.iter_mut().zip(state_in.into_iter()) {
634 block.map_instrs(|instr| {
635 if let Some(textures_left) = sim.visit_instr(&instr) {
636 let bar = Instr::new(OpTexDepBar { textures_left });
637 MappedInstrs::Many(vec![bar, instr])
638 } else {
639 MappedInstrs::One(instr)
640 }
641 });
642 }
643 }
644
645 fn assign_barriers(f: &mut Function, sm: &ShaderModelInfo) {
646 let mut uses = Box::new(RegTracker::new_with(&|| RegUse::None));
647 let mut deps = DepGraph::new();
648
649 for (bi, b) in f.blocks.iter().enumerate() {
650 for (ip, instr) in b.instrs.iter().enumerate() {
651 if instr.is_branch() {
652 deps.add_barrier(bi, ip);
653 } else {
654 // Execution predicates are handled immediately and we don't
655 // need barriers for them, regardless of whether or not it's a
656 // fixed-latency instruction.
657 let mut waits = Vec::new();
658 uses.for_each_instr_pred_mut(instr, |u| {
659 let u = u.clear_write();
660 waits.extend_from_slice(u.deps());
661 });
662
663 if sm.op_needs_scoreboard(&instr.op) {
664 let (rd, wr) = deps.add_instr(bi, ip);
665 uses.for_each_instr_src_mut(instr, |_, u| {
666 // Only mark a dep as signaled if we actually have
667 // something that shows up in the register file as
668 // needing scoreboarding
669 deps.add_signal(rd);
670 let u = u.add_read(rd);
671 waits.extend_from_slice(u.deps());
672 });
673 uses.for_each_instr_dst_mut(instr, |_, u| {
674 // Only mark a dep as signaled if we actually have
675 // something that shows up in the register file as
676 // needing scoreboarding
677 deps.add_signal(wr);
678 let u = u.set_write(wr);
679 for dep in u.deps() {
680 // Don't wait on ourselves
681 if *dep != rd {
682 waits.push(*dep);
683 }
684 }
685 });
686 } else {
687 // Delays will cover us here. We just need to make sure
688 // that we wait on any uses that we consume.
689 uses.for_each_instr_src_mut(instr, |_, u| {
690 let u = u.clear_write();
691 waits.extend_from_slice(u.deps());
692 });
693 uses.for_each_instr_dst_mut(instr, |_, u| {
694 let u = u.clear();
695 waits.extend_from_slice(u.deps());
696 });
697 }
698 deps.add_waits(bi, ip, waits);
699 }
700 }
701 }
702
703 let mut bars = BarAlloc::new();
704
705 for (bi, b) in f.blocks.iter_mut().enumerate() {
706 for (ip, instr) in b.instrs.iter_mut().enumerate() {
707 let mut wait_mask = 0_u8;
708 for dep in deps.get_instr_waits(bi, ip) {
709 if let Some(bar) = bars.get_bar_for_dep(*dep) {
710 wait_mask |= 1 << bar;
711 bars.free_bar(bar);
712 }
713 }
714 instr.deps.add_wt_bar_mask(wait_mask);
715
716 if instr.needs_yield() {
717 instr.deps.set_yield(true);
718 }
719
720 if !sm.op_needs_scoreboard(&instr.op) {
721 continue;
722 }
723
724 let (rd_dep, wr_dep) = deps.get_instr_deps(bi, ip);
725 if deps.dep_is_waited_after(rd_dep, bi, ip) {
726 let rd_bar = bars.try_find_free_bar().unwrap_or_else(|| {
727 let bar = bars.free_some_bar();
728 instr.deps.add_wt_bar(bar);
729 bar
730 });
731 bars.set_bar_dep(rd_bar, rd_dep);
732 instr.deps.set_rd_bar(rd_bar);
733 }
734 if deps.dep_is_waited_after(wr_dep, bi, ip) {
735 let wr_bar = bars.try_find_free_bar().unwrap_or_else(|| {
736 let bar = bars.free_some_bar();
737 instr.deps.add_wt_bar(bar);
738 bar
739 });
740 bars.set_bar_dep(wr_bar, wr_dep);
741 instr.deps.set_wr_bar(wr_bar);
742 }
743 }
744 }
745 }
746
747 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
748 struct RegOrigin {
749 loc: InstrIdx,
750 // Index of the src (for reads) or dst (for writes) in the instruction.
751 src_dst_idx: u16,
752 }
753
754 impl Default for RegOrigin {
755 fn default() -> Self {
756 // Lower bound
757 Self {
758 loc: InstrIdx::new(0, 0),
759 src_dst_idx: 0,
760 }
761 }
762 }
763
764 // Delay accumulated from the blocks it passed, used to check for cross-block hazards.
765 type AccumulatedDelay = u8;
766 type DelayRegTracker = SparseRegTracker<RegUseMap<RegOrigin, AccumulatedDelay>>;
767
768 struct BlockDelayScheduler<'a> {
769 sm: &'a ShaderModelInfo,
770 f: &'a Function,
771 // Map from barrier to last waited cycle
772 bars: [u32; 6],
773 // Current cycle count until end-of-block.
774 current_cycle: u32,
775 // Map from idx (block, instr) to block-relative cycle
776 instr_cycles: &'a mut Vec<Vec<u32>>,
777 }
778
779 impl BlockDelayScheduler<'_> {
780 /// Compute the starting cycle for an instruction to avoid a dependency hazard.
781 fn dependency_to_cycle(
782 &self,
783 curr_loc: InstrIdx, // Location of the current instruction
784 reg: &RegOrigin, // Register and location of instruction that will be executed later
785 delay: AccumulatedDelay, // Delay between the end of the current block and the later instruction
786 latency: u32, // Latency between current and later instruction
787 ) -> u32 {
788 debug_assert!(latency <= self.sm.latency_upper_bound());
789
790 let same_block = reg.loc.block_idx == curr_loc.block_idx
791 && reg.loc.instr_idx > curr_loc.instr_idx;
792
793 if same_block {
794 // Created this transfer pass
795 self.instr_cycles[reg.loc.block_idx as usize]
796 [reg.loc.instr_idx as usize]
797 + latency
798 } else {
799 // Remember that cycles are always counted from the end of a block.
800 // The next instruction happens after `delay` cycles after the
801 // current block is complete, so it is effectively executed at cycle
802 // `0 - delay`, adding the latency we get `latency - delay`
803 // Underflow means that the instruction is already done (delay > latency).
804 latency.saturating_sub(delay.into())
805 }
806 }
807
808 fn process_instr(&mut self, loc: InstrIdx, reg_uses: &mut DelayRegTracker) {
809 let instr = &self.f[loc];
810
811 let mut min_start =
812 self.current_cycle + self.sm.exec_latency(&instr.op);
813
814 // Wait on rd/wr barriers
815 if let Some(bar) = instr.deps.rd_bar() {
816 min_start = max(min_start, self.bars[usize::from(bar)] + 2);
817 }
818 if let Some(bar) = instr.deps.wr_bar() {
819 min_start = max(min_start, self.bars[usize::from(bar)] + 2);
820 }
821
822 reg_uses.for_each_instr_dst_mut(instr, |i, u| {
823 for (orig, delay) in u.iter_writes() {
824 let l = self.sm.waw_latency(
825 &instr.op,
826 i,
827 !instr.pred.pred_ref.is_none(),
828 &self.f[orig.loc].op,
829 orig.src_dst_idx as usize,
830 );
831 let s = self.dependency_to_cycle(loc, orig, *delay, l);
832 min_start = max(min_start, s);
833 }
834 for (orig, delay) in u.iter_reads() {
835 let l = if orig.src_dst_idx == u16::MAX {
836 self.sm.paw_latency(&instr.op, i)
837 } else {
838 self.sm.raw_latency(
839 &instr.op,
840 i,
841 &self.f[orig.loc].op,
842 orig.src_dst_idx as usize,
843 )
844 };
845 let s = self.dependency_to_cycle(loc, orig, *delay, l);
846 min_start = max(min_start, s);
847 }
848
849 u.set_write(
850 RegOrigin {
851 loc,
852 src_dst_idx: i as u16,
853 },
854 0,
855 );
856 });
857
858 reg_uses.for_each_instr_pred_mut(instr, |c| {
859 // WaP does not exist
860 c.add_read(
861 RegOrigin {
862 loc,
863 src_dst_idx: u16::MAX,
864 },
865 0,
866 );
867 });
868 reg_uses.for_each_instr_src_mut(instr, |i, u| {
869 for (orig, delay) in u.iter_writes() {
870 let l = self.sm.war_latency(
871 &instr.op,
872 i,
873 &self.f[orig.loc].op,
874 orig.src_dst_idx as usize,
875 );
876 let s = self.dependency_to_cycle(loc, orig, *delay, l);
877 min_start = max(min_start, s);
878 }
879
880 u.add_read(
881 RegOrigin {
882 loc,
883 src_dst_idx: i as u16,
884 },
885 0,
886 );
887 });
888
889 self.instr_cycles[loc.block_idx as usize][loc.instr_idx as usize] =
890 min_start;
891
892 // Kepler A membar conflicts with predicate writes
893 if self.sm.is_kepler_a() && matches!(&instr.op, Op::MemBar(_)) {
894 let read_origin = RegOrigin {
895 loc,
896 src_dst_idx: u16::MAX,
897 };
898 reg_uses.for_each_pred(|c| {
899 c.add_read(read_origin, 0);
900 });
901 reg_uses.for_each_carry(|c| {
902 c.add_read(read_origin, 0);
903 });
904 }
905
906 // "Issue" barriers other instructions will wait on.
907 for (bar, c) in self.bars.iter_mut().enumerate() {
908 if instr.deps.wt_bar_mask & (1 << bar) != 0 {
909 *c = min_start;
910 }
911 }
912
913 self.current_cycle = min_start;
914 }
915 }
916
917 fn calc_delays(f: &mut Function, sm: &ShaderModelInfo) -> u64 {
918 let mut instr_cycles: Vec<Vec<u32>> =
919 f.blocks.iter().map(|b| vec![0; b.instrs.len()]).collect();
920
921 let mut state_in: Vec<_> = vec![DelayRegTracker::default(); f.blocks.len()];
922 let mut state_out: Vec<_> =
923 vec![DelayRegTracker::default(); f.blocks.len()];
924
925 let latency_upper_bound: u8 = sm
926 .latency_upper_bound()
927 .try_into()
928 .expect("Latency upper bound too large!");
929
930 // Compute instruction delays using an optimistic backwards data-flow
931 // algorithm. For back-cycles we assume the best and recompute when
932 // new data is available. This is yields correct results as long as
933 // the data flow analysis is run until completion.
934 BackwardDataflow {
935 cfg: &f.blocks,
936 block_in: &mut state_in[..],
937 block_out: &mut state_out[..],
938 transfer: |block_idx, block, reg_in, reg_out| {
939 let mut uses = reg_out.clone();
940
941 let mut sched = BlockDelayScheduler {
942 sm,
943 f,
944 // Barriers are handled by `assign_barriers`, and it does
945 // not handle cross-block barrier signal/wait.
946 // We can safely assume that no barrier is active at the
947 // start and end of the block
948 bars: [0_u32; 6],
949 current_cycle: 0_u32,
950 instr_cycles: &mut instr_cycles,
951 };
952
953 for ip in (0..block.instrs.len()).rev() {
954 let loc = InstrIdx::new(block_idx, ip);
955 sched.process_instr(loc, &mut uses);
956 }
957
958 // Update accumulated delay
959 let block_cycles = sched.current_cycle;
960 uses.retain(|reg_use| {
961 reg_use.map.retain(|(_rw, k), v| {
962 let overcount = if k.loc.block_idx as usize == block_idx {
963 // Only instrs before instr_idx must be counted
964 instr_cycles[k.loc.block_idx as usize]
965 [k.loc.instr_idx as usize]
966 } else {
967 0
968 };
969 let instr_executed = (block_cycles - overcount)
970 .try_into()
971 .unwrap_or(u8::MAX);
972 // We only care about the accumulated delay until it
973 // is bigger than the maximum delay of an instruction.
974 // after that, it cannot cause hazards.
975 let (added, overflow) =
976 (*v).overflowing_add(instr_executed);
977 *v = added;
978 // Stop keeping track of entries that happened too
979 // many cycles "in the future", and cannot affect
980 // scheduling anymore
981 !overflow && added <= latency_upper_bound
982 });
983 !reg_use.map.is_empty()
984 });
985
986 if *reg_in == uses {
987 false
988 } else {
989 *reg_in = uses;
990 true
991 }
992 },
993 join: |curr_in, succ_out| {
994 // We start with an optimistic assumption and gradually make it
995 // less optimistic. So in the join operation we need to keep
996 // the "worst" accumulated latency, that is the lowest one.
997 // i.e. if an instruction has an accumulated latency of 2 cycles,
998 // it can interfere with the next block, while if it had 200 cycles
999 // it's highly unlikely that it could interfere.
1000 curr_in.merge_with(succ_out, |a, b| {
1001 a.merge_with(b, |ai, bi| (*ai).min(*bi))
1002 });
1003 },
1004 }
1005 .solve();
1006
1007 // Update the deps.delay for each instruction and compute
1008 for (bi, b) in f.blocks.iter_mut().enumerate() {
1009 let cycles = &instr_cycles[bi];
1010 for (ip, i) in b.instrs.iter_mut().enumerate() {
1011 let delay = cycles[ip] - cycles.get(ip + 1).copied().unwrap_or(0);
1012 let delay: u8 = delay.try_into().expect("Delay overflow");
1013 i.deps.delay = delay.max(MIN_INSTR_DELAY);
1014 }
1015 }
1016
1017 let min_num_static_cycles = instr_cycles
1018 .iter()
1019 .enumerate()
1020 .map(|(block_idx, cycles)| {
1021 let cycles = cycles.last().copied().unwrap_or(0);
1022 let block_weight = estimate_block_weight(&f.blocks, block_idx);
1023 u64::from(cycles)
1024 .checked_mul(block_weight)
1025 .expect("Cycle count estimate overflow")
1026 })
1027 .reduce(|a, b| a.checked_add(b).expect("Cycle count estimate overflow"))
1028 .unwrap_or(0);
1029
1030 let max_instr_delay = sm.max_instr_delay();
1031 f.map_instrs(|mut instr, _| {
1032 if instr.deps.delay > max_instr_delay {
1033 let mut delay = instr.deps.delay - max_instr_delay;
1034 instr.deps.set_delay(max_instr_delay);
1035 let mut instrs = vec![instr];
1036 while delay > 0 {
1037 let mut nop = Instr::new(OpNop { label: None });
1038 nop.deps.set_delay(delay.min(max_instr_delay));
1039 delay -= nop.deps.delay;
1040 instrs.push(nop);
1041 }
1042 MappedInstrs::Many(instrs)
1043 } else if matches!(instr.op, Op::SrcBar(_)) {
1044 instr.op = Op::Nop(OpNop { label: None });
1045 MappedInstrs::One(instr)
1046 } else if sm.exec_latency(&instr.op) > 1 {
1047 // It's unclear exactly why but the blob inserts a Nop with a delay
1048 // of 2 after every instruction which has an exec latency. Perhaps
1049 // it has something to do with .yld? In any case, the extra 2
1050 // cycles aren't worth the chance of weird bugs.
1051 let mut nop = Instr::new(OpNop { label: None });
1052 nop.deps.set_delay(2);
1053 MappedInstrs::Many(vec![instr, nop])
1054 } else {
1055 MappedInstrs::One(instr)
1056 }
1057 });
1058
1059 min_num_static_cycles
1060 }
1061
1062 impl Shader<'_> {
1063 pub fn assign_deps_serial(&mut self) {
1064 for f in &mut self.functions {
1065 for b in &mut f.blocks.iter_mut().rev() {
1066 let mut wt = 0_u8;
1067 for instr in &mut b.instrs {
1068 if matches!(&instr.op, Op::Bar(_))
1069 || matches!(&instr.op, Op::BClear(_))
1070 || matches!(&instr.op, Op::BSSy(_))
1071 || matches!(&instr.op, Op::BSync(_))
1072 {
1073 instr.deps.set_yield(true);
1074 } else if instr.is_branch() {
1075 instr.deps.add_wt_bar_mask(0x3f);
1076 } else {
1077 instr.deps.add_wt_bar_mask(wt);
1078 if instr.dsts().len() > 0 {
1079 instr.deps.set_wr_bar(0);
1080 wt |= 1 << 0;
1081 }
1082 if !instr.pred.pred_ref.is_none()
1083 || instr.srcs().len() > 0
1084 {
1085 instr.deps.set_rd_bar(1);
1086 wt |= 1 << 1;
1087 }
1088 }
1089 }
1090 }
1091 }
1092 }
1093
1094 pub fn calc_instr_deps(&mut self) {
1095 if self.sm.is_kepler() {
1096 for f in &mut self.functions {
1097 insert_texture_barriers(f, self.sm);
1098 }
1099 }
1100
1101 if DEBUG.serial() {
1102 self.assign_deps_serial();
1103 } else {
1104 let mut min_num_static_cycles = 0u64;
1105 for f in &mut self.functions {
1106 assign_barriers(f, self.sm);
1107 min_num_static_cycles += calc_delays(f, self.sm);
1108 }
1109
1110 if DEBUG.cycles() {
1111 // This is useful for debugging differences in the scheduler
1112 // cycle count model and the calc_delays() model. However, it
1113 // isn't totally valid since assign_barriers() can add extra
1114 // dependencies for barrier re-use and those may add cycles.
1115 // The chances of it doing this are low, thanks to our LRU
1116 // allocation strategy, but it's still not an assert we want
1117 // running in production.
1118 assert!(self.info.num_static_cycles >= min_num_static_cycles);
1119 }
1120 }
1121 }
1122 }
1123
1124 #[cfg(test)]
1125 mod tests {
1126 use super::*;
1127
1128 fn reg_gpr(range: Range<usize>) -> RegRef {
1129 RegRef::new(
1130 RegFile::GPR,
1131 range.start as u32,
1132 (range.end - range.start) as u8,
1133 )
1134 }
1135
1136 #[test]
1137 fn test_texdepbar_basic() {
1138 let mut sim = TexQueueSimulationState::new();
1139
1140 // RaW
1141 assert_eq!(sim.push(reg_gpr(0..4)), None);
1142 assert_eq!(sim.flush(reg_gpr(2..3)), Some(0));
1143
1144 // 2 entries in the queue
1145 assert_eq!(sim.push(reg_gpr(0..2)), None); // [A]
1146 assert_eq!(sim.push(reg_gpr(2..4)), None); // [B, A]
1147 assert_eq!(sim.flush(reg_gpr(0..1)), Some(1)); // [B]
1148 assert_eq!(sim.flush(reg_gpr(3..4)), Some(0)); // []
1149
1150 // Test bucket conflicts
1151 assert_eq!(sim.push(reg_gpr(0..1)), None);
1152 assert_eq!(sim.flush(reg_gpr(1..3)), None);
1153 assert_eq!(sim.flush(reg_gpr(0..3)), Some(0));
1154
1155 // Bucket conflict part 2: Electric Boogaloo
1156 assert_eq!(sim.push(reg_gpr(1..2)), None);
1157 assert_eq!(sim.push(reg_gpr(0..1)), None);
1158 assert_eq!(sim.flush(reg_gpr(1..2)), Some(1));
1159 assert_eq!(sim.flush(reg_gpr(0..1)), Some(0));
1160
1161 // Interesting CFG case that the old pass got wrong.
1162 // CFG: A -> [B, C] -> D
1163 // A pushes
1164 assert_eq!(sim.push(reg_gpr(0..4)), None);
1165 // B: pushes a tex then flushes it
1166 let mut b_sim = sim.clone();
1167 assert_eq!(b_sim.push(reg_gpr(4..8)), None);
1168 assert_eq!(b_sim.flush(reg_gpr(4..8)), Some(0));
1169 // C: pushes 3 tex and never flishes them
1170 let mut c_sim = sim.clone();
1171 assert_eq!(c_sim.push(reg_gpr(4..5)), None);
1172 assert_eq!(c_sim.push(reg_gpr(5..6)), None);
1173 assert_eq!(c_sim.push(reg_gpr(6..7)), None);
1174 // D: flushes the tex pushed by A
1175 let mut d_sim = b_sim;
1176 d_sim.merge(&c_sim);
1177 assert_eq!(c_sim.flush(reg_gpr(0..4)), Some(3));
1178 // the "shortest push path" would pass by B but in fact
1179 // by passing in B our texture is flushed off the queue.
1180 // (old algorithm would insert a texdepbar 1)
1181 }
1182
1183 #[test]
1184 fn test_texdepbar_overflow() {
1185 let mut sim = TexQueueSimulationState::new();
1186
1187 // Fill the texture queue
1188 for i in 0..(usize::from(OpTexDepBar::MAX_TEXTURES_LEFT) + 1) {
1189 assert_eq!(sim.push(reg_gpr(i..(i + 1))), None);
1190 }
1191 // The new push would overflow the queue, we NEED a barrier
1192 assert_eq!(
1193 sim.push(reg_gpr(64..65)),
1194 Some(OpTexDepBar::MAX_TEXTURES_LEFT)
1195 );
1196 assert_eq!(
1197 sim.push(reg_gpr(65..66)),
1198 Some(OpTexDepBar::MAX_TEXTURES_LEFT)
1199 );
1200 }
1201 }