| 1 |
// Copyright © 2025 Valve Corporation |
| 2 |
// SPDX-License-Identifier: MIT |
| 3 |
|
| 4 |
use crate::api::{GetDebugFlags, DEBUG}; |
| 5 |
use crate::ir::*; |
| 6 |
use crate::liveness::{BlockLiveness, LiveSet, Liveness, SimpleLiveness}; |
| 7 |
use crate::opt_instr_sched_common::{ |
| 8 |
calc_statistics, estimate_variable_latency, side_effect_type, DepGraph, |
| 9 |
EdgeLabel, FutureReadyInstr, ReadyInstr, SideEffect, |
| 10 |
}; |
| 11 |
use rustc_hash::FxHashMap; |
| 12 |
use std::cmp::Reverse; |
| 13 |
use std::cmp::{max, min}; |
| 14 |
use std::collections::BTreeSet; |
| 15 |
|
| 16 |
// This is the maximum number of reserved gprs - (TODO: Model more cases where |
| 17 |
// we actually need 2) |
| 18 |
const SW_RESERVED_GPRS: i32 = 1; |
| 19 |
const SW_RESERVED_GPRS_SPILL: i32 = 2; |
| 20 |
|
| 21 |
/// Target number of free GPRs. This is used for the threshold to switch to |
| 22 |
/// scheduling for register pressure |
| 23 |
const TARGET_FREE: i32 = 4; |
| 24 |
|
| 25 |
/// Typically using an extra register is free... until you hit a threshold where |
| 26 |
/// one more register causes occupancy to plummet. This function figures out how |
| 27 |
/// many GPRs you can use without costing occupancy, assuming you always need at |
| 28 |
/// least `x` GPRs. |
| 29 |
fn next_occupancy_cliff(sm: &ShaderModelInfo, x: u32) -> u32 { |
| 30 |
let total_regs: u32 = 65536; |
| 31 |
let threads = max_warps_per_sm(sm, x) * 32; |
| 32 |
|
| 33 |
// This function doesn't actually model the maximum number of registers |
| 34 |
// correctly - callers need to worry about that separately. We do, |
| 35 |
// however, want to avoid a divide by zero. |
| 36 |
let threads = max(threads, 1); |
| 37 |
|
| 38 |
prev_multiple_of(total_regs / threads, 8) |
| 39 |
} |
| 40 |
|
| 41 |
#[cfg(test)] |
| 42 |
#[test] |
| 43 |
fn test_next_occupancy_cliff() { |
| 44 |
for max_hw_warps in [32, 48, 64] { |
| 45 |
let sm = ShaderModelInfo::new(75, max_hw_warps); |
| 46 |
for x in 0..255 { |
| 47 |
let y = next_occupancy_cliff(&sm, x); |
| 48 |
assert!(y >= x); |
| 49 |
assert_eq!(max_warps_per_sm(&sm, x), max_warps_per_sm(&sm, y)); |
| 50 |
assert!(max_warps_per_sm(&sm, y) > max_warps_per_sm(&sm, y + 1)); |
| 51 |
} |
| 52 |
} |
| 53 |
} |
| 54 |
|
| 55 |
fn next_occupancy_cliff_with_reserved( |
| 56 |
sm: &ShaderModelInfo, |
| 57 |
gprs: i32, |
| 58 |
reserved: i32, |
| 59 |
) -> i32 { |
| 60 |
i32::try_from(next_occupancy_cliff( |
| 61 |
sm, |
| 62 |
(gprs + reserved).try_into().unwrap(), |
| 63 |
)) |
| 64 |
.unwrap() |
| 65 |
- reserved |
| 66 |
} |
| 67 |
|
| 68 |
fn generate_dep_graph(sm: &ShaderModelInfo, instrs: &[Instr]) -> DepGraph { |
| 69 |
let mut g = DepGraph::new((0..instrs.len()).map(|_| Default::default())); |
| 70 |
|
| 71 |
let mut defs = FxHashMap::<SSAValue, (usize, usize)>::default(); |
| 72 |
|
| 73 |
let mut last_memory_op = None; |
| 74 |
let mut last_barrier_op = None; |
| 75 |
|
| 76 |
for ip in 0..instrs.len() { |
| 77 |
let instr = &instrs[ip]; |
| 78 |
|
| 79 |
if let Some(bar_ip) = last_barrier_op { |
| 80 |
g.add_edge(bar_ip, ip, EdgeLabel { latency: 0 }); |
| 81 |
} |
| 82 |
|
| 83 |
match side_effect_type(&instr.op) { |
| 84 |
SideEffect::None => (), |
| 85 |
SideEffect::Barrier => { |
| 86 |
let first_ip = last_barrier_op.unwrap_or(0); |
| 87 |
for other_ip in first_ip..ip { |
| 88 |
g.add_edge(other_ip, ip, EdgeLabel { latency: 0 }); |
| 89 |
} |
| 90 |
last_barrier_op = Some(ip); |
| 91 |
} |
| 92 |
SideEffect::Memory => { |
| 93 |
if let Some(mem_ip) = last_memory_op { |
| 94 |
g.add_edge(mem_ip, ip, EdgeLabel { latency: 0 }); |
| 95 |
} |
| 96 |
last_memory_op = Some(ip); |
| 97 |
} |
| 98 |
} |
| 99 |
|
| 100 |
for (i, src) in instr.srcs().iter().enumerate() { |
| 101 |
for ssa in src.src_ref.iter_ssa() { |
| 102 |
if let Some(&(def_ip, def_idx)) = defs.get(ssa) { |
| 103 |
let def_instr = &instrs[def_ip]; |
| 104 |
let latency = |
| 105 |
if def_instr.op.is_virtual() || instr.op.is_virtual() { |
| 106 |
0 |
| 107 |
} else { |
| 108 |
max( |
| 109 |
sm.raw_latency( |
| 110 |
&def_instr.op, |
| 111 |
def_idx, |
| 112 |
&instr.op, |
| 113 |
i, |
| 114 |
), |
| 115 |
estimate_variable_latency(sm, &def_instr.op), |
| 116 |
) |
| 117 |
}; |
| 118 |
|
| 119 |
g.add_edge(def_ip, ip, EdgeLabel { latency }); |
| 120 |
} |
| 121 |
} |
| 122 |
} |
| 123 |
|
| 124 |
if let PredRef::SSA(ssa) = &instr.pred.pred_ref { |
| 125 |
if let Some(&(def_ip, def_idx)) = defs.get(ssa) { |
| 126 |
let def_instr = &instrs[def_ip]; |
| 127 |
|
| 128 |
let latency = if def_instr.op.is_virtual() { |
| 129 |
0 |
| 130 |
} else { |
| 131 |
max( |
| 132 |
sm.paw_latency(&def_instr.op, def_idx), |
| 133 |
estimate_variable_latency(sm, &def_instr.op), |
| 134 |
) |
| 135 |
}; |
| 136 |
|
| 137 |
g.add_edge(def_ip, ip, EdgeLabel { latency }); |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
for (i, dst) in instr.dsts().iter().enumerate() { |
| 142 |
for &ssa in dst.iter_ssa() { |
| 143 |
defs.insert(ssa, (ip, i)); |
| 144 |
} |
| 145 |
} |
| 146 |
} |
| 147 |
|
| 148 |
g |
| 149 |
} |
| 150 |
|
| 151 |
mod net_live { |
| 152 |
use crate::ir::*; |
| 153 |
use crate::liveness::LiveSet; |
| 154 |
use rustc_hash::FxHashMap; |
| 155 |
use std::ops::Index; |
| 156 |
|
| 157 |
/// The net change in live values, from the end of an instruction to a |
| 158 |
/// specific point during the instruction's execution |
| 159 |
pub(super) struct InstrCount { |
| 160 |
/// The net change in live values across the whole instruction |
| 161 |
pub net: PerRegFile<i8>, |
| 162 |
|
| 163 |
/// peak1 is at the end of the instruction, where any immediately-killed |
| 164 |
/// defs are live |
| 165 |
pub peak1: PerRegFile<i8>, |
| 166 |
|
| 167 |
/// peak2 is just before sources are read, and after vector defs are live |
| 168 |
pub peak2: PerRegFile<i8>, |
| 169 |
} |
| 170 |
|
| 171 |
/// For each instruction, keep track of a "net live" value, which is how |
| 172 |
/// much the size of the live values set will change if we chedule a given |
| 173 |
/// instruction next. This is tracked per-register-file. |
| 174 |
/// |
| 175 |
/// Assumes that we are iterating over instructions in reverse order |
| 176 |
pub(super) struct NetLive { |
| 177 |
counts: Vec<InstrCount>, |
| 178 |
ssa_to_instr: FxHashMap<SSAValue, Vec<usize>>, |
| 179 |
} |
| 180 |
|
| 181 |
impl NetLive { |
| 182 |
pub(super) fn new(instrs: &[Instr], live_out: &LiveSet) -> Self { |
| 183 |
let mut use_set = LiveSet::new(); |
| 184 |
let mut ssa_to_instr = FxHashMap::default(); |
| 185 |
|
| 186 |
let mut counts: Vec<InstrCount> = instrs |
| 187 |
.iter() |
| 188 |
.enumerate() |
| 189 |
.map(|(instr_idx, instr)| { |
| 190 |
use_set.clear(); |
| 191 |
for ssa in instr.ssa_uses() { |
| 192 |
if !live_out.contains(ssa) { |
| 193 |
if use_set.insert(*ssa) { |
| 194 |
ssa_to_instr |
| 195 |
.entry(*ssa) |
| 196 |
.or_insert_with(Vec::new) |
| 197 |
.push(instr_idx); |
| 198 |
} |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
let net = PerRegFile::new_with(|f| { |
| 203 |
use_set.count(f).try_into().unwrap() |
| 204 |
}); |
| 205 |
InstrCount { |
| 206 |
net: net, |
| 207 |
peak1: Default::default(), |
| 208 |
peak2: net, |
| 209 |
} |
| 210 |
}) |
| 211 |
.collect(); |
| 212 |
|
| 213 |
for (instr_idx, instr) in instrs.iter().enumerate() { |
| 214 |
for dst in instr.dsts() { |
| 215 |
let is_vector = dst.iter_ssa().len() > 1; |
| 216 |
let count = &mut counts[instr_idx]; |
| 217 |
|
| 218 |
for &ssa in dst.iter_ssa() { |
| 219 |
if ssa_to_instr.contains_key(&ssa) |
| 220 |
|| live_out.contains(&ssa) |
| 221 |
{ |
| 222 |
count.net[ssa.file()] -= 1; |
| 223 |
} else { |
| 224 |
count.peak1[ssa.file()] += 1; |
| 225 |
count.peak2[ssa.file()] += 1; |
| 226 |
} |
| 227 |
|
| 228 |
if !is_vector { |
| 229 |
count.peak2[ssa.file()] -= 1; |
| 230 |
} |
| 231 |
} |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
NetLive { |
| 236 |
counts, |
| 237 |
ssa_to_instr, |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
pub(super) fn remove(&mut self, ssa: SSAValue) -> bool { |
| 242 |
match self.ssa_to_instr.remove(&ssa) { |
| 243 |
Some(instr_idxs) => { |
| 244 |
assert!(!instr_idxs.is_empty()); |
| 245 |
let file = ssa.file(); |
| 246 |
for i in instr_idxs { |
| 247 |
self.counts[i].net[file] -= 1; |
| 248 |
self.counts[i].peak2[file] -= 1; |
| 249 |
} |
| 250 |
true |
| 251 |
} |
| 252 |
None => false, |
| 253 |
} |
| 254 |
} |
| 255 |
} |
| 256 |
|
| 257 |
impl Index<usize> for NetLive { |
| 258 |
type Output = InstrCount; |
| 259 |
|
| 260 |
fn index(&self, index: usize) -> &Self::Output { |
| 261 |
&self.counts[index] |
| 262 |
} |
| 263 |
} |
| 264 |
} |
| 265 |
|
| 266 |
use net_live::NetLive; |
| 267 |
|
| 268 |
/// The third element of each tuple is a weight meant to approximate the cost of |
| 269 |
/// spilling a value from the first register file to the second. Right now, the |
| 270 |
/// values are meant to approximate the cost of a spill + fill, in cycles |
| 271 |
const SPILL_FILES: [(RegFile, RegFile, i32); 5] = [ |
| 272 |
(RegFile::Bar, RegFile::GPR, 6 + 6), |
| 273 |
(RegFile::Pred, RegFile::GPR, 12 + 6), |
| 274 |
(RegFile::UPred, RegFile::UGPR, 12 + 6), |
| 275 |
(RegFile::UGPR, RegFile::GPR, 15 + 6), |
| 276 |
(RegFile::GPR, RegFile::Mem, 32 + 32), |
| 277 |
]; |
| 278 |
|
| 279 |
/// Models how many gprs will be used after spilling other register files |
| 280 |
fn calc_used_gprs(mut p: PerRegFile<i32>, max_regs: PerRegFile<i32>) -> i32 { |
| 281 |
for (src, dest, _) in SPILL_FILES { |
| 282 |
if p[src] > max_regs[src] { |
| 283 |
p[dest] += p[src] - max_regs[src]; |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
p[RegFile::GPR] |
| 288 |
} |
| 289 |
|
| 290 |
fn calc_score_part( |
| 291 |
mut p: PerRegFile<i32>, |
| 292 |
max_regs: PerRegFile<i32>, |
| 293 |
) -> (i32, i32) { |
| 294 |
// We separate "badness" and "goodness" because we don't want eg. two extra |
| 295 |
// free predicates to offset the weight of spilling a UGPR - the spill is |
| 296 |
// always more important than keeping extra registers free |
| 297 |
let mut badness: i32 = 0; |
| 298 |
let mut goodness: i32 = 0; |
| 299 |
|
| 300 |
for (src, dest, weight) in SPILL_FILES { |
| 301 |
if p[src] > max_regs[src] { |
| 302 |
let spill_count = p[src] - max_regs[src]; |
| 303 |
p[dest] += spill_count; |
| 304 |
badness += spill_count * weight; |
| 305 |
} else { |
| 306 |
let free_count = max_regs[src] - p[src]; |
| 307 |
goodness += free_count * weight; |
| 308 |
} |
| 309 |
} |
| 310 |
(badness, goodness) |
| 311 |
} |
| 312 |
|
| 313 |
type Score = (bool, Reverse<i32>, i32); |
| 314 |
fn calc_score( |
| 315 |
net: PerRegFile<i32>, |
| 316 |
peak1: PerRegFile<i32>, |
| 317 |
peak2: PerRegFile<i32>, |
| 318 |
max_regs: PerRegFile<i32>, |
| 319 |
delay_cycles: u32, |
| 320 |
thresholds: ScheduleThresholds, |
| 321 |
) -> Score { |
| 322 |
let peak_gprs = max( |
| 323 |
calc_used_gprs(peak1, max_regs), |
| 324 |
calc_used_gprs(peak2, max_regs), |
| 325 |
); |
| 326 |
let instruction_usable = peak_gprs <= thresholds.quit_threshold; |
| 327 |
if !instruction_usable { |
| 328 |
return (false, Reverse(0), 0); |
| 329 |
} |
| 330 |
|
| 331 |
let (mut badness, goodness) = calc_score_part(net, max_regs); |
| 332 |
badness += i32::try_from(delay_cycles).unwrap(); |
| 333 |
|
| 334 |
(true, Reverse(badness), goodness) |
| 335 |
} |
| 336 |
|
| 337 |
#[derive(Copy, Clone)] |
| 338 |
struct ScheduleThresholds { |
| 339 |
/// Start scheduling for pressure if we use this many gprs |
| 340 |
heuristic_threshold: i32, |
| 341 |
|
| 342 |
/// Give up if we use this many gprs |
| 343 |
quit_threshold: i32, |
| 344 |
} |
| 345 |
|
| 346 |
struct GenerateOrder<'a> { |
| 347 |
max_regs: PerRegFile<i32>, |
| 348 |
net_live: NetLive, |
| 349 |
live: LiveSet, |
| 350 |
instrs: &'a [Instr], |
| 351 |
} |
| 352 |
|
| 353 |
impl<'a> GenerateOrder<'a> { |
| 354 |
fn new( |
| 355 |
max_regs: PerRegFile<i32>, |
| 356 |
instrs: &'a [Instr], |
| 357 |
live_out: &LiveSet, |
| 358 |
) -> Self { |
| 359 |
let net_live = NetLive::new(instrs, live_out); |
| 360 |
let live: LiveSet = live_out.clone(); |
| 361 |
|
| 362 |
GenerateOrder { |
| 363 |
max_regs, |
| 364 |
net_live, |
| 365 |
live, |
| 366 |
instrs, |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
fn new_used_regs(&self, net: PerRegFile<i8>) -> PerRegFile<i32> { |
| 371 |
PerRegFile::new_with(|file| { |
| 372 |
i32::try_from(self.live.count(file)).unwrap() + (net[file] as i32) |
| 373 |
}) |
| 374 |
} |
| 375 |
|
| 376 |
fn current_used_gprs(&self) -> i32 { |
| 377 |
calc_used_gprs( |
| 378 |
PerRegFile::new_with(|f| self.live.count(f).try_into().unwrap()), |
| 379 |
self.max_regs, |
| 380 |
) |
| 381 |
} |
| 382 |
|
| 383 |
fn new_used_gprs_net(&self, instr_index: usize) -> i32 { |
| 384 |
calc_used_gprs( |
| 385 |
self.new_used_regs(self.net_live[instr_index].net), |
| 386 |
self.max_regs, |
| 387 |
) |
| 388 |
} |
| 389 |
|
| 390 |
fn new_used_gprs_peak1(&self, instr_index: usize) -> i32 { |
| 391 |
calc_used_gprs( |
| 392 |
self.new_used_regs(self.net_live[instr_index].peak1), |
| 393 |
self.max_regs, |
| 394 |
) |
| 395 |
} |
| 396 |
|
| 397 |
fn new_used_gprs_peak2(&self, instr_index: usize) -> i32 { |
| 398 |
calc_used_gprs( |
| 399 |
self.new_used_regs(self.net_live[instr_index].peak2), |
| 400 |
self.max_regs, |
| 401 |
) |
| 402 |
} |
| 403 |
|
| 404 |
fn new_score( |
| 405 |
&self, |
| 406 |
instr_index: usize, |
| 407 |
delay_cycles: u32, |
| 408 |
thresholds: ScheduleThresholds, |
| 409 |
) -> Score { |
| 410 |
calc_score( |
| 411 |
self.new_used_regs(self.net_live[instr_index].net), |
| 412 |
self.new_used_regs(self.net_live[instr_index].peak1), |
| 413 |
self.new_used_regs(self.net_live[instr_index].peak2), |
| 414 |
self.max_regs, |
| 415 |
delay_cycles, |
| 416 |
thresholds, |
| 417 |
) |
| 418 |
} |
| 419 |
|
| 420 |
fn generate_order( |
| 421 |
mut self, |
| 422 |
g: &DepGraph, |
| 423 |
init_ready_list: &[usize], |
| 424 |
thresholds: ScheduleThresholds, |
| 425 |
) -> Option<(Vec<usize>, PerRegFile<i32>)> { |
| 426 |
let mut ready_instrs: BTreeSet<ReadyInstr> = init_ready_list |
| 427 |
.iter() |
| 428 |
.map(|&i| ReadyInstr::new(g, i)) |
| 429 |
.collect(); |
| 430 |
let mut future_ready_instrs = BTreeSet::new(); |
| 431 |
|
| 432 |
struct InstrInfo { |
| 433 |
num_uses: u32, |
| 434 |
ready_cycle: u32, |
| 435 |
} |
| 436 |
let mut instr_info: Vec<InstrInfo> = g |
| 437 |
.nodes |
| 438 |
.iter() |
| 439 |
.map(|node| InstrInfo { |
| 440 |
num_uses: node.label.num_uses, |
| 441 |
ready_cycle: node.label.ready_cycle, |
| 442 |
}) |
| 443 |
.collect(); |
| 444 |
|
| 445 |
let mut current_cycle = 0; |
| 446 |
let mut instr_order = Vec::with_capacity(g.nodes.len()); |
| 447 |
loop { |
| 448 |
let used_gprs = self.current_used_gprs(); |
| 449 |
|
| 450 |
// Move ready instructions to the ready list |
| 451 |
loop { |
| 452 |
match future_ready_instrs.last() { |
| 453 |
None => break, |
| 454 |
Some(FutureReadyInstr { |
| 455 |
ready_cycle: std::cmp::Reverse(ready_cycle), |
| 456 |
index, |
| 457 |
}) => { |
| 458 |
if current_cycle >= *ready_cycle { |
| 459 |
ready_instrs.insert(ReadyInstr::new(g, *index)); |
| 460 |
future_ready_instrs.pop_last(); |
| 461 |
} else { |
| 462 |
break; |
| 463 |
} |
| 464 |
} |
| 465 |
} |
| 466 |
} |
| 467 |
|
| 468 |
if ready_instrs.is_empty() { |
| 469 |
match future_ready_instrs.last() { |
| 470 |
None => break, // Both lists are empty. We're done! |
| 471 |
Some(&FutureReadyInstr { |
| 472 |
ready_cycle: Reverse(ready_cycle), |
| 473 |
.. |
| 474 |
}) => { |
| 475 |
// Fast-forward time to when the next instr is ready |
| 476 |
assert!(ready_cycle > current_cycle); |
| 477 |
current_cycle = ready_cycle; |
| 478 |
continue; |
| 479 |
} |
| 480 |
} |
| 481 |
} |
| 482 |
|
| 483 |
// Pick an instruction to schedule |
| 484 |
let next_idx = if used_gprs <= thresholds.heuristic_threshold { |
| 485 |
let ReadyInstr { index, .. } = ready_instrs.pop_last().unwrap(); |
| 486 |
index |
| 487 |
} else { |
| 488 |
let (new_score, ready_instr) = ready_instrs |
| 489 |
.iter() |
| 490 |
.map(|ready_instr| { |
| 491 |
( |
| 492 |
self.new_score(ready_instr.index, 0, thresholds), |
| 493 |
ready_instr.clone(), |
| 494 |
) |
| 495 |
}) |
| 496 |
.max() |
| 497 |
.unwrap(); |
| 498 |
|
| 499 |
let better_candidate = future_ready_instrs |
| 500 |
.iter() |
| 501 |
.filter_map(|future_ready_instr| { |
| 502 |
let ready_cycle = future_ready_instr.ready_cycle.0; |
| 503 |
let s = self.new_score( |
| 504 |
future_ready_instr.index, |
| 505 |
ready_cycle - current_cycle, |
| 506 |
thresholds, |
| 507 |
); |
| 508 |
if s > new_score { |
| 509 |
Some((s, future_ready_instr.clone())) |
| 510 |
} else { |
| 511 |
None |
| 512 |
} |
| 513 |
}) |
| 514 |
.max(); |
| 515 |
|
| 516 |
if let Some((_, future_ready_instr)) = better_candidate { |
| 517 |
future_ready_instrs.remove(&future_ready_instr); |
| 518 |
let ready_cycle = future_ready_instr.ready_cycle.0; |
| 519 |
// Fast-forward time to when this instr is ready |
| 520 |
assert!(ready_cycle > current_cycle); |
| 521 |
current_cycle = ready_cycle; |
| 522 |
future_ready_instr.index |
| 523 |
} else { |
| 524 |
ready_instrs.remove(&ready_instr); |
| 525 |
ready_instr.index |
| 526 |
} |
| 527 |
}; |
| 528 |
|
| 529 |
// Schedule the instuction |
| 530 |
let predicted_new_used_gprs_peak = max( |
| 531 |
self.new_used_gprs_peak1(next_idx), |
| 532 |
self.new_used_gprs_peak2(next_idx), |
| 533 |
); |
| 534 |
let predicted_new_used_gprs_net = self.new_used_gprs_net(next_idx); |
| 535 |
|
| 536 |
if predicted_new_used_gprs_peak > thresholds.quit_threshold { |
| 537 |
return None; |
| 538 |
} |
| 539 |
|
| 540 |
let outgoing_edges = &g.nodes[next_idx].outgoing_edges; |
| 541 |
for edge in outgoing_edges { |
| 542 |
let dep_instr = &mut instr_info[edge.head_idx]; |
| 543 |
dep_instr.ready_cycle = max( |
| 544 |
dep_instr.ready_cycle, |
| 545 |
current_cycle + edge.label.latency, |
| 546 |
); |
| 547 |
dep_instr.num_uses -= 1; |
| 548 |
if dep_instr.num_uses <= 0 { |
| 549 |
future_ready_instrs |
| 550 |
.insert(FutureReadyInstr::new(g, edge.head_idx)); |
| 551 |
} |
| 552 |
} |
| 553 |
|
| 554 |
// We're walking backwards, so the instr's defs are killed |
| 555 |
let instr = &self.instrs[next_idx]; |
| 556 |
for dst in instr.dsts() { |
| 557 |
for ssa in dst.iter_ssa() { |
| 558 |
self.live.remove(ssa); |
| 559 |
} |
| 560 |
} |
| 561 |
|
| 562 |
// We're walking backwards, so uses are now live |
| 563 |
for &ssa in instr.ssa_uses() { |
| 564 |
if self.net_live.remove(ssa) { |
| 565 |
self.live.insert(ssa); |
| 566 |
} else { |
| 567 |
// This branch should only happen if one instruction |
| 568 |
// uses the same SSAValue multiple times |
| 569 |
debug_assert!(!self.live.insert(ssa)); |
| 570 |
} |
| 571 |
} |
| 572 |
|
| 573 |
instr_order.push(next_idx); |
| 574 |
current_cycle += 1; |
| 575 |
|
| 576 |
debug_assert_eq!( |
| 577 |
self.current_used_gprs(), |
| 578 |
predicted_new_used_gprs_net |
| 579 |
); |
| 580 |
} |
| 581 |
|
| 582 |
return Some(( |
| 583 |
instr_order, |
| 584 |
PerRegFile::new_with(|f| self.live.count(f).try_into().unwrap()), |
| 585 |
)); |
| 586 |
} |
| 587 |
} |
| 588 |
|
| 589 |
struct InstructionOrder { |
| 590 |
order: Vec<usize>, |
| 591 |
} |
| 592 |
|
| 593 |
impl InstructionOrder { |
| 594 |
fn apply<'a>( |
| 595 |
&'a self, |
| 596 |
instrs: Vec<Instr>, |
| 597 |
) -> impl 'a + Iterator<Item = Instr> { |
| 598 |
assert_eq!(self.order.len(), instrs.len()); |
| 599 |
|
| 600 |
let mut instrs: Vec<Option<Instr>> = |
| 601 |
instrs.into_iter().map(|instr| Some(instr)).collect(); |
| 602 |
|
| 603 |
self.order.iter().map(move |&i| { |
| 604 |
std::mem::take(&mut instrs[i]).expect("Instruction scheduled twice") |
| 605 |
}) |
| 606 |
} |
| 607 |
} |
| 608 |
|
| 609 |
fn sched_buffer( |
| 610 |
max_regs: PerRegFile<i32>, |
| 611 |
instrs: &[Instr], |
| 612 |
graph: &ScheduleUnitGraph, |
| 613 |
live_in_count: PerRegFile<u32>, |
| 614 |
live_out: &LiveSet, |
| 615 |
thresholds: ScheduleThresholds, |
| 616 |
) -> Option<InstructionOrder> { |
| 617 |
let (mut new_order, live_in_count2) = GenerateOrder::new( |
| 618 |
max_regs, instrs, live_out, |
| 619 |
) |
| 620 |
.generate_order(&graph.g, &graph.init_ready_list, thresholds)?; |
| 621 |
|
| 622 |
// If our accounting is correct, it should match live_in |
| 623 |
assert_eq!( |
| 624 |
live_in_count2, |
| 625 |
PerRegFile::new_with(|f| { live_in_count[f].try_into().unwrap() }) |
| 626 |
); |
| 627 |
|
| 628 |
new_order.reverse(); |
| 629 |
|
| 630 |
Some(InstructionOrder { order: new_order }) |
| 631 |
} |
| 632 |
|
| 633 |
struct ScheduleUnitGraph { |
| 634 |
g: DepGraph, |
| 635 |
init_ready_list: Vec<usize>, |
| 636 |
} |
| 637 |
|
| 638 |
impl ScheduleUnitGraph { |
| 639 |
fn new(sm: &ShaderModelInfo, instrs: &[Instr]) -> Self { |
| 640 |
let mut g = generate_dep_graph(sm, instrs); |
| 641 |
|
| 642 |
let init_ready_list = calc_statistics(&mut g); |
| 643 |
|
| 644 |
// use crate::opt_instr_sched_common::save_graphviz; |
| 645 |
// save_graphviz(instrs, &g).unwrap(); |
| 646 |
g.reverse(); |
| 647 |
|
| 648 |
ScheduleUnitGraph { g, init_ready_list } |
| 649 |
} |
| 650 |
} |
| 651 |
|
| 652 |
#[derive(Default)] |
| 653 |
struct ScheduleUnit { |
| 654 |
/// live counts from after the phi_srcs |
| 655 |
live_in_count: Option<PerRegFile<u32>>, |
| 656 |
/// live variables from before phi_dsts/branch |
| 657 |
live_out: Option<LiveSet>, |
| 658 |
|
| 659 |
instrs: Vec<Instr>, |
| 660 |
new_order: Option<InstructionOrder>, |
| 661 |
last_tried_schedule_type: Option<ScheduleType>, |
| 662 |
peak_gpr_count: i32, |
| 663 |
|
| 664 |
// Phis and branches aren't scheduled. Phis and par copies are the only |
| 665 |
// instructions that can take an arbitrary number of srs/dests and therefore |
| 666 |
// can overflow in net_live tracking. We simplify that accounting by not |
| 667 |
// handling these instructions there. |
| 668 |
phi_dsts: Option<Instr>, |
| 669 |
phi_srcs: Option<Instr>, |
| 670 |
branch: Option<Instr>, |
| 671 |
|
| 672 |
graph: Option<ScheduleUnitGraph>, |
| 673 |
} |
| 674 |
|
| 675 |
impl ScheduleUnit { |
| 676 |
fn schedule( |
| 677 |
&mut self, |
| 678 |
sm: &ShaderModelInfo, |
| 679 |
max_regs: PerRegFile<i32>, |
| 680 |
schedule_type: ScheduleType, |
| 681 |
thresholds: ScheduleThresholds, |
| 682 |
) { |
| 683 |
let graph = self |
| 684 |
.graph |
| 685 |
.get_or_insert_with(|| ScheduleUnitGraph::new(sm, &self.instrs)); |
| 686 |
|
| 687 |
self.last_tried_schedule_type = Some(schedule_type); |
| 688 |
let new_order = sched_buffer( |
| 689 |
max_regs, |
| 690 |
&self.instrs, |
| 691 |
graph, |
| 692 |
self.live_in_count.unwrap(), |
| 693 |
self.live_out.as_ref().unwrap(), |
| 694 |
thresholds, |
| 695 |
); |
| 696 |
|
| 697 |
if let Some(x) = new_order { |
| 698 |
self.new_order = Some(x); |
| 699 |
} |
| 700 |
} |
| 701 |
|
| 702 |
fn finish_block(&mut self, live_out: &LiveSet) { |
| 703 |
if self.live_out.is_none() { |
| 704 |
self.live_out = Some(live_out.clone()); |
| 705 |
} |
| 706 |
} |
| 707 |
|
| 708 |
fn to_instrs(self) -> Vec<Instr> { |
| 709 |
let mut instrs = Vec::new(); |
| 710 |
instrs.extend(self.phi_dsts); |
| 711 |
match self.new_order { |
| 712 |
Some(order) => instrs.extend(order.apply(self.instrs)), |
| 713 |
None => instrs.extend(self.instrs.into_iter()), |
| 714 |
} |
| 715 |
instrs.extend(self.phi_srcs); |
| 716 |
instrs.extend(self.branch); |
| 717 |
instrs |
| 718 |
} |
| 719 |
} |
| 720 |
|
| 721 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 722 |
enum ScheduleType { |
| 723 |
RegLimit(u8), |
| 724 |
Spill, |
| 725 |
} |
| 726 |
|
| 727 |
impl ScheduleType { |
| 728 |
fn thresholds( |
| 729 |
&self, |
| 730 |
max_regs: PerRegFile<i32>, |
| 731 |
schedule_unit: &ScheduleUnit, |
| 732 |
) -> ScheduleThresholds { |
| 733 |
match self { |
| 734 |
ScheduleType::RegLimit(gpr_target) => ScheduleThresholds { |
| 735 |
heuristic_threshold: i32::from(*gpr_target) - TARGET_FREE, |
| 736 |
quit_threshold: i32::from(*gpr_target), |
| 737 |
}, |
| 738 |
ScheduleType::Spill => ScheduleThresholds { |
| 739 |
heuristic_threshold: max_regs[RegFile::GPR] |
| 740 |
- SW_RESERVED_GPRS_SPILL |
| 741 |
- TARGET_FREE, |
| 742 |
quit_threshold: schedule_unit.peak_gpr_count, |
| 743 |
}, |
| 744 |
} |
| 745 |
} |
| 746 |
} |
| 747 |
|
| 748 |
fn get_schedule_types( |
| 749 |
sm: &ShaderModelInfo, |
| 750 |
max_regs: PerRegFile<i32>, |
| 751 |
min_gpr_target: i32, |
| 752 |
max_gpr_target: i32, |
| 753 |
reserved_gprs: i32, |
| 754 |
) -> Vec<ScheduleType> { |
| 755 |
let mut out = Vec::new(); |
| 756 |
|
| 757 |
let mut gpr_target = |
| 758 |
next_occupancy_cliff_with_reserved(sm, min_gpr_target, reserved_gprs); |
| 759 |
while gpr_target < max_regs[RegFile::GPR] { |
| 760 |
out.push(ScheduleType::RegLimit(gpr_target.try_into().unwrap())); |
| 761 |
|
| 762 |
// We want only 1 entry that's greater than or equal to the original |
| 763 |
// schedule (it can be greater in cases where increasing the number of |
| 764 |
// registers doesn't change occupancy) |
| 765 |
if gpr_target >= max_gpr_target { |
| 766 |
return out; |
| 767 |
} |
| 768 |
|
| 769 |
gpr_target = next_occupancy_cliff_with_reserved( |
| 770 |
sm, |
| 771 |
gpr_target + 1, |
| 772 |
reserved_gprs, |
| 773 |
); |
| 774 |
} |
| 775 |
|
| 776 |
assert!(gpr_target >= max_regs[RegFile::GPR]); |
| 777 |
out.push(ScheduleType::RegLimit( |
| 778 |
(max_regs[RegFile::GPR] - SW_RESERVED_GPRS) |
| 779 |
.try_into() |
| 780 |
.unwrap(), |
| 781 |
)); |
| 782 |
|
| 783 |
// Only allow spilling if the original schedule spilled |
| 784 |
if max_gpr_target > max_regs[RegFile::GPR] { |
| 785 |
out.push(ScheduleType::Spill); |
| 786 |
} |
| 787 |
return out; |
| 788 |
} |
| 789 |
|
| 790 |
impl Function { |
| 791 |
pub fn opt_instr_sched_prepass( |
| 792 |
&mut self, |
| 793 |
sm: &ShaderModelInfo, |
| 794 |
max_regs: PerRegFile<i32>, |
| 795 |
) { |
| 796 |
let liveness = SimpleLiveness::for_function(self); |
| 797 |
let mut live_out_sets: Vec<LiveSet> = Vec::new(); |
| 798 |
|
| 799 |
#[cfg(debug_assertions)] |
| 800 |
let orig_instr_counts: Vec<usize> = |
| 801 |
self.blocks.iter().map(|b| b.instrs.len()).collect(); |
| 802 |
|
| 803 |
let reserved_gprs = SW_RESERVED_GPRS + (sm.hw_reserved_gprs() as i32); |
| 804 |
|
| 805 |
// First pass: Set up data structures and gather some statistics about |
| 806 |
// register pressure |
| 807 |
|
| 808 |
// lower and upper bounds for how many gprs we will use |
| 809 |
let mut min_gpr_target = 1; |
| 810 |
let mut max_gpr_target = 1; |
| 811 |
|
| 812 |
let mut schedule_units = Vec::new(); |
| 813 |
|
| 814 |
for block_idx in 0..self.blocks.len() { |
| 815 |
let block_live = liveness.block_live(block_idx); |
| 816 |
let mut live_set = match self.blocks.pred_indices(block_idx) { |
| 817 |
[] => LiveSet::new(), |
| 818 |
[pred, ..] => LiveSet::from_iter( |
| 819 |
live_out_sets[*pred] |
| 820 |
.iter() |
| 821 |
.filter(|ssa| block_live.is_live_in(ssa)) |
| 822 |
.cloned(), |
| 823 |
), |
| 824 |
}; |
| 825 |
|
| 826 |
let block = &mut self.blocks[block_idx]; |
| 827 |
let mut unit: ScheduleUnit = Default::default(); |
| 828 |
|
| 829 |
for (ip, instr) in |
| 830 |
std::mem::take(&mut block.instrs).into_iter().enumerate() |
| 831 |
{ |
| 832 |
let starts_block = match instr.op { |
| 833 |
Op::PhiDsts(_) => true, |
| 834 |
_ => false, |
| 835 |
}; |
| 836 |
let ends_block = match instr.op { |
| 837 |
Op::PhiSrcs(_) => true, |
| 838 |
_ => instr.op.is_branch(), |
| 839 |
}; |
| 840 |
|
| 841 |
// First use the live set before the instr |
| 842 |
if !starts_block && unit.live_in_count == None { |
| 843 |
unit.live_in_count = |
| 844 |
Some(PerRegFile::new_with(|f| live_set.count(f))); |
| 845 |
} |
| 846 |
if ends_block { |
| 847 |
unit.finish_block(&live_set); |
| 848 |
} |
| 849 |
|
| 850 |
// Update the live set |
| 851 |
let live_count = |
| 852 |
live_set.insert_instr_top_down(ip, &instr, block_live); |
| 853 |
|
| 854 |
// Now use the live set after the instruction |
| 855 |
{ |
| 856 |
let live_count = PerRegFile::new_with(|f| { |
| 857 |
live_count[f].try_into().unwrap() |
| 858 |
}); |
| 859 |
let mut used_gprs = calc_used_gprs(live_count, max_regs); |
| 860 |
|
| 861 |
if let Op::RegOut(reg_out) = &instr.op { |
| 862 |
// This should be the last instruction. Everything should |
| 863 |
// be dead once we've processed it. |
| 864 |
assert_eq!(live_set.count(RegFile::GPR), 0); |
| 865 |
let num_gprs_out = |
| 866 |
reg_out.srcs.len().try_into().unwrap(); |
| 867 |
used_gprs = max(used_gprs, num_gprs_out); |
| 868 |
} |
| 869 |
|
| 870 |
// We never want our target to be worse than the original schedule |
| 871 |
max_gpr_target = max(max_gpr_target, used_gprs); |
| 872 |
|
| 873 |
if side_effect_type(&instr.op) == SideEffect::Barrier { |
| 874 |
// If we can't reorder an instruction, then it forms a lower |
| 875 |
// bound on how well we can do after rescheduling |
| 876 |
min_gpr_target = max(min_gpr_target, used_gprs); |
| 877 |
} |
| 878 |
|
| 879 |
if !starts_block && !ends_block { |
| 880 |
unit.peak_gpr_count = |
| 881 |
max(unit.peak_gpr_count, used_gprs); |
| 882 |
} |
| 883 |
} |
| 884 |
|
| 885 |
match instr.op { |
| 886 |
Op::PhiDsts(_) => { |
| 887 |
unit.phi_dsts = Some(instr); |
| 888 |
} |
| 889 |
Op::PhiSrcs(_) => { |
| 890 |
unit.phi_srcs = Some(instr); |
| 891 |
} |
| 892 |
_ => { |
| 893 |
if instr.op.is_branch() { |
| 894 |
unit.branch = Some(instr); |
| 895 |
} else { |
| 896 |
assert!(unit.live_out.is_none()); |
| 897 |
unit.instrs.push(instr); |
| 898 |
} |
| 899 |
} |
| 900 |
}; |
| 901 |
} |
| 902 |
unit.finish_block(&live_set); |
| 903 |
schedule_units.push(unit); |
| 904 |
|
| 905 |
live_out_sets.push(live_set); |
| 906 |
} |
| 907 |
|
| 908 |
// Second pass: Generate a schedule for each schedule_unit |
| 909 |
let mut schedule_types = get_schedule_types( |
| 910 |
sm, |
| 911 |
max_regs, |
| 912 |
min_gpr_target, |
| 913 |
max_gpr_target, |
| 914 |
reserved_gprs, |
| 915 |
); |
| 916 |
schedule_types.reverse(); |
| 917 |
|
| 918 |
for u in schedule_units.iter_mut() { |
| 919 |
if u.instrs.is_empty() { |
| 920 |
continue; |
| 921 |
} |
| 922 |
loop { |
| 923 |
let schedule_type = *schedule_types.last().unwrap(); |
| 924 |
let thresholds = schedule_type.thresholds(max_regs, u); |
| 925 |
|
| 926 |
u.schedule(sm, max_regs, schedule_type, thresholds); |
| 927 |
|
| 928 |
if u.new_order.is_some() { |
| 929 |
// Success! |
| 930 |
break; |
| 931 |
} |
| 932 |
|
| 933 |
if schedule_types.len() > 1 { |
| 934 |
// We've failed to schedule using the existing settings, so |
| 935 |
// switch to the next schedule type, which will have more |
| 936 |
// gprs |
| 937 |
schedule_types.pop(); |
| 938 |
} else { |
| 939 |
// No other schedule types to try - this implies that the |
| 940 |
// original program has a better instruction order than what |
| 941 |
// our heuristics can generate. Just keep the original |
| 942 |
// instruction order |
| 943 |
break; |
| 944 |
} |
| 945 |
} |
| 946 |
} |
| 947 |
|
| 948 |
// Third pass: Apply the generated schedules |
| 949 |
let schedule_type = schedule_types.into_iter().last().unwrap(); |
| 950 |
|
| 951 |
for (mut u, block) in |
| 952 |
schedule_units.into_iter().zip(self.blocks.iter_mut()) |
| 953 |
{ |
| 954 |
// If the global register limit has increased, then we can schedule |
| 955 |
// again with the new parameters |
| 956 |
if !u.instrs.is_empty() |
| 957 |
&& u.last_tried_schedule_type != Some(schedule_type) |
| 958 |
{ |
| 959 |
let thresholds = schedule_type.thresholds(max_regs, &u); |
| 960 |
u.schedule(sm, max_regs, schedule_type, thresholds); |
| 961 |
} |
| 962 |
|
| 963 |
block.instrs = u.to_instrs(); |
| 964 |
} |
| 965 |
|
| 966 |
#[cfg(debug_assertions)] |
| 967 |
debug_assert_eq!( |
| 968 |
orig_instr_counts, |
| 969 |
self.blocks |
| 970 |
.iter() |
| 971 |
.map(|b| b.instrs.len()) |
| 972 |
.collect::<Vec<usize>>() |
| 973 |
); |
| 974 |
|
| 975 |
if let ScheduleType::RegLimit(limit) = schedule_type { |
| 976 |
// Our liveness calculations should ideally agree with SimpleLiveness |
| 977 |
debug_assert!( |
| 978 |
{ |
| 979 |
let live = SimpleLiveness::for_function(self); |
| 980 |
let max_live = live.calc_max_live(self); |
| 981 |
max_live[RegFile::GPR] |
| 982 |
} <= limit.into() |
| 983 |
); |
| 984 |
} |
| 985 |
} |
| 986 |
} |
| 987 |
|
| 988 |
impl Shader<'_> { |
| 989 |
/// Pre-RA instruction scheduling |
| 990 |
/// |
| 991 |
/// We prioritize: |
| 992 |
/// 1. Occupancy |
| 993 |
/// 2. Preventing spills to memory |
| 994 |
/// 3. Instruction level parallelism |
| 995 |
/// |
| 996 |
/// We accomplish this by having an outer loop that tries different register |
| 997 |
/// limits in order of most to least occupancy. The inner loop computes |
| 998 |
/// actual schedules using a heuristic inspired by Goodman & Hsu 1988 |
| 999 |
/// section 3, although the heuristic from that paper cannot be used |
| 1000 |
/// directly here because they assume a single register file and we have |
| 1001 |
/// multiple. Care is also taken to model quirks of register pressure on |
| 1002 |
/// NVIDIA GPUs corretly. |
| 1003 |
/// |
| 1004 |
/// J. R. Goodman and W.-C. Hsu. 1988. Code scheduling and register |
| 1005 |
/// allocation in large basic blocks. In Proceedings of the 2nd |
| 1006 |
/// international conference on Supercomputing (ICS '88). Association |
| 1007 |
/// for Computing Machinery, New York, NY, USA, 442–452. |
| 1008 |
/// https://doi.org/10.1145/55364.55407 |
| 1009 |
pub fn opt_instr_sched_prepass(&mut self) { |
| 1010 |
if DEBUG.annotate() { |
| 1011 |
self.remove_annotations(); |
| 1012 |
} |
| 1013 |
|
| 1014 |
let mut max_regs = PerRegFile::<i32>::new_with(|f| { |
| 1015 |
self.sm.num_regs(f).try_into().unwrap() |
| 1016 |
}); |
| 1017 |
if let ShaderStageInfo::Compute(cs_info) = &self.info.stage { |
| 1018 |
max_regs[RegFile::GPR] = min( |
| 1019 |
max_regs[RegFile::GPR], |
| 1020 |
(gpr_limit_from_local_size(&cs_info.local_size) |
| 1021 |
- self.sm.hw_reserved_gprs()) |
| 1022 |
.try_into() |
| 1023 |
.unwrap(), |
| 1024 |
); |
| 1025 |
} |
| 1026 |
max_regs[RegFile::GPR] -= SW_RESERVED_GPRS; |
| 1027 |
|
| 1028 |
for f in &mut self.functions { |
| 1029 |
f.opt_instr_sched_prepass(self.sm, max_regs); |
| 1030 |
} |
| 1031 |
} |
| 1032 |
} |