CLI: --device returns, as the way to compile for a runtime's device

06a35ed9e4 deleted `--device <device.json>` (a ReproDevice: a device description and a policy) on
the premise that only a runtime's FALLBACK bundle would write that file and none does. The
premise missed what the option reproduces: metal2vulkan-runtime compiles with the device's
description restricted to the features it enables and with the identity pointer and handle
domains (crates/metal2vulkan-runtime/src/device.rs, `translator`), while `--profile` always
compiles with the default domains (DevicePolicy::UNTRUSTED). So `--profile` cannot reproduce a
refusal the runtime meets, and `--device` is the command line's one way to: a lane's whole-library
translation of a guest library (job m3-max-61778) ran through it hours before the deletion landed.

This restores 06a35ed9e4's code as it was: ReproDevice (new, to_json, from_json), the command
line's DeviceFile and `--device`, its usage and help lines and the cli test
a_device_file_takes_the_place_of_a_profile. The docs say what it is for now, not a runtime's
bundle: repro.rs's module doc no longer says a runtime may write a bundle (none does), the
ReproDevice doc and the help text name a runtime's compile device and the default domains a
profile takes, and the README's command-line section says the same. The module stays gated on
`cli`, its only user.

Verified: m3-max-61797 (msi) at 26ef12d7a3 (this change on 36e763e80e): clippy -p metal2vulkan --all-targets with all features,
with none and with serde alone, -D warnings, all 0; rustdoc -D warnings 0; the cli binary's 9 tests
pass, a_device_file_takes_the_place_of_a_profile among them.
This commit is contained in:
Anees Iqbal committed 2026-11-20 22:05:59 -08:00
1 parent d10a14d5af
commit e149088bd0
4 files changed
+178 -25

No files matched your search

+5 -1
View File
@@ -79,7 +79,11 @@ metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json
- `--profile` is required: the crate ships no device description. Any Khronos profiles JSON works;
[`crates/metal2vulkan-validation/profiles/`](crates/metal2vulkan-validation/profiles) has
examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK.
examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK. A profile compiles with the
default domains (`DevicePolicy::UNTRUSTED`). `--device FILE` takes its place with a device
description and policy as JSON (`{"description": ..., "policy": ...}`), which is how a runtime's
compile device is reproduced: metal2vulkan-runtime's is the description restricted to the
features it enables, with the identity pointer and handle domains.
- Without `--function` it compiles the library's only kernel or vertex function. A kernel with
`--color-format` compiles as a tile pipeline. A post-tessellation vertex function adds
`.tesc.spv` and `.tese.spv` modules; on a device without `tessellationShader` it answers
+77 -21
View File
@@ -3,7 +3,9 @@
//! the library's API (`Device::compile_compute_pipeline`, `compile_render_pipeline`, and
//! `compile_tile_pipeline`).
//!
//! Usage: `metal2vulkan <in.metallib|in.air|in.ll> [out.spv] --profile <profile.json> [options]`.
//! Usage: `metal2vulkan <in.metallib|in.air|in.ll> [out.spv] --profile <profile.json> [options]`,
//! or `--device <device.json>` in place of `--profile` (a device description and policy, such as a
//! runtime's compile device).
//! A success prints a line containing `PASS`. Any failure prints `metal2vulkan: FALLBACK (why)`
//! and exits with status 2; a failure after the inputs are read also writes a repro bundle
//! (`metal2vulkan::repro`; `METAL2VULKAN_REPRO_DIR`, by default `$TMPDIR/metal2vulkan-repros`).
@@ -29,13 +31,14 @@ use metal2vulkan::pipeline::{
SpecializationLayout, StageEntries, StageInputDescriptor, StageModule, StageSource,
TileRenderPipelineDescriptor, VertexDescriptor, VertexInputState,
};
use metal2vulkan::repro::{shell_join, ReproBundle};
use metal2vulkan::repro::{shell_join, ReproBundle, ReproDevice};
use metal2vulkan::{vk, Budget};
const USAGE: &str =
"usage: metal2vulkan <in.metallib|in.air|in.ll> [out.spv] --profile <profile.json> [options]";
const HELP: &str = r#"usage: metal2vulkan <in.metallib|in.air|in.ll> [out.spv] --profile <profile.json> [options]
metal2vulkan <in.metallib|in.air|in.ll> [out.spv] --device <device.json> [options]
Compiles one pipeline of the input library for the device a Khronos profile describes, and writes
its SPIR-V. A kernel writes out.spv; a render pipeline writes one module per stage, named by
@@ -45,9 +48,14 @@ output is <input-without-extension>.vk.spv. A .ll input is assembled with llvm-a
newer).
options:
--profile FILE Khronos profiles JSON for the target device (required; the
repository's crates/metal2vulkan-validation/profiles/ holds examples)
--profile FILE Khronos profiles JSON for the target device (this or --device is
required; the repository's crates/metal2vulkan-validation/profiles/
holds examples)
--profile-name NAME the profile to read when FILE holds more than one
--device FILE the target device as a description and a policy: the JSON form of
metal2vulkan::device::DeviceDescription and DevicePolicy,
{"description": ..., "policy": ...}, in place of --profile (a
runtime's compile device; --profile takes the default domains)
--function NAME the kernel or vertex function (default: the library's only one)
--fragment NAME the fragment function of a render pipeline
--constant ID:TYPE:VALUE function-constant value (repeatable): ID is an index or a name, TYPE a
@@ -76,6 +84,29 @@ const DESCRIPTOR_FILES: [(&str, &str); 2] = [
("--vertex-descriptor", "vertex-descriptor.json"),
];
/// The device the command compiles for, as its file reads: a Khronos profiles document
/// (`--profile`), or a device description and policy (`--device`).
enum DeviceFile {
Profile(String),
Device(String),
}
impl DeviceFile {
/// The device file's name in a repro bundle, and the options that name it there.
fn bundled(&self) -> (&'static str, [&'static str; 2], &[u8]) {
match self {
DeviceFile::Profile(json) => (
"profile.json",
["--profile", "profile.json"],
json.as_bytes(),
),
DeviceFile::Device(json) => {
("device.json", ["--device", "device.json"], json.as_bytes())
}
}
}
}
/// What the command line asks for.
#[derive(Default)]
struct Args {
@@ -83,6 +114,7 @@ struct Args {
output: Option<String>,
profile: Option<String>,
profile_name: Option<String>,
device: Option<String>,
function: Option<String>,
fragment: Option<String>,
constants: Vec<(String, FunctionConstantValue)>,
@@ -96,7 +128,8 @@ struct Args {
timeout: Option<Duration>,
emit_meta: Option<String>,
spirv_val: bool,
/// The options a repro bundle replays: every one but `--profile` and `--emit-meta`, with each descriptor file named as the bundle's copy of it
/// The options a repro bundle replays: every one but `--profile`, `--device` and
/// `--emit-meta`, with each descriptor file named as the bundle's copy of it
/// ([`DESCRIPTOR_FILES`]).
replay: Vec<String>,
}
@@ -148,20 +181,27 @@ fn main() {
let read = |path: &str| {
fs::read_to_string(path).unwrap_or_else(|e| fail(&format!("cannot read {path}: {e}")))
};
let Some(profile) = &args.profile else {
fail(
let device_file = match (&args.profile, &args.device) {
(Some(profile), None) => DeviceFile::Profile(read(profile)),
(None, Some(device)) => {
if args.profile_name.is_some() {
fail("--profile-name names a profile of --profile's document; --device has none");
}
DeviceFile::Device(read(device))
}
(Some(_), Some(_)) => fail("--profile and --device each name the device: give one"),
(None, None) => fail(
"no --profile: name a Khronos profiles JSON for the target device (the repository's \
crates/metal2vulkan-validation/profiles/ holds examples, and the Vulkan SDK and \
vulkaninfo --json produce more)",
)
vulkaninfo --json produce more), or a device description and policy with --device",
),
};
let profile = read(profile);
let source = fs::read(&input).unwrap_or_else(|e| fail(&format!("cannot read {input}: {e}")));
let output = args
.output
.clone()
.unwrap_or_else(|| default_output_path(&input));
match run(&args, &source, &profile, &input, &output) {
match run(&args, &source, &device_file, &input, &output) {
Ok(line) => println!("{line}"),
Err(failure) => {
if let Some(detail) = &failure.detail {
@@ -171,7 +211,7 @@ fn main() {
original: &original,
input: &input,
source: &source,
profile: &profile,
device_file: &device_file,
args: &args,
output: &output,
};
@@ -188,14 +228,25 @@ fn main() {
fn run(
args: &Args,
source: &[u8],
profile: &str,
device_file: &DeviceFile,
input: &str,
output: &str,
) -> Result<String, Failure> {
let description = DeviceDescription::from_khronos_json(profile, args.profile_name.as_deref())
.map_err(|e| Failure::detailed("profile not read", e.to_string()))?;
let device = Device::from_queries(description, DevicePolicy::default())
.map_err(|e| Failure::detailed("profile refused", e.to_string()))?;
let device = match device_file {
DeviceFile::Profile(json) => {
let description =
DeviceDescription::from_khronos_json(json, args.profile_name.as_deref())
.map_err(|e| Failure::detailed("profile not read", e.to_string()))?;
Device::from_queries(description, DevicePolicy::default())
.map_err(|e| Failure::detailed("profile refused", e.to_string()))?
}
DeviceFile::Device(json) => {
let device = ReproDevice::from_json(json)
.map_err(|e| Failure::detailed("device not read", e))?;
Device::from_queries(device.description, device.policy)
.map_err(|e| Failure::detailed("device refused", e.to_string()))?
}
};
let assembled;
let bitcode: &[u8] = if input.ends_with(".ll") {
assembled = assemble(source)?;
@@ -693,6 +744,10 @@ fn parse_args(args: &[String]) -> Args {
parsed.profile = Some(value());
replayed = false;
}
"--device" => {
parsed.device = Some(value());
replayed = false;
}
"--profile-name" => parsed.profile_name = Some(value()),
"--function" => parsed.function = Some(value()),
"--fragment" => parsed.fragment = Some(value()),
@@ -943,22 +998,23 @@ struct Bundle<'a> {
original: &'a [String],
input: &'a str,
source: &'a [u8],
profile: &'a str,
device_file: &'a DeviceFile,
args: &'a Args,
output: &'a str,
}
impl Bundle<'_> {
/// A bundle (`metal2vulkan::repro`) holding the input, the profile, the descriptor files,
/// A bundle (`metal2vulkan::repro`) holding the input, the device file, the descriptor files,
/// the command that replays the failure on them, and why it failed, under
/// `METAL2VULKAN_REPRO_DIR` or `$TMPDIR/metal2vulkan-repros`.
fn write(&self, failure: &Failure) -> Result<PathBuf, String> {
let base = metal2vulkan::env_vars::repro_dir()
.map(PathBuf::from)
.unwrap_or_else(|| env::temp_dir().join("metal2vulkan-repros"));
let (device_name, device_options, device_bytes) = self.device_file.bundled();
let mut bundle = ReproBundle::new(repro_input_name(self.input), self.source)
.file("profile.json", self.profile.as_bytes().to_vec())
.options(["--profile", "profile.json"]);
.file(device_name, device_bytes.to_vec())
.options(device_options);
let descriptors = [&self.args.stage_input, &self.args.vertex_descriptor];
for (path, (_, name)) in descriptors.into_iter().zip(DESCRIPTOR_FILES) {
// A descriptor file that cannot be read is the failure the bundle records: its replay
+37 -3
View File
@@ -2,9 +2,10 @@
//! `metal2vulkan` command line, which writes one for a failure after it read its inputs, under
//! `METAL2VULKAN_REPRO_DIR` (`env_vars`). Not consumer API: the binary's, hidden as `env_vars` is.
//!
//! A bundle holds the input (`input.metallib`, `input.air`, `input.ll` or `input.bin`), the
//! profile (`profile.json`, which `--profile` reads), the descriptor files the command names
//! (`stage-input.json`, `vertex-descriptor.json`), the command (`repro-command.txt`, and `repro.sh`, which runs it from
//! A bundle holds the input (`input.metallib`, `input.air`, `input.ll` or `input.bin`), the device
//! file (`profile.json`, which `--profile` reads, or `device.json`, which `--device` reads: a
//! [`ReproDevice`]), the descriptor files the command names (`stage-input.json`,
//! `vertex-descriptor.json`), the command (`repro-command.txt`, and `repro.sh`, which runs it from
//! the bundle's directory) and `failure.txt`: why it failed, and each part of the request the
//! command does not replay ([`ReproBundle::unreplayed`]).
//!
@@ -21,6 +22,39 @@ use std::sync::atomic::{AtomicU64, Ordering};
use sha2::{Digest, Sha256};
use crate::cache::Hash256;
use crate::device::{DeviceDescription, DevicePolicy};
/// The device a command compiles for, as `device.json` holds it and the command line's `--device`
/// reads it: a description and a policy, which build the same `Device` (`Device::from_queries`).
/// A runtime's compile device is one: metal2vulkan-runtime's is the device's description
/// restricted to the features it enables, with the identity pointer and handle domains, which a
/// Khronos profile read by `--profile` (the default domains) does not reproduce.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ReproDevice {
pub description: DeviceDescription,
pub policy: DevicePolicy,
}
impl ReproDevice {
/// The device of `description` and `policy`.
pub fn new(description: DeviceDescription, policy: DevicePolicy) -> ReproDevice {
ReproDevice {
description,
policy,
}
}
/// The device's `device.json`.
pub fn to_json(&self) -> Result<Vec<u8>, String> {
serde_json::to_vec_pretty(self).map_err(|e| e.to_string())
}
/// The device a `device.json` holds.
pub fn from_json(json: &str) -> Result<ReproDevice, String> {
serde_json::from_str(json).map_err(|e| e.to_string())
}
}
/// One bundle, built in memory and written by [`write`](Self::write).
#[derive(Clone, Debug)]
+59
View File
@@ -15,6 +15,7 @@ use metal2vulkan::pipeline::{
ComputePipelineDescriptor, FunctionDescriptor, StageSource, VertexAttributeDescriptor,
VertexBufferLayoutDescriptor, VertexDescriptor,
};
use metal2vulkan::repro::ReproDevice;
use metal2vulkan::Budget;
fn repo() -> &'static Path {
@@ -457,3 +458,61 @@ fn a_bundle_carries_its_descriptor_files_and_replays_the_failure() {
"{replayed}"
);
}
/// `--device` reads a device description and policy (`ReproDevice`'s JSON) in place of
/// `--profile`, and compiles the same pipeline the profile's device does; the
/// two together, or `--profile-name` with `--device`, are usage errors.
#[test]
fn a_device_file_takes_the_place_of_a_profile() {
let scratch = Scratch::new();
let json = std::fs::read_to_string(profile("moltenvk-m3")).unwrap();
let description = DeviceDescription::from_khronos_json(&json, None).unwrap();
let device_file = scratch.join("device.json");
std::fs::write(
&device_file,
ReproDevice::new(description, DevicePolicy::default())
.to_json()
.unwrap(),
)
.unwrap();
let input = fixture("ob3_texture_array.air");
let by_profile = scratch.join("profile.spv");
let by_device = scratch.join("device.spv");
for (output, flag, file) in [
(&by_profile, "--profile", profile("moltenvk-m3")),
(&by_device, "--device", device_file.clone()),
] {
let result = cli(
&scratch,
&[
input.as_os_str(),
output.as_os_str(),
os(flag),
file.as_os_str(),
os("--no-spirv-val"),
],
&[],
);
assert!(result.status.success(), "{}", text(&result.stderr));
}
assert_eq!(
std::fs::read(&by_profile).unwrap(),
std::fs::read(&by_device).unwrap()
);
let profile_path = profile("moltenvk-m3");
for extra in [
[os("--profile"), profile_path.as_os_str()],
[os("--profile-name"), os("any")],
] {
let mut args = vec![
input.as_os_str(),
by_device.as_os_str(),
os("--device"),
device_file.as_os_str(),
];
args.extend(extra);
let result = cli(&scratch, &args, &[]);
assert_eq!(result.status.code(), Some(2), "{}", text(&result.stderr));
assert!(text(&result.stderr).contains("--device"));
}
}