Browse Source

Merge day/shaders

local 1 day ago
parent
commit
01e1f525d7

+ 84 - 0
apps/victory/src/replay.rs

@@ -195,6 +195,25 @@ pub(crate) struct Replay {
     /// `<list>:<command>` (repeatable).
     #[arg(long)]
     split: Vec<String>,
+    /// Take shaders from this folder where it has them (`<hash>.dxil`, by the
+    /// hash the runtime names the title's shader by).
+    #[arg(long)]
+    shaders: Option<PathBuf>,
+    /// With --compare: the folder the second run's shaders are from.
+    #[arg(long)]
+    shaders_b: Option<PathBuf>,
+    /// Only translate the capture's shaders, into this folder (for --shaders),
+    /// with the translator's settings of this run. Containers are looked up in
+    /// `containers` beside the capture, and first collected there from the
+    /// title's files.
+    #[arg(long)]
+    retranslate: Option<PathBuf>,
+    /// With --retranslate: the view heap's null slot, and where raw twins of
+    /// views start, as the capture's shaders have them (0: none).
+    #[arg(long, default_value_t = 0)]
+    view_limit: u32,
+    #[arg(long, default_value_t = 0)]
+    raw_views: u32,
     /// Use the D3D12 debug layer (slow).
     #[arg(long)]
     debug_layer: bool,
@@ -229,6 +248,9 @@ pub(crate) fn run(r: Replay) -> Result<()> {
         let lists = range(text).with_context(|| format!("--flow {text}"))?;
         return play::look::flow(&r.folder, lists, r.flow_draws, r.flow_slots, &mut |line| println!("{line}"));
     }
+    if let Some(into) = &r.retranslate {
+        return retranslate(&r.folder, into, r.view_limit, r.raw_views);
+    }
     let until = match &r.until {
         Some(text) => Some(
             text.split_once(':')
@@ -270,6 +292,8 @@ pub(crate) fn run(r: Replay) -> Result<()> {
         only,
         until,
         skip_shaders: r.skip_shader,
+        shaders: r.shaders,
+        shaders_b: r.shaders_b,
         compare: r.compare,
         debug: r.debug_layer,
         breadcrumbs: r.breadcrumbs,
@@ -409,6 +433,66 @@ pub(crate) fn run(r: Replay) -> Result<()> {
     Ok(())
 }
 
+/// Translates the capture's shaders into `into`.
+fn retranslate(folder: &std::path::Path, into: &std::path::Path, view_limit: u32, raw_views: u32) -> Result<()> {
+    use std::sync::atomic::{AtomicUsize, Ordering};
+    let wanted = play::title_shaders(folder)?;
+    let kept = play::find(folder)?.with_file_name("containers");
+    std::fs::create_dir_all(&kept)?;
+    std::fs::create_dir_all(into)?;
+    let mut missing: std::collections::HashSet<&str> = wanted
+        .iter()
+        .map(|w| w.1.as_str())
+        .filter(|h| !kept.join(format!("{h}.cdxil")).exists())
+        .collect();
+    if !missing.is_empty() {
+        println!("{} of {} containers are looked for in the title's files", missing.len(), wanted.len());
+        for root in crate::default_paths(Vec::new())? {
+            for entry in walkdir::WalkDir::new(root).into_iter().filter_map(std::result::Result::ok) {
+                let size = entry.metadata().map_or(0, |m| m.len());
+                if missing.is_empty() || !entry.file_type().is_file() || size > crate::shader::MAX_FILE {
+                    continue;
+                }
+                let Ok(data) = std::fs::read(entry.path()) else { continue };
+                for source in crate::shader::sources(&data) {
+                    let Some(bytes) = source.bytes() else { continue };
+                    let hash = blake3::hash(&bytes).to_hex()[..16].to_owned();
+                    if missing.remove(hash.as_str()) {
+                        std::fs::write(kept.join(format!("{hash}.cdxil")), &bytes[..])?;
+                    }
+                }
+            }
+        }
+    }
+    println!("{} containers not found", missing.len());
+    victory_shader::emit::set_host_max_wave(64);
+    victory_shader::emit::set_host_rdna(true);
+    victory_shader::emit::set_view_heap_limit(view_limit);
+    victory_shader::emit::set_raw_views(raw_views);
+    let all: Vec<_> = wanted.iter().collect();
+    let (next, done) = (AtomicUsize::new(0), AtomicUsize::new(0));
+    let started = std::time::Instant::now();
+    std::thread::scope(|s| {
+        for _ in 0..std::thread::available_parallelism().map_or(4, |n| n.get()) {
+            s.spawn(|| {
+                while let Some((stage, hash)) = all.get(next.fetch_add(1, Ordering::Relaxed)) {
+                    let Ok(bytes) = std::fs::read(kept.join(format!("{hash}.cdxil"))) else { continue };
+                    match victory_shader::emit::translate(&bytes) {
+                        Ok(t) => {
+                            if std::fs::write(into.join(format!("{hash}.dxil")), &t.dxil).is_ok() {
+                                done.fetch_add(1, Ordering::Relaxed);
+                            }
+                        }
+                        Err(e) => println!("{stage} {hash}: {e}"),
+                    }
+                }
+            });
+        }
+    });
+    println!("{} of {} shaders translated, {:.1} s", done.into_inner(), all.len(), started.elapsed().as_secs_f64());
+    Ok(())
+}
+
 #[cfg(test)]
 mod tests {
     #[test]

+ 12 - 0
crates/victory-gpu/src/host.rs

@@ -921,6 +921,9 @@ fn create() -> windows::core::Result<Host> {
         {
             tracing::info!(min = o1.WaveLaneCountMin, max = o1.WaveLaneCountMax, "host wave lanes");
             victory_shader::emit::set_host_max_wave(o1.WaveLaneCountMax);
+            // (RDNA has waves of 32 and 64, the vendor's older cards of 64 alone.)
+            let amd = crate::indirect::amd(&device);
+            victory_shader::emit::set_host_rdna(amd && o1.WaveLaneCountMin == 32 && o1.WaveLaneCountMax == 64);
         }
         let messages = debug
             .then(|| device.cast::<ID3D12InfoQueue>().ok())
@@ -968,6 +971,15 @@ fn create() -> windows::core::Result<Host> {
     }
 }
 
+impl Host {
+    /// The driver's version, as the system counts it (0: not known).
+    pub(crate) fn driver(&self) -> i64 {
+        let adapter = self.adapter.as_ref();
+        // SAFETY: a plain query.
+        adapter.map_or(0, |a| unsafe { a.CheckInterfaceSupport(&IDXGIDevice::IID) }.unwrap_or(0))
+    }
+}
+
 /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
 /// Reject it before creating a device in diagnostics' software-only mode.
 pub(crate) fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {

+ 1 - 1
crates/victory-gpu/src/indirect.rs

@@ -268,7 +268,7 @@ fn widest(amd: bool) -> u32 {
 }
 
 /// Whether `device` is an AMD card's.
-fn amd(device: &ID3D12Device) -> bool {
+pub(crate) fn amd(device: &ID3D12Device) -> bool {
     use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4};
     // SAFETY: plain queries.
     unsafe {

+ 131 - 25
crates/victory-gpu/src/replay/play.rs

@@ -96,6 +96,11 @@ pub struct Options {
     /// Skip what runs a pipeline whose name or shader hash has one of
     /// these in it.
     pub skip_shaders: Vec<String>,
+    /// Shaders taken from this folder where it has them: `<hash>.dxil`, by
+    /// the hash the runtime names the title's shader by.
+    pub shaders: Option<PathBuf>,
+    /// With `compare`: the folder the shaders of the second are from.
+    pub shaders_b: Option<PathBuf>,
     /// Run the frame unchanged first, and compare.
     pub compare: bool,
     /// The debug layer, if it is installed.
@@ -129,6 +134,8 @@ impl Default for Options {
             only: None,
             until: None,
             skip_shaders: Vec::new(),
+            shaders: None,
+            shaders_b: None,
             compare: false,
             debug: false,
             breadcrumbs: false,
@@ -180,7 +187,7 @@ pub struct Report {
     pub delta_ms: Vec<f64>,
     /// Of the last loop, by submission: lists, ms.
     pub submits: Vec<(usize, f64)>,
-    /// With detailed timing, of the last loop: ms and count by category.
+    /// With detailed timing: ms (median of the loops) and count by category.
     pub categories: Vec<(String, f64, u32)>,
     /// With detailed timing: ms, count and name of the costliest pipelines.
     pub shaders: Vec<(f64, u32, String)>,
@@ -326,6 +333,43 @@ pub fn find(folder: &Path) -> Result<PathBuf> {
         .ok_or_else(|| anyhow!("no capture (frame.bin) in {}", folder.display()))
 }
 
+/// The stage and hash by which the runtime names each of the title's shaders
+/// in a capture.
+pub fn title_shaders(folder: &Path) -> Result<std::collections::BTreeSet<(String, String)>> {
+    let frame = Frame::read(&find(folder)?.join("frame.bin"))?;
+    let mut all = std::collections::BTreeSet::new();
+    for p in &frame.pipelines {
+        for part in &p.parts {
+            if let wire::Part::Code { blob, .. } = part
+                && let Some(hash) = title_hash(p, *blob)
+            {
+                let at = p.name.find(hash).unwrap_or(0);
+                let stage = p.name[..at].trim_end().rsplit(['[', ' ']).next().unwrap_or("");
+                all.insert((stage.to_owned(), hash.to_owned()));
+            }
+        }
+    }
+    Ok(all)
+}
+
+/// The hash by which the runtime names the title's shader that code blob
+/// `blob` of pipeline `p` is the translation of.
+fn title_hash(p: &wire::Pipeline, blob: u32) -> Option<&str> {
+    let kind = p.parts.iter().find_map(|part| match part {
+        wire::Part::Code { kind, blob: b } if *b == blob => Some(*kind),
+        _ => None,
+    })?;
+    let stage = match D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(kind) {
+        D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS => "vertex ",
+        D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS => "pixel ",
+        D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_MS => "mesh ",
+        D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS => "compute ",
+        _ => return None,
+    };
+    let at = p.name.find(stage)? + stage.len();
+    p.name.get(at..at + 16)
+}
+
 /// Writes the DXIL of the pipelines whose name has `text` in it to `shaders`
 /// in the capture, and the pipelines' descriptions; what was written.
 pub fn dump(folder: &Path, text: &str) -> Result<Vec<String>> {
@@ -411,7 +455,7 @@ pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) ->
 pub fn replay(folder: &Path, options: &Options) -> Result<Vec<(String, Report)>> {
     let mut player = Player::load(folder, options)?;
     let mut out = Vec::new();
-    if options.compare && options.edited() {
+    if options.compare && (options.edited() || options.shaders_b.is_some()) {
         // Turn by turn: what else the machine does falls on both.
         let image = Some(player.folder.join("replay-unchanged.png"));
         let plain = Options {
@@ -419,11 +463,20 @@ pub fn replay(folder: &Path, options: &Options) -> Result<Vec<(String, Report)>>
             ..options.plain()
         };
         let mut a = player.prepare(&plain)?;
+        // The lists of the first hold its pipelines by name alone: kept.
+        let _pipelines = match &options.shaders_b {
+            Some(folder) => {
+                let kept = std::mem::take(&mut player.pipelines);
+                player.make_pipelines(Some(folder))?;
+                kept
+            }
+            None => HashMap::new(),
+        };
         let mut b = player.prepare(options)?;
         let (mut stamps_a, mut stamps_b) = (Vec::new(), Vec::new());
         for _ in 0..options.loops.max(1) {
-            stamps_a = player.once(&plain, &mut a)?;
-            stamps_b = player.once(options, &mut b)?;
+            stamps_a.push(player.once(&plain, &mut a)?);
+            stamps_b.push(player.once(options, &mut b)?);
         }
         out.push(("unchanged".into(), player.finish(&plain, a, &stamps_a)?));
         out.push(("with the experiments".into(), player.finish(options, b, &stamps_b)?));
@@ -580,7 +633,7 @@ impl Player {
         let mut at = Instant::now();
         player.make_resources(options.buffers, &options.only_buffers)?;
         step("resources", &mut at);
-        player.make_pipelines()?;
+        player.make_pipelines(options.shaders.as_deref())?;
         step("pipelines", &mut at);
         player.make_descriptors()?;
         step("descriptors", &mut at);
@@ -832,14 +885,21 @@ impl Player {
         Ok(())
     }
 
-    fn make_pipelines(&mut self) -> Result<()> {
+    fn make_pipelines(&mut self, shaders: Option<&Path>) -> Result<()> {
         for (id, blob) in &self.frame.roots {
+            if self.roots.contains_key(id) {
+                // (Made for another set of shaders: the root signatures are the same.)
+                continue;
+            }
             // SAFETY: a blob the host took.
             let root = unsafe { self.device.CreateRootSignature(0, &blob.0) }
                 .with_context(|| format!("root signature {id}"))?;
             self.roots.insert(*id, root);
         }
         for s in &self.frame.signatures {
+            if self.signatures.contains_key(&s.id) {
+                continue;
+            }
             let desc = D3D12_COMMAND_SIGNATURE_DESC {
                 ByteStride: s.stride,
                 NumArgumentDescs: s.args.len() as u32,
@@ -855,6 +915,9 @@ impl Player {
             self.signatures.extend(made.map(|m| (s.id, m)));
         }
         for q in &self.frame.query_heaps {
+            if self.queries.contains_key(&q.id) {
+                continue;
+            }
             let desc = D3D12_QUERY_HEAP_DESC {
                 Type: D3D12_QUERY_HEAP_TYPE(q.kind),
                 Count: q.count,
@@ -874,18 +937,34 @@ impl Player {
             .map_or(4, |n| n.get() / 2)
             .max(1);
         let (frame, roots) = (&self.frame, &self.roots);
+        let (swapped, kept) = (AtomicUsize::new(0), AtomicUsize::new(0));
         std::thread::scope(|scope| {
             for _ in 0..threads {
                 scope.spawn(|| {
                     while let Some(p) = frame.pipelines.get(next.fetch_add(1, Ordering::Relaxed)) {
-                        let code = |i: u32| {
+                        let recorded = |i: u32| {
                             let c = frame.codes.get(i as usize)?;
                             let mut bytes = vec![0; c.len as usize];
                             read_at(&file, &mut bytes, c.at).ok()?;
                             Some(bytes)
                         };
-                        let m =
-                            super::pso::make(&device, &p.parts, |id| roots.get(&id).cloned(), code);
+                        let root = |id: u32| roots.get(&id).cloned();
+                        let taken = std::cell::Cell::new(false);
+                        let mut m = super::pso::make(&device, &p.parts, root, |i| {
+                            let other = shaders.and_then(|dir| {
+                                let hash = title_hash(p, i)?;
+                                std::fs::read(dir.join(format!("{hash}.dxil"))).ok()
+                            });
+                            taken.set(taken.get() || other.is_some());
+                            other.or_else(|| recorded(i))
+                        });
+                        if taken.get() && m.is_err() {
+                            // Not for the root signature or the other stage recorded.
+                            kept.fetch_add(1, Ordering::Relaxed);
+                            m = super::pso::make(&device, &p.parts, root, recorded);
+                        } else if taken.get() {
+                            swapped.fetch_add(1, Ordering::Relaxed);
+                        }
                         made.lock()
                             .unwrap_or_else(|e| e.into_inner())
                             .push((p.id, m));
@@ -900,6 +979,15 @@ impl Player {
                 Err(e) => refused.push((id, e)),
             }
         }
+        if shaders.is_some() {
+            let n = format!(
+                "{} of {} pipelines made with shaders of the folder given, {} refused with them (as recorded)",
+                swapped.into_inner(),
+                self.frame.pipelines.len(),
+                kept.into_inner()
+            );
+            self.note(n);
+        }
         if let Some((id, e)) = refused.first() {
             let n = format!(
                 "{} pipelines could not be made again, first {}: {e}",
@@ -2978,7 +3066,7 @@ impl Player {
         let _awake = if o.awake { crate::host::awake::start(&self.device, || true) } else { None };
         let mut stamps = Vec::new();
         for _ in 0..o.loops.max(1) {
-            stamps = self.once(o, &mut made)?;
+            stamps.push(self.once(o, &mut made)?);
         }
         self.finish(o, made, &stamps)
     }
@@ -3038,7 +3126,7 @@ impl Player {
     }
 
     /// The report after the last run.
-    fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[u64]) -> Result<Report> {
+    fn finish(&mut self, o: &Options, (built, mut report): (Sends, Report), stamps: &[Vec<u64>]) -> Result<Report> {
         if o.detailed {
             self.detail(&built, stamps, o, &mut report);
         }
@@ -3053,23 +3141,41 @@ impl Player {
         Ok(report)
     }
 
-    /// The last loop's time by command.
-    fn detail(&self, built: &Sends, stamps: &[u64], o: &Options, report: &mut Report) {
-        let mut kinds: BTreeMap<&str, (f64, u32)> = BTreeMap::new();
-        let mut shaders: HashMap<u32, (f64, u32)> = HashMap::new();
-        for l in built.steps.iter().flat_map(|(_, l)| l) {
-            let mut before = stamps[l.first as usize];
-            for &(at, kind, pso) in &l.stamps {
-                let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency;
-                before = before.max(stamps[at]);
-                let k = kinds.entry(kind).or_default();
-                *k = (k.0 + ms, k.1 + 1);
-                if pso != NONE {
-                    let s = shaders.entry(pso).or_default();
-                    *s = (s.0 + ms, s.1 + 1);
+    /// The time by command: the median of the loops, without the first (which
+    /// is slower) where there are others.
+    fn detail(&self, built: &Sends, stamps: &[Vec<u64>], o: &Options, report: &mut Report) {
+        let mut kinds: BTreeMap<&str, (Vec<f64>, u32)> = BTreeMap::new();
+        let mut shaders: HashMap<u32, (Vec<f64>, u32)> = HashMap::new();
+        let loops = if stamps.len() > 2 { &stamps[1..] } else { stamps };
+        for stamps in loops {
+            let mut of_kind: BTreeMap<&str, (f64, u32)> = BTreeMap::new();
+            let mut of_shader: HashMap<u32, (f64, u32)> = HashMap::new();
+            for l in built.steps.iter().flat_map(|(_, l)| l) {
+                let mut before = stamps[l.first as usize];
+                for &(at, kind, pso) in &l.stamps {
+                    let ms = stamps[at].saturating_sub(before) as f64 * 1e3 / self.frequency;
+                    before = before.max(stamps[at]);
+                    let k = of_kind.entry(kind).or_default();
+                    *k = (k.0 + ms, k.1 + 1);
+                    if pso != NONE {
+                        let s = of_shader.entry(pso).or_default();
+                        *s = (s.0 + ms, s.1 + 1);
+                    }
                 }
             }
+            for (k, (ms, n)) in of_kind {
+                let all = kinds.entry(k).or_default();
+                all.0.push(ms);
+                all.1 = n;
+            }
+            for (k, (ms, n)) in of_shader {
+                let all = shaders.entry(k).or_default();
+                all.0.push(ms);
+                all.1 = n;
+            }
         }
+        let kinds = kinds.into_iter().map(|(k, (ms, n))| (k, (median(&ms), n)));
+        let shaders = shaders.into_iter().map(|(k, (ms, n))| (k, (median(&ms), n)));
         report.categories = kinds
             .into_iter()
             .map(|(k, (ms, n))| (k.to_owned(), ms, n))

+ 76 - 0
crates/victory-shader/src/emit/bitcode/opt.rs

@@ -399,6 +399,82 @@ impl Module {
         Some((bits, *x as u64 & mask(bits)))
     }
 
+    /// The bits of a 32-bit float that is a constant, given as one or as a
+    /// cast of an integer constant.
+    pub(crate) fn float_k(&self, v: V) -> Option<f32> {
+        let (v, cast) = match v {
+            V::Inst(i) => match self.insts[i as usize].op {
+                Op::Cast(Cast::Bitcast, x) => (x, true),
+                _ => return None,
+            },
+            _ => (v, false),
+        };
+        let V::Const(i) = v else { return None };
+        match &self.consts[i as usize].1 {
+            Const::Float(bits) if !cast => Some(f32::from_bits(*bits)),
+            Const::Int(_) if cast => {
+                let (bits, x) = self.int_k(v)?;
+                (bits == 32).then_some(f32::from_bits(x as u32))
+            }
+            _ => None,
+        }
+    }
+
+    /// For a float that is a number and not an infinity whatever the program
+    /// reads: a power of two its magnitude does not pass.
+    pub(crate) fn bounded(&self, v: V, depth: u32) -> Option<f32> {
+        if let Some(k) = self.float_k(v) {
+            return k.is_finite().then(|| k.abs().max(1e-30).log2().ceil());
+        }
+        let V::Inst(i) = v else { return None };
+        let depth = depth.checked_sub(1)?;
+        let of = |v: V| self.bounded(v, depth);
+        // (A power that overflows, or might with rounding, is no bound.)
+        let held = |b: f32| (b < 126.0).then_some(b);
+        match &self.insts[i as usize].op {
+            Op::Cast(Cast::UiToFp | Cast::SiToFp, _) => Some(32.0),
+            Op::Cast(Cast::Bitcast, x) => match *x {
+                V::Inst(j) => match self.insts[j as usize].op {
+                    Op::Cast(Cast::Bitcast, y) if self.type_of(y) == self.type_of(v) => of(y),
+                    _ => None,
+                },
+                _ => None,
+            },
+            Op::Bin(Bin::Mul, a, b) => held(of(*a)? + of(*b)?),
+            Op::Bin(Bin::Add | Bin::Sub, a, b) => held(of(*a)?.max(of(*b)?) + 1.0),
+            Op::Select(_, a, b) => Some(of(*a)?.max(of(*b)?)),
+            Op::Call(_, args) => {
+                let (_, code) = self.int_k(*args.first()?)?;
+                match (code, &args[1..]) {
+                    // Saturated, a fraction, a cosine or sine (of a number).
+                    (7, [_]) => Some(0.0),
+                    (6, [x]) => of(*x),
+                    (22 | 12 | 13, [x]) => of(*x).map(|_| 0.0),
+                    (26..=29, [x]) => held(of(*x)? + 1.0),
+                    // Of two numbers; or one of them the other way round: the
+                    // minimum (36) of a constant and a maximum of another.
+                    (35 | 36, [a, b]) => match (of(*a), of(*b)) {
+                        (Some(x), Some(y)) => Some(x.max(y)),
+                        _ => {
+                            let other = if code == 35 { 36 } else { 35 };
+                            let (inner, k) = if self.float_k(*b).is_some() { (*a, *b) } else { (*b, *a) };
+                            let k = self.float_k(k).and_then(|_| of(k))?;
+                            let V::Inst(j) = inner else { return None };
+                            let Op::Call(_, inner) = &self.insts[j as usize].op else { return None };
+                            let (_, code) = self.int_k(*inner.first()?)?;
+                            let low = inner[1..].iter().find(|x| self.float_k(**x).is_some())?;
+                            (code == other).then_some(())?;
+                            Some(k.max(of(*low)?))
+                        }
+                    },
+                    (46, [a, b, c]) => held((of(*a)? + of(*b)?).max(of(*c)?) + 1.0),
+                    _ => None,
+                }
+            }
+            _ => None,
+        }
+    }
+
     /// The constant `x` of the integer type `ty`, kept sign-extended as
     /// [`Module::i32`] and [`Module::bool`] keep theirs.
     fn k(&mut self, ty: Ty, bits: u32, x: u64) -> V {

+ 74 - 3
crates/victory-shader/src/emit/lower.rs

@@ -1111,9 +1111,33 @@ fn own_bits_on() -> bool {
 }
 
 /// What the translator was told of the host, for a cache's key: the widest
-/// wave, the view heap's limit and where the raw twins of its views start.
-pub fn host_settings() -> [u32; 3] {
-    [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views()]
+/// wave, the view heap's limit, where the raw twins of its views start, and
+/// what it writes for the console's own hardware.
+pub fn host_settings() -> [u32; 4] {
+    [host_max_wave(), super::shader::view_heap_limit(), super::shader::raw_views(), host_rdna()]
+}
+
+static HOST_RDNA: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
+
+/// Tells the translator that the host's shaders run on AMD RDNA hardware
+/// ([`super::rdna_float`]).
+pub fn set_host_rdna(on: bool) {
+    HOST_RDNA.store(on, std::sync::atomic::Ordering::Relaxed);
+}
+
+#[cfg(test)]
+thread_local! {
+    /// A test's choice for [`host_rdna`], for its thread only.
+    pub(super) static TEST_RDNA: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
+}
+
+/// The bits of [`super::rdna`] that count on this host.
+pub(super) fn host_rdna() -> u32 {
+    #[cfg(test)]
+    if let Some(bits) = TEST_RDNA.get() {
+        return bits;
+    }
+    if HOST_RDNA.load(std::sync::atomic::Ordering::Relaxed) { super::rdna_float() } else { 0 }
 }
 
 /// The refusal of a first half of an interpolation whose result is read
@@ -3686,6 +3710,9 @@ impl<'a> Lower<'a> {
     fn max_min(&mut self, max: bool, a: V, b: V) -> V {
         let c = self.cur;
         let r = self.binary(if max { 35 } else { 36 }, a, b);
+        if host_rdna() & super::rdna::MAX_MIN != 0 {
+            return r;
+        }
         let (ia, ib) = (self.as_int(a), self.as_int(b));
         let either = self.s.m.bin(c, Bin::Or, ia, ib);
         let magnitude = self.s.m.i32(0x7FFF_FFFF);
@@ -3819,6 +3846,25 @@ impl<'a> Lower<'a> {
     /// is the smallest number among them).
     fn med3(&mut self, a: V, b: V, third: V) -> V {
         let c = self.cur;
+        // Between two constants in order: the lower one for a NaN either way.
+        if host_rdna() & super::rdna::MED3 != 0 {
+            let k = [a, b, third].map(|x| self.s.m.float_k(x));
+            let ordered = match k {
+                [None, Some(x), Some(y)] => Some((a, b, third, x, y)),
+                [Some(x), None, Some(y)] => Some((b, a, third, x, y)),
+                [Some(x), Some(y), None] => Some((third, a, b, x, y)),
+                _ => None,
+            };
+            if let Some((v, p, q, x, y)) = ordered
+                && !x.is_nan()
+                && !y.is_nan()
+                && x != y
+            {
+                let (low, high) = if x < y { (p, q) } else { (q, p) };
+                let t = self.binary(35, v, low);
+                return self.binary(36, t, high);
+            }
+        }
         let lo = self.binary(36, a, b);
         let hi = self.binary(35, a, b);
         let t = self.binary(36, hi, third);
@@ -3841,6 +3887,9 @@ impl<'a> Lower<'a> {
     fn fract(&mut self, a: V, threshold: f32, below_one: f32) -> V {
         let c = self.cur;
         let r = self.unary(22, a);
+        if host_rdna() & super::rdna::FRACT != 0 && below_one == f32::from_bits(0x3F7F_FFFF) {
+            return r;
+        }
         let limit = self.s.m.f32(threshold.to_bits());
         let k = self.s.m.f32(below_one.to_bits());
         let over = self.s.m.cmp(c, pred::OGE, r, limit);
@@ -3890,6 +3939,28 @@ impl<'a> Lower<'a> {
     /// `0 × anything = 0`, as in D3D9.
     fn legacy_mul(&mut self, a: V, b: V) -> V {
         let c = self.cur;
+        if host_rdna() & super::rdna::LEGACY != 0 {
+            let m = self.s.m.bin(c, Bin::Mul, a, b);
+            let zero = self.s.m.f32(0);
+            // A product is not 0 only where one factor is 0 and the other an
+            // infinity or no number: never of a value with itself, nor of two
+            // finite ones, and only where the finite one of two is 0.
+            let (fa, fb) = (self.s.m.bounded(a, 12).is_some(), self.s.m.bounded(b, 12).is_some());
+            let not_zero = |l: &Self, x: V| l.s.m.float_k(x).is_some_and(|k| k != 0.0 && k.is_finite());
+            if a == b || fa && fb || not_zero(self, a) || not_zero(self, b) {
+                return m;
+            }
+            let asked = match (fa, fb) {
+                (true, _) => a,
+                (_, true) => b,
+                _ => {
+                    let (a, b) = (self.unary(6, a), self.unary(6, b));
+                    self.binary(36, a, b)
+                }
+            };
+            let z = self.s.m.cmp(c, pred::OEQ, asked, zero);
+            return self.s.m.select(c, z, zero, m);
+        }
         let m = self.s.m.bin(c, Bin::Mul, a, b);
         let zero = self.s.m.f32(0);
         let az = self.s.m.cmp(c, pred::OEQ, a, zero);

+ 55 - 1
crates/victory-shader/src/emit/mod.rs

@@ -101,6 +101,8 @@ mod threading;
 #[cfg(windows)]
 pub mod validator;
 #[cfg(all(test, windows))]
+mod probe_tests;
+#[cfg(all(test, windows))]
 mod size_tests;
 #[cfg(all(test, windows))]
 mod valu_tests;
@@ -116,7 +118,7 @@ use crate::{ShaderError, io, ir, resource, structure};
 
 pub use bitcode::census;
 pub use sampler::StaticSampler;
-pub use lower::{host_settings, set_host_max_wave};
+pub use lower::{host_settings, set_host_max_wave, set_host_rdna};
 pub use rect::rect_list_gs;
 pub use shader::{
     MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
@@ -219,6 +221,57 @@ pub fn shader_opt() -> u32 {
     *PASSES.get_or_init(|| parse_shader_opt(std::env::var("VICTORY_SHADER_OPT").ok().as_deref()))
 }
 
+/// On a host whose shaders run on the console's own kind of hardware (AMD
+/// RDNA, [`set_host_rdna`]): which of the console's float instructions are
+/// written as the one host operation the driver makes the same instruction
+/// of, instead of spelled out in operations every host agrees on.
+/// `VICTORY_RDNA_FLOAT`: a set of [`rdna`]'s bits (decimal or `0x` hex); all
+/// of them when it is unset, `0` none. Nothing on other hosts.
+///
+/// Measured on an RX 7900 XTX (a frame of the yard, replayed turn by turn with
+/// and without): the title's dispatches and draws 18.4 -> 17.6 ms, 0.4 of it
+/// without [`rdna::LEGACY`]. Tried and worth nothing there: `v_mad_f32` as one
+/// multiply-add, a fast reciprocal, scalar buffer loads of four dwords at once,
+/// a wave size for every compute program (32, 64, the console's).
+///
+/// Part of the translation: the shader cache keys on it ([`host_settings`]).
+pub fn rdna_float() -> u32 {
+    static BITS: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
+    *BITS.get_or_init(|| {
+        let value = std::env::var("VICTORY_RDNA_FLOAT").ok();
+        parse_set(value.as_deref(), rdna::ALL, rdna::ALL)
+    })
+}
+
+/// The bits of [`rdna_float`].
+pub mod rdna {
+    /// `v_max_f32` and the like: the host's FMax and FMin, without the code
+    /// that orders -0 below +0.
+    pub const MAX_MIN: u32 = 1;
+    /// `v_mul_legacy_f32` and the like (0 times anything is 0): a plain product
+    /// where no factor can be an infinity or no number where the other is 0,
+    /// and one comparison where it can. A zero may have the other sign.
+    pub const LEGACY: u32 = 2;
+    /// `v_med3_f32` of a value between two ordered constants: a minimum of a
+    /// maximum.
+    pub const MED3: u32 = 4;
+    /// `v_fract_f32`: the host's Frc as it is.
+    pub const FRACT: u32 = 8;
+    pub const ALL: u32 = 15;
+}
+
+/// A switch's set of bits; `unset` when it is unset or unreadable. Pure, for
+/// testing.
+fn parse_set(value: Option<&str>, unset: u32, all: u32) -> u32 {
+    let parsed = value
+        .map(str::trim)
+        .and_then(|v| match v.strip_prefix("0x") {
+            Some(hex) => u32::from_str_radix(hex, 16).ok(),
+            None => v.parse().ok(),
+        });
+    parsed.map_or(unset, |n| n & all)
+}
+
 /// Everything a translation depends on besides the container: the
 /// translator's own source (hashed at build time), the value of every
 /// `VICTORY_*` switch it reads, the host facts the device hands it (widest
@@ -239,6 +292,7 @@ pub fn translation_fingerprint() -> Vec<u8> {
         out.push(0);
     }
     out.extend_from_slice(&lower::host_max_wave().to_le_bytes());
+    out.extend_from_slice(&lower::host_rdna().to_le_bytes());
     out.extend_from_slice(&shader::view_heap_limit().to_le_bytes());
     out.extend_from_slice(&shader::raw_views().to_le_bytes());
     out.extend_from_slice(&loop_limit().to_le_bytes());

+ 74 - 0
crates/victory-shader/src/emit/probe_tests.rs

@@ -0,0 +1,74 @@
+//! Not a test of the translator: what the host's compiler makes of DXIL.
+//! `VICTORY_PROBE=<folder>` and `--ignored probe`: each `.dxil` there (a
+//! compute program with a constant buffer `b0` of four dwords and a raw
+//! buffer, slot 0 of the view heap) is run on the card. `sem*` programs are
+//! given the bits of 0.0, infinity, -0.0 and a NaN and what they store is
+//! printed; of the others the time is (several runs of 4096 groups).
+
+use super::HostShader;
+use super::host::{Dispatch, Host, Root, View};
+use crate::native::{HwStage, RootType};
+
+#[test]
+#[ignore = "a tool: VICTORY_PROBE=<folder>"]
+fn probe() {
+    let Some(folder) = std::env::var_os("VICTORY_PROBE") else { return };
+    let host = Host::new(false).expect("a card");
+    let mut files: Vec<_> = std::fs::read_dir(folder)
+        .expect("the folder")
+        .filter_map(|e| Some(e.ok()?.path()))
+        .filter(|p| p.extension().is_some_and(|e| e == "dxil"))
+        .collect();
+    files.sort();
+    for file in files {
+        let name = file.file_stem().unwrap_or_default().to_string_lossy().into_owned();
+        let shader = HostShader {
+            stage: HwStage::Cs,
+            dxil: std::fs::read(&file).expect("the file"),
+            user_data: (0..4)
+                .map(|n| super::UserData { index: n, slot: 0, root: RootType::Constants, dword: n })
+                .collect(),
+            samplers: Vec::new(),
+            static_samplers: Vec::new(),
+            root_cbvs: Vec::new(),
+            root_srvs: Vec::new(),
+            root_uavs: Vec::new(),
+            root_indexed_views: Vec::new(),
+        };
+        let (root, pso) = match host.compute_pipeline(&shader) {
+            Ok(made) => made,
+            Err(e) => {
+                println!("{name}: {e}");
+                continue;
+            }
+        };
+        let run = |constants: [u32; 4], groups: u32| {
+            let began = std::time::Instant::now();
+            let out = host
+                .dispatch(
+                    &root,
+                    &pso,
+                    &Dispatch {
+                        roots: vec![(0, Root::Constants(constants.to_vec()))],
+                        views: &[View::RawUav(64)],
+                        samplers: &[],
+                        groups: [groups, 1, 1],
+                    },
+                )
+                .expect("a dispatch");
+            (out[0].clone(), began.elapsed().as_secs_f64() * 1e3)
+        };
+        if name.starts_with("sem") {
+            let (out, _) = run([0, 0x7F80_0000, 0x8000_0000, 0x7FC0_0000], 1);
+            for (n, x) in out.iter().enumerate().take(40) {
+                println!("{name} {n:>2}: {x:08x} {}", f32::from_bits(*x));
+            }
+            continue;
+        }
+        let constants = [0.37f32.to_bits(), 0.11f32.to_bits(), 16384, 0];
+        run(constants, 64);
+        let mut times: Vec<f64> = (0..9).map(|_| run(constants, 4096).1).collect();
+        times.sort_by(f64::total_cmp);
+        println!("{name}: {:.2} ms (least {:.2})", times[times.len() / 2], times[0]);
+    }
+}

+ 85 - 0
crates/victory-shader/src/emit/valu_tests.rs

@@ -1972,3 +1972,88 @@ fn whole_wave_f64_sum_and_cvt_f32_f64() {
         }
     }
 }
+
+/// Whether the hardware adapter is an AMD RDNA card's: what the translator
+/// writes for one ([`super::rdna`]) holds there.
+fn rdna_card() -> bool {
+    use windows::Win32::Graphics::Direct3D12::*;
+    use windows::Win32::Graphics::Dxgi::*;
+    let Ok(host) = Host::new(false) else { return false };
+    let mut waves = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default();
+    // SAFETY: plain queries.
+    unsafe {
+        let amd = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
+            .and_then(|f| f.EnumAdapterByLuid::<IDXGIAdapter1>(host.device.GetAdapterLuid()))
+            .and_then(|a| a.GetDesc1())
+            .is_ok_and(|d| d.VendorId == 0x1002);
+        amd && host
+            .device
+            .CheckFeatureSupport(
+                D3D12_FEATURE_D3D12_OPTIONS1,
+                (&raw mut waves).cast(),
+                size_of_val(&waves) as u32,
+            )
+            .is_ok()
+            && waves.WaveLaneCountMin == 32
+            && waves.WaveLaneCountMax == 64
+    }
+}
+
+/// The forms written for the console's own kind of hardware give, on such a
+/// card, what the ones spelled out for every host give; a legacy product's
+/// zero may have the other sign.
+#[test]
+fn rdna_forms_give_what_the_spelled_out_ones_give() {
+    if !rdna_card() {
+        eprintln!("no RDNA card; skipped");
+        return;
+    }
+    const ONE: u16 = 242;
+    const MINUS_ONE: u16 = 243;
+    let (a, b, c) = (vgpr(1), vgpr(2), vgpr(3));
+    let saturated = vop3_mod(0x110, 5, vgpr(1), vgpr(1), 0, 0, 0, 0, true);
+    let two = |x: [u32; 2], y: [u32; 2]| [x, y].concat();
+    let bodies: [(&str, Vec<u32>, bool); 14] = [
+        ("max", vop3(0x110, 0, a, b, 0).to_vec(), true),
+        ("min", vop3(0x10F, 0, a, b, 0).to_vec(), true),
+        ("max3", vop3(0x154, 0, a, b, c).to_vec(), true),
+        ("min3", vop3(0x151, 0, a, b, c).to_vec(), true),
+        ("med3 0 1", vop3(0x157, 0, a, 128, ONE).to_vec(), true),
+        ("med3 1 0", vop3(0x157, 0, ONE, a, 128).to_vec(), true),
+        ("med3 1 -1", vop3(0x157, 0, ONE, MINUS_ONE, a).to_vec(), true),
+        ("fract", vec![vop1(0x020, 0, a)], true),
+        ("mul_legacy", vop3(0x107, 0, a, b, 0).to_vec(), false),
+        ("mul_legacy by itself", vop3(0x107, 0, a, a, 0).to_vec(), false),
+        ("mul_legacy by a constant", vop3(0x107, 0, a, MINUS_ONE, 0).to_vec(), false),
+        ("mul_legacy of a saturated", two(saturated, vop3(0x107, 0, vgpr(5), b, 0)), false),
+        ("mad_legacy", vop3(0x140, 0, a, b, c).to_vec(), false),
+        ("max of a mul_legacy", two(vop3(0x107, 5, a, b, 0), vop3(0x110, 0, vgpr(5), c, 0)), false),
+    ];
+    let numbers = [0.0f32, -0.0, 1.0, -1.0, 0.3, -2.5e-7, 3e38, f32::INFINITY, f32::NEG_INFINITY, f32::NAN];
+    let mut cases = Vec::new();
+    for (i, x) in numbers.iter().enumerate() {
+        for (j, y) in numbers.iter().enumerate() {
+            let z = numbers[(3 * i + j) % numbers.len()];
+            cases.push([x.to_bits(), y.to_bits(), z.to_bits(), 0]);
+        }
+    }
+    for (name, body, exact) in bodies {
+        let mut got: Vec<Vec<u32>> = Vec::new();
+        let mut written = Vec::new();
+        for bits in [0, super::rdna::ALL] {
+            lower::TEST_RDNA.set(Some(bits));
+            let shader = build_valu_cs(&body);
+            lower::TEST_RDNA.set(None);
+            written.push(shader.dxil.clone());
+            let mut all = Vec::new();
+            run_cases_on(&shader, &cases, &[("hardware", false)], |_, _, _, r| all.push(r));
+            got.push(all);
+        }
+        assert_ne!(written[0], written[1], "{name}: written alike");
+        for (case, (&was, &is)) in cases.iter().zip(got[0].iter().zip(&got[1])) {
+            let (x, y) = (f32::from_bits(was), f32::from_bits(is));
+            let same = was == is || x.is_nan() && y.is_nan() || !exact && x == 0.0 && y == 0.0;
+            assert!(same, "{name} of {:?}: {x} ({was:#x}), now {y} ({is:#x})", case.map(f32::from_bits));
+        }
+    }
+}

+ 2 - 0
docs/replay.md

@@ -69,6 +69,8 @@ with the presented one.
 | `--only 3..7` | runs these lists; of the others only barriers |
 | `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) |
 | `--skip-shader <text>` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) |
+| `--shaders <folder>` | takes shaders from the folder where it has them: `<hash>.dxil`, by the hash the runtime names the title's shader by; with `--compare --shaders-b <folder>` a second set, turn by turn with the first |
+| `--retranslate <folder>` | only writes that folder: the capture's shaders translated by this build with the `VICTORY_*` switches of this run (`--view-limit`, `--raw-views`: the view heap's null slot and where raw views start, as the capture's shaders have them) |
 | `--no-restore` | leaves what a loop changed, and makes no copies to restore from (of a capture that does not fit in the card's memory with them) |
 | `--pace <ms>` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one |
 | `--awake` | keeps the card's clocks up (`VICTORY_CARD_AWAKE=1`) |