More RDNA2 instructions, complete console descriptor heaps, more structured loops

- instructions: one 32-bit atomic generator for buffer / flat / global / DS / image (inc,
  dec, rsub, csub, mskor, cmpst, add_f32, signed min/max on LDS: bounded CAS loops), 64-bit
  _x2 atomics, sub-dword and d16 accesses, scratch (per-lane private memory), SAD / lerp,
  division helpers, saturating adds, packs, v_swap, s_memtime; ISA coverage 766 -> 975 of
  1157, checked on the GPU
- console heaps: sampler heaps (16-byte S# slots), CreateConstantBufferView, CopyDescriptors
  (Simple) with index renumbering, slots freed on heap release
- structure: loops with unconditional back edges, continue, jumps into a loop's middle;
  programs needing the pc dispatcher 2274 -> 2046 of 24064
This commit is contained in:
ivall
2026-11-21 12:56:22 +01:00
parent 74cd9db58e
commit c2123ecfd0
6 changed files with 918 additions and 114 deletions
+29
View File
@@ -536,6 +536,35 @@ Nic otwartego.
Niewyjaśnione: 6 pakietów na podblok przy różnicy w tablicy 12·960 – TOC 0xFC to CELT FB 20 ms **stereo**, więc tablica
liczy chyba próbki × kanały.
## Instrukcje spoza paczki, sterty konsoli, struktura (sesja 5, 2026-11-21)
- **Pokrycie ISA** (`isa_coverage`, każda instrukcja dekodera osobno; MIMG z DMASK=1, VOP3_SDST z VCC – wcześniej
fałszywe braki): **975 / 1157 (84,3%)**, było 766. Dodane (test GPU `gpu_more_atomics_sub_dword_scratch_valu` +
`image_atomic_inc` w `gpu_images_sample_load_store_atomic`):
- wspólny generator atomików 32-bit (`emit::rmw32`, `At::Mem` / `At::Ref`) dla buffer / flat / global / DS / obrazów:
inc, dec, rsub, csub, mskor, cmpst / fcmpswap (porównanie bitowe), add_f32, min/max ze znakiem na LDS i obrazach –
ograniczona pętla CAS (4096); fmin/fmax w `mem` dalej bez pętli (sztuczka ze znakiem); **64-bit `_x2`**
(`rmw64`: InterlockedXxx64 SM 6.6) – add/sub/and/or/xor/swap/min/max/cmpswap; `ds_wrxchg2(st64)_rtn_b32`;
- flat/global/scratch bajt/półsłowo + **d16 / d16_hi** (też buffer_*_d16, ds_read_*_d16, ds_write_*_d16_hi);
- **scratch_*** – prywatna pamięć wątku `static uint xcl_scratch[1024]` (4 KB/wątek);
- `v_sad_u8/hi_u8/u16`, `v_msad_u8`, `v_lerp_u8`, `v_div_scale/fmas/fixup_f32` (bez skalowania: VCC=0, fixup =
przypadki specjalne IEEE), `v_add/sub_nc_i32` z clamp, `v_mad_u32_u16/i32_i16`, `v_cvt_pk_u16_u32/i16_i32`,
`v_cvt_pknorm_*_f32`, `v_mul_hi_i32_i24`, `v_sat_pk_u8_i16`, `v_swap_b32`; `s_memtime/s_memrealtime` (= 0);
`buffer_gl0/gl1_inv`, `ds_nop` (bez efektu); `image_sample_cd*` jak `_d`.
- Dalej brak: f64 (sqrt/rsq/frexp/…), 64-bit LDS, GWS / append / consume, debug/trap, `s_setpc/s_call`, obrazy
`pck` / `by2` / `msaa_load` / `store_mip`, formaty d16 (`buffer/tbuffer_*_format_d16_*`), `v_cvt_*_f16` norm.
- **Sterty deskryptorów konsoli – dokończone** (`console_heap.rs`; test `slots_copy_and_release`):
- **sterty samplerów**: sloty S# 16 B w UMA, slot k → sampler PC k, S# słowo 3 [11:0] = k (`#22 CreateSampler`);
- **`#17 CreateConstantBufferView`** → surowy V# z adresem konsoli (UMA; inaczej pusty V#);
- **`#24 CopyDescriptorsSimple` / `#23 CopyDescriptors`** – kopia deskryptorów PC (2 na slot widoków) + slotów z
przenumerowaniem indeksu (T# słowo 0, S# słowo 3; V# bez zmian); zakresy mieszane konsola/PC → log, tylko PC;
- **Release sterty** zwalnia jej sloty (`heap_release`). Increment konsoli: widoki 32, samplery 16.
- #17 / #22–#24 przyjęte za układem PC (jak #14–#19 widziane z kodu konsoli) – do potwierdzenia z exe.
- **Struktura**: pętle z bezwarunkowym skokiem wstecz (wyjście przez flagi + break), **`continue`** (skok wstecz do
głowy najbliższej pętli), **wejście do środka pętli** skokiem z wcześniejszego kodu (cel przechodzi do poziomu ciała
jako oczekujący: kod przed nim od 2. iteracji), zakres równy pętli (np. ciało if) = ta pętla. Cała paczka: programów
z blokami `pc` **2274 → 2046 (8,5%)**. Zostaje: skok wstecz bez cyklu (kompilator współdzieli kod między ścieżkami –
wymagałby powielenia), `continue` do zewnętrznej pętli, pętle z wieloma krawędziami wstecz.
## Pipeline'y MS (NGG) i GS w tworzeniu PSO (sesja 5, 2026-11-21)
- 9 282 MS + 195 GS z `shaders.rpf` (~40% paczki) dostawały dotąd shadery zastępcze (`real.rs` obsługiwał tylko VS+PS
i CS). Teraz:
+423 -53
View File
@@ -33,6 +33,8 @@ pub(super) struct Em {
ps_done: bool,
/// LDS used (compute): declare the groupshared array
uses_lds: bool,
/// scratch_* used: declare the per-lane private memory
uses_scratch: bool,
/// highest VGPR the program references (v_movrel* ranges)
pub max_vgpr: u64,
}
@@ -42,7 +44,7 @@ const NOOPS: &[&str] = &[
"s_nop", "s_waitcnt", "s_waitcnt_vscnt", "s_waitcnt_vmcnt", "s_waitcnt_expcnt", "s_waitcnt_lgkmcnt", "s_waitcnt_depctr",
"s_inst_prefetch", "s_clause", "s_code_end", "s_setprio", "s_sleep", "s_icache_inv", "s_dcache_inv", "s_gl1_inv", "s_ttracedata",
"s_ttracedata_imm", "v_nop", "s_denorm_mode", "s_round_mode", "s_setreg_imm32_b32", "s_setreg_b32", "s_sendmsg", "s_sendmsghalt",
"s_set_gpr_idx_off", "s_version",
"s_set_gpr_idx_off", "s_version", "buffer_gl0_inv", "buffer_gl1_inv", "ds_nop",
];
fn sname(code: u64) -> Option<String> {
@@ -233,6 +235,7 @@ impl Em {
ps_modes: BTreeMap::new(),
ps_done: false,
uses_lds: false,
uses_scratch: false,
max_vgpr: 0,
}
}
@@ -509,7 +512,7 @@ impl Em {
"ENC_DS" => self.ds(d, &name),
"ENC_VINTRP" => self.interp(d, &name),
"ENC_MIMG" => self.mimg(d, &name),
"ENC_FLAT" | "ENC_FLAT_GLBL" => self.flat(d, &name),
"ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" => self.flat(d, &name),
e if e.starts_with("ENC_VOP") || e.starts_with("VOP") => self.valu(d, &name),
_ => Err("kodowanie"),
};
@@ -896,6 +899,13 @@ impl Em {
// ---------------------------------------------------------------- memory (flat model)
fn smem(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> {
if name == "s_memtime" || name == "s_memrealtime" {
// no clock in this model: a constant time (profiling deltas come out 0)
let sdata = Self::field(d, "SDATA");
let (lo, hi) = (self.sreg(sdata), self.sreg(sdata + 1));
self.line(&format!("{lo} = 0u; {hi} = 0u;"));
return Ok(());
}
let count = match name.trim_start_matches("s_buffer_load_").trim_start_matches("s_load_") {
"dword" => 1,
"dwordx2" => 2,
@@ -953,6 +963,9 @@ impl Em {
"buffer_store_short" => Some((2, false, true)),
_ => None,
};
if let Some((n, signed, store, half)) = d16_small(name.trim_start_matches("buffer_")) {
return self.mubuf_d16(d, n, signed, store, half);
}
let (kind, count) = match small {
Some(_) => (BufKind::Load, 1),
None => buffer_op(name).ok_or("MUBUF")?,
@@ -1291,12 +1304,10 @@ impl Em {
let sampling = base.starts_with("sample") || base.starts_with("gather4");
let rest = base.trim_start_matches("sample").trim_start_matches("gather4");
let mods: Vec<&str> = if sampling { rest.split('_').filter(|x| !x.is_empty()).collect() } else { Vec::new() };
if mods.contains(&"cd") {
return Err("MIMG cd");
}
// `cd` (coarse derivatives) samples like `d`: the gradients are the instruction's own
let (has_cl, has_o) = (mods.contains(&"cl"), mods.contains(&"o"));
let (has_b, has_c, has_d, has_l, has_lz) =
(mods.contains(&"b"), mods.contains(&"c"), mods.contains(&"d"), mods.contains(&"l"), mods.contains(&"lz"));
(mods.contains(&"b"), mods.contains(&"c"), mods.contains(&"d") || mods.contains(&"cd"), mods.contains(&"l"), mods.contains(&"lz"));
let grad_n = if has_d { [1u64, 2, 3, 2, 1, 2, 2, 2][dim as usize] } else { 0 };
// address components: (16-bit?, starts a dword?)
let h = if a16 { 16 } else { 32 };
@@ -1624,6 +1635,17 @@ impl Em {
uav("float")
));
}
_ if base.starts_with("atomic_") && matches!(&base[7..], "cmpswap" | "sub" | "inc" | "dec" | "fcmpswap" | "fmin" | "fmax") => {
// the operations without an int view: on the uint texel (CAS loops where needed)
let (v, cmp) = (self.vreg(vdata), self.vreg(vdata + 1));
self.line(&format!("RWTexture{rty}<uint> {t}_U = ResourceDescriptorHeap[NonUniformResourceIndex({tw0} + 1u)];"));
self.line(&format!("uint {t}_old = 0u;"));
let body = rmw32(&base[7..], &At::Ref(format!("{t}_U[{icoord}]")), &v, &cmp, &format!("{t}_old"), &t).ok_or("image_atomic")?;
self.line(&format!("if ({act}) {{ {body} }}"));
if f("GLC") == 1 {
self.line(&format!("if ({act}) {v} = {t}_old;"));
}
}
_ if base.starts_with("atomic_") => {
let op = match &base[7..] {
"add" => "InterlockedAdd",
@@ -2210,7 +2232,10 @@ impl Em {
return self.interp(d, name);
}
let (outs, ins) = Self::ops(d);
let f16 = name.contains("f16") || name.contains("_i16") || name.contains("_u16") || name.contains("_b16");
// 32-bit operations whose names mention 16-bit halves
const WIDE16: &[&str] =
&["v_cvt_pknorm_i16_f32", "v_cvt_pknorm_u16_f32", "v_cvt_pk_u16_u32", "v_cvt_pk_i16_i32", "v_mad_u32_u16", "v_mad_i32_i16", "v_sad_u16", "v_sat_pk_u8_i16"];
let f16 = (name.contains("f16") || name.contains("_i16") || name.contains("_u16") || name.contains("_b16")) && !WIDE16.contains(&name);
let cmp = name.starts_with("v_cmp");
// inline constants are f16 patterns only where the source itself is 16-bit
let src_f16 = matches!(name, "v_cvt_f32_f16" | "v_pack_b32_f16") || (cmp && name.ends_with("_f16"));
@@ -2221,6 +2246,17 @@ impl Em {
if name.starts_with("v_movrel") {
return self.movrel(d, name);
}
if name == "v_swap_b32" && d.variant == Variant::Plain {
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
let s0 = f("SRC0");
if s0 < 256 {
return Err("v_swap_b32: SRC0 nie jest VGPR");
}
let (x, y) = (self.vreg(f("VDST")), self.vreg(s0 - 256));
let (t, act) = (self.t(), self.act());
self.line(&format!("uint {t} = {x}; {x} = select({act}, {y}, {x}); {y} = select({act}, {t}, {y});"));
return Ok(());
}
if d.enc.name == "ENC_VOP3P" && !mix {
return Err("VOP3P");
}
@@ -2404,6 +2440,33 @@ impl Em {
"v_max3_i32" => format!("(uint)max(max((int){a}, (int){b}), (int){c})"),
"v_med3_i32" => format!("(uint)med3i((int){a}, (int){b}, (int){c})"),
"v_sad_u32" => format!("(max({a}, {b}) - min({a}, {b})) + {c}"),
"v_sad_u8" => format!("sad_u8({a}, {b}) + {c}"),
"v_sad_hi_u8" => format!("(sad_u8({a}, {b}) << 16) + {c}"),
"v_sad_u16" => format!("absd16({a}, {b}, 0u) + absd16({a}, {b}, 16u) + {c}"),
"v_msad_u8" => format!("msad_u8({a}, {b}) + {c}"),
"v_lerp_u8" => format!("lerp_u8({a}, {b}, {c})"),
"v_add_nc_i32" if m.clamp => format!("sat_i32((int64_t)(int){a} + (int64_t)(int){b})"),
"v_sub_nc_i32" if m.clamp => format!("sat_i32((int64_t)(int){a} - (int64_t)(int){b})"),
"v_add_nc_i32" => format!("{a} + {b}"),
"v_sub_nc_i32" => format!("{a} - {b}"),
"v_mad_u32_u16" => format!("(({a} >> {}u) & 0xFFFFu) * (({b} >> {}u) & 0xFFFFu) + {c}", 16 * (m.opsel & 1), 8 * (m.opsel & 2)),
"v_mad_i32_i16" => format!(
"(uint)((((int)(({a} >> {}u) << 16)) >> 16) * (((int)(({b} >> {}u) << 16)) >> 16) + (int){c})",
16 * (m.opsel & 1),
8 * (m.opsel & 2)
),
"v_cvt_pk_u16_u32" => format!("min({a}, 0xFFFFu) | (min({b}, 0xFFFFu) << 16)"),
"v_cvt_pk_i16_i32" => format!("((uint)clamp((int){a}, -32768, 32767) & 0xFFFFu) | (((uint)clamp((int){b}, -32768, 32767) & 0xFFFFu) << 16)"),
"v_cvt_pknorm_i16_f32" => format!(
"((uint)(int)round(clamp({}, -1.0f, 1.0f) * 32767.0f) & 0xFFFFu) | (((uint)(int)round(clamp({}, -1.0f, 1.0f) * 32767.0f) & 0xFFFFu) << 16)",
fs(0),
fs(1)
),
"v_cvt_pknorm_u16_f32" => format!("(uint)round(saturate({}) * 65535.0f) | ((uint)round(saturate({}) * 65535.0f) << 16)", fs(0), fs(1)),
"v_mul_hi_i32_i24" => format!("(uint)(((int64_t)i24({a}) * (int64_t)i24({b})) >> 32)"),
"v_sat_pk_u8_i16" => format!("(uint)clamp(((int)({a} << 16)) >> 16, 0, 255) | ((uint)clamp((int){a} >> 16, 0, 255) << 8)"),
"v_div_fmas_f32" => fr(format!("mad({}, {}, {})", fs(0), fs(1), fs(2))),
"v_div_fixup_f32" => fr(format!("div_fixup({}, {}, {})", fs(0), fs(1), fs(2))),
"v_cvt_pk_u8_f32" => format!(
"({c} & ~(0xFFu << (8u * ({b} & 3u)))) | (((uint)clamp(round({}), 0.0f, 255.0f)) << (8u * ({b} & 3u)))",
fs(0)
@@ -2456,6 +2519,15 @@ impl Em {
}
return Ok(());
}
"v_div_scale_f32" => {
// no pre-scaling (the quotient sequence still gives a/b; only extreme ranges lose
// precision): src0 unchanged, VCC 0 = no post-scale in v_div_fmas
let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106));
self.write_mask(&sdst, "false");
let r = format!("asuint({})", fs(0));
self.vwrite(d, &dst, &r);
return Ok(());
}
"v_add_co_u32" | "v_sub_co_u32" | "v_subrev_co_u32" => {
let (x, y) = if name == "v_subrev_co_u32" { (b.clone(), a.clone()) } else { (a.clone(), b.clone()) };
let t = self.t();
@@ -2601,17 +2673,54 @@ impl Em {
fn buffer_atomic(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> {
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
let op = name.trim_start_matches("buffer_atomic_");
let func = match op {
"add" => "InterlockedAdd",
"smin" | "umin" => "InterlockedMin",
"smax" | "umax" => "InterlockedMax",
"and" => "InterlockedAnd",
"or" => "InterlockedOr",
"xor" => "InterlockedXor",
"swap" => "InterlockedExchange",
"cmpswap" => "InterlockedCompareExchange",
_ => return Err("buffer_atomic"),
};
let (vdata, vaddr, srsrc) = (f("VDATA"), f("VADDR"), Self::field(d, "SRSRC"));
let soff = self.code32(f("SOFFSET"), None, false).ok_or("op")?;
let (offen, idxen) = (f("OFFEN") != 0, f("IDXEN") != 0);
let (d0, d1, d2) = (self.sreg(srsrc), self.sreg(srsrc + 1), self.sreg(srsrc + 2));
let index = if idxen { self.vreg(vaddr) } else { "0u".into() };
let voff = if offen { self.vreg(vaddr + idxen as u64) } else { "0u".into() };
let t = self.t();
let x2 = op.ends_with("_x2");
let op = op.trim_end_matches("_x2");
let bytes = if x2 { 8 } else { 4 };
self.line(&format!("uint {t}_stride = ({d1} >> 16) & 0x3FFFu;"));
self.line(&format!("uint {t}_off = {voff} + {}u;", f("OFFSET")));
self.line(&format!("uint {t}_a = ({d0} + {soff} + {t}_off + {t}_stride * {index}) & ~{}u;", bytes - 1));
self.line(&format!("bool {t}_ok = select({t}_stride == 0u, {t}_off + {bytes}u <= {d2}, {index} < {d2});"));
let act = self.act();
if x2 {
return self.atomic64(op, &format!("{t}_a"), vdata, vdata + 2, f("GLC") == 1, vdata, &format!("and({act}, {t}_ok)"));
}
let (v, cmp) = (self.vreg(vdata), self.vreg(vdata + 1));
let body = rmw32(op, &At::Mem(format!("{t}_a")), &v, &cmp, &format!("{t}_old"), &t).ok_or("buffer_atomic")?;
self.line(&format!("uint {t}_old = 0u;"));
self.line(&format!("if (and({act}, {t}_ok)) {{ {body} }}"));
if f("GLC") == 1 {
self.line(&format!("{v} = select({act}, select({t}_ok, {t}_old, 0u), {v});"));
}
Ok(())
}
/// A 64-bit atomic (`_x2`) at byte address `a` of the flat memory; data in VGPRs
/// `data`, `data + 1` (compare value of cmpswap at `cmp`); the old value to `dst` (GLC).
#[allow(clippy::too_many_arguments)]
fn atomic64(&mut self, op: &str, a: &str, data: u64, cmp: u64, glc: bool, dst: u64, active: &str) -> Result<(), &'static str> {
let t = self.t();
let (lo, hi) = (self.vreg(data), self.vreg(data + 1));
let (clo, chi) = (self.vreg(cmp), self.vreg(cmp + 1));
self.line(&format!("uint64_t {t}_v = (uint64_t){lo} | ((uint64_t){hi} << 32); uint64_t {t}_cmp = (uint64_t){clo} | ((uint64_t){chi} << 32); uint64_t {t}_old = 0;"));
let body = rmw64(op, a, &format!("{t}_v"), &format!("{t}_cmp"), &format!("{t}_old"), &t).ok_or("atomic 64")?;
self.line(&format!("if ({active}) {{ {body} }}"));
if glc {
let (r0, r1) = (self.vreg(dst), self.vreg(dst + 1));
self.line(&format!("if ({active}) {{ {r0} = (uint){t}_old; {r1} = (uint)({t}_old >> 32); }}"));
}
Ok(())
}
/// buffer_* d16 sub-dword loads / stores (half of the VGPR, the other half kept).
fn mubuf_d16(&mut self, d: &Decoded, n: u32, signed: bool, store: bool, half: u32) -> Result<(), &'static str> {
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
let (vdata, vaddr, srsrc) = (f("VDATA"), f("VADDR"), Self::field(d, "SRSRC"));
let soff = self.code32(f("SOFFSET"), None, false).ok_or("op")?;
let (offen, idxen) = (f("OFFEN") != 0, f("IDXEN") != 0);
@@ -2621,24 +2730,15 @@ impl Em {
let t = self.t();
self.line(&format!("uint {t}_stride = ({d1} >> 16) & 0x3FFFu;"));
self.line(&format!("uint {t}_off = {voff} + {}u;", f("OFFSET")));
self.line(&format!("uint {t}_a = ({d0} + {soff} + {t}_off + {t}_stride * {index}) & ~3u;"));
self.line(&format!("bool {t}_ok = select({t}_stride == 0u, {t}_off + 4u <= {d2}, {index} < {d2});"));
let v = self.vreg(vdata);
self.line(&format!("uint {t}_a = {d0} + {soff} + {t}_off + {t}_stride * {index};"));
let ok = format!("select({t}_stride == 0u, {t}_off + {n}u <= {d2}, {index} < {d2})");
let act = self.act();
let signed = op == "smin" || op == "smax";
let ty = if signed { "int" } else { "uint" };
self.line(&format!("{ty} {t}_old = 0;"));
let call = if op == "cmpswap" {
let cmp = self.vreg(vdata + 1);
format!("mem.InterlockedCompareExchange({t}_a, {cmp}, {v}, {t}_old);")
} else if signed {
format!("mem.{func}({t}_a, (int){v}, {t}_old);")
let v = self.vreg(vdata);
if store {
self.line(&format!("if (and({act}, {ok})) st_bytes({t}_a, uint4({}, 0u, 0u, 0u), {n}u);", d16_data(&v, half)));
} else {
format!("mem.{func}({t}_a, {v}, {t}_old);")
};
self.line(&format!("if (and({act}, {t}_ok)) {{ {call} }}"));
if f("GLC") == 1 {
self.line(&format!("{v} = select({act}, select({t}_ok, (uint){t}_old, 0u), {v});"));
let raw = format!("select({ok}, ld_raw({t}_a).x, 0u)");
self.line(&format!("if ({act}) {v} = {};", d16_merge(&v, &raw, n, signed, half)));
}
Ok(())
}
@@ -2646,10 +2746,33 @@ impl Em {
/// FLAT / global: the flat memory model (address = low 32 bits).
fn flat(&mut self, d: &Decoded, name: &str) -> Result<(), &'static str> {
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
let op = name.trim_start_matches("global_").trim_start_matches("flat_");
let op = name.trim_start_matches("global_").trim_start_matches("flat_").trim_start_matches("scratch_");
let scratch = d.enc.name == "ENC_FLAT_SCRATCH";
if let Some(a) = op.strip_prefix("atomic_") {
return self.flat_atomic(d, a);
}
if scratch {
return self.scratch(d, op);
}
if let Some((n, signed, store, half)) = flat_small(op) {
let global = d.enc.name == "ENC_FLAT_GLBL";
let addr = self.vreg(f("ADDR"));
let saddr = f("SADDR");
let base = if global && saddr != 0x7D && saddr != 0x7F { format!("{} + {addr}", self.sreg(saddr)) } else { addr };
let raw = f("OFFSET") as u32;
let off = if global { (((raw << 20) as i32) >> 20) as u32 } else { raw };
let t = self.t();
self.line(&format!("uint {t}_a = {base} + {};", hex(off)));
let act = self.act();
if store {
let v = self.vreg(f("DATA"));
self.line(&format!("if ({act}) st_bytes({t}_a, uint4({}, 0u, 0u, 0u), {n}u);", d16_data(&v, half)));
} else {
let v = self.vreg(f("VDST"));
self.line(&format!("if ({act}) {v} = {};", d16_merge(&v, &format!("ld_raw({t}_a).x"), n, signed, half)));
}
return Ok(());
}
let (store, count) = match op {
"load_dword" => (false, 1),
"load_dwordx2" => (false, 2),
@@ -2689,6 +2812,51 @@ impl Em {
Ok(())
}
/// scratch_*: per-lane private memory (`xcl_scratch`); address = SADDR or VADDR + offset.
fn scratch(&mut self, d: &Decoded, op: &str) -> Result<(), &'static str> {
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
self.uses_scratch = true;
let saddr = f("SADDR");
let base = if saddr != 0x7D && saddr != 0x7F { self.sreg(saddr) } else { self.vreg(f("ADDR")) };
let raw = f("OFFSET") as u32;
let off = (((raw << 20) as i32) >> 20) as u32;
let t = self.t();
self.line(&format!("uint {t}_a = {base} + {};", hex(off)));
let act = self.act();
if let Some((n, signed, store, half)) = flat_small(op) {
if store {
let v = self.vreg(f("DATA"));
self.line(&format!("if ({act}) scr_st({t}_a, {}, {n}u);", d16_data(&v, half)));
} else {
let v = self.vreg(f("VDST"));
self.line(&format!("if ({act}) {v} = {};", d16_merge(&v, &format!("scr_ld({t}_a)"), n, signed, half)));
}
return Ok(());
}
let (store, count) = match op {
"load_dword" => (false, 1),
"load_dwordx2" => (false, 2),
"load_dwordx3" => (false, 3),
"load_dwordx4" => (false, 4),
"store_dword" => (true, 1),
"store_dwordx2" => (true, 2),
"store_dwordx3" => (true, 3),
"store_dwordx4" => (true, 4),
_ => return Err("SCRATCH"),
};
let mut st = Vec::new();
for i in 0..count {
let slot = format!("xcl_scratch[(({t}_a + {}u) >> 2) & 1023u]", 4 * i);
if store {
st.push(format!("{slot} = {};", self.vreg(f("DATA") + i)));
} else {
st.push(format!("{} = {slot};", self.vreg(f("VDST") + i)));
}
}
self.line(&format!("if ({act}) {{ {} }}", st.join(" ")));
Ok(())
}
/// FLAT / global atomics on the flat memory (dword ops; float min / max by a CAS loop).
fn flat_atomic(&mut self, d: &Decoded, op: &str) -> Result<(), &'static str> {
let f = |n: &str| rdna2::field_value(d.enc, &d.words, n).unwrap_or(0);
@@ -2699,11 +2867,19 @@ impl Em {
let raw = f("OFFSET") as u32;
let off = if global { (((raw << 20) as i32) >> 20) as u32 } else { raw };
let t = self.t();
self.line(&format!("uint {t}_a = ({base} + {}) & ~3u;", hex(off)));
let v = self.vreg(f("DATA"));
let x2 = op.ends_with("_x2");
let op = op.trim_end_matches("_x2");
self.line(&format!("uint {t}_a = ({base} + {}) & ~{}u;", hex(off), if x2 { 7 } else { 3 }));
let act = self.act();
if x2 {
let data = f("DATA");
return self.atomic64(op, &format!("{t}_a"), data, data + 2, f("GLC") == 1, f("VDST"), &act);
}
let v = self.vreg(f("DATA"));
self.line(&format!("uint {t}_old = 0u;"));
let cmpv = self.vreg(f("DATA") + 1);
let body = match op {
"inc" | "dec" | "csub" | "fcmpswap" => rmw32(op, &At::Mem(format!("{t}_a")), &v, &cmpv, &format!("{t}_old"), &t).ok_or("FLAT atomic")?,
"add" => format!("mem.InterlockedAdd({t}_a, {v}, {t}_old);"),
"sub" => format!("mem.InterlockedAdd({t}_a, 0u - {v}, {t}_old);"),
"and" => format!("mem.InterlockedAnd({t}_a, {v}, {t}_old);"),
@@ -2809,6 +2985,22 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}"
_ => return None,
})
};
// d16 8 / 16-bit LDS accesses (half of the VGPR)
if let Some((bits, signed, write, half)) = ds_d16(name) {
let at = format!("{a} + {off16}u");
let slot = lds(at.clone());
let sh = format!("((({at}) & 3u) * 8u)");
let mask = (1u64 << bits) - 1;
if write {
let v = d16_data(&self.vreg(f("DATA0")), half);
self.line(&format!("if ({act}) {{ InterlockedAnd({slot}, ~({mask}u << {sh})); InterlockedOr({slot}, ({v} & {mask}u) << {sh}); }}"));
} else {
let v = self.vreg(f("VDST"));
let raw = format!("({slot} >> {sh})");
self.line(&format!("if ({act}) {v} = {};", d16_merge(&v, &raw, bits / 8, signed, half)));
}
return Ok(());
}
// 8 / 16-bit LDS accesses: atomic and / or keep the rest of the dword intact
let small = match name {
"ds_write_b8" => Some((8u32, false, true)),
@@ -2871,24 +3063,24 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}"
Some(r) => (r.to_string(), false),
None => return Err("DS"),
};
let func = match op.as_str() {
"add_u32" => "InterlockedAdd",
"min_u32" | "min_i32" => "InterlockedMin",
"max_u32" | "max_i32" => "InterlockedMax",
"and_b32" => "InterlockedAnd",
"or_b32" => "InterlockedOr",
"xor_b32" => "InterlockedXor",
"wrxchg_b32" => "InterlockedExchange",
"sub_u32" => "InterlockedAdd",
_ => return Err("DS"),
};
if op.ends_with("_i32") {
return Err("DS min/max i32");
// two exchanges (ds_wrxchg2(st64)_rtn_b32): old values to VDST, VDST + 1
if op == "wrxchg2_b32" || op == "wrxchg2st64_b32" {
let stride = if op == "wrxchg2_b32" { 4 } else { 256 };
let (s0, s1) = (lds(format!("{a} + {}u", o0 * stride)), lds(format!("{a} + {}u", o1 * stride)));
let (v0, v1) = (self.vreg(f("DATA0")), self.vreg(f("DATA1")));
self.line(&format!("uint {t}_o0 = 0u, {t}_o1 = 0u; if ({act}) {{ InterlockedExchange({s0}, {v0}, {t}_o0); InterlockedExchange({s1}, {v1}, {t}_o1); }}"));
if rtn {
let (r0, r1) = (self.vreg(f("VDST")), self.vreg(f("VDST") + 1));
self.line(&format!("if ({act}) {{ {r0} = {t}_o0; {r1} = {t}_o1; }}"));
}
return Ok(());
}
let v = self.vreg(f("DATA0"));
let val = if op == "sub_u32" { format!("(0u - {v})") } else { v };
// operands: cmpst = (compare DATA0, new DATA1), mskor = (mask DATA0, or DATA1)
let (d0, d1) = (self.vreg(f("DATA0")), self.vreg(f("DATA1")));
let (v, v2) = if op.starts_with("cmpst_") { (d1, d0) } else { (d0, d1) };
let slot = lds(format!("{a} + {off16}u"));
self.line(&format!("uint {t}_o = 0u; if ({act}) {{ {func}({slot}, {val}, {t}_o); }}"));
let body = rmw32(&op, &At::Ref(slot), &v, &v2, &format!("{t}_o"), &t).ok_or("DS")?;
self.line(&format!("uint {t}_o = 0u; if ({act}) {{ {body} }}"));
if rtn {
let r = self.vreg(f("VDST"));
self.line(&format!("if ({act}) {r} = {t}_o;"));
@@ -2914,6 +3106,9 @@ else {{ mem.{neg}({t}_a, {v}, {t}_old); }}"
let infos: Vec<String> = (0..BUF_FORMATS.len()).map(|i| format!("0x{:08X}u", buf_format_info(i))).collect();
let _ = writeln!(h, "static const uint FMT_INFO[78] = {{ {} }};", infos.join(", "));
h.push_str(PRELUDE_MEM);
if self.uses_scratch {
h.push_str(PRELUDE_SCRATCH);
}
let mut sg: BTreeSet<u64> = self.sgprs.clone();
sg.extend([106, 107, 124, 126, 127]);
let load_sgprs = |h: &mut String| {
@@ -3375,6 +3570,173 @@ fn cmp_op(rest: &str) -> Option<(&'static str, bool)> {
))
}
/// Where a 32-bit atomic works: a byte address in `mem`, or an lvalue (LDS slot, texel).
enum At {
Mem(String),
Ref(String),
}
/// A 32-bit atomic read-modify-write: HLSL statements leaving the old value in `old` (a
/// declared uint). `v` = data, `v2` = second operand (cmpswap: the compare value; DS mskor:
/// the or value). Operations without an HLSL intrinsic run as a bounded compare-exchange
/// loop. Operation names as in buffer / flat / image (`umin`) and DS (`min_u32`).
fn rmw32(op: &str, at: &At, v: &str, v2: &str, old: &str, t: &str) -> Option<String> {
let direct = |f: &str, val: &str| match at {
At::Mem(a) => format!("mem.{f}({a}, {val}, {old});"),
At::Ref(r) => format!("{f}({r}, {val}, {old});"),
};
let cas = |new: String| {
let (load, cx) = match at {
At::Mem(a) => (format!("mem.Load({a})"), format!("mem.InterlockedCompareExchange({a}, {t}_c, {t}_n, {t}_p);")),
At::Ref(r) => (r.clone(), format!("InterlockedCompareExchange({r}, {t}_c, {t}_n, {t}_p);")),
};
format!(
"uint {t}_c = {load}; [allow_uav_condition] for (uint {t}_i = 0u; {t}_i < 4096u; {t}_i++) {{ uint {t}_n = {new}; uint {t}_p = 0u; {cx} if ({t}_p == {t}_c) break; {t}_c = {t}_p; }} {old} = {t}_c;"
)
};
let c = format!("{t}_c");
let signed = |f: &str, pick: &str| match at {
At::Mem(a) => format!("int {t}_s = 0; mem.{f}({a}, (int){v}, {t}_s); {old} = (uint){t}_s;"),
At::Ref(_) => cas(format!("(uint){pick}((int){c}, (int){v})")),
};
Some(match op {
"add" | "add_u32" => direct("InterlockedAdd", v),
"sub" | "sub_u32" => direct("InterlockedAdd", &format!("(0u - {v})")),
"and" | "and_b32" => direct("InterlockedAnd", v),
"or" | "or_b32" => direct("InterlockedOr", v),
"xor" | "xor_b32" => direct("InterlockedXor", v),
"swap" | "wrxchg_b32" => direct("InterlockedExchange", v),
"umin" | "min_u32" => direct("InterlockedMin", v),
"umax" | "max_u32" => direct("InterlockedMax", v),
// float compare-swap compares bits (differs only for -0 / NaN)
"cmpswap" | "fcmpswap" | "cmpst_b32" | "cmpst_f32" => match at {
At::Mem(a) => format!("mem.InterlockedCompareExchange({a}, {v2}, {v}, {old});"),
At::Ref(r) => format!("InterlockedCompareExchange({r}, {v2}, {v}, {old});"),
},
"smin" | "min_i32" => signed("InterlockedMin", "min"),
"smax" | "max_i32" => signed("InterlockedMax", "max"),
// float min / max in memory as one integer atomic: non-negative floats order like
// signed ints, negative ones like unsigned ints in reverse (no CAS loop – a program
// with 168 such loops was too much for the driver's compiler)
"fmin" | "fmax" | "min_f32" | "max_f32" => {
let min = op == "fmin" || op == "min_f32";
match at {
At::Mem(a) => {
let (pos, neg) = if min { ("InterlockedMin", "InterlockedMax") } else { ("InterlockedMax", "InterlockedMin") };
format!("if (asfloat({v}) >= 0.0f) {{ int {t}_s = 0; mem.{pos}({a}, asint({v}), {t}_s); {old} = asuint({t}_s); }} else {{ mem.{neg}({a}, {v}, {old}); }}")
}
At::Ref(_) => cas(format!("asuint({}(asfloat({c}), asfloat({v})))", if min { "min" } else { "max" })),
}
}
"rsub" | "rsub_u32" => cas(format!("{v} - {c}")),
"inc" | "inc_u32" => cas(format!("select({c} >= {v}, 0u, {c} + 1u)")),
"dec" | "dec_u32" => cas(format!("select(or({c} == 0u, {c} > {v}), {v}, {c} - 1u)")),
"csub" => cas(format!("select({c} >= {v}, {c} - {v}, 0u)")),
"add_f32" => cas(format!("asuint(asfloat({c}) + asfloat({v}))")),
"mskor_b32" => cas(format!("({c} & ~{v}) | {v2}")),
_ => return None,
})
}
/// A 64-bit atomic at byte address `a` of the flat memory (SM 6.6 InterlockedXxx64);
/// `v`, `cmp`, `old` are uint64_t variables.
fn rmw64(op: &str, a: &str, v: &str, cmp: &str, old: &str, t: &str) -> Option<String> {
let f = match op {
"add" | "sub" => "InterlockedAdd64",
"and" => "InterlockedAnd64",
"or" => "InterlockedOr64",
"xor" => "InterlockedXor64",
"swap" => "InterlockedExchange64",
"umin" => "InterlockedMin64",
"umax" => "InterlockedMax64",
"smin" | "smax" => {
let f = if op == "smin" { "InterlockedMin64" } else { "InterlockedMax64" };
return Some(format!("int64_t {t}_s = 0; mem.{f}({a}, (int64_t){v}, {t}_s); {old} = (uint64_t){t}_s;"));
}
"cmpswap" => return Some(format!("mem.InterlockedCompareExchange64({a}, {cmp}, {v}, {old});")),
_ => return None,
};
let val = if op == "sub" { format!("((uint64_t)0 - {v})") } else { v.to_string() };
Some(format!("mem.{f}({a}, {val}, {old});"))
}
/// Sub-dword d16 forms: (bytes, sign-extend, store, half: 0 low / 1 high) by the name after
/// the `buffer_` / `flat_` / `global_` prefix.
fn d16_small(op: &str) -> Option<(u32, bool, bool, u32)> {
Some(match op {
"load_ubyte_d16" => (1, false, false, 0),
"load_ubyte_d16_hi" => (1, false, false, 1),
"load_sbyte_d16" => (1, true, false, 0),
"load_sbyte_d16_hi" => (1, true, false, 1),
"load_short_d16" => (2, false, false, 0),
"load_short_d16_hi" => (2, false, false, 1),
"store_byte_d16_hi" => (1, false, true, 1),
"store_short_d16_hi" => (2, false, true, 1),
_ => return None,
})
}
/// FLAT / global sub-dword forms (plain and d16): (bytes, sign-extend, store, half: 0 low,
/// 1 high, 2 = the whole VGPR).
fn flat_small(op: &str) -> Option<(u32, bool, bool, u32)> {
Some(match op {
"load_ubyte" => (1, false, false, 2),
"load_sbyte" => (1, true, false, 2),
"load_ushort" => (2, false, false, 2),
"load_sshort" => (2, true, false, 2),
"store_byte" => (1, false, true, 2),
"store_short" => (2, false, true, 2),
_ => return d16_small(op),
})
}
/// DS d16 forms: (bits, sign-extend, write, half).
fn ds_d16(name: &str) -> Option<(u32, bool, bool, u32)> {
Some(match name {
"ds_read_u8_d16" => (8, false, false, 0),
"ds_read_u8_d16_hi" => (8, false, false, 1),
"ds_read_i8_d16" => (8, true, false, 0),
"ds_read_i8_d16_hi" => (8, true, false, 1),
"ds_read_u16_d16" => (16, false, false, 0),
"ds_read_u16_d16_hi" => (16, false, false, 1),
"ds_write_b8_d16_hi" => (8, false, true, 1),
"ds_write_b16_d16_hi" => (16, false, true, 1),
_ => return None,
})
}
/// The data a d16 store takes from VGPR `v` (half 1: the high 16 bits).
fn d16_data(v: &str, half: u32) -> String {
if half == 1 {
format!("({v} >> 16)")
} else {
v.to_string()
}
}
/// VGPR `v` after loading `n` bytes (`raw`, low bits) as half 0 / 1 (the other half kept)
/// or as the whole register (half 2).
fn d16_merge(v: &str, raw: &str, n: u32, signed: bool, half: u32) -> String {
let bits = 8 * n;
let val = if signed { format!("(uint)(((int)(({raw}) << {}u)) >> {}u)", 32 - bits, 32 - bits) } else { format!("(({raw}) & {}u)", (1u64 << bits) - 1) };
match half {
0 => format!("({v} & 0xFFFF0000u) | ({val} & 0xFFFFu)"),
1 => format!("({v} & 0xFFFFu) | ({val} << 16)"),
_ => val,
}
}
/// Per-lane private memory of scratch_* (static = thread-private in HLSL; 4 KB per lane).
const PRELUDE_SCRATCH: &str = r#"
static uint xcl_scratch[1024];
uint scr_ld(uint a) { uint b = (a >> 2) & 1023u; uint s = (a & 3u) * 8u; uint lo = xcl_scratch[b]; uint hi = xcl_scratch[(b + 1u) & 1023u]; return select(s == 0u, lo, (lo >> s) | (hi << ((32u - s) & 31u))); }
void scr_st(uint a, uint v, uint n) {
uint b = (a >> 2) & 1023u; uint s = (a & 3u) * 8u; uint m = select(n >= 4u, 0xFFFFFFFFu, (1u << ((8u * n) & 31u)) - 1u);
xcl_scratch[b] = (xcl_scratch[b] & ~(m << s)) | ((v & m) << s);
if (s != 0u && s + 8u * n > 32u) { uint b2 = (b + 1u) & 1023u; xcl_scratch[b2] = (xcl_scratch[b2] & ~(m >> (32u - s))) | ((v & m) >> (32u - s)); }
}
"#;
const PRELUDE_MEM: &str = r#"
uint4 ld_raw(uint a) {
uint b = a & ~3u; uint s = (a & 3u) * 8u;
@@ -3539,6 +3901,14 @@ uint lanemask_lt_lo() { return lane_id >= 32u ? 0xFFFFFFFFu : (lane_id == 0u ? 0
uint lanemask_lt_hi() { return lane_id <= 32u ? 0u : (0xFFFFFFFFu >> (64u - lane_id)); }
uint wqm(uint m) { uint q = m | (m >> 1); q = q | (q >> 2); q &= 0x11111111u; return q * 15u; }
float mul_legacy(float a, float b) { return select(or(a == 0.0f, b == 0.0f), 0.0f, a * b); }
uint absd8(uint a, uint b, uint k) { uint x = (a >> k) & 0xFFu; uint y = (b >> k) & 0xFFu; return max(x, y) - min(x, y); }
uint absd16(uint a, uint b, uint k) { uint x = (a >> k) & 0xFFFFu; uint y = (b >> k) & 0xFFFFu; return max(x, y) - min(x, y); }
uint sad_u8(uint a, uint b) { return absd8(a, b, 0u) + absd8(a, b, 8u) + absd8(a, b, 16u) + absd8(a, b, 24u); }
uint msad_u8(uint a, uint b) { return select((b & 0xFFu) != 0u, absd8(a, b, 0u), 0u) + select(((b >> 8) & 0xFFu) != 0u, absd8(a, b, 8u), 0u) + select(((b >> 16) & 0xFFu) != 0u, absd8(a, b, 16u), 0u) + select((b >> 24) != 0u, absd8(a, b, 24u), 0u); }
uint lerp8(uint a, uint b, uint c, uint k) { return ((((a >> k) & 0xFFu) + ((b >> k) & 0xFFu) + ((c >> k) & 1u)) >> 1) << k; }
uint lerp_u8(uint a, uint b, uint c) { return lerp8(a, b, c, 0u) | lerp8(a, b, c, 8u) | lerp8(a, b, c, 16u) | lerp8(a, b, c, 24u); }
uint sat_i32(int64_t r) { return select(r > (int64_t)0x7FFFFFFF, 0x7FFFFFFFu, select(r < -(int64_t)0x80000000u, 0x80000000u, (uint)r)); }
float div_fixup(float q, float d, float n) { return select(or(or(isnan(d), isnan(n)), or(d == 0.0f, or(isinf(d), isinf(n)))), n / d, q); }
float fma_legacy(float a, float b, float c) { return (a == 0.0f || b == 0.0f) ? c : mad(a, b, c); }
float mad_nf(float a, float b, float c) { precise float p = a * b; precise float r = p + c; return r; }
float med3f(float a, float b, float c) { return max(min(a, b), min(max(a, b), c)); }
+90 -32
View File
@@ -342,7 +342,7 @@ struct Ctx<'a> {
/// every branch: (address of the branch, target)
edges: &'a [(u64, u64)],
/// `structurable_to` results: (lo, hi, exit) → targets leaving the range
memo: std::cell::RefCell<std::collections::HashMap<(u64, u64, Option<u64>, usize), Option<BTreeSet<u64>>>>,
memo: std::cell::RefCell<std::collections::HashMap<MemoKey, Option<BTreeSet<u64>>>>,
}
/// How a block ends (from its last instruction).
@@ -379,8 +379,13 @@ fn why(_at: u64, msg: &str) {
}
}
/// (lo, hi, exit, nest, loop head of `continue`, targets entering the range)
type MemoKey = (u64, u64, Option<u64>, usize, Option<u64>, Vec<u64>);
/// Target of an s_endpgm before the end of the program: "skip to the end".
const END: u64 = u64::MAX;
/// "Target" of a jump back to the head of the innermost loop: `continue`.
const CONT: u64 = u64::MAX - 1;
/// Deepest if / loop nesting of structured code: deeper conditional jumps become skip flags
/// (flat). Pixel shaders check for "no live lane left" after every discard and jump to one
/// shared exit – as ifs that would nest hundreds deep (the translator's recursion and DXC's
@@ -425,15 +430,16 @@ impl Item {
/// at this level – no if may swallow one, a conditional jump past it becomes a skip flag).
/// Err: a shape the structured form cannot express (backward jumps other than loop latches,
/// s_setpc …).
fn item_at(c: &Ctx, i: usize, lo: u64, hi: u64, exit: Option<u64>, nest: usize, pending: &BTreeSet<u64>) -> Result<(Item, usize), String> {
fn item_at(c: &Ctx, i: usize, lo: u64, hi: u64, exit: Option<u64>, nest: usize, cont: Option<u64>, pending: &BTreeSet<u64>) -> Result<(Item, usize), String> {
let start = c.leaders[i];
let end = block_end(c, i);
let next = |x: u64| c.leaders.partition_point(|&l| l < x);
let inside = |a: u64, b: u64| pending.iter().any(|&p| p > a && p < b);
if let Some(&(a, b)) = c.loops.iter().find(|&&(a, b)| a == start && b <= hi && (a, b) != (lo, hi)) {
// (a range that is exactly a loop – e.g. the body of an if – is that loop)
if let Some(&(a, b)) = c.loops.iter().find(|&&(a, b)| a == start && b <= hi) {
let last = next(b) - 1;
let latch = c.leaders[last];
if !matches!(term(c, latch, b), Term::Cond(t) if t == a) {
if !matches!(term(c, latch, b), Term::Cond(t) | Term::Jump(t) if t == a) {
return Err(format!("pętla {a:#x}..{b:#x}: koniec {:?}", term(c, latch, b)));
}
return Ok((Item::Loop { a, b, latch, entry: None }, next(b)));
@@ -441,6 +447,8 @@ fn item_at(c: &Ctx, i: usize, lo: u64, hi: u64, exit: Option<u64>, nest: usize,
let last_pc = c.insts.last().map_or(0, |d| d.pc);
let item = match term(c, start, end) {
Term::Next => Item::Block { start, end, raise: None },
// back to the head of the innermost loop: continue
Term::Cond(t) | Term::Jump(t) if Some(t) == cont => Item::Block { start, end, raise: Some(CONT) },
// a jump into the loop that starts right after: the rotated form (the jump itself is
// the loop entry, emitted as nothing)
Term::Jump(u) if rotated_loop(c, start, end, u, lo, hi).is_some() => Item::Block { start, end, raise: None },
@@ -448,7 +456,7 @@ fn item_at(c: &Ctx, i: usize, lo: u64, hi: u64, exit: Option<u64>, nest: usize,
// if / else only when both branches are structured on their own, the if branch
// does not jump into the else branch and no earlier jump lands in it; otherwise a
// plain if (the else branch then runs under the skip flag of the jump over it)
let u = else_end(c, end, t, hi).filter(|&u| !inside(start, u) && else_ok(c, end, t, u, nest));
let u = else_end(c, end, t, hi).filter(|&u| !inside(start, u) && else_ok(c, end, t, u, nest, cont));
return Ok((Item::If { start, end, t, u }, next(u.unwrap_or(t))));
}
// past the level, or over a target an earlier jump waits for: a skip flag
@@ -483,7 +491,7 @@ fn rotated_loop(c: &Ctx, start: u64, end: u64, u: u64, lo: u64, hi: u64) -> Opti
c.leaders.binary_search(&u).ok()?;
let last = c.leaders.partition_point(|&l| l < b) - 1;
let latch = c.leaders[last];
if u > latch || !matches!(term(c, latch, b), Term::Cond(t) if t == a) {
if u > latch || !matches!(term(c, latch, b), Term::Cond(t) | Term::Jump(t) if t == a) {
return None;
}
let outside_in = c.edges.iter().any(|&(src, dst)| dst >= a && dst < b && (src < a || src >= b) && !(dst == u && src >= start && src < end));
@@ -492,19 +500,21 @@ fn rotated_loop(c: &Ctx, start: u64, end: u64, u: u64, lo: u64, hi: u64) -> Opti
/// `if (!c) { [end, t) } else { [t, u) }` holds: both branches structured, the if branch does
/// not jump into the else branch.
fn else_ok(c: &Ctx, end: u64, t: u64, u: u64, nest: usize) -> bool {
match structurable_to(c, end, t, Some(u), nest + 1) {
Some(r) if !r.iter().any(|&x| x >= t && x < u) => structurable_to(c, t, u, None, nest + 1).is_some(),
fn else_ok(c: &Ctx, end: u64, t: u64, u: u64, nest: usize, cont: Option<u64>) -> bool {
let none = BTreeSet::new();
match structurable_to(c, end, t, Some(u), nest + 1, cont, &none) {
Some(r) if !r.iter().any(|&x| x >= t && x < u) => structurable_to(c, t, u, None, nest + 1, cont, &none).is_some(),
_ => false,
}
}
/// Can [lo, hi) be emitted as structured code (no `pc` guards)? Linear blocks, forward
/// conditional skips, if / else, loops whose only way back is a branch at their end, and
/// conditional skips, if / else, loops whose only way back is a (conditional or not) branch
/// at their end, and
/// forward jumps out of nested code (loop breaks, jumps past a join, s_endpgm before the end)
/// whose target starts an item of an enclosing level. Some(targets that leave the range).
fn structurable(c: &Ctx, lo: u64, hi: u64) -> Option<BTreeSet<u64>> {
structurable_to(c, lo, hi, None, 0)
structurable_to(c, lo, hi, None, 0, None, &BTreeSet::new())
}
/// The else branch of `if (cond) { [then_lo, t) } else { [t, u) }`: the last block of the
@@ -521,18 +531,30 @@ fn else_end(c: &Ctx, then_lo: u64, t: u64, hi: u64) -> Option<u64> {
}
}
fn structurable_to(c: &Ctx, lo: u64, hi: u64, exit: Option<u64>, nest: usize) -> Option<BTreeSet<u64>> {
let key = (lo, hi, exit, nest.min(MAX_NEST));
/// `cont`: head of the innermost loop (a jump back to it is `continue`); `incoming`: forward
/// targets of jumps from before the range that land inside it (a loop entered in its middle:
/// the code before them runs under their skip flags, i.e. from the second iteration on).
fn structurable_to(c: &Ctx, lo: u64, hi: u64, exit: Option<u64>, nest: usize, cont: Option<u64>, incoming: &BTreeSet<u64>) -> Option<BTreeSet<u64>> {
let key = (lo, hi, exit, nest.min(MAX_NEST), cont, incoming.iter().copied().collect::<Vec<_>>());
if let Some(r) = c.memo.borrow().get(&key) {
return r.clone();
}
let r = structurable_uncached(c, lo, hi, exit, nest);
let r = structurable_uncached(c, lo, hi, exit, nest, cont, incoming);
c.memo.borrow_mut().insert(key, r.clone());
r
}
fn structurable_uncached(c: &Ctx, lo: u64, hi: u64, exit: Option<u64>, nest: usize) -> Option<BTreeSet<u64>> {
let mut pending: BTreeSet<u64> = BTreeSet::new();
/// Targets of `pending` strictly inside loop [a, b): they enter it (taken out of `pending`).
fn enter_loop(pending: &mut BTreeSet<u64>, a: u64, b: u64) -> BTreeSet<u64> {
let inner: BTreeSet<u64> = pending.range(a + 1..b).copied().collect();
for t in &inner {
pending.remove(t);
}
inner
}
fn structurable_uncached(c: &Ctx, lo: u64, hi: u64, exit: Option<u64>, nest: usize, cont: Option<u64>, incoming: &BTreeSet<u64>) -> Option<BTreeSet<u64>> {
let mut pending: BTreeSet<u64> = incoming.clone();
let mut i = c.leaders.partition_point(|&l| l < lo);
let mut queued: Option<Item> = None;
while queued.is_some() || (i < c.leaders.len() && c.leaders[i] < hi) {
@@ -540,7 +562,7 @@ fn structurable_uncached(c: &Ctx, lo: u64, hi: u64, exit: Option<u64>, nest: usi
Some(q) => q,
None => {
pending.remove(&c.leaders[i]);
match item_at(c, i, lo, hi, exit, nest, &pending) {
match item_at(c, i, lo, hi, exit, nest, cont, &pending) {
Ok((it, n)) => {
queued = rotated_after(c, i, lo, hi);
i = if let Some(Item::Loop { b, .. }) = queued { c.leaders.partition_point(|&l| l < b) } else { n };
@@ -555,37 +577,43 @@ fn structurable_uncached(c: &Ctx, lo: u64, hi: u64, exit: Option<u64>, nest: usi
};
let (s, e) = it.range();
pending.remove(&s);
let inner = match it {
Item::Loop { a, b, entry: None, .. } => enter_loop(&mut pending, a, b),
_ => BTreeSet::new(),
};
if let Some(t) = pending.iter().find(|&&t| t > s && t < e) {
why(s, &format!("skok do {t:#x} wewnątrz {s:#x}..{e:#x}"));
return None;
}
let none = BTreeSet::new();
let raised: BTreeSet<u64> = match it {
Item::Loop { a, latch, entry: None, .. } => {
let mut r = structurable_to(c, a, latch, None, nest + 1)?;
let mut r = structurable_to(c, a, latch, None, nest + 1, Some(a), &inner)?;
r.remove(&latch);
r
}
Item::Loop { a, latch, entry: Some(u), .. } => {
// the head [a, u) runs at the end of an iteration and may only fall into u
if structurable_to(c, a, u, None, nest + 1)?.iter().any(|&t| t != u) {
if structurable_to(c, a, u, None, nest + 1, None, &none)?.iter().any(|&t| t != u) {
why(a, &format!("pętla obrócona {a:#x}: głowa wychodzi poza {u:#x}"));
return None;
}
let mut r = structurable_to(c, u, latch, None, nest + 1)?;
let mut r = structurable_to(c, u, latch, None, nest + 1, None, &none)?;
r.remove(&latch);
r
}
Item::If { end, t, u, .. } => {
let mut r = structurable_to(c, end, t, u, nest + 1)?;
let mut r = structurable_to(c, end, t, u, nest + 1, cont, &none)?;
if let Some(u) = u {
if r.contains(&t) {
why(t, &format!("skok z if na początek else {t:#x}"));
return None;
}
r.extend(structurable_to(c, t, u, None, nest + 1)?);
r.extend(structurable_to(c, t, u, None, nest + 1, cont, &none)?);
}
r
}
Item::Block { raise: Some(CONT), .. } => BTreeSet::new(),
Item::Block { raise, .. } => raise.into_iter().collect(),
};
if let Some(t) = raised.iter().find(|&&t| t < e) {
@@ -616,9 +644,24 @@ fn emit_block(c: &Ctx, em: &mut emit::Em, body: &mut String, start: u64, end: u6
/// Emit a range `structurable` accepted; returns the jump targets that leave it (their flags
/// are set; `flags` collects every flag for the declarations).
fn emit_structured(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, exit: Option<u64>, nest: usize, depth: usize, blocks: &mut usize, flags: &mut BTreeSet<u64>) -> BTreeSet<u64> {
#[allow(clippy::too_many_arguments)]
fn emit_structured(
c: &Ctx,
em: &mut emit::Em,
body: &mut String,
lo: u64,
hi: u64,
exit: Option<u64>,
nest: usize,
cont: Option<u64>,
incoming: &BTreeSet<u64>,
depth: usize,
blocks: &mut usize,
flags: &mut BTreeSet<u64>,
) -> BTreeSet<u64> {
let pad = " ".repeat(depth);
let mut pending: BTreeSet<u64> = BTreeSet::new();
let mut pending: BTreeSet<u64> = incoming.clone();
let none = BTreeSet::new();
// flags of the open `if (!(skip …)) {` around the following items
let mut guard: Option<BTreeSet<u64>> = None;
let mut i = c.leaders.partition_point(|&l| l < lo);
@@ -628,13 +671,18 @@ fn emit_structured(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u
let it = match queued.take() {
Some(q) => q,
None => {
let Ok((it, n)) = item_at(c, i, lo, hi, exit, nest, &pending) else { break };
let Ok((it, n)) = item_at(c, i, lo, hi, exit, nest, cont, &pending) else { break };
queued = rotated_after(c, i, lo, hi);
i = if let Some(Item::Loop { b, .. }) = queued { c.leaders.partition_point(|&l| l < b) } else { n };
it
}
};
let (s, _) = it.range();
// targets inside a loop enter it: not a guard around the loop
let inner = match it {
Item::Loop { a, b, entry: None, .. } => enter_loop(&mut pending, a, b),
_ => BTreeSet::new(),
};
if guard.as_ref() != Some(&pending).filter(|p| !p.is_empty()) {
if guard.take().is_some() {
body.push_str(&format!("{pad}}}\n"));
@@ -653,7 +701,8 @@ fn emit_structured(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u
let raised: BTreeSet<u64> = match it {
Item::Loop { a, b, latch, entry } => {
body.push_str(&format!("{ipad}[loop] for (;;) {{\n"));
let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, d + 1, blocks, flags);
let (lcont, lin) = if entry.is_none() { (Some(a), &inner) } else { (None, &none) };
let mut r = emit_structured(c, em, body, entry.unwrap_or(a), latch, None, nest + 1, lcont, lin, d + 1, blocks, flags);
for &t in &r {
if t == latch {
body.push_str(&format!("{ipad} {} = false;\n", skip_flag(t)));
@@ -664,11 +713,13 @@ fn emit_structured(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u
r.remove(&latch);
match emit_block(c, em, body, latch, b, d + 1, blocks) {
emit::Flow::Cond(cond, _) => body.push_str(&format!("{ipad} if (!({cond})) break;\n")),
// unconditional back edge: the loop is left through the skip flags' breaks
emit::Flow::Jump(_) => {}
_ => body.push_str(&format!("{ipad} break;\n")),
}
if let Some(u) = entry {
// rotated: the head after the latch, falling into the next iteration
for t in emit_structured(c, em, body, a, u, None, nest + 1, d + 1, blocks, flags) {
for t in emit_structured(c, em, body, a, u, None, nest + 1, None, &none, d + 1, blocks, flags) {
body.push_str(&format!("{ipad} {} = false;\n", skip_flag(t)));
}
}
@@ -681,10 +732,10 @@ fn emit_structured(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u
_ => "false".into(),
};
body.push_str(&format!("{ipad}if (!({cond})) {{\n"));
let mut r = emit_structured(c, em, body, end, t, u, nest + 1, d + 1, blocks, flags);
let mut r = emit_structured(c, em, body, end, t, u, nest + 1, cont, &none, d + 1, blocks, flags);
if let Some(u) = u {
body.push_str(&format!("{ipad}}} else {{\n"));
r.extend(emit_structured(c, em, body, t, u, None, nest + 1, d + 1, blocks, flags));
r.extend(emit_structured(c, em, body, t, u, None, nest + 1, cont, &none, d + 1, blocks, flags));
}
body.push_str(&format!("{ipad}}}\n"));
r
@@ -693,6 +744,13 @@ fn emit_structured(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u
let flow = emit_block(c, em, body, start, end, d, blocks);
match raise {
None => BTreeSet::new(),
Some(CONT) => {
match flow {
emit::Flow::Cond(cond, _) => body.push_str(&format!("{ipad}if ({cond}) continue;\n")),
_ => body.push_str(&format!("{ipad}continue;\n")),
}
BTreeSet::new()
}
Some(t) => {
flags.insert(t);
match flow {
@@ -736,7 +794,7 @@ fn structured_span(c: &Ctx, i: usize, hi: u64) -> Option<u64> {
}
// entered only at start: no branch from outside lands strictly inside
let entered_inside = |x: u64| c.edges.iter().any(|&(src, dst)| dst > start && dst < x && (src < start || src >= x));
ends.iter().rev().take(64).copied().find(|&x| !entered_inside(x) && structurable_to(c, start, x, None, 0).is_some_and(|r| r.iter().all(|&t| t == x)))
ends.iter().rev().take(64).copied().find(|&x| !entered_inside(x) && structurable_to(c, start, x, None, 0, None, &BTreeSet::new()).is_some_and(|r| r.iter().all(|&t| t == x)))
}
/// Emit the blocks starting in [lo, hi) at nesting `depth`; loop ranges become `while`.
@@ -756,7 +814,7 @@ fn emit_range(c: &Ctx, em: &mut emit::Em, body: &mut String, lo: u64, hi: u64, d
// a single-entry, single-exit stretch: structured code under one guard
if let Some(x) = structured_span(c, i, hi) {
body.push_str(&format!("{pad}if (pc == {start}u) {{\n"));
for t in emit_structured(c, em, body, start, x, None, 0, depth + 1, blocks, flags) {
for t in emit_structured(c, em, body, start, x, None, 0, None, &BTreeSet::new(), depth + 1, blocks, flags) {
body.push_str(&format!("{pad} {} = false;\n", skip_flag(t)));
}
let next = if x == u64::MAX || !c.starts.contains(&x) { "0xFFFFFFFFu".to_string() } else { format!("{x}u") };
@@ -954,7 +1012,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result<Translation, String> {
if gs_jump.is_none() && std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none() && structurable(&ctx, 0, u64::MAX).is_some() {
// structured control flow: plain if / loops, no block dispatch on `pc` (much
// smaller for DXC and the driver on big programs)
emit_structured(&ctx, &mut em, &mut code, 0, u64::MAX, None, 0, 1, &mut blocks, &mut flags);
emit_structured(&ctx, &mut em, &mut code, 0, u64::MAX, None, 0, None, &BTreeSet::new(), 1, &mut blocks, &mut flags);
} else {
code.push_str(" uint pc = 0;\n");
emit_range(&ctx, &mut em, &mut code, 0, u64::MAX, 1, &mut blocks, &mut flags);
+144 -2
View File
@@ -558,6 +558,8 @@ fn gpu_images_sample_load_store_atomic() {
// tex1: R32_UINT UAV, T# in s[32:39] (SRSRC = 8); tex2: 1x1 R32_UINT UAV in s[40:47] (10)
code.extend(mimg("IMAGE_STORE", &[("VDATA", 6), ("VADDR", 37), ("SRSRC", 8), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)]));
code.extend(mimg("IMAGE_ATOMIC_UMAX", &[("VDATA", 7), ("VADDR", 35), ("SRSRC", 10), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)]));
// tex3: 1x1 R32_UINT UAV in s[48:55] (12): image_atomic_inc (no HLSL intrinsic: CAS loop)
code.extend(mimg("IMAGE_ATOMIC_INC", &[("VDATA", 39), ("VADDR", 35), ("SRSRC", 12), ("DMASK", 0x1), ("DIM", 1), ("UNORM", 1)]));
code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
let mut st = KernelState::default();
@@ -566,6 +568,7 @@ fn gpu_images_sample_load_store_atomic() {
st.sgpr[28..32].copy_from_slice(&[0, 0, 0, 1]);
st.sgpr[32..40].copy_from_slice(&tsharp(2, 20, 9));
st.sgpr[40..48].copy_from_slice(&tsharp(4, 20, 9));
st.sgpr[48..56].copy_from_slice(&tsharp(6, 20, 9));
for (l, r) in st.vgpr.iter_mut().enumerate() {
let (x, y) = ((l % 4) as u32, (l / 4 % 4) as u32);
r[0] = f((x as f32 + 0.5) / 4.0);
@@ -584,6 +587,7 @@ fn gpu_images_sample_load_store_atomic() {
r[36] = 0;
r[37] = x; // lanes 16.. land outside the 4x4 texture: their stores are dropped
r[38] = l as u32 / 4;
r[39] = 100;
}
// tex0: 4x4 RGBA32F, texel (x, y) = (x, y, x + 4y, 1)
let mut t0 = Vec::new();
@@ -598,6 +602,7 @@ fn gpu_images_sample_load_store_atomic() {
TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32G32B32A32_FLOAT, width: 4, height: 4, depth: 1, texel_bytes: 16, data: t0, uav: false },
TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32_UINT, width: 4, height: 4, depth: 1, texel_bytes: 4, data: vec![0xEE; 64], uav: true },
TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32_UINT, width: 1, height: 1, depth: 1, texel_bytes: 4, data: vec![0; 4], uav: true },
TestTexture { dim: TexDim::D2, format: DXGI_FORMAT_R32_UINT, width: 1, height: 1, depth: 1, texel_bytes: 4, data: vec![0; 4], uav: true },
];
let samp = vec![
TestSampler { filter: D3D12_FILTER_MIN_MAG_MIP_POINT, address: D3D12_TEXTURE_ADDRESS_MODE_CLAMP, comparison: None },
@@ -619,6 +624,7 @@ fn gpu_images_sample_load_store_atomic() {
assert_eq!(t1[i], 10 * i as u32, "image_store texel {i}");
}
assert_eq!(u32::from_le_bytes(r.textures[1][..4].try_into().unwrap()), 63, "image_atomic_umax");
assert_eq!(u32::from_le_bytes(r.textures[2][..4].try_into().unwrap()), 64, "image_atomic_inc (64 lanes, limit 100)");
}
#[test]
@@ -1937,6 +1943,135 @@ fn gpu_global_atomics_and_sub_dword_access() {
}
}
/// The instructions added for code outside the retail pack: global inc / dec / csub /
/// 64-bit add, LDS signed min / max, cmpst, mskor, float add (CAS loops), global sub-dword
/// and d16 accesses, scratch, SAD / lerp, the division helpers, saturating adds, packs, swap.
#[test]
fn gpu_more_atomics_sub_dword_scratch_valu() {
if !gpu_ready() {
return;
}
let enc = |n: &'static str, e: &'static str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}"));
let glbl = |n: &'static str, f: &[(&str, u64)]| enc(n, "ENC_FLAT_GLBL", f);
let ds = |n: &'static str, f: &[(&str, u64)]| enc(n, "ENC_DS", f);
let vop3 = |n: &'static str, f: &[(&str, u64)]| enc(n, "ENC_VOP3", f);
let mut code = Vec::new();
// global atomics at 0x600 + offset (s[2:3] + v30 = 0)
code.extend(glbl("GLOBAL_ATOMIC_INC", &[("ADDR", 30), ("DATA", 21), ("SADDR", 2), ("OFFSET", 0)]));
code.extend(glbl("GLOBAL_ATOMIC_DEC", &[("ADDR", 30), ("DATA", 21), ("SADDR", 2), ("OFFSET", 4)]));
code.extend(glbl("GLOBAL_ATOMIC_CSUB", &[("ADDR", 30), ("DATA", 35), ("SADDR", 2), ("OFFSET", 8)]));
code.extend(glbl("GLOBAL_ATOMIC_ADD_X2", &[("ADDR", 30), ("DATA", 38), ("SADDR", 2), ("OFFSET", 16)]));
// LDS: initial values, then the atomics, then read back
for (a, v) in [(7, 8), (17, 9), (18, 10), (19, 12), (20, 15)] {
code.extend(ds("DS_WRITE_B32", &[("ADDR", a), ("DATA0", v)]));
}
code.extend(enc("S_BARRIER", "ENC_SOPP", &[]));
code.extend(ds("DS_MAX_I32", &[("ADDR", 7), ("DATA0", 33)]));
code.extend(ds("DS_MIN_I32", &[("ADDR", 17), ("DATA0", 33)]));
code.extend(ds("DS_CMPST_RTN_B32", &[("VDST", 53), ("ADDR", 18), ("DATA0", 10), ("DATA1", 11)]));
code.extend(ds("DS_MSKOR_B32", &[("ADDR", 19), ("DATA0", 13), ("DATA1", 14)]));
code.extend(ds("DS_ADD_F32", &[("ADDR", 20), ("DATA0", 16)]));
code.extend(enc("S_BARRIER", "ENC_SOPP", &[]));
for (k, a) in [7u64, 17, 18, 19, 20].iter().enumerate() {
code.extend(ds("DS_READ_B32", &[("VDST", 54 + k as u64), ("ADDR", *a)]));
}
// global bytes at 0x780 + lane, shorts at 0x700 + 2 · lane (s[2:3] + v + 0x100 / 0x180)
code.extend(glbl("GLOBAL_STORE_BYTE", &[("ADDR", 3), ("DATA", 36), ("SADDR", 2), ("OFFSET", 0x100)]));
code.extend(glbl("GLOBAL_LOAD_UBYTE", &[("VDST", 59), ("ADDR", 3), ("SADDR", 2), ("OFFSET", 0x100)]));
code.extend(glbl("GLOBAL_LOAD_SBYTE", &[("VDST", 60), ("ADDR", 3), ("SADDR", 2), ("OFFSET", 0x100)]));
code.extend(glbl("GLOBAL_LOAD_UBYTE_D16_HI", &[("VDST", 61), ("ADDR", 3), ("SADDR", 2), ("OFFSET", 0x100)]));
code.extend(glbl("GLOBAL_STORE_SHORT_D16_HI", &[("ADDR", 2), ("DATA", 62), ("SADDR", 2), ("OFFSET", 0x100)]));
code.extend(glbl("GLOBAL_LOAD_USHORT", &[("VDST", 63), ("ADDR", 2), ("SADDR", 2), ("OFFSET", 0x100)]));
// scratch (per lane): a dword at 2 · lane + 16, a byte at 2 · lane + 40
code.extend(enc("SCRATCH_STORE_DWORD", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 11), ("SADDR", 0x7F), ("OFFSET", 16)]));
code.extend(enc("SCRATCH_STORE_BYTE", "ENC_FLAT_SCRATCH", &[("ADDR", 2), ("DATA", 36), ("SADDR", 0x7F), ("OFFSET", 40)]));
code.extend(enc("SCRATCH_LOAD_DWORD", "ENC_FLAT_SCRATCH", &[("VDST", 64), ("ADDR", 2), ("SADDR", 0x7F), ("OFFSET", 16)]));
code.extend(enc("SCRATCH_LOAD_UBYTE", "ENC_FLAT_SCRATCH", &[("VDST", 65), ("ADDR", 2), ("SADDR", 0x7F), ("OFFSET", 40)]));
// VALU
let vv = |n: u64| V + n;
code.extend(vop3("V_SAD_U8", &[("VDST", 66), ("SRC0", vv(22)), ("SRC1", vv(23)), ("SRC2", vv(24))]));
code.extend(vop3("V_MSAD_U8", &[("VDST", 67), ("SRC0", vv(22)), ("SRC1", vv(25)), ("SRC2", vv(24))]));
code.extend(vop3("V_LERP_U8", &[("VDST", 68), ("SRC0", vv(22)), ("SRC1", vv(23)), ("SRC2", vv(26))]));
code.extend(vop3("V_DIV_FIXUP_F32", &[("VDST", 69), ("SRC0", vv(37)), ("SRC1", vv(28)), ("SRC2", vv(27))]));
code.extend(vop3("V_DIV_FIXUP_F32", &[("VDST", 70), ("SRC0", vv(37)), ("SRC1", 128), ("SRC2", vv(27))]));
code.extend(vop3("V_DIV_FMAS_F32", &[("VDST", 71), ("SRC0", vv(28)), ("SRC1", vv(27)), ("SRC2", vv(28))]));
code.extend(enc("V_DIV_SCALE_F32", "VOP3_SDST_ENC", &[("VDST", 72), ("SDST", 106), ("SRC0", vv(27)), ("SRC1", vv(28)), ("SRC2", vv(27))]));
code.extend(vop3("V_ADD_NC_I32", &[("VDST", 73), ("SRC0", vv(29)), ("SRC1", vv(35)), ("CLAMP", 1)]));
code.extend(vop3("V_CVT_PK_U16_U32", &[("VDST", 74), ("SRC0", vv(76)), ("SRC1", vv(24))]));
code.extend(vop3("V_MAD_U32_U16", &[("VDST", 75), ("SRC0", vv(77)), ("SRC1", vv(78)), ("SRC2", vv(35))]));
code.extend(vop3("V_CVT_PKNORM_U16_F32", &[("VDST", 79), ("SRC0", 242), ("SRC1", 240)]));
code.extend(enc("V_SWAP_B32", "ENC_VOP1", &[("VDST", 80), ("SRC0", vv(81))]));
code.extend(enc("S_ENDPGM", "ENC_SOPP", &[]));
let mut st = KernelState::default();
st.sgpr[2] = 0x600;
for (l, r) in st.vgpr.iter_mut().enumerate() {
let l32 = l as u32;
r[2] = 2 * l32;
r[3] = 0x80 + l32;
for (k, a) in [(7, 512u32), (17, 516), (18, 520), (19, 524), (20, 528)] {
r[k] = a;
}
r[8] = (-100i32) as u32;
r[9] = 100;
r[10] = 7;
r[11] = l32 + 1;
r[12] = 0xFF00;
r[13] = 0xF0F0;
r[14] = 0x0101;
r[15] = 0;
r[16] = f(0.5);
r[21] = 10;
r[22] = 0x1020_3040;
r[23] = 0x4030_2010;
r[24] = 5;
r[25] = 0x0030_2010;
r[26] = 0x0101_0101;
r[27] = f(7.0);
r[28] = f(2.0);
r[29] = 0x7FFF_FFFF;
r[30] = 0;
r[33] = (l as i32 - 30) as u32;
r[35] = 1;
r[36] = 0x90 + l32;
r[37] = f(3.5);
r[38] = 1;
r[39] = 0;
r[61] = 0x1234;
r[62] = 0xBEEF_1111;
r[76] = 70000;
r[77] = 0x1_0003;
r[78] = 0x2_0004;
r[80] = 1;
r[81] = 2;
}
let mut mem = vec![0u32; 1024];
mem[0x604 / 4] = 5;
mem[0x608 / 4] = 50;
mem[0x610 / 4] = 0xFFFF_FFF0;
let r = runner::run_code(&code, &st, &mem).unwrap();
assert_eq!(r.mem[0x600 / 4], 64 % 11, "global_atomic_inc wraps at 10");
assert_eq!(r.mem[0x604 / 4], 7, "global_atomic_dec wraps to 10 below 0");
assert_eq!(r.mem[0x608 / 4], 0, "global_atomic_csub clamps at 0");
assert_eq!((r.mem[0x610 / 4], r.mem[0x614 / 4]), (0x30, 1), "global_atomic_add_x2 carries into the high dword");
assert_eq!(r.vgpr.iter().filter(|v| v[53] == 7).count(), 1, "ds_cmpst: one lane finds the compare value");
for l in 0..64usize {
let v = &r.vgpr[l];
let b = 0x90 + l as u32;
assert_eq!((v[54] as i32, v[55] as i32), (33, -30), "lane {l}: ds_max_i32 / ds_min_i32");
assert!((1..=64).contains(&v[56]), "lane {l}: ds_cmpst stored a lane's value");
assert_eq!((v[57], f32::from_bits(v[58])), (0x0F01, 32.0), "lane {l}: ds_mskor_b32 / ds_add_f32");
assert_eq!((v[59], v[60], v[61]), (b, b | 0xFFFF_FF00, 0x1234 | b << 16), "lane {l}: global ubyte / sbyte / ubyte_d16_hi");
assert_eq!(v[63], 0xBEEF, "lane {l}: global_store_short_d16_hi + load_ushort");
assert_eq!((v[64], v[65]), (l as u32 + 1, b), "lane {l}: scratch dword / byte");
assert_eq!((v[66], v[67], v[68]), (133, 85, 0x2828_2828), "lane {l}: v_sad_u8 / v_msad_u8 / v_lerp_u8");
assert_eq!((f32::from_bits(v[69]), f32::from_bits(v[70]), f32::from_bits(v[71])), (3.5, f32::INFINITY, 16.0), "lane {l}: div_fixup / fixup(x/0) / div_fmas");
assert_eq!((f32::from_bits(v[72]), v[73]), (7.0, 0x7FFF_FFFF), "lane {l}: v_div_scale_f32 / v_add_nc_i32 clamp");
assert_eq!((v[74], v[75], v[79]), (0x0005_FFFF, 13, 0x8000_FFFF), "lane {l}: cvt_pk_u16_u32 / mad_u32_u16 / cvt_pknorm_u16_f32");
assert_eq!((v[80], v[81]), (2, 1), "lane {l}: v_swap_b32");
}
assert_eq!(r.sgpr[106] | r.sgpr[107], 0, "v_div_scale_f32: VCC 0 (no post-scale)");
}
/// `XCL_BLOB=<console CS container>`: HLSL size and shape of its translation.
#[test]
#[ignore]
@@ -2249,7 +2384,13 @@ fn isa_coverage() {
let Some(ie) = inst.encs.iter().find(|e| ENCODINGS[e.encoding as usize].primary) else { continue };
let enc = ENCODINGS[ie.encoding as usize].name;
let lit = inst.always_literal.then_some(0);
let Ok(mut code) = encode(inst.name, enc, &[], lit) else { continue };
// operands that must not be 0: MIMG channel mask, VOP3 SDST (VCC)
let fields: &[(&str, u64)] = match enc {
"ENC_MIMG" => &[("DMASK", 1)],
"VOP3_SDST_ENC" => &[("SDST", 106)],
_ => &[],
};
let Ok(mut code) = encode(inst.name, enc, fields, lit) else { continue };
code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap());
let ok = std::panic::catch_unwind(|| {
try_mode(&code, Mode::Kernel) || try_mode(&code, Mode::Pixel(super::PsInterface { inputs: vec![], outputs: vec![], input_ena: 0x7F }))
@@ -2268,6 +2409,7 @@ fn isa_coverage() {
println!("instrukcje RDNA2 (spec + konsola): {all}, tłumaczone: {ok} ({:.1}%)", 100.0 * ok as f64 / all.max(1) as f64);
for (enc, (ok, all, missing)) in &per_enc {
let m: Vec<String> = missing.iter().map(|n| n.to_lowercase()).collect();
println!(" {enc:<12} {ok:>4} / {all:<4} brak: {}", if m.len() > 14 { format!("{} … (+{})", m[..14].join(", "), m.len() - 14) } else { m.join(", ") });
let full = std::env::var_os("XCL_ISA_FULL").is_some();
println!(" {enc:<12} {ok:>4} / {all:<4} brak: {}", if m.len() > 14 && !full { format!("{} … (+{})", m[..14].join(", "), m.len() - 14) } else { m.join(", ") });
}
}
+106 -20
View File
@@ -1,16 +1,20 @@
//! Console CBV/SRV/UAV descriptor heaps.
//! Console descriptor heaps (CBV/SRV/UAV and samplers).
//!
//! On the console a descriptor is GPU-readable memory: 32 bytes per slot (T# / V#), and a
//! descriptor table in a root argument is a 32-bit GPU address (shaders load it with the
//! high half 0 – amd_fidelityfx_upscaler_xbox.dll, HANDOFF "FSR4"). XCL gives console code
//! a heap whose slots live in unified memory (so the table addresses console code computes
//! from the heap start work as they are in the recompiler's `mem` model) and keeps a PC heap
//! with two descriptors per slot beside it: slot k → PC SRV at 2k, PC UAV at 2k + 1. The
//! slot holds the descriptor in the XCL shader ABI (`desc::xcl_image_words`: word 0 = 2k).
//! On the console a descriptor is GPU-readable memory: 32 bytes per CBV/SRV/UAV slot (T# /
//! V#), 16 per sampler (S#), and a descriptor table in a root argument is a 32-bit GPU address
//! (shaders load it with the high half 0 – amd_fidelityfx_upscaler_xbox.dll, HANDOFF "FSR4").
//! XCL gives console code heaps whose slots live in unified memory (so the table addresses
//! console code computes from the heap start work as they are in the recompiler's `mem`
//! model) and keeps a PC heap beside each: view slot k → PC SRV at 2k, PC UAV at 2k + 1;
//! sampler slot k → PC sampler k. A slot holds the descriptor in the XCL shader ABI
//! (`desc::xcl_image_words`: T# word 0 = 2k; `desc::xcl_sampler_words`: S# word 3 [11:0] = k;
//! V# with its unified-memory address).
use std::sync::Mutex;
/// bytes of a CBV/SRV/UAV slot (T# / V#) and of a sampler slot (S#)
pub const SLOT: u32 = 32;
pub const SAMPLER_SLOT: u32 = 16;
struct Heap {
obj: usize,
@@ -20,42 +24,70 @@ struct Heap {
/// 0: not shader visible
pc_gpu: u64,
inc: u32,
sampler: bool,
}
impl Heap {
fn slot_bytes(&self) -> u32 {
if self.sampler {
SAMPLER_SLOT
} else {
SLOT
}
}
}
static HEAPS: Mutex<Vec<Heap>> = Mutex::new(Vec::new());
/// `obj` is a PC heap with 2·`n` descriptors from `pc_cpu` / `pc_gpu` (increment `inc`;
/// `pc_gpu` 0 when not shader visible): give it `n` console slots in unified memory.
pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32) -> bool {
/// `obj` is a PC heap from `pc_cpu` / `pc_gpu` (increment `inc`; `pc_gpu` 0 when not shader
/// visible) with 2·`n` view descriptors or `n` samplers: give it `n` console slots in
/// unified memory.
pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: bool) -> bool {
let Some(u) = crate::gpu::uma::get() else { return false };
let Some(p) = u.alloc((n.max(1) * SLOT) as usize, 256) else { return false };
unsafe { std::ptr::write_bytes(p, 0, (n * SLOT) as usize) };
HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc });
let bytes = n.max(1) * if sampler { SAMPLER_SLOT } else { SLOT };
let Some(p) = u.alloc(bytes as usize, 256) else { return false };
unsafe { std::ptr::write_bytes(p, 0, bytes as usize) };
HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler });
true
}
/// The heap object was released for good: its slots go back to unified memory.
pub fn unregister(obj: usize) {
let gone = {
let mut heaps = HEAPS.lock().unwrap();
heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i))
};
if let (Some(h), Some(u)) = (gone, crate::gpu::uma::get()) {
u.free(h.shadow);
}
}
/// Start of the console slots of heap `obj` (CPU handle = GPU handle on the console).
pub fn start(obj: usize) -> Option<u64> {
HEAPS.lock().unwrap().iter().find(|h| h.obj == obj).map(|h| h.shadow as u64)
}
/// A console slot: where its descriptor goes and its two PC descriptors.
/// A console slot: where its descriptor goes and its PC descriptors.
#[derive(Clone, Copy, Debug)]
pub struct Slot {
pub at: usize,
/// PC heap index of the SRV (the UAV is at + 1)
/// views: PC heap index of the SRV (the UAV is at + 1); samplers: of the sampler
pub index: u32,
pub pc_srv: u64,
pub pc_uav: u64,
/// PC GPU handle of the UAV (0: heap not shader visible)
pub pc_gpu_uav: u64,
pub sampler: bool,
}
/// The slot behind a console CPU handle (None: not one of XCL's console heaps).
pub fn slot(cpu: u64) -> Option<Slot> {
let heaps = HEAPS.lock().unwrap();
let h = heaps.iter().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * SLOT) as usize) as u64)?;
let k = ((cpu - h.shadow as u64) / SLOT as u64) as u32;
let h = heaps.iter().find(|h| cpu >= h.shadow as u64 && cpu < (h.shadow + (h.n * h.slot_bytes()) as usize) as u64)?;
let k = ((cpu - h.shadow as u64) / h.slot_bytes() as u64) as u32;
if h.sampler {
return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index: k, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true });
}
let uav = ((2 * k + 1) * h.inc) as u64;
Some(Slot {
at: h.shadow + (k * SLOT) as usize,
@@ -63,18 +95,72 @@ pub fn slot(cpu: u64) -> Option<Slot> {
pc_srv: h.pc_cpu + (2 * k * h.inc) as u64,
pc_uav: h.pc_cpu + uav,
pc_gpu_uav: if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav },
sampler: false,
})
}
pub fn write(s: &Slot, words: &[u32]) {
let n = words.len().min(8);
let n = words.len().min(if s.sampler { 4 } else { 8 });
unsafe { std::ptr::copy_nonoverlapping(words.as_ptr(), s.at as *mut u32, n) };
}
/// Copy a console slot's descriptor to another slot of the same kind, the PC heap index
/// in it (T# word 0, S# word 3 [11:0]) renumbered for the destination. Buffer V# carry
/// their address and stay as they are.
pub fn copy_words(src: &Slot, dst: &Slot) {
let n = if src.sampler { 4 } else { 8 };
let mut w = [0u32; 8];
unsafe { std::ptr::copy_nonoverlapping(src.at as *const u32, w.as_mut_ptr(), n) };
if src.sampler {
w[3] = (w[3] & !0xFFF) | (dst.index & 0xFFF);
} else if w[3] >> 28 >= 8 {
w[0] = dst.index;
}
write(dst, &w[..n]);
}
/// The descriptor at a console GPU address (low 32 bits, as in a descriptor table), if it
/// is in one of the console heaps.
pub fn words_at(addr32: u32) -> Option<[u32; 8]> {
let u = crate::gpu::uma::get()?;
let s = slot((u.base() + addr32 as usize) as u64)?;
Some(unsafe { std::ptr::read(s.at as *const [u32; 8]) })
let mut w = [0u32; 8];
unsafe { std::ptr::copy_nonoverlapping(s.at as *const u32, w.as_mut_ptr(), if s.sampler { 4 } else { 8 }) };
Some(w)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slots_copy_and_release() {
let Some(u) = crate::gpu::uma::get() else { return };
let rel = |p: u64| (p as usize - u.base()) as u32;
// views: 4 slots over a PC heap at 0x1000 (increment 32, GPU 0x5000); samplers: 2 at 0x9000
assert!(register(0xA1, 4, 0x1000, 0x5000, 32, false));
assert!(register(0xA2, 2, 0x9000, 0, 16, true));
let (v, sm) = (start(0xA1).unwrap(), start(0xA2).unwrap());
let s1 = slot(v + 32).unwrap();
assert_eq!((s1.index, s1.pc_srv, s1.pc_uav, s1.pc_gpu_uav), (2, 0x1040, 0x1060, 0x5060));
// a 2D T# from slot 1 to slot 3: word 0 = the destination's SRV index
write(&s1, &[2, 0x0470_0000, 0, 9 << 28, 0, 0, 0, 0]);
let s3 = slot(v + 96).unwrap();
copy_words(&s1, &s3);
assert_eq!(words_at(rel(v + 96)).unwrap()[..4], [6, 0x0470_0000, 0, 9 << 28]);
// a buffer V# keeps its address
write(&s1, &[0x1234, 0, 64, 0x3101_6FAC, 0, 0, 0, 0]);
copy_words(&s1, &s3);
assert_eq!(words_at(rel(v + 96)).unwrap()[0], 0x1234);
// samplers: 16-byte slots, S# word 3 [11:0] = sampler index
let (q0, q1) = (slot(sm).unwrap(), slot(sm + 16).unwrap());
assert!(q1.sampler && q1.index == 1 && q1.pc_srv == 0x9010);
write(&q0, &[1, 2, 3, 0xABC0_0000]);
copy_words(&q0, &q1);
assert_eq!(words_at(rel(sm + 16)).unwrap()[..4], [1, 2, 3, 0xABC0_0001]);
assert!(slot(sm + 32).is_none(), "past the last sampler slot");
unregister(0xA1);
unregister(0xA2);
assert!(start(0xA1).is_none() && slot(v).is_none() && slot(sm).is_none());
}
}
+126 -7
View File
@@ -469,9 +469,12 @@ unsafe fn class_for(obj: *mut c_void, orig: usize, kind: Kind) -> usize {
/// * descriptor heap #9 / #10: the heap start handles come back in rax on the console.
/// * resource #11 GetGPUVirtualAddress: console buffers live in unified memory; their console
/// address (= CPU address, low 32 bits = offset in `mem`) is what console code gets.
/// * device #14 / #15 / #18 / #19 (CreateDescriptorHeap, GetDescriptorHandleIncrementSize,
/// CreateShaderResourceView, CreateUnorderedAccessView): CBV/SRV/UAV heaps of console code
/// get 32-byte slots in unified memory (`console_heap`).
/// * device #14 / #15 / #17 / #18 / #19 / #22 / #23 / #24 (CreateDescriptorHeap,
/// GetDescriptorHandleIncrementSize, CreateConstantBufferView, CreateShaderResourceView,
/// CreateUnorderedAccessView, CreateSampler, CopyDescriptors, CopyDescriptorsSimple):
/// CBV/SRV/UAV and sampler heaps of console code get 32 / 16-byte slots in unified memory
/// (`console_heap`). #14–#19 seen from console code with the PC layout; #17 and #22–#24
/// assumed to follow it (each checks its arguments and otherwise goes to the PC method).
/// * device #12 `CreateCommandList` (only with console lists on): console code gets a
/// console-shaped list (D3D12.X inline code writes into it), XCL's own code a PC one.
fn console_slots(kind: Kind) -> Vec<(usize, usize)> {
@@ -480,8 +483,12 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> {
let mut v = vec![
(14, dev_create_descriptor_heap_x as usize),
(15, dev_increment_size_x as usize),
(17, dev_create_cbv_x as usize),
(18, dev_create_srv_x as usize),
(19, dev_create_uav_x as usize),
(22, dev_create_sampler_x as usize),
(23, dev_copy_descriptors_x as usize),
(24, dev_copy_descriptors_simple_x as usize),
(62, dev_create_compute_pso_x as usize),
(76, dev_create_committed_resource_x as usize),
];
@@ -521,10 +528,12 @@ unsafe extern "system" fn heap_gpu_start_x(this: *mut c_void) -> u64 {
unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc: *const [u32; 4], riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT {
let d = if desc.is_null() { [u32::MAX; 4] } else { *desc };
if d[0] != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 {
let sampler = d[0] == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32;
if d[0] != D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 && !sampler {
return dev_create_descriptor_heap(this, desc as usize, riid, ppv);
}
let pc = [d[0], d[1].saturating_mul(2), d[2], d[3]];
// views: an SRV / UAV pair per console slot; samplers: one per slot
let pc = [d[0], if sampler { d[1] } else { d[1].saturating_mul(2) }, d[2], d[3]];
let hr = dev_create_descriptor_heap(this, pc.as_ptr() as usize, riid, ppv);
if hr >= 0 {
let raw = *ppv;
@@ -532,8 +541,8 @@ unsafe extern "system" fn dev_create_descriptor_heap_x(this: *mut c_void, desc:
let dev = ID3D12Device::from_raw_borrowed(&this).unwrap();
let cpu = heap.GetCPUDescriptorHandleForHeapStart().ptr as u64;
let gpu = if d[2] & D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE.0 as u32 != 0 { heap.GetGPUDescriptorHandleForHeapStart().ptr } else { 0 };
let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
if !super::console_heap::register(raw as usize, d[1], cpu, gpu, inc) {
let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE(d[0] as i32));
if !super::console_heap::register(raw as usize, d[1], cpu, gpu, inc, sampler) {
crate::xlog_warn!("sterta deskryptorów konsoli: brak miejsca w UMA na {} slotów", d[1]);
}
}
@@ -544,6 +553,9 @@ unsafe extern "system" fn dev_increment_size_x(this: *mut c_void, ty: u32) -> u3
if ty == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0 as u32 {
return super::console_heap::SLOT;
}
if ty == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32 {
return super::console_heap::SAMPLER_SLOT;
}
let f: unsafe extern "system" fn(*mut c_void, u32) -> u32 = std::mem::transmute(orig_fn(this, 15));
f(this, ty)
}
@@ -697,6 +709,112 @@ fn note_buffer_view() {
}
}
/// #17 CreateConstantBufferView: a raw V# of the buffer's console address (unified memory;
/// anything else gets an empty V#). No PC CBV: translated shaders read buffers through `mem`.
unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, cpu: u64) {
let Some(slot) = super::console_heap::slot(cpu).filter(|s| !s.sampler) else {
let f: unsafe extern "system" fn(*mut c_void, *const D3D12_CONSTANT_BUFFER_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 17));
return f(this, desc, cpu);
};
let (va, size) = desc.as_ref().map_or((0, 0), |d| (d.BufferLocation, d.SizeInBytes));
let in_uma = crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize));
if !in_uma {
note_buffer_view();
}
let (va, size) = if in_uma { (va, size) } else { (0, 0) };
super::console_heap::write(&slot, &crate::gpu::desc::buffer_words(va, 0, size, 22));
}
/// #22 CreateSampler: the PC sampler at the slot's index, the S# in XCL ABI form (word 3
/// [11:0] = sampler heap index; the state lives in the PC sampler).
unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, desc: *const D3D12_SAMPLER_DESC, cpu: u64) {
let f: unsafe extern "system" fn(*mut c_void, *const D3D12_SAMPLER_DESC, u64) = std::mem::transmute(orig_fn(this, 22));
let Some(slot) = super::console_heap::slot(cpu).filter(|s| s.sampler) else { return f(this, desc, cpu) };
f(this, desc, slot.pc_srv);
super::console_heap::write(&slot, &[0, 0, 0, slot.index & 0xFFF]);
}
/// Copy `n` console slots from `src` to `dst` (both in console heaps of one kind): the PC
/// descriptors (2 per view slot) and the slots. False: not two console ranges.
unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) -> bool {
use super::console_heap::{copy_words, slot, SAMPLER_SLOT, SLOT};
let (Some(d0), Some(s0)) = (slot(dst), slot(src)) else { return false };
if d0.sampler != s0.sampler {
return false;
}
let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24));
f(this, if d0.sampler { n } else { 2 * n }, d0.pc_srv, s0.pc_srv, ty);
let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64;
for k in 0..n as u64 {
if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) {
copy_words(&s, &d);
}
}
true
}
static MIXED_COPIES: AtomicU64 = AtomicU64::new(0);
fn note_mixed_copy() {
if MIXED_COPIES.fetch_add(1, Ordering::Relaxed) == 0 {
crate::xlog_warn!("CopyDescriptors (konsola): zakres spoza stert konsoli XCL – kopiowanie tylko na PC");
}
}
/// #24 CopyDescriptorsSimple(n, dst, src, type)
unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) {
if copy_console_slots(this, n, dst, src, ty) {
return;
}
if super::console_heap::slot(dst).is_some() || super::console_heap::slot(src).is_some() {
note_mixed_copy();
return;
}
let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24));
f(this, n, dst, src, ty);
}
/// #23 CopyDescriptors(dst ranges, src ranges, type): range by range over console slots.
#[allow(clippy::too_many_arguments)]
unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32, ty: u32) {
use super::console_heap::{slot, SAMPLER_SLOT, SLOT};
let console = !dsts.is_null() && !srcs.is_null() && nd > 0 && slot(*dsts).is_some();
if !console {
if !srcs.is_null() && ns > 0 && slot(*srcs).is_some() {
note_mixed_copy();
return;
}
type F = unsafe extern "system" fn(*mut c_void, u32, *const u64, *const u32, u32, *const u64, *const u32, u32);
let f: F = std::mem::transmute(orig_fn(this, 23));
return f(this, nd, dsts, dsizes, ns, srcs, ssizes, ty);
}
// every descriptor as (dst, src) handle, ranges walked in step
let step = if ty == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0 as u32 { SAMPLER_SLOT } else { SLOT } as u64;
let expand = |starts: *const u64, sizes: *const u32, n: u32| -> Vec<u64> {
(0..n as usize).flat_map(|r| {
let (h, len) = (*starts.add(r), if sizes.is_null() { 1 } else { *sizes.add(r) });
(0..len as u64).map(move |k| h + k * step)
})
.collect()
};
let (d, s) = (expand(dsts, dsizes, nd), expand(srcs, ssizes, ns));
for (a, b) in d.iter().zip(s.iter()) {
if !copy_console_slots(this, 1, *a, *b, ty) {
note_mixed_copy();
}
}
}
/// descriptor heap Release (every caller): a console heap's slots go with it
unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 {
let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2));
let n = f(this);
if n == 0 {
super::console_heap::unregister(this as usize);
}
n
}
unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, cpu: u64) {
let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18));
let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) };
@@ -888,6 +1006,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> {
Kind::CommandQueue => v.push(("ExecuteCommandLists", q_execute_command_lists as usize)),
Kind::CommandAllocator => v.push(("Reset", alloc_reset as usize)),
Kind::Resource => v.push(("Release", res_release as usize)),
Kind::DescriptorHeap => v.push(("Release", heap_release as usize)),
_ => {}
}
v