mirror of
https://github.com/ivall/xcl.git
synced 2026-11-24 05:14:57 +01:00
Merge pull request #113 from Foniass/t3/faster-shader-compile
This commit is contained in:
@@ -116,9 +116,19 @@ struct Job {
|
||||
reply: std::sync::mpsc::Sender<Result<Vec<u8>, String>>,
|
||||
}
|
||||
|
||||
/// Compile threads at most: big translated programs take gigabytes each in DXC and the driver,
|
||||
/// and a title compiles hundreds at once – the machine must not run out of memory.
|
||||
pub const MAX_COMPILE_THREADS: usize = 6;
|
||||
/// Compile threads (DXC workers, and the PSO workers of `pso_async` that feed them): every core
|
||||
/// but one, `XCL_DXC_THREADS` to choose. Memory is what `wait_for_memory` watches: a retail
|
||||
/// pack's biggest translations take ~0.7 GB in DXC (a typical one 0.1–0.3 GB). The cap used
|
||||
/// to be 6, which left most of a 16-thread CPU idle while a title with ~24 000 shaders
|
||||
/// compiled for half an hour. (Normal priority: a title thread can wait for a pipeline –
|
||||
/// `resolve_wait`, a compute pipeline's first bind – and must not wait behind its own threads.)
|
||||
pub fn compile_threads() -> usize {
|
||||
static N: OnceLock<usize> = OnceLock::new();
|
||||
*N.get_or_init(|| {
|
||||
let cores = std::thread::available_parallelism().map_or(4, |n| n.get());
|
||||
std::env::var("XCL_DXC_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(cores.saturating_sub(1)).clamp(1, 64)
|
||||
})
|
||||
}
|
||||
|
||||
/// Compiles running on the DXC workers (`wait_for_memory` lets them in).
|
||||
static WORKING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
@@ -132,7 +142,8 @@ impl Drop for MemorySlot {
|
||||
}
|
||||
}
|
||||
|
||||
/// Before a compile: with 6 GB of commit left or more, at once; with less, one compile at a
|
||||
/// Before a compile: with 6 GB of commit left or more, plus 1 GB for every compile already
|
||||
/// running (each can still grow to ~0.7 GB), at once; with less, one compile at a
|
||||
/// time – it goes when no other is running (and after a minute in any case). Each compile used
|
||||
/// to wait the minute while commit was short: with XDefiant's own 10 GB committed, 4 GB were
|
||||
/// left, and its last cold-cache shaders came a few a minute.
|
||||
@@ -143,7 +154,8 @@ pub fn wait_for_memory() -> MemorySlot {
|
||||
loop {
|
||||
let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() };
|
||||
m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32;
|
||||
let plenty = unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= 6 << 30;
|
||||
let need = (6u64 << 30) + ((WORKING.load(Ordering::Acquire) as u64) << 30);
|
||||
let plenty = unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= need;
|
||||
if plenty || start.elapsed().as_secs() >= 60 {
|
||||
WORKING.fetch_add(1, Ordering::AcqRel);
|
||||
return MemorySlot;
|
||||
@@ -155,14 +167,14 @@ pub fn wait_for_memory() -> MemorySlot {
|
||||
}
|
||||
}
|
||||
|
||||
/// DXC workers (one per core, at most `MAX_COMPILE_THREADS`, each with its own compiler and a
|
||||
/// `DXC_STACK` stack), started on first use; callers wait for their job.
|
||||
/// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started
|
||||
/// on first use; callers wait for their job.
|
||||
fn pool() -> &'static std::sync::Mutex<std::sync::mpsc::Sender<Job>> {
|
||||
static POOL: OnceLock<std::sync::Mutex<std::sync::mpsc::Sender<Job>>> = OnceLock::new();
|
||||
POOL.get_or_init(|| {
|
||||
let (tx, rx) = std::sync::mpsc::channel::<Job>();
|
||||
let rx = std::sync::Arc::new(std::sync::Mutex::new(rx));
|
||||
for k in 0..std::thread::available_parallelism().map_or(4, |n| n.get()).min(MAX_COMPILE_THREADS) {
|
||||
for k in 0..compile_threads() {
|
||||
let rx = rx.clone();
|
||||
let _ = std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || loop {
|
||||
let job = match rx.lock().unwrap().recv() {
|
||||
|
||||
@@ -179,8 +179,8 @@ fn dpp16_src(ctrl: u64) -> Option<String> {
|
||||
let n = ctrl & 15;
|
||||
Some(match ctrl {
|
||||
0x000..=0x0FF => format!("(int)((lane_id & ~3u) | (({ctrl}u >> (2u * (lane_id & 3u))) & 3u))"),
|
||||
0x101..=0x10F => format!("(((lane_id & 15u) + {n}u < 16u) ? (int)(lane_id + {n}u) : -1)"),
|
||||
0x111..=0x11F => format!("(((lane_id & 15u) >= {n}u) ? (int)(lane_id - {n}u) : -1)"),
|
||||
0x101..=0x10F => format!("select((lane_id & 15u) + {n}u < 16u, (int)(lane_id + {n}u), -1)"),
|
||||
0x111..=0x11F => format!("select((lane_id & 15u) >= {n}u, (int)(lane_id - {n}u), -1)"),
|
||||
0x121..=0x12F => format!("(int)((lane_id & ~15u) | (((lane_id & 15u) - {n}u) & 15u))"),
|
||||
0x140 => "(int)((lane_id & ~15u) | (15u - (lane_id & 15u)))".into(),
|
||||
0x141 => "(int)((lane_id & ~15u) | (lane_id & 8u) | (7u - (lane_id & 7u)))".into(),
|
||||
@@ -1020,7 +1020,7 @@ impl Em {
|
||||
let dst = Dst::S(sd);
|
||||
match name {
|
||||
"s_movk_i32" => self.write32(&dst, &hex(k_s)),
|
||||
"s_cmovk_i32" => self.write32(&dst, &format!("(scc != 0u) ? {} : {cur}", hex(k_s))),
|
||||
"s_cmovk_i32" => self.write32(&dst, &format!("select(scc != 0u, {}, {cur})", hex(k_s))),
|
||||
"s_addk_i32" => {
|
||||
let t = self.t();
|
||||
self.line(&format!("uint {t} = {cur} + {};", hex(k_s)));
|
||||
@@ -1165,7 +1165,7 @@ impl Em {
|
||||
Dst::S(n) => self.sreg(*n),
|
||||
_ => "0u".into(),
|
||||
};
|
||||
(format!("(scc != 0u) ? {a} : {cur}"), None)
|
||||
(format!("select(scc != 0u, {a}, {cur})"), None)
|
||||
}
|
||||
"s_not_b32" => (format!("~{a}"), Some(format!("{t} != 0u"))),
|
||||
"s_brev_b32" => (format!("reversebits({a})"), None),
|
||||
@@ -1209,7 +1209,7 @@ impl Em {
|
||||
"s_max_u32" => (format!("max({a}, {b})"), Some(format!("{a} > {b}"))),
|
||||
"s_min_i32" => (format!("(uint)min((int){a}, (int){b})"), Some(format!("(int){a} < (int){b}"))),
|
||||
"s_max_i32" => (format!("(uint)max((int){a}, (int){b})"), Some(format!("(int){a} > (int){b}"))),
|
||||
"s_cselect_b32" => (format!("(scc != 0u) ? {a} : {b}"), None),
|
||||
"s_cselect_b32" => (format!("select(scc != 0u, {a}, {b})"), None),
|
||||
"s_wqm_b32" => (format!("wqm({a})"), Some(format!("{t} != 0u"))),
|
||||
"s_bitset0_b32" | "s_bitset1_b32" => {
|
||||
let cur = match &dst {
|
||||
@@ -1327,22 +1327,22 @@ impl Em {
|
||||
Dst::S(n) => (self.sreg(*n), self.sreg(*n + 1)),
|
||||
_ => ("0u".into(), "0u".into()),
|
||||
};
|
||||
(format!("(scc != 0u) ? {al} : {}", cur.0), format!("(scc != 0u) ? {ah} : {}", cur.1), None)
|
||||
(format!("select(scc != 0u, {al}, {})", cur.0), format!("select(scc != 0u, {ah}, {})", cur.1), None)
|
||||
}
|
||||
"s_not_b64" => (format!("~{al}"), format!("~{ah}"), Some(nz.clone())),
|
||||
"s_cselect_b64" => (format!("(scc != 0u) ? {al} : {bl}"), format!("(scc != 0u) ? {ah} : {bh}"), None),
|
||||
"s_cselect_b64" => (format!("select(scc != 0u, {al}, {bl})"), format!("select(scc != 0u, {ah}, {bh})"), None),
|
||||
"s_wqm_b64" => (format!("wqm({al})"), format!("wqm({ah})"), Some(nz.clone())),
|
||||
"s_brev_b64" => (format!("reversebits({ah})"), format!("reversebits({al})"), None),
|
||||
"s_bcnt1_i32_b64" => (format!("countbits({al}) + countbits({ah})"), "0u".into(), Some(format!("{t0} != 0u"))),
|
||||
"s_bcnt0_i32_b64" => (format!("64u - countbits({al}) - countbits({ah})"), "0u".into(), Some(format!("{t0} != 0u"))),
|
||||
"s_ff1_i32_b64" => {
|
||||
(format!("({al} != 0u) ? firstbitlow({al}) : (({ah} != 0u) ? 32u + firstbitlow({ah}) : 0xFFFFFFFFu)"), "0u".into(), None)
|
||||
(format!("select({al} != 0u, firstbitlow({al}), select({ah} != 0u, 32u + firstbitlow({ah}), 0xFFFFFFFFu))"), "0u".into(), None)
|
||||
}
|
||||
"s_ff0_i32_b64" => {
|
||||
(format!("(~{al} != 0u) ? firstbitlow(~{al}) : ((~{ah} != 0u) ? 32u + firstbitlow(~{ah}) : 0xFFFFFFFFu)"), "0u".into(), None)
|
||||
(format!("select(~{al} != 0u, firstbitlow(~{al}), select(~{ah} != 0u, 32u + firstbitlow(~{ah}), 0xFFFFFFFFu))"), "0u".into(), None)
|
||||
}
|
||||
"s_flbit_i32_b64" => (
|
||||
format!("({ah} != 0u) ? 31u - firstbithigh({ah}) : (({al} != 0u) ? 63u - firstbithigh({al}) : 0xFFFFFFFFu)"),
|
||||
format!("select({ah} != 0u, 31u - firstbithigh({ah}), select({al} != 0u, 63u - firstbithigh({al}), 0xFFFFFFFFu))"),
|
||||
"0u".into(),
|
||||
None,
|
||||
),
|
||||
@@ -1351,7 +1351,7 @@ impl Em {
|
||||
let (nl, nh) = (self.t(), self.t());
|
||||
self.line(&format!("uint {nl} = select((int){ah} < 0, ~{al}, {al}); uint {nh} = select((int){ah} < 0, ~{ah}, {ah});"));
|
||||
(
|
||||
format!("({nh} != 0u) ? 31u - firstbithigh({nh}) : (({nl} != 0u) ? 63u - firstbithigh({nl}) : 0xFFFFFFFFu)"),
|
||||
format!("select({nh} != 0u, 31u - firstbithigh({nh}), select({nl} != 0u, 63u - firstbithigh({nl}), 0xFFFFFFFFu))"),
|
||||
"0u".into(),
|
||||
None,
|
||||
)
|
||||
@@ -1423,7 +1423,7 @@ impl Em {
|
||||
self.line(&format!("{lo} = 0u; {hi} = 0u;"));
|
||||
return Ok(());
|
||||
}
|
||||
let count = match name.trim_start_matches("s_buffer_load_").trim_start_matches("s_load_") {
|
||||
let count: usize = match name.trim_start_matches("s_buffer_load_").trim_start_matches("s_load_") {
|
||||
"dword" => 1,
|
||||
"dwordx2" => 2,
|
||||
"dwordx4" => 4,
|
||||
@@ -1443,22 +1443,48 @@ impl Em {
|
||||
let (d0, d1, d2) = (self.sreg(sbase), self.sreg(sbase + 1), self.sreg(sbase + 2));
|
||||
self.window(&d1);
|
||||
self.line(&format!("uint {t}_off = {} + {soff};", hex(imm)));
|
||||
self.line(&format!("uint {t}_lim = ((({d1} >> 16) & 0x3FFFu) == 0u) ? {d2} : {d2} * (({d1} >> 16) & 0x3FFFu);"));
|
||||
for i in 0..count {
|
||||
let v = format!("{t}_{i}");
|
||||
self.line(&format!("uint {v} = ({t}_off + {}u < {t}_lim) ? mem.Load(({d0} + {t}_off + {}u) & ~3u) : 0u;", 4 * i, 4 * i));
|
||||
vals.push(v);
|
||||
self.line(&format!("uint {t}_st = ({d1} >> 16) & 0x3FFFu;"));
|
||||
self.line(&format!("uint {t}_lim = select({t}_st == 0u, {d2}, {d2} * {t}_st);"));
|
||||
self.line(&format!("uint {t}_a = ({d0} + {t}_off) & ~3u;"));
|
||||
// Branch-free: a dword past num_records reads offset 0 (always in the window) and
|
||||
// comes out 0. HLSL 2021's `?:` is a branch, and with several memory windows every
|
||||
// access is a switch between them (`windowed`): one per dword made DXC several
|
||||
// times slower on big programs. Four dwords share one switch (`xcl_loadx4`).
|
||||
if count == 1 {
|
||||
self.line(&format!("bool {t}_in = {t}_off < {t}_lim;"));
|
||||
self.line(&format!("uint {t}_0 = select({t}_in, mem.Load(select({t}_in, {t}_a, 0u)), 0u);"));
|
||||
vals.push(format!("{t}_0"));
|
||||
} else {
|
||||
for g in 0..count.div_ceil(4) {
|
||||
let n = (count - 4 * g).min(4);
|
||||
let o = (0..4).map(|k| format!("{}u", 16 * g + 4 * k.min(n - 1))).collect::<Vec<_>>().join(", ");
|
||||
self.line(&format!("bool4 {t}_in{g} = {t}_off + uint4({o}) < {t}_lim;"));
|
||||
self.line(&format!("uint4 {t}_g{g} = select({t}_in{g}, xcl_loadx4(select({t}_in{g}, {t}_a + uint4({o}), 0u)), 0u);"));
|
||||
vals.extend(["x", "y", "z", "w"][..n].iter().map(|c| format!("{t}_g{g}.{c}")));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let imm = ((imm << 11) as i32 >> 11) as u32; // 21-bit signed
|
||||
let b = self.sreg(sbase);
|
||||
let hi = self.sreg(sbase + 1);
|
||||
self.window(&hi);
|
||||
self.line(&format!("uint {t}_a = {b} + {} + {soff};", hex(imm)));
|
||||
for i in 0..count {
|
||||
let v = format!("{t}_{i}");
|
||||
self.line(&format!("uint {v} = mem.Load(({t}_a + {}u) & ~3u);", 4 * i));
|
||||
vals.push(v);
|
||||
// the dwords are contiguous: Load2 / Load4 (one window switch per four dwords)
|
||||
self.line(&format!("uint {t}_a = ({b} + {} + {soff}) & ~3u;", hex(imm)));
|
||||
match count {
|
||||
1 => {
|
||||
self.line(&format!("uint {t}_0 = mem.Load({t}_a);"));
|
||||
vals.push(format!("{t}_0"));
|
||||
}
|
||||
2 => {
|
||||
self.line(&format!("uint2 {t}_g0 = mem.Load2({t}_a);"));
|
||||
vals.extend([format!("{t}_g0.x"), format!("{t}_g0.y")]);
|
||||
}
|
||||
_ => {
|
||||
for g in 0..count / 4 {
|
||||
self.line(&format!("uint4 {t}_g{g} = mem.Load4({t}_a + {}u);", 16 * g));
|
||||
vals.extend(["x", "y", "z", "w"].iter().map(|c| format!("{t}_g{g}.{c}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// split wave64, a coherent load (GLC / DLC: memory other waves may be writing): both
|
||||
@@ -1570,13 +1596,26 @@ impl Em {
|
||||
}
|
||||
match kind {
|
||||
BufKind::Load => {
|
||||
let mut assigns = Vec::new();
|
||||
for i in 0..count {
|
||||
let ok = in_range(format!("{}u", 4 * i + 4));
|
||||
let v = self.vreg(vdata + i);
|
||||
assigns.push(format!("{v} = {ok} ? mem.Load(({t}_a + {}u) & ~3u) : 0u;", 4 * i));
|
||||
// branch-free (see `smem`): a lane that is inactive or out of range reads offset
|
||||
// 0 and keeps its register / gets 0; one window switch per four dwords
|
||||
self.line(&format!("bool {t}_act = {act};"));
|
||||
if count == 1 {
|
||||
let ok = in_range("4u".into());
|
||||
let v = self.vreg(vdata);
|
||||
self.line(&format!("bool {t}_ok = {ok};"));
|
||||
self.line(&format!("uint {t}_v = mem.Load(select(and({t}_act, {t}_ok), {t}_a & ~3u, 0u));"));
|
||||
self.line(&format!("{v} = select({t}_act, select({t}_ok, {t}_v, 0u), {v});"));
|
||||
} else {
|
||||
let oks: Vec<String> = (0..4).map(|i| in_range(format!("{}u", 4 * i.min(count - 1) + 4))).collect();
|
||||
let o = (0..4).map(|i| format!("{}u", 4 * i.min(count - 1))).collect::<Vec<_>>().join(", ");
|
||||
self.line(&format!("bool4 {t}_ok = bool4({});", oks.join(", ")));
|
||||
self.line(&format!("uint4 {t}_v = xcl_loadx4(select(and({t}_act, {t}_ok), ({t}_a & ~3u) + uint4({o}), 0u));"));
|
||||
for i in 0..count {
|
||||
let v = self.vreg(vdata + i);
|
||||
let c = ["x", "y", "z", "w"][i as usize];
|
||||
self.line(&format!("{v} = select({t}_act, select({t}_ok.{c}, {t}_v.{c}, 0u), {v});"));
|
||||
}
|
||||
}
|
||||
self.line(&format!("if ({act}) {{ {} }}", assigns.join(" ")));
|
||||
}
|
||||
BufKind::Store => {
|
||||
let mut st = Vec::new();
|
||||
@@ -1825,7 +1864,7 @@ impl Em {
|
||||
"v_interp_p2_f32" => {
|
||||
let v = self.vreg(vdst);
|
||||
// (float): the value of an int / uint input, not its bits (see v_interp_mov_f32)
|
||||
self.line(&format!("if ({act}) {v} = asuint((float){src});"));
|
||||
self.line(&format!("{v} = select({act}, asuint((float){src}), {v});"));
|
||||
}
|
||||
"v_interp_mov_f32" => {
|
||||
if ij != 2 {
|
||||
@@ -1838,14 +1877,14 @@ impl Em {
|
||||
// nothing, with the converted value (never 1 or 2) it draws the text (red; whether
|
||||
// the console's is another colour is not known). Open: why those branches draw
|
||||
// nothing (they sample the font with gradients from ds_swizzle derivatives).
|
||||
self.line(&format!("if ({act}) {v} = asuint((float){src});"));
|
||||
self.line(&format!("{v} = select({act}, asuint((float){src}), {v});"));
|
||||
}
|
||||
"v_interp_p2_f16" => {
|
||||
let v = self.vreg(vdst);
|
||||
let hi = rdna2::field_value(d.enc, &d.words, "OP_SEL").unwrap_or(0) >> 3 & 1 == 1;
|
||||
let h = to_f16_expr(self.dynamic_f16_rm, &format!("(float){src}"));
|
||||
let e = if hi { format!("({v} & 0xFFFFu) | ({h} << 16)") } else { format!("({v} & 0xFFFF0000u) | {h}") };
|
||||
self.line(&format!("if ({act}) {v} = {e};"));
|
||||
self.line(&format!("{v} = select({act}, {e}, {v});"));
|
||||
}
|
||||
_ => return Err("interpolation"),
|
||||
}
|
||||
@@ -2011,21 +2050,23 @@ impl Em {
|
||||
let comps: Vec<u64> = (0..4).filter(|c| dmask >> c & 1 == 1).collect();
|
||||
// write the selected result components (`r` is a uint4 of raw bits); D16 packs halves
|
||||
let write_result = |s: &mut Self, r: &str, n: usize, sel: &dyn Fn(usize) -> u64, half: &dyn Fn(&str) -> String| {
|
||||
let mut st = Vec::new();
|
||||
// selects, not `if (act)`: a branch per image instruction is work for DXC on big
|
||||
// programs, and the result is computed for every lane anyway
|
||||
let a = format!("{r}_act");
|
||||
s.line(&format!("bool {a} = {act};"));
|
||||
if d16 {
|
||||
for k in (0..n).step_by(2) {
|
||||
let v = s.vreg(vdata + k as u64 / 2);
|
||||
let lo = half(&format!("{r}.{}", ["x", "y", "z", "w"][sel(k) as usize]));
|
||||
let hi = if k + 1 < n { half(&format!("{r}.{}", ["x", "y", "z", "w"][sel(k + 1) as usize])) } else { "0u".into() };
|
||||
st.push(format!("{v} = ({lo} & 0xFFFFu) | ({hi} << 16);"));
|
||||
s.line(&format!("{v} = select({a}, ({lo} & 0xFFFFu) | ({hi} << 16), {v});"));
|
||||
}
|
||||
} else {
|
||||
for k in 0..n {
|
||||
let v = s.vreg(vdata + k as u64);
|
||||
st.push(format!("{v} = {r}.{};", ["x", "y", "z", "w"][sel(k) as usize]));
|
||||
s.line(&format!("{v} = select({a}, {r}.{}, {v});", ["x", "y", "z", "w"][sel(k) as usize]));
|
||||
}
|
||||
}
|
||||
s.line(&format!("if ({act}) {{ {} }}", st.join(" ")));
|
||||
};
|
||||
let f16 = |e: &str| format!("f32tof16(asfloat({e}))");
|
||||
|
||||
@@ -3138,7 +3179,7 @@ impl Em {
|
||||
"v_bfe_u32" => format!("bfe_u({a}, {b}, {c})"),
|
||||
"v_bfe_i32" => format!("(uint)bfe_i({a}, {b}, {c})"),
|
||||
"v_bfi_b32" => format!("({a} & {b}) | (~{a} & {c})"),
|
||||
"v_bfm_b32" => format!("((({a} & 31u) == 0u) ? 0u : (0xFFFFFFFFu >> (32u - ({a} & 31u)))) << ({b} & 31u)"),
|
||||
"v_bfm_b32" => format!("select(({a} & 31u) == 0u, 0u, 0xFFFFFFFFu >> (32u - ({a} & 31u))) << ({b} & 31u)"),
|
||||
"v_bcnt_u32_b32" => format!("countbits({a}) + {b}"),
|
||||
"v_perm_b32" => format!("perm_b32({a}, {b}, {c})"),
|
||||
"v_alignbit_b32" => format!("alignbit({a}, {b}, {c})"),
|
||||
@@ -3918,6 +3959,8 @@ impl Em {
|
||||
}
|
||||
h.push_str("static uint xcl_w = 0u;\n");
|
||||
h.push_str(MEM_ACCESSORS_HERE);
|
||||
} else {
|
||||
h.push_str(LOADX4_ONE_WINDOW);
|
||||
}
|
||||
for (i, (_, cmp)) in self.static_used.iter().enumerate() {
|
||||
let k = self.opt.static_sampler_base as usize + i;
|
||||
@@ -4662,6 +4705,10 @@ fn float_minmax_mem(min: bool, x2: bool, a: &str, v: &str, old: &str, t: &str) -
|
||||
/// Placeholder where the memory window accessors go (after the `mem` declarations).
|
||||
const MEM_ACCESSORS_HERE: &str = "//XCL_MEM_ACCESSORS\n";
|
||||
|
||||
/// Four dwords at four addresses (scalar buffer loads with their bounds checks); with several
|
||||
/// windows `mem_accessors` defines it, with one switch for all four.
|
||||
const LOADX4_ONE_WINDOW: &str = "uint4 xcl_loadx4(uint4 a) { return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }\n";
|
||||
|
||||
/// Several memory windows: every `mem.Method(` of the program (and of the preludes) becomes
|
||||
/// an accessor `xcl_mMethod(` that switches on `xcl_w` between `mem` and `mem1`.., whose
|
||||
/// definitions replace the placeholder.
|
||||
@@ -4712,6 +4759,11 @@ fn mem_accessors(windows: u32) -> String {
|
||||
}
|
||||
}
|
||||
let mut s = String::new();
|
||||
let _ = write!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] switch (xcl_w) {{ ");
|
||||
for k in 1..windows {
|
||||
let _ = write!(s, "case {k}u: return uint4(mem{k}.Load(a.x), mem{k}.Load(a.y), mem{k}.Load(a.z), mem{k}.Load(a.w)); ");
|
||||
}
|
||||
let _ = writeln!(s, "default: return uint4(mem.Load(a.x), mem.Load(a.y), mem.Load(a.z), mem.Load(a.w)); }} }}");
|
||||
for (ret, name, params, args) in sigs {
|
||||
let r = if ret == "void" { "" } else { "return " };
|
||||
let _ = write!(s, "{ret} xcl_m{name}({params}) {{ [branch] switch (xcl_w) {{ ");
|
||||
@@ -4802,10 +4854,11 @@ void scr_st(uint a, uint v, uint n) {
|
||||
|
||||
const PRELUDE_MEM: &str = r#"
|
||||
uint4 ld_raw(uint a) {
|
||||
// one Load4 + one Load (with several memory windows each is a switch) and no branch
|
||||
uint b = a & ~3u; uint s = (a & 3u) * 8u;
|
||||
uint w0 = mem.Load(b), w1 = mem.Load(b + 4u), w2 = mem.Load(b + 8u), w3 = mem.Load(b + 12u), w4 = mem.Load(b + 16u);
|
||||
if (s == 0u) return uint4(w0, w1, w2, w3);
|
||||
return uint4((w0 >> s) | (w1 << (32u - s)), (w1 >> s) | (w2 << (32u - s)), (w2 >> s) | (w3 << (32u - s)), (w3 >> s) | (w4 << (32u - s)));
|
||||
uint4 w = mem.Load4(b); uint w4 = mem.Load(b + 16u);
|
||||
uint4 n = uint4(w.yzw, w4);
|
||||
return select((s == 0u).xxxx, w, (w >> s) | (n << ((32u - s) & 31u)));
|
||||
}
|
||||
// format helpers: no loops, no branches (inlined at every buffer access; `?:` and `if`
|
||||
// on scalars become control flow in HLSL 2021, which DXC is slow to clean up)
|
||||
|
||||
@@ -1187,6 +1187,62 @@ fn gpu_memory_and_exports() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Multi-dword loads as the emitter groups them (four dwords per memory access, bounds checks
|
||||
/// without branches): an unaligned `s_load`, `s_buffer_load`s that straddle num_records, and
|
||||
/// vector buffer loads with lanes past the end and inactive lanes (which keep their registers).
|
||||
#[test]
|
||||
fn gpu_grouped_loads_bounds_and_inactive_lanes() {
|
||||
if !gpu_ready() {
|
||||
return;
|
||||
}
|
||||
let code = prog(&[
|
||||
("S_LOAD_DWORDX8", "ENC_SMEM", &[("SDATA", 16), ("SBASE", 0), ("OFFSET", 0x22), ("SOFFSET", 125)], None), // low bits ignored
|
||||
("S_BUFFER_LOAD_DWORDX8", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 2), ("OFFSET", 0), ("SOFFSET", 125)], None), // 5 of 8 in range
|
||||
("S_BUFFER_LOAD_DWORDX16", "ENC_SMEM", &[("SDATA", 32), ("SBASE", 4), ("OFFSET", 0), ("SOFFSET", 125)], None),
|
||||
("S_BUFFER_LOAD_DWORDX2", "ENC_SMEM", &[("SDATA", 48), ("SBASE", 2), ("OFFSET", 16), ("SOFFSET", 125)], None), // 1 of 2
|
||||
("V_CMPX_GT_U32", "ENC_VOPC", &[("SRC0", 128 + 48), ("VSRC1", 1)], None), // lanes 0..47
|
||||
("BUFFER_LOAD_DWORDX3", "ENC_MUBUF", &[("VDATA", 10), ("VADDR", 1), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None),
|
||||
("BUFFER_LOAD_DWORDX2", "ENC_MUBUF", &[("VDATA", 13), ("VADDR", 2), ("SRSRC", 13), ("SOFFSET", 128), ("OFFEN", 1)], None),
|
||||
]);
|
||||
let mut mem = vec![0u32; 1024];
|
||||
for (i, m) in mem.iter_mut().enumerate() {
|
||||
*m = 0x1000 + i as u32;
|
||||
}
|
||||
let mut st = KernelState::default();
|
||||
st.sgpr[0] = 0; // flat pointer 0
|
||||
st.sgpr[4..8].copy_from_slice(&[0x80, 0, 20, 0]); // V#: base 0x80, 20 bytes
|
||||
st.sgpr[8..12].copy_from_slice(&[0x100, 0, 0x100, 0]); // V#: base 0x100, 0x100 bytes
|
||||
st.sgpr[12..16].copy_from_slice(&[0x100, 12 << 16, 40, 0]); // V#: base 0x100, stride 12, 40 records
|
||||
st.sgpr[52..56].copy_from_slice(&[0x400, 0, 0x104, 0]); // V#: base 0x400, 0x104 bytes
|
||||
for (l, r) in st.vgpr.iter_mut().enumerate() {
|
||||
r[1] = l as u32;
|
||||
r[2] = 8 * l as u32;
|
||||
for k in 10..15 {
|
||||
r[k] = 0xDEAD;
|
||||
}
|
||||
}
|
||||
let r = runner::run_code(&code, &st, &mem).unwrap();
|
||||
for i in 0..8 {
|
||||
assert_eq!(r.sgpr[16 + i], 0x1008 + i as u32, "s_load_dwordx8 dword {i}");
|
||||
assert_eq!(r.sgpr[24 + i], if i < 5 { 0x1020 + i as u32 } else { 0 }, "s_buffer_load_dwordx8 dword {i}");
|
||||
}
|
||||
for i in 0..16 {
|
||||
assert_eq!(r.sgpr[32 + i], 0x1040 + i as u32, "s_buffer_load_dwordx16 dword {i}");
|
||||
}
|
||||
assert_eq!((r.sgpr[48], r.sgpr[49]), (0x1024, 0), "s_buffer_load_dwordx2 across num_records");
|
||||
for l in 0..64usize {
|
||||
for k in 0..3usize {
|
||||
let want = if l >= 48 { 0xDEAD } else if l < 40 { 0x1040 + 3 * l as u32 + k as u32 } else { 0 };
|
||||
assert_eq!(r.vgpr[l][10 + k], want, "lane {l} buffer_load_dwordx3 (idxen) dword {k}");
|
||||
}
|
||||
for k in 0..2usize {
|
||||
let off = 8 * l + 4 * k;
|
||||
let want = if l >= 48 { 0xDEAD } else if off + 4 <= 0x104 { 0x1100 + (off / 4) as u32 } else { 0 };
|
||||
assert_eq!(r.vgpr[l][13 + k], want, "lane {l} buffer_load_dwordx2 (offen) dword {k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A real console vertex shader from the retail pack, run on the PC GPU
|
||||
/// (needs XCL_SAMPLE_RPF=…\shaders.rpf).
|
||||
#[test]
|
||||
@@ -2329,6 +2385,7 @@ fn gpu_memory_windows_above_4_gib() {
|
||||
let list = vec![
|
||||
("S_LOAD_DWORDX2", "ENC_SMEM", vec![("SDATA", 20), ("SBASE", 1), ("OFFSET", 0)], None), // s[2:3] → window 1
|
||||
("BUFFER_LOAD_DWORD", "ENC_MUBUF", vec![("VDATA", 1), ("VADDR", 0), ("SRSRC", 2), ("SOFFSET", 128), ("IDXEN", 1)], None), // V# in window 1
|
||||
("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", vec![("SDATA", 24), ("SBASE", 4), ("OFFSET", 4)], None), // that V#: one switch, 4 dwords
|
||||
("BUFFER_STORE_DWORD", "ENC_MUBUF", vec![("VDATA", 2), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)], None), // V# in window 0
|
||||
glbl("GLOBAL_LOAD_DWORD", &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 0)]), // v[4:5] → window 1
|
||||
glbl("GLOBAL_STORE_DWORD", &[("ADDR", 8), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0)]), // v[8:9] → window 1
|
||||
@@ -2360,6 +2417,7 @@ fn gpu_memory_windows_above_4_gib() {
|
||||
}
|
||||
let r = runner::run_in_arena(&dxil, &st, &arena).unwrap();
|
||||
assert_eq!((r.sgpr[20], r.sgpr[21]), (0xC0FFEE, 0x1234), "s_load from window 1");
|
||||
assert_eq!(r.sgpr[24..28], [1001, 1002, 1003, 1004], "s_buffer_load_dwordx4 from window 1");
|
||||
for l in 0..64u64 {
|
||||
assert_eq!(r.vgpr[l as usize][1], 1000 + l as u32, "lane {l}: buffer_load from window 1");
|
||||
assert_eq!(r.vgpr[l as usize][6], 5000 + l as u32, "lane {l}: global_load from window 1");
|
||||
|
||||
@@ -39,7 +39,7 @@ fn queue() -> &'static Mutex<mpsc::Sender<(Arc<Pending>, Job)>> {
|
||||
let (tx, rx) = mpsc::channel::<(Arc<Pending>, Job)>();
|
||||
let rx = Arc::new(Mutex::new(rx));
|
||||
// translation recurses deeply on big programs; DXC itself runs on its own pool
|
||||
let n = std::thread::available_parallelism().map_or(4, |n| n.get()).min(crate::gpu::recomp::dxc::MAX_COMPILE_THREADS);
|
||||
let n = crate::gpu::recomp::dxc::compile_threads();
|
||||
for k in 0..n {
|
||||
let rx = rx.clone();
|
||||
let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop {
|
||||
|
||||
@@ -346,6 +346,12 @@ impl RecompAgg {
|
||||
}
|
||||
|
||||
fn add(&mut self, name: &str, code: &[u8], keep: usize, mode: recomp::Mode) {
|
||||
// `XCL_RECOMP_ONLY=<hash>` (the hex prefix of an `XCL_DUMP_HLSL` file): that program alone
|
||||
if let Ok(only) = std::env::var("XCL_RECOMP_ONLY") {
|
||||
if format!("{:016x}", name_hash(name)) != only {
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.programs += 1;
|
||||
let wave64 = recomp::detect_wave64(code);
|
||||
self.wave32 += !wave64 as usize;
|
||||
@@ -371,7 +377,9 @@ impl RecompAgg {
|
||||
self.graphics_wave32 += 1;
|
||||
}
|
||||
}
|
||||
match recomp::translate(code, &recomp::Options { mode, wave64, ..Default::default() }) {
|
||||
// `XCL_RECOMP_WINDOWS=4`: as a title with unified memory translates (`pso::mem_windows`)
|
||||
let mem_windows = std::env::var("XCL_RECOMP_WINDOWS").ok().and_then(|v| v.parse().ok()).unwrap_or(1);
|
||||
match recomp::translate(code, &recomp::Options { mode, wave64, mem_windows, ..Default::default() }) {
|
||||
Ok(t) => {
|
||||
let e = self.by_mode.entry(label.to_string()).or_default();
|
||||
e.0 += 1;
|
||||
@@ -406,6 +414,7 @@ impl RecompAgg {
|
||||
}
|
||||
}
|
||||
if t.complete() {
|
||||
dump_hlsl(name, label, profile, &t.hlsl);
|
||||
self.complete += 1;
|
||||
if self.samples.len() < keep {
|
||||
self.samples.push((name.to_string(), t.hlsl, profile));
|
||||
@@ -693,7 +702,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 {
|
||||
}
|
||||
};
|
||||
if args.iter().any(|a| a == "--precompile") {
|
||||
return precompile(&input, opt("--limit").unwrap_or(usize::MAX), t0);
|
||||
return precompile(&input, opt("--limit").unwrap_or(usize::MAX), opt("--windows").unwrap_or(4) as u32, opt("--split").map(|v| v != 0), t0);
|
||||
}
|
||||
let agg = analyze(&input, recomp_on, compile, iface_on);
|
||||
drop(input);
|
||||
@@ -704,13 +713,27 @@ pub fn run(path: &Path, args: &[String]) -> i32 {
|
||||
/// (`recomp::dxc::cache_dir()`), the same HLSL the runtime will ask for, so a title does not
|
||||
/// wait for DXC on first use. Resumable: cached programs are skipped. GS halves need their
|
||||
/// pipeline partner and are left to the runtime.
|
||||
fn precompile(input: &Input, limit: usize, t0: std::time::Instant) -> i32 {
|
||||
/// The cache key is the HLSL, so the options are the runtime's: `windows` memory windows as a
|
||||
/// title's unified memory has (`pso::mem_windows`, 4; `--windows 1` for a title without it),
|
||||
/// and the split wave64 form when this machine's GPU (`XCL_ADAPTER`) runs only 32-lane waves
|
||||
/// (`pso::wave32_only_for_device`). Before, the programs were translated with one window and
|
||||
/// no split form, so a title asked for other HLSL and compiled everything again. Still
|
||||
/// different at run time: a PS's static samplers after its VS's (sampler base 0 here) and the
|
||||
/// mesh pass-through, which the runtime builds for its pixel shader.
|
||||
fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, t0: std::time::Instant) -> i32 {
|
||||
let n = input.len().min(limit);
|
||||
let next = AtomicUsize::new(0);
|
||||
let (done, compiled, cached, failed, skipped) = (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0));
|
||||
let errors: Mutex<Vec<String>> = Mutex::new(Vec::new());
|
||||
let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).min(16);
|
||||
println!("precompiling {n} shaders into {} ({threads} threads)", recomp::dxc::cache_dir().display());
|
||||
// the compiles run on the DXC pool; these threads translate and keep it fed
|
||||
let threads = recomp::dxc::compile_threads() + 2;
|
||||
let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::runner::wave64_supported().is_ok_and(|w| !w));
|
||||
println!(
|
||||
"precompiling {n} shaders into {} ({} compile threads; {windows} memory windows{})",
|
||||
recomp::dxc::cache_dir().display(),
|
||||
recomp::dxc::compile_threads(),
|
||||
if split { ", split wave64 for a GPU with 32-lane waves" } else { "" }
|
||||
);
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..threads {
|
||||
s.spawn(|| loop {
|
||||
@@ -735,7 +758,10 @@ fn precompile(input: &Input, limit: usize, t0: std::time::Instant) -> i32 {
|
||||
};
|
||||
for p in &f.programs {
|
||||
let code = &f.data[p.offset..p.offset + p.len];
|
||||
let opt = recomp::Options { mode: mode.clone(), wave64: recomp::detect_wave64(code), ..Default::default() };
|
||||
// as `pso` translates: VS / PS / CS with the title's memory windows
|
||||
// (`console_translation`), MS with one (`translate_mesh`)
|
||||
let mem_windows = if matches!(mode, recomp::Mode::Mesh(_)) { 1 } else { windows };
|
||||
let opt = recomp::Options { mode: mode.clone(), wave64: recomp::detect_wave64(code), split_wave64: split, mem_windows, ..Default::default() };
|
||||
let Ok(t) = recomp::translate(code, &opt) else { continue };
|
||||
if !t.complete() {
|
||||
continue;
|
||||
@@ -1105,3 +1131,26 @@ mod tests {
|
||||
assert_eq!(agg.insts.undecoded, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// `XCL_DUMP_HLSL=<folder>` (`--recomp`): every `XCL_DUMP_EVERY`-th complete translation (by a
|
||||
/// hash of its name, default 100) is written there – samples for timing DXC on its own.
|
||||
fn dump_hlsl(name: &str, label: &str, profile: &str, hlsl: &str) {
|
||||
let Some(dir) = std::env::var_os("XCL_DUMP_HLSL") else { return };
|
||||
let every: u64 = std::env::var("XCL_DUMP_EVERY").ok().and_then(|v| v.parse().ok()).unwrap_or(100).max(1);
|
||||
let h = name_hash(name);
|
||||
if h % every != 0 {
|
||||
return;
|
||||
}
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let _ = std::fs::write(std::path::Path::new(&dir).join(format!("{h:016x}_{label}_{profile}.hlsl")), hlsl);
|
||||
}
|
||||
|
||||
/// FNV-1a of a program's name (`XCL_DUMP_HLSL` file names, `XCL_RECOMP_ONLY`).
|
||||
fn name_hash(name: &str) -> u64 {
|
||||
let mut h = 0xcbf2_9ce4_8422_2325u64;
|
||||
for b in name.bytes() {
|
||||
h ^= b as u64;
|
||||
h = h.wrapping_mul(0x100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user