mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 17:30:43 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bccb815e96 | ||
|
|
5442503d57 | ||
|
|
f0c61c7a91 | ||
|
|
0caca18634 | ||
|
|
2ea75603be |
No files matched your search
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation.
|
||||
- Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle).
|
||||
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
|
||||
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
|
||||
@@ -34,6 +35,7 @@ remains unsupported.
|
||||
### Added
|
||||
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
|
||||
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
|
||||
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
|
||||
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
|
||||
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
|
||||
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
|
||||
|
||||
+440
-11
@@ -233,6 +233,22 @@ fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result<Vec<u64>,
|
||||
/// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array.
|
||||
const TLS_ARRAY_SIZE: usize = 0x1000;
|
||||
|
||||
/// Bytes read per step when a template is checked and then copied into its
|
||||
/// block.
|
||||
const TEMPLATE_COPY_CHUNK: usize = 4096;
|
||||
|
||||
/// Smallest template copied into the zeroed block instead of a staging buffer.
|
||||
///
|
||||
/// Release timings of original synthetic templates on an Apple M2 Pro put the
|
||||
/// point where a second buffer dominates at 64 KiB. Below that, one read into
|
||||
/// a staging buffer is as fast or faster.
|
||||
const DIRECT_TEMPLATE_MIN: usize = 64 * 1024;
|
||||
|
||||
/// Templates at least this big keep the single staged read. On the same
|
||||
/// machine, proving the bytes readable and then copying them was no faster
|
||||
/// than the staging buffer once the template reached 1 MiB.
|
||||
const DIRECT_TEMPLATE_LIMIT: usize = 1024 * 1024;
|
||||
|
||||
/// Set up TLS runtime state in guest memory:
|
||||
/// 1. Assign TLS index 0 at `index_address`.
|
||||
/// 2. Map the thread's TLS pointer array at `thread_tls_base`.
|
||||
@@ -244,6 +260,12 @@ const TLS_ARRAY_SIZE: usize = 0x1000;
|
||||
/// TLS pointer. Compiled code loads that pointer, indexes it by the module's
|
||||
/// TLS index to find the data block, and then adds a variable's offset, so the
|
||||
/// array and the data are separate regions.
|
||||
///
|
||||
/// The block is the template followed by `SizeOfZeroFill` zero bytes. A
|
||||
/// template of at least 64 KiB and below 1 MiB is proved readable and then
|
||||
/// copied into a zeroed block. Every other size is read once into a staging
|
||||
/// buffer that initializes the block. Either way, a template that cannot be
|
||||
/// read leaves the pointer array unmapped.
|
||||
pub fn setup_tls(
|
||||
tls: &TlsDirectory,
|
||||
loaded_base: u64,
|
||||
@@ -278,11 +300,19 @@ pub fn setup_tls(
|
||||
let total_size = template_size + (tls.size_of_zero_fill as usize);
|
||||
|
||||
if total_size > 0 {
|
||||
// Read template bytes from image
|
||||
let mut template_data = vec![0u8; template_size];
|
||||
if template_size > 0 {
|
||||
memory.read_bytes(actual_start, &mut template_data)?;
|
||||
}
|
||||
let direct = (DIRECT_TEMPLATE_MIN..DIRECT_TEMPLATE_LIMIT).contains(&template_size);
|
||||
// The read happens before anything is mapped, so a missing or
|
||||
// unreadable template does not leave a pointer array behind.
|
||||
let staged = if direct {
|
||||
prove_template_readable(memory, actual_start, template_size)?;
|
||||
None
|
||||
} else {
|
||||
let mut staged = vec![0u8; template_size];
|
||||
if template_size > 0 {
|
||||
memory.read_bytes(actual_start, &mut staged)?;
|
||||
}
|
||||
Some(staged)
|
||||
};
|
||||
|
||||
// Allocate the pointer array and the per-thread TLS block.
|
||||
let block_base = thread_tls_base
|
||||
@@ -295,12 +325,17 @@ pub fn setup_tls(
|
||||
TLS_ARRAY_SIZE,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
)?;
|
||||
memory.map_region_with_data(
|
||||
block_base,
|
||||
map_size,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&template_data,
|
||||
)?;
|
||||
if let Some(staged) = staged.as_deref() {
|
||||
memory.map_region_with_data(
|
||||
block_base,
|
||||
map_size,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
staged,
|
||||
)?;
|
||||
} else {
|
||||
memory.map_region(block_base, map_size, MemoryPermissions::READ_WRITE)?;
|
||||
copy_template(memory, actual_start, block_base, template_size)?;
|
||||
}
|
||||
// Slot 0 belongs to the index assigned above.
|
||||
memory.write_u64(thread_tls_base, block_base)?;
|
||||
}
|
||||
@@ -308,6 +343,44 @@ pub fn setup_tls(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read every template byte, discarding the contents.
|
||||
///
|
||||
/// Failure here means the template is not available. Callers map the block
|
||||
/// only after this returns.
|
||||
fn prove_template_readable(memory: &GuestMemory, addr: u64, len: usize) -> Result<(), TlsError> {
|
||||
let mut chunk = [0u8; TEMPLATE_COPY_CHUNK];
|
||||
let mut offset = 0usize;
|
||||
while offset < len {
|
||||
let n = (len - offset).min(TEMPLATE_COPY_CHUNK);
|
||||
let at = addr
|
||||
.checked_add(offset as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.read_bytes(at, &mut chunk[..n])?;
|
||||
offset += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copy `len` bytes from `src` to `dst`. `dst` is already zeroed, which is the
|
||||
/// template's `SizeOfZeroFill` and the rounded tail of the block.
|
||||
fn copy_template(memory: &mut GuestMemory, src: u64, dst: u64, len: usize) -> Result<(), TlsError> {
|
||||
let mut chunk = [0u8; TEMPLATE_COPY_CHUNK];
|
||||
let mut offset = 0usize;
|
||||
while offset < len {
|
||||
let n = (len - offset).min(TEMPLATE_COPY_CHUNK);
|
||||
let from = src
|
||||
.checked_add(offset as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let to = dst
|
||||
.checked_add(offset as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.read_bytes(from, &mut chunk[..n])?;
|
||||
memory.write_bytes(to, &chunk[..n])?;
|
||||
offset += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute all registered TLS callbacks in sequence.
|
||||
/// Signature: void (NTAPI *PIMAGE_TLS_CALLBACK)(PVOID DllHandle, DWORD Reason, PVOID Reserved);
|
||||
/// - RCX = DllHandle (loaded_base)
|
||||
@@ -392,6 +465,8 @@ mod tests {
|
||||
|
||||
use super::*;
|
||||
use crate::pe::PeSection;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
const IMAGE_BASE: u64 = 0x1_4000_0000;
|
||||
const SECTION_RVA: u32 = 0x1000;
|
||||
@@ -680,4 +755,358 @@ mod tests {
|
||||
assert_eq!(none, Ok(0));
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes that do not repeat every 256 or every 4096 bytes, so a chunk
|
||||
/// copied from the wrong offset cannot match.
|
||||
fn synthetic_template(len: usize) -> Vec<u8> {
|
||||
(0..len)
|
||||
.map(|index| {
|
||||
let mixed = index ^ (index >> 8) ^ (index >> 16);
|
||||
mixed.wrapping_mul(131).wrapping_add(17) as u8
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Image template at `template_at`, with `sentinel` 0xA5 bytes after it, and
|
||||
/// a writable index that does not start at zero.
|
||||
fn template_memory(
|
||||
template_at: u64,
|
||||
template: &[u8],
|
||||
sentinel: usize,
|
||||
index_at: u64,
|
||||
) -> GuestMemory {
|
||||
let mut image = template.to_vec();
|
||||
image.extend(std::iter::repeat_n(0xA5, sentinel));
|
||||
let map = (image.len() + 0xFFF) & !0xFFF;
|
||||
image.resize(map, 0);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(template_at, map, MemoryPermissions::READ_ONLY, &image)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(index_at, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn directory_at(
|
||||
template_at: u64,
|
||||
template_len: u64,
|
||||
index_at: u64,
|
||||
zero_fill: u32,
|
||||
) -> TlsDirectory {
|
||||
TlsDirectory {
|
||||
raw_data_start_va: template_at,
|
||||
raw_data_end_va: template_at + template_len,
|
||||
index_address: index_at,
|
||||
size_of_zero_fill: zero_fill,
|
||||
..TlsDirectory::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_block(
|
||||
memory: &GuestMemory,
|
||||
thread: u64,
|
||||
index: u64,
|
||||
template: &[u8],
|
||||
zero_fill: usize,
|
||||
) {
|
||||
assert_eq!(memory.read_u32(index).unwrap(), 0);
|
||||
let block = memory.read_u64(thread).unwrap();
|
||||
assert_eq!(block, thread + 0x1000, "the data block is the next page");
|
||||
// The block is mapped up to the next page boundary and no further.
|
||||
let mapped = (template.len() + zero_fill + 0xFFF) & !0xFFF;
|
||||
let mut got = vec![0xEEu8; mapped];
|
||||
memory.read_bytes(block, &mut got).unwrap();
|
||||
assert_eq!(&got[..template.len()], template);
|
||||
assert!(got[template.len()..].iter().all(|byte| *byte == 0));
|
||||
let end = block + mapped as u64;
|
||||
assert_eq!(memory.read_u8(end), Err(MemoryError::UnmappedAddress(end)));
|
||||
}
|
||||
|
||||
const TEMPLATE_AT: u64 = 0x2_0020_0000;
|
||||
const INDEX_AT: u64 = 0x2_0000_1000;
|
||||
const THREAD_AT: u64 = 0x5_0000_0000;
|
||||
|
||||
#[test]
|
||||
fn a_small_template_is_copied_and_zero_fill_does_not_take_the_following_bytes() {
|
||||
let template = synthetic_template(48);
|
||||
let mut memory = template_memory(TEMPLATE_AT, &template, 16, INDEX_AT);
|
||||
setup_tls(
|
||||
&directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 16),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_block(&memory, THREAD_AT, INDEX_AT, &template, 16);
|
||||
let mut tail = [0u8; 16];
|
||||
memory
|
||||
.read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail)
|
||||
.unwrap();
|
||||
assert_eq!(tail, [0xA5; 16]);
|
||||
let block = memory.read_u64(THREAD_AT).unwrap();
|
||||
memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap();
|
||||
let mut image = [0u8; 8];
|
||||
memory.read_bytes(TEMPLATE_AT + 8, &mut image).unwrap();
|
||||
assert_eq!(image, template[8..16]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_staged_and_direct_copy_boundaries_keep_every_template_byte() {
|
||||
for len in [
|
||||
DIRECT_TEMPLATE_MIN - 1,
|
||||
DIRECT_TEMPLATE_MIN,
|
||||
DIRECT_TEMPLATE_MIN + TEMPLATE_COPY_CHUNK + 100,
|
||||
DIRECT_TEMPLATE_LIMIT - 1,
|
||||
DIRECT_TEMPLATE_LIMIT,
|
||||
] {
|
||||
let template = synthetic_template(len);
|
||||
let mut memory = template_memory(TEMPLATE_AT, &template, 24, INDEX_AT);
|
||||
setup_tls(
|
||||
&directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 24),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_block(&memory, THREAD_AT, INDEX_AT, &template, 24);
|
||||
let mut tail = [0u8; 24];
|
||||
memory
|
||||
.read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail)
|
||||
.unwrap();
|
||||
assert_eq!(tail, [0xA5; 24], "len {len}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rebased_direct_copy_reads_the_loaded_image() {
|
||||
let template = synthetic_template(DIRECT_TEMPLATE_MIN);
|
||||
let preferred = 0x1_4000_0000u64;
|
||||
let loaded = preferred + 0x80_0000;
|
||||
let template_at = preferred + 0x20_0000;
|
||||
let index_at = preferred + 0x1000;
|
||||
let mut memory =
|
||||
template_memory(template_at + 0x80_0000, &template, 0, index_at + 0x80_0000);
|
||||
setup_tls(
|
||||
&directory_at(template_at, template.len() as u64, index_at, 8),
|
||||
loaded,
|
||||
preferred,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_block(&memory, THREAD_AT, index_at + 0x80_0000, &template, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_template_maps_no_pointer_array() {
|
||||
for len in [32usize, DIRECT_TEMPLATE_MIN, DIRECT_TEMPLATE_MIN + 50] {
|
||||
let mut missing = GuestMemory::new();
|
||||
missing
|
||||
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
let missing_result = setup_tls(
|
||||
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut missing,
|
||||
THREAD_AT,
|
||||
);
|
||||
assert_eq!(
|
||||
missing_result,
|
||||
Err(TlsError::Memory(MemoryError::UnmappedAddress(TEMPLATE_AT))),
|
||||
"{len}"
|
||||
);
|
||||
assert_eq!(missing.read_u32(INDEX_AT).unwrap(), 0);
|
||||
assert!(matches!(
|
||||
missing.read_u64(THREAD_AT),
|
||||
Err(MemoryError::UnmappedAddress(_))
|
||||
));
|
||||
|
||||
let mut denied = GuestMemory::new();
|
||||
denied
|
||||
.map_region(TEMPLATE_AT, len.max(0x1000), MemoryPermissions::NO_ACCESS)
|
||||
.unwrap();
|
||||
denied
|
||||
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
let denied_result = setup_tls(
|
||||
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut denied,
|
||||
THREAD_AT,
|
||||
);
|
||||
assert_eq!(
|
||||
denied_result,
|
||||
Err(TlsError::Memory(MemoryError::PermissionViolation {
|
||||
address: TEMPLATE_AT,
|
||||
required: "read",
|
||||
})),
|
||||
"{len}"
|
||||
);
|
||||
assert_eq!(denied.read_u32(INDEX_AT).unwrap(), 0);
|
||||
assert!(matches!(
|
||||
denied.read_u64(THREAD_AT),
|
||||
Err(MemoryError::UnmappedAddress(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_direct_copy_template_that_runs_out_of_its_mapping_maps_nothing() {
|
||||
let len = DIRECT_TEMPLATE_MIN + 100;
|
||||
let mut memory = GuestMemory::new();
|
||||
// Only the first chunk is mapped. The rest of the template is not.
|
||||
memory
|
||||
.map_region_with_data(
|
||||
TEMPLATE_AT,
|
||||
TEMPLATE_COPY_CHUNK,
|
||||
MemoryPermissions::READ_ONLY,
|
||||
&synthetic_template(TEMPLATE_COPY_CHUNK),
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
let result = setup_tls(
|
||||
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
);
|
||||
// The same first unreadable byte the single staged read reports.
|
||||
assert_eq!(
|
||||
result,
|
||||
Err(TlsError::Memory(MemoryError::UnmappedAddress(
|
||||
TEMPLATE_AT + TEMPLATE_COPY_CHUNK as u64
|
||||
)))
|
||||
);
|
||||
assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0);
|
||||
assert!(matches!(
|
||||
memory.read_u64(THREAD_AT),
|
||||
Err(MemoryError::UnmappedAddress(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_template_and_zero_fill_only_assigns_the_index() {
|
||||
let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT);
|
||||
setup_tls(
|
||||
&directory_at(TEMPLATE_AT, 0, INDEX_AT, 0),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0);
|
||||
assert!(matches!(
|
||||
memory.read_u64(THREAD_AT),
|
||||
Err(MemoryError::UnmappedAddress(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_fill_only_block_is_zero_and_separate_from_the_array() {
|
||||
let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT);
|
||||
setup_tls(
|
||||
&directory_at(TEMPLATE_AT, 0, INDEX_AT, 24),
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
&mut memory,
|
||||
THREAD_AT,
|
||||
)
|
||||
.unwrap();
|
||||
assert_block(&memory, THREAD_AT, INDEX_AT, &[], 24);
|
||||
}
|
||||
|
||||
/// Byte pattern from the before/after timing runs. It is not the pattern
|
||||
/// the correctness tests use to catch a chunk copied from the wrong offset.
|
||||
fn timed_template(len: usize) -> Vec<u8> {
|
||||
(0..len)
|
||||
.map(|index| (index.wrapping_mul(131).wrapping_add(17)) as u8)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn timed_guest(template_len: usize, zero_fill: u32) -> (GuestMemory, TlsDirectory) {
|
||||
let template = timed_template(template_len);
|
||||
let mut memory = GuestMemory::new();
|
||||
if template_len > 0 {
|
||||
let map = (template_len + 0xFFF) & !0xFFF;
|
||||
memory
|
||||
.map_region_with_data(TEMPLATE_AT, map, MemoryPermissions::READ_ONLY, &template)
|
||||
.unwrap();
|
||||
}
|
||||
memory
|
||||
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
(
|
||||
memory,
|
||||
directory_at(TEMPLATE_AT, template_len as u64, INDEX_AT, zero_fill),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual TLS template timing run; release build on an otherwise idle host"]
|
||||
fn tls_template_initialization_profile() {
|
||||
// Sizes, zero fill and batch counts from the interleaved before/after runs.
|
||||
let cases = [
|
||||
(64usize, 0u32, 80usize),
|
||||
(4096, 0, 40),
|
||||
(65535, 0, 20),
|
||||
(65536, 128, 16),
|
||||
(262144, 0, 6),
|
||||
(786432, 0, 4),
|
||||
(1048576, 0, 4),
|
||||
(0, 1048576, 4),
|
||||
];
|
||||
for (template_len, zero_fill, batch) in cases {
|
||||
let (mut memory, directory) = timed_guest(template_len, zero_fill);
|
||||
setup_tls(&directory, IMAGE_BASE, IMAGE_BASE, &mut memory, THREAD_AT).unwrap();
|
||||
if template_len > 0 {
|
||||
let template = timed_template(template_len);
|
||||
let block = memory.read_u64(THREAD_AT).unwrap();
|
||||
let mut byte = [0u8; 1];
|
||||
memory.read_bytes(block, &mut byte).unwrap();
|
||||
assert_eq!(byte[0], template[0]);
|
||||
memory
|
||||
.read_bytes(block + template_len as u64 - 1, &mut byte)
|
||||
.unwrap();
|
||||
assert_eq!(byte[0], template[template_len - 1]);
|
||||
}
|
||||
|
||||
let mut samples = Vec::new();
|
||||
for run in 0..33 {
|
||||
let mut guests: Vec<_> = (0..batch)
|
||||
.map(|_| timed_guest(template_len, zero_fill))
|
||||
.collect();
|
||||
let start = Instant::now();
|
||||
for (memory, directory) in &mut guests {
|
||||
setup_tls(directory, IMAGE_BASE, IMAGE_BASE, memory, THREAD_AT).unwrap();
|
||||
black_box(memory);
|
||||
}
|
||||
if run >= 2 {
|
||||
let per_ns = start.elapsed().as_secs_f64() * 1e9 / batch as f64;
|
||||
samples.push(per_ns);
|
||||
}
|
||||
}
|
||||
samples.sort_by(f64::total_cmp);
|
||||
let n = samples.len();
|
||||
let mean = samples.iter().sum::<f64>() / n as f64;
|
||||
let sample_variance = samples
|
||||
.iter()
|
||||
.map(|sample| (sample - mean).powi(2))
|
||||
.sum::<f64>()
|
||||
/ (n - 1) as f64;
|
||||
println!(
|
||||
"template={template_len} zero_fill={zero_fill} batch={batch} n={n} median_ns={:.1} sample_variance_ns2={sample_variance:.1}",
|
||||
samples[n / 2]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+171
-3
@@ -2,6 +2,7 @@
|
||||
|
||||
//! Verified compilation for Xenora's synthetic compute and graphics ABIs.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::{self, Write};
|
||||
|
||||
mod graphics;
|
||||
@@ -34,8 +35,8 @@ pub struct CompiledShader {
|
||||
/// Optional translation passes applied after verification.
|
||||
///
|
||||
/// Default options preserve the historical IR shape: constants from scalar
|
||||
/// evaluation and immediates remain, but pure vector expressions between
|
||||
/// constants are not rewritten.
|
||||
/// evaluation and immediates remain, pure vector expressions between
|
||||
/// constants are not rewritten, and duplicate pure expressions are not reused.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct CompileOptions {
|
||||
/// Replace pure vector unary/binary ops whose operands are already
|
||||
@@ -43,6 +44,12 @@ pub struct CompileOptions {
|
||||
/// the existing exact positive-normal rules accept the result. Loads,
|
||||
/// stores, lane masks, merges and branches are never folded.
|
||||
pub fold_constants: bool,
|
||||
/// Reuse the first result of an equivalent pure vector unary or binary
|
||||
/// expression. Equivalence is the same operation and the same operand
|
||||
/// values in the same order; constant operands compare by bit pattern.
|
||||
/// Loads, stores, constants, lane masks, merges, branches and other
|
||||
/// mask-dependent or side-effecting ops are never reused.
|
||||
pub eliminate_common_subexpressions: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -155,6 +162,9 @@ enum Op {
|
||||
fallthrough: Value,
|
||||
taken: Value,
|
||||
},
|
||||
/// The value is the earlier pure result `source`. The definition index stays
|
||||
/// so later operands do not need renumbering.
|
||||
Reuse(Value),
|
||||
}
|
||||
|
||||
impl Op {
|
||||
@@ -186,6 +196,7 @@ impl Op {
|
||||
fallthrough,
|
||||
taken,
|
||||
} => vec![mask, fallthrough, taken],
|
||||
Self::Reuse(source) => vec![source],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,6 +273,7 @@ impl Op {
|
||||
_ => unreachable!("not a VCC arithmetic operation"),
|
||||
}
|
||||
}
|
||||
Self::Reuse(source) => name(source),
|
||||
Self::Store(_)
|
||||
| Self::ScalarBranch { .. }
|
||||
| Self::CarryMask { .. }
|
||||
@@ -303,7 +315,7 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Binary {
|
||||
FloatAdd,
|
||||
FloatMul,
|
||||
@@ -506,6 +518,11 @@ pub fn compile_with(
|
||||
if options.fold_constants {
|
||||
fold_constant_ops(&mut operations);
|
||||
}
|
||||
// Fold first so a constant expression is `const.u32` before reuse. CSE does
|
||||
// not fold, and it does not turn those constants back into arithmetic.
|
||||
if options.eliminate_common_subexpressions {
|
||||
eliminate_common_subexpressions(&mut operations);
|
||||
}
|
||||
|
||||
let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect();
|
||||
let mut ir = String::new();
|
||||
@@ -685,6 +702,10 @@ pub fn compile_with(
|
||||
format!("store.u32 output[index], {value}"),
|
||||
format!("output[index] = {value};"),
|
||||
),
|
||||
Op::Reuse(source) => (
|
||||
format!("{dest} = reuse.u32 {source}"),
|
||||
format!("uint {dest} = {source};"),
|
||||
),
|
||||
};
|
||||
// Writing to a String is infallible.
|
||||
let _ = writeln!(ir, "{offset:04x}: {step}");
|
||||
@@ -1489,6 +1510,153 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
})
|
||||
}
|
||||
|
||||
/// Reuse the first equivalent pure vector unary or binary.
|
||||
///
|
||||
/// Equivalence is the operation plus its operand values in order. Constant
|
||||
/// operands match by bit pattern, so two temps folded to the same `const.u32`
|
||||
/// compare equal. That match only selects reuse: an op that is kept keeps
|
||||
/// its own constant operands, so a shader with no repeat compiles unchanged.
|
||||
/// Loads, stores, the constant definitions themselves, lane masks, merges,
|
||||
/// branches and other mask-dependent or side-effecting ops are never
|
||||
/// candidates. A reused definition stays at its index as `reuse.u32`.
|
||||
fn eliminate_common_subexpressions(operations: &mut [(usize, Op)]) {
|
||||
let mut expr_alias = vec![None; operations.len()];
|
||||
let mut const_bits: HashMap<u32, usize> = HashMap::new();
|
||||
let mut seen: Vec<(PureExpr, usize)> = Vec::new();
|
||||
|
||||
for index in 0..operations.len() {
|
||||
let current = operations[index].1;
|
||||
if let Op::Constant(bits) = current {
|
||||
const_bits.entry(bits).or_insert(index);
|
||||
continue;
|
||||
}
|
||||
let canonical = match current {
|
||||
Op::Unary(operator, source) => Op::Unary(
|
||||
operator,
|
||||
equivalent_value(&expr_alias, &const_bits, operations, source),
|
||||
),
|
||||
Op::Binary(operator, left, right) => Op::Binary(
|
||||
operator,
|
||||
equivalent_value(&expr_alias, &const_bits, operations, left),
|
||||
equivalent_value(&expr_alias, &const_bits, operations, right),
|
||||
),
|
||||
other => other,
|
||||
};
|
||||
let rewritten = map_uses(current, |value| reused_value(&expr_alias, value));
|
||||
if let Some(key) = pure_expr(canonical) {
|
||||
if let Some(&(_, first)) = seen.iter().find(|(seen_key, _)| *seen_key == key) {
|
||||
expr_alias[index] = Some(first);
|
||||
operations[index].1 = Op::Reuse(Value(first));
|
||||
continue;
|
||||
}
|
||||
seen.push((key, index));
|
||||
}
|
||||
operations[index].1 = rewritten;
|
||||
}
|
||||
}
|
||||
|
||||
fn reused_value(expr_alias: &[Option<usize>], value: Value) -> Value {
|
||||
match expr_alias.get(value.0).and_then(|slot| *slot) {
|
||||
Some(index) => Value(index),
|
||||
None => value,
|
||||
}
|
||||
}
|
||||
|
||||
/// SSA value to use when matching a pure expression. Follows a reuse edge, then
|
||||
/// the earliest constant with the same bits.
|
||||
fn equivalent_value(
|
||||
expr_alias: &[Option<usize>],
|
||||
const_bits: &HashMap<u32, usize>,
|
||||
operations: &[(usize, Op)],
|
||||
value: Value,
|
||||
) -> Value {
|
||||
let root = reused_value(expr_alias, value);
|
||||
match operations.get(root.0).map(|(_, operation)| *operation) {
|
||||
Some(Op::Constant(bits)) => const_bits.get(&bits).copied().map(Value).unwrap_or(root),
|
||||
_ => root,
|
||||
}
|
||||
}
|
||||
|
||||
fn map_uses(operation: Op, map: impl Fn(Value) -> Value) -> Op {
|
||||
match operation {
|
||||
Op::Load | Op::Constant(_) | Op::ScalarBranch { .. } => operation,
|
||||
Op::Binary(operator, left, right) => Op::Binary(operator, map(left), map(right)),
|
||||
Op::Unary(operator, source) => Op::Unary(operator, map(source)),
|
||||
Op::MergeLanes {
|
||||
mask,
|
||||
active,
|
||||
inactive,
|
||||
} => Op::MergeLanes {
|
||||
mask,
|
||||
active: map(active),
|
||||
inactive: map(inactive),
|
||||
},
|
||||
Op::Store(value) => Op::Store(map(value)),
|
||||
Op::VccArithmetic {
|
||||
primitive,
|
||||
left,
|
||||
right,
|
||||
mask,
|
||||
flag,
|
||||
} => Op::VccArithmetic {
|
||||
primitive,
|
||||
left: map(left),
|
||||
right: map(right),
|
||||
mask: map(mask),
|
||||
flag,
|
||||
},
|
||||
Op::CarryMask { flag, exec } => Op::CarryMask {
|
||||
flag: map(flag),
|
||||
exec,
|
||||
},
|
||||
Op::LaneMask {
|
||||
op,
|
||||
name,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
high,
|
||||
exec,
|
||||
} => Op::LaneMask {
|
||||
op,
|
||||
name,
|
||||
sdst,
|
||||
src0: map(src0),
|
||||
src1: map(src1),
|
||||
high: high.map(|(left, right)| (map(left), map(right))),
|
||||
exec,
|
||||
},
|
||||
Op::RuntimeBranch { mask, target } => Op::RuntimeBranch {
|
||||
mask: map(mask),
|
||||
target,
|
||||
},
|
||||
Op::JoinVccz {
|
||||
mask,
|
||||
fallthrough,
|
||||
taken,
|
||||
} => Op::JoinVccz {
|
||||
mask: map(mask),
|
||||
fallthrough: map(fallthrough),
|
||||
taken: map(taken),
|
||||
},
|
||||
Op::Reuse(source) => Op::Reuse(map(source)),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum PureExpr {
|
||||
Unary(VectorUnary, usize),
|
||||
Binary(Binary, usize, usize),
|
||||
}
|
||||
|
||||
fn pure_expr(operation: Op) -> Option<PureExpr> {
|
||||
match operation {
|
||||
Op::Unary(operator, source) => Some(PureExpr::Unary(operator, source.0)),
|
||||
Op::Binary(operator, left, right) => Some(PureExpr::Binary(operator, left.0, right.0)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace pure constant expressions with `Op::Constant` in place.
|
||||
///
|
||||
/// Operands stay addressable by their original `Value` indices so later uses
|
||||
|
||||
@@ -649,6 +649,7 @@ fn compile_fold_off(code: &[u8]) -> xenora_shader::CompiledShader {
|
||||
code,
|
||||
CompileOptions {
|
||||
fold_constants: false,
|
||||
..CompileOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
@@ -660,6 +661,7 @@ fn compile_fold_on(code: &[u8]) -> xenora_shader::CompiledShader {
|
||||
code,
|
||||
CompileOptions {
|
||||
fold_constants: true,
|
||||
..CompileOptions::default()
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
@@ -843,6 +845,7 @@ fn rejects_inexact_float_add_of_constants_at_verify() {
|
||||
&code,
|
||||
CompileOptions {
|
||||
fold_constants: false,
|
||||
..CompileOptions::default()
|
||||
},
|
||||
);
|
||||
let on = compile_with(
|
||||
@@ -850,6 +853,7 @@ fn rejects_inexact_float_add_of_constants_at_verify() {
|
||||
&code,
|
||||
CompileOptions {
|
||||
fold_constants: true,
|
||||
..CompileOptions::default()
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
@@ -862,3 +866,660 @@ fn rejects_inexact_float_add_of_constants_at_verify() {
|
||||
);
|
||||
// Folder unchanged: no stay-unfolded path exists for this pair.
|
||||
}
|
||||
|
||||
// --- Opt-in common-subexpression elimination (#142) ---------------------------
|
||||
// Expected IR is derived from the lifter's value order and the reuse rule
|
||||
// (same unary/binary op, same operand values in order), not from the pass
|
||||
// output. Constant bits cited below are computed by hand.
|
||||
|
||||
fn compile_options(code: &[u8], fold: bool, cse: bool) -> xenora_shader::CompiledShader {
|
||||
compile_with(
|
||||
Architecture::Gfx1030,
|
||||
code,
|
||||
CompileOptions {
|
||||
fold_constants: fold,
|
||||
eliminate_common_subexpressions: cse,
|
||||
},
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn vopc(op: u32, src0_vgpr: u32, src1_vgpr: u32) -> u32 {
|
||||
// VOPC: encoding bits 0x7c00_0000, OP in bits 17-24, VSRC1 in bits 9-16,
|
||||
// SRC0 in bits 0-8 (VGPR selector 256 + register).
|
||||
0x7c00_0000 | (op << 17) | (src1_vgpr << 9) | (0x100 + src0_vgpr)
|
||||
}
|
||||
|
||||
/// load; mov v2, 0xff00ff00; and v3 and v4 with v1, v2; xor each and with v2.
|
||||
/// The two ands are the same pure op. The two xors become the same pure op
|
||||
/// only after the second and is reused, so the second xor must reuse the first.
|
||||
fn duplicate_and_xor_fixture() -> Vec<u8> {
|
||||
words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
mov_lit(2),
|
||||
0xff00_ff00,
|
||||
vop2(27, 3, 1, 2), // v_and_b32 v3, v1, v2
|
||||
vop2(27, 4, 1, 2), // v_and_b32 v4, v1, v2
|
||||
vop2(29, 5, 3, 2), // v_xor_b32 v5, v3, v2
|
||||
vop2(29, 6, 4, 2), // v_xor_b32 v6, v4, v2
|
||||
0xe070_2000,
|
||||
0x8001_0600, // buffer_store_dword v6
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
])
|
||||
}
|
||||
|
||||
const DUPLICATE_AND_OFF: &str = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0xff00ff00
|
||||
0014: t2 = and.b32 t0, t1
|
||||
0018: t3 = and.b32 t0, t1
|
||||
001c: t4 = xor.b32 t2, t1
|
||||
0020: t5 = xor.b32 t3, t1
|
||||
0024: store.u32 output[index], t5
|
||||
";
|
||||
|
||||
const DUPLICATE_AND_ON: &str = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0xff00ff00
|
||||
0014: t2 = and.b32 t0, t1
|
||||
0018: t3 = reuse.u32 t2
|
||||
001c: t4 = xor.b32 t2, t1
|
||||
0020: t5 = reuse.u32 t4
|
||||
0024: store.u32 output[index], t4
|
||||
";
|
||||
|
||||
const DUPLICATE_AND_MSL_OFF: &str = "\
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t1 = 0xff00ff00u;
|
||||
uint t2 = t0 & t1;
|
||||
uint t3 = t0 & t1;
|
||||
uint t4 = t2 ^ t1;
|
||||
uint t5 = t3 ^ t1;
|
||||
output[index] = t5;
|
||||
}
|
||||
";
|
||||
|
||||
const DUPLICATE_AND_MSL_ON: &str = "\
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
uint t0 = input[index];
|
||||
uint t1 = 0xff00ff00u;
|
||||
uint t2 = t0 & t1;
|
||||
uint t3 = t2;
|
||||
uint t4 = t2 ^ t1;
|
||||
uint t5 = t4;
|
||||
output[index] = t4;
|
||||
}
|
||||
";
|
||||
|
||||
#[test]
|
||||
fn default_compile_matches_cse_off() {
|
||||
assert_eq!(
|
||||
CompileOptions::default(),
|
||||
CompileOptions {
|
||||
fold_constants: false,
|
||||
eliminate_common_subexpressions: false,
|
||||
}
|
||||
);
|
||||
let code = duplicate_and_xor_fixture();
|
||||
let baseline = compile(Architecture::Gfx1030, &code).unwrap();
|
||||
let explicit = compile_options(&code, false, false);
|
||||
assert_eq!(baseline.ir, explicit.ir);
|
||||
assert_eq!(baseline.msl, explicit.msl);
|
||||
assert_eq!(baseline.ir, DUPLICATE_AND_OFF);
|
||||
assert_eq!(baseline.msl, DUPLICATE_AND_MSL_OFF);
|
||||
// add.bin has no duplicate pure expression. CSE on must not touch it.
|
||||
let add = compile(Architecture::Gfx1030, FIXTURE).unwrap();
|
||||
let add_cse = compile_options(FIXTURE, false, true);
|
||||
assert_eq!(add.ir, include_str!("../../../fixtures/golden/add.ir"));
|
||||
assert_eq!(add_cse.ir, add.ir);
|
||||
assert_eq!(add_cse.msl, add.msl);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuses_duplicate_and_and_the_xor_of_that_and() {
|
||||
// Off: two and.b32 and two xor.b32. On: one of each, plus reuse.u32.
|
||||
// The xor is not evaluated: xor of a value with a different operand stays
|
||||
// xor.b32. (xor with itself is not what this fixture computes.)
|
||||
let code = duplicate_and_xor_fixture();
|
||||
let off = compile_options(&code, false, false);
|
||||
let on = compile_options(&code, false, true);
|
||||
assert_eq!(off.ir, DUPLICATE_AND_OFF);
|
||||
assert_eq!(off.msl, DUPLICATE_AND_MSL_OFF);
|
||||
assert_eq!(on.ir, DUPLICATE_AND_ON);
|
||||
assert_eq!(on.msl, DUPLICATE_AND_MSL_ON);
|
||||
assert_eq!(off.ir.matches("and.b32").count(), 2);
|
||||
assert_eq!(on.ir.matches("and.b32").count(), 1);
|
||||
assert_eq!(off.ir.matches("xor.b32").count(), 2);
|
||||
assert_eq!(on.ir.matches("xor.b32").count(), 1);
|
||||
assert_eq!(on.ir.matches("store.u32").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reuses_duplicate_not() {
|
||||
// v_not_b32 twice on the loaded word. ~x computed once.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
vop1(55, 2, 1), // v_not_b32 v2, v1 (VOP1 opcode 55)
|
||||
vop1(55, 3, 1), // v_not_b32 v3, v1
|
||||
0xe070_2000,
|
||||
0x8001_0300,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
let off = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = not.b32 t0
|
||||
0010: t2 = not.b32 t0
|
||||
0014: store.u32 output[index], t2
|
||||
";
|
||||
let on = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = not.b32 t0
|
||||
0010: t2 = reuse.u32 t1
|
||||
0014: store.u32 output[index], t1
|
||||
";
|
||||
assert_eq!(compile_options(&code, false, false).ir, off);
|
||||
assert_eq!(compile_options(&code, false, true).ir, on);
|
||||
let msl = compile_options(&code, false, true).msl;
|
||||
assert!(msl.contains("uint t1 = ~t0;"));
|
||||
assert!(msl.contains("uint t2 = t1;"));
|
||||
assert_eq!(msl.matches("~t0").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_reuse_swapped_subtract() {
|
||||
// sub is not commutative: if the load is 0, v1 - 1 = 0xffffffff and
|
||||
// 1 - v1 = 1. The third sub repeats the first and is reused.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
mov_lit(2),
|
||||
1,
|
||||
vop2(38, 3, 1, 2), // v_sub_nc_u32 v3, v1, v2
|
||||
vop2(38, 4, 2, 1), // v_sub_nc_u32 v4, v2, v1
|
||||
vop2(38, 5, 1, 2), // v_sub_nc_u32 v5, v1, v2
|
||||
0xe070_2000,
|
||||
0x8001_0500,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
let off = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x00000001
|
||||
0014: t2 = sub.u32 t0, t1
|
||||
0018: t3 = sub.u32 t1, t0
|
||||
001c: t4 = sub.u32 t0, t1
|
||||
0020: store.u32 output[index], t4
|
||||
";
|
||||
let on = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x00000001
|
||||
0014: t2 = sub.u32 t0, t1
|
||||
0018: t3 = sub.u32 t1, t0
|
||||
001c: t4 = reuse.u32 t2
|
||||
0020: store.u32 output[index], t2
|
||||
";
|
||||
assert_eq!(compile_options(&code, false, false).ir, off);
|
||||
assert_eq!(compile_options(&code, false, true).ir, on);
|
||||
assert_eq!(
|
||||
compile_options(&code, false, true)
|
||||
.ir
|
||||
.matches("sub.u32")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_reuse_a_different_opcode() {
|
||||
// and vs or of the same bits differ. 0xff00ff00 & 0x0f0f0f0f = 0x0f000f00;
|
||||
// 0xff00ff00 | 0x0f0f0f0f = 0xff0fff0f.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
mov_lit(2),
|
||||
0xff00_ff00,
|
||||
vop2(27, 3, 1, 2), // v_and_b32
|
||||
vop2(28, 4, 1, 2), // v_or_b32
|
||||
0xe070_2000,
|
||||
0x8001_0300,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
let ir = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0xff00ff00
|
||||
0014: t2 = and.b32 t0, t1
|
||||
0018: t3 = or.b32 t0, t1
|
||||
001c: store.u32 output[index], t2
|
||||
";
|
||||
let off = compile_options(&code, false, false);
|
||||
let on = compile_options(&code, false, true);
|
||||
assert_eq!(off.ir, ir);
|
||||
assert_eq!(on.ir, ir);
|
||||
assert!(!on.ir.contains("reuse.u32"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_merge_loads_or_duplicate_constant_definitions() {
|
||||
// Two loads of input[index] stay two loads. Two movs of the same immediate
|
||||
// stay two const.u32 definitions. The ands use different constant temps
|
||||
// with equal bits, so the pure and is reused and the consts remain.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100, // buffer_load_dword v1
|
||||
0xbf8c_3f70,
|
||||
0xe030_2000,
|
||||
0x8000_0200, // buffer_load_dword v2
|
||||
0xbf8c_3f70,
|
||||
mov_lit(3),
|
||||
0x1234_5678,
|
||||
mov_lit(4),
|
||||
0x1234_5678,
|
||||
vop2(27, 5, 1, 3), // v_and_b32 v5, v1, v3
|
||||
vop2(27, 6, 1, 4), // v_and_b32 v6, v1, v4
|
||||
0xe070_2000,
|
||||
0x8001_0600,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
let off = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = load.u32 input[index]
|
||||
0018: t2 = const.u32 0x12345678
|
||||
0020: t3 = const.u32 0x12345678
|
||||
0028: t4 = and.b32 t0, t2
|
||||
002c: t5 = and.b32 t0, t3
|
||||
0030: store.u32 output[index], t5
|
||||
";
|
||||
// Constant temps compare by bits, so the second and reuses the first.
|
||||
// The load temps differ, and neither load is removed.
|
||||
let on = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = load.u32 input[index]
|
||||
0018: t2 = const.u32 0x12345678
|
||||
0020: t3 = const.u32 0x12345678
|
||||
0028: t4 = and.b32 t0, t2
|
||||
002c: t5 = reuse.u32 t4
|
||||
0030: store.u32 output[index], t4
|
||||
";
|
||||
assert_eq!(compile_options(&code, false, false).ir, off);
|
||||
assert_eq!(compile_options(&code, false, true).ir, on);
|
||||
assert_eq!(
|
||||
compile_options(&code, false, true)
|
||||
.ir
|
||||
.matches("load.u32")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
assert_eq!(
|
||||
compile_options(&code, false, true)
|
||||
.ir
|
||||
.matches("const.u32 0x12345678")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_merge_lane_masks() {
|
||||
// Two identical v_cmp_eq_u32_e32 (VOPC opcode 194) write the wave mask.
|
||||
// The results are lane-mask values and are not reused.
|
||||
let code = words(&[
|
||||
mov_lit(1),
|
||||
1,
|
||||
mov_lit(2),
|
||||
2,
|
||||
vopc(194, 1, 2),
|
||||
vopc(194, 1, 2),
|
||||
mov_lit(3),
|
||||
0,
|
||||
0xe070_2000,
|
||||
0x8001_0300,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
let ir = "\
|
||||
0000: t0 = const.u32 0x00000001
|
||||
0008: t1 = const.u32 0x00000002
|
||||
0010: t2 = wave.mask v_cmp_eq_u32_e32 t0, t1 exec=0xffffffff
|
||||
0014: t3 = wave.mask v_cmp_eq_u32_e32 t0, t1 exec=0xffffffff
|
||||
0018: t4 = const.u32 0x00000000
|
||||
0020: store.u32 output[index], t4
|
||||
";
|
||||
let off = compile_options(&code, false, false);
|
||||
let on = compile_options(&code, false, true);
|
||||
assert_eq!(off.ir, ir);
|
||||
assert_eq!(on.ir, ir);
|
||||
assert_eq!(on.ir.matches("wave.mask").count(), 2);
|
||||
assert!(!on.ir.contains("reuse.u32"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_merge_lane_merges_under_partial_exec() {
|
||||
// EXEC = 1 merges each and with that destination's previous value.
|
||||
// The and itself is pure and is reused. The two merges see different
|
||||
// inactive values (the two zero temps) and both remain.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
mov_lit(2),
|
||||
0xff00_ff00,
|
||||
mov_lit(3),
|
||||
0, // v3 initialized before the partial write
|
||||
mov_lit(4),
|
||||
0, // v4 initialized before the partial write
|
||||
0xbefe_0381, // s_mov_b32 exec_lo, 1
|
||||
vop2(27, 3, 1, 2), // v_and_b32 v3, v1, v2
|
||||
vop2(27, 4, 1, 2), // v_and_b32 v4, v1, v2
|
||||
0xbefe_03c1, // s_mov_b32 exec_lo, -1
|
||||
0xe070_2000,
|
||||
0x8001_0300, // buffer_store_dword v3
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
let off = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0xff00ff00
|
||||
0014: t2 = const.u32 0x00000000
|
||||
001c: t3 = const.u32 0x00000000
|
||||
0028: t4 = and.b32 t0, t1
|
||||
0028: t5 = merge.lanes mask=0x00000001, t4, t2
|
||||
002c: t6 = and.b32 t0, t1
|
||||
002c: t7 = merge.lanes mask=0x00000001, t6, t3
|
||||
0034: store.u32 output[index], t5
|
||||
";
|
||||
let on = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0xff00ff00
|
||||
0014: t2 = const.u32 0x00000000
|
||||
001c: t3 = const.u32 0x00000000
|
||||
0028: t4 = and.b32 t0, t1
|
||||
0028: t5 = merge.lanes mask=0x00000001, t4, t2
|
||||
002c: t6 = reuse.u32 t4
|
||||
002c: t7 = merge.lanes mask=0x00000001, t4, t3
|
||||
0034: store.u32 output[index], t5
|
||||
";
|
||||
assert_eq!(compile_options(&code, false, false).ir, off);
|
||||
assert_eq!(compile_options(&code, false, true).ir, on);
|
||||
assert_eq!(
|
||||
compile_options(&code, false, true)
|
||||
.ir
|
||||
.matches("merge.lanes")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_merge_vcc_select() {
|
||||
// v_cndmask_b32 reads VCC. Two identical selects stay two vcc.Select ops.
|
||||
let code = words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
mov_lit(2),
|
||||
0x1111_1111,
|
||||
0xbeea_0381, // s_mov_b32 vcc_lo, 1
|
||||
vop2(1, 3, 1, 2), // v_cndmask_b32 v3, v1, v2
|
||||
vop2(1, 4, 1, 2), // v_cndmask_b32 v4, v1, v2
|
||||
0xe070_2000,
|
||||
0x8001_0300,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
let ir = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x11111111
|
||||
0018: t2 = const.u32 0x00000001
|
||||
0018: t3 = vcc.Select t0, t1, t2
|
||||
001c: t4 = const.u32 0x00000001
|
||||
001c: t5 = vcc.Select t0, t1, t4
|
||||
0020: store.u32 output[index], t3
|
||||
";
|
||||
let off = compile_options(&code, false, false);
|
||||
let on = compile_options(&code, false, true);
|
||||
assert_eq!(off.ir, ir);
|
||||
assert_eq!(on.ir, ir);
|
||||
assert_eq!(on.ir.matches("vcc.Select").count(), 2);
|
||||
assert!(!on.ir.contains("reuse.u32"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cse_leaves_branch_and_float_fixtures_unchanged() {
|
||||
// No duplicate pure expression, so the pass is a no-op, including on the
|
||||
// uniform branches and the load-derived float ops.
|
||||
for (code, ir) in [
|
||||
(
|
||||
BRANCH,
|
||||
include_str!("../../../fixtures/golden/bitwise-branch.ir"),
|
||||
),
|
||||
(
|
||||
FLOAT,
|
||||
include_str!("../../../fixtures/golden/float-exact.ir"),
|
||||
),
|
||||
] {
|
||||
let plain = compile(Architecture::Gfx1030, code).unwrap();
|
||||
let on = compile_options(code, false, true);
|
||||
assert_eq!(plain.ir, ir);
|
||||
assert_eq!(on.ir, plain.ir);
|
||||
assert_eq!(on.msl, plain.msl);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cse_leaves_every_golden_fixture_unchanged() {
|
||||
// None of these fixtures repeats a pure op. Several use equal-bit
|
||||
// constants in different ops whose operands must not be renamed.
|
||||
macro_rules! golden {
|
||||
($name:literal) => {{
|
||||
let code = include_bytes!(concat!("../../../fixtures/rdna2/", $name, ".bin"));
|
||||
let shader = compile_options(code, false, true);
|
||||
assert_eq!(
|
||||
shader.ir,
|
||||
include_str!(concat!("../../../fixtures/golden/", $name, ".ir")),
|
||||
"ir changed for {}",
|
||||
$name
|
||||
);
|
||||
assert_eq!(
|
||||
shader.msl,
|
||||
include_str!(concat!("../../../fixtures/golden/", $name, ".metal")),
|
||||
"msl changed for {}",
|
||||
$name
|
||||
);
|
||||
}};
|
||||
}
|
||||
golden!("add");
|
||||
golden!("bitwise-branch");
|
||||
golden!("float-exact");
|
||||
golden!("scalar-alu");
|
||||
golden!("scalar-arith");
|
||||
golden!("scalar-compare");
|
||||
golden!("scalar-immediate");
|
||||
golden!("scalar-logic");
|
||||
golden!("scalar-unary");
|
||||
golden!("vector-compare");
|
||||
golden!("vector-compare-ft");
|
||||
golden!("vector-integer");
|
||||
golden!("vector-unary");
|
||||
}
|
||||
|
||||
/// 1 + 2 = 3, and the same add twice, then and the load with each sum.
|
||||
fn fold_and_cse_fixture() -> Vec<u8> {
|
||||
words(&[
|
||||
0xe030_2000,
|
||||
0x8000_0100,
|
||||
0xbf8c_3f70,
|
||||
mov_lit(2),
|
||||
1,
|
||||
mov_lit(3),
|
||||
2,
|
||||
vop2(37, 4, 2, 3), // v_add_nc_u32 v4, v2, v3
|
||||
vop2(37, 5, 2, 3), // v_add_nc_u32 v5, v2, v3
|
||||
vop2(27, 6, 1, 4), // v_and_b32 v6, v1, v4
|
||||
vop2(27, 7, 1, 5), // v_and_b32 v7, v1, v5
|
||||
0xe070_2000,
|
||||
0x8001_0700,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cse_interacts_with_constant_folding() {
|
||||
// Hand-computed: 1 + 2 = 3 (0x00000003). Folding rewrites the adds and
|
||||
// does not reuse the ands. CSE reuses both the add and the and, and does
|
||||
// not invent the constant 3. Both passes: the adds are constants first,
|
||||
// the two const 3 temps stay, and the ands reuse because those temps have
|
||||
// the same bits.
|
||||
let code = fold_and_cse_fixture();
|
||||
let off = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x00000001
|
||||
0014: t2 = const.u32 0x00000002
|
||||
001c: t3 = add.u32 t1, t2
|
||||
0020: t4 = add.u32 t1, t2
|
||||
0024: t5 = and.b32 t0, t3
|
||||
0028: t6 = and.b32 t0, t4
|
||||
002c: store.u32 output[index], t6
|
||||
";
|
||||
let cse_only = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x00000001
|
||||
0014: t2 = const.u32 0x00000002
|
||||
001c: t3 = add.u32 t1, t2
|
||||
0020: t4 = reuse.u32 t3
|
||||
0024: t5 = and.b32 t0, t3
|
||||
0028: t6 = reuse.u32 t5
|
||||
002c: store.u32 output[index], t5
|
||||
";
|
||||
let fold_only = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x00000001
|
||||
0014: t2 = const.u32 0x00000002
|
||||
001c: t3 = const.u32 0x00000003
|
||||
0020: t4 = const.u32 0x00000003
|
||||
0024: t5 = and.b32 t0, t3
|
||||
0028: t6 = and.b32 t0, t4
|
||||
002c: store.u32 output[index], t6
|
||||
";
|
||||
let both = "\
|
||||
0000: t0 = load.u32 input[index]
|
||||
000c: t1 = const.u32 0x00000001
|
||||
0014: t2 = const.u32 0x00000002
|
||||
001c: t3 = const.u32 0x00000003
|
||||
0020: t4 = const.u32 0x00000003
|
||||
0024: t5 = and.b32 t0, t3
|
||||
0028: t6 = reuse.u32 t5
|
||||
002c: store.u32 output[index], t5
|
||||
";
|
||||
assert_eq!(compile_options(&code, false, false).ir, off);
|
||||
assert_eq!(compile_options(&code, false, true).ir, cse_only);
|
||||
assert_eq!(compile_options(&code, true, false).ir, fold_only);
|
||||
assert_eq!(compile_options(&code, true, true).ir, both);
|
||||
assert!(!cse_only.contains("0x00000003"));
|
||||
assert_eq!(fold_only.matches("const.u32 0x00000003").count(), 2);
|
||||
assert_eq!(both.matches("and.b32").count(), 1);
|
||||
assert!(!both.contains("add.u32"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cse_does_not_fold_exact_float_add() {
|
||||
// 1.0 + 2.0 = 3.0 exactly. Bits 0x3f800000 + 0x40000000 = 0x40400000.
|
||||
// CSE reuses the add and leaves the operation. Folding replaces both
|
||||
// adds with that constant. Enabling both matches folding alone: the adds
|
||||
// are gone before reuse, and the two result constants are not merged.
|
||||
let code = words(&[
|
||||
mov_lit(2),
|
||||
0x3f80_0000,
|
||||
mov_lit(3),
|
||||
0x4000_0000,
|
||||
vop2(3, 4, 2, 3), // v_add_f32 v4, v2, v3
|
||||
vop2(3, 5, 2, 3), // v_add_f32 v5, v2, v3
|
||||
0xe070_2000,
|
||||
0x8001_0500,
|
||||
0xbbfd_0000,
|
||||
0xbf81_0000,
|
||||
]);
|
||||
let cse_ir = "\
|
||||
0000: t0 = const.u32 0x3f800000
|
||||
0008: t1 = const.u32 0x40000000
|
||||
0010: t2 = add.f32 t0, t1
|
||||
0014: t3 = reuse.u32 t2
|
||||
0018: store.u32 output[index], t2
|
||||
";
|
||||
let fold_ir = "\
|
||||
0000: t0 = const.u32 0x3f800000
|
||||
0008: t1 = const.u32 0x40000000
|
||||
0010: t2 = const.u32 0x40400000
|
||||
0014: t3 = const.u32 0x40400000
|
||||
0018: store.u32 output[index], t3
|
||||
";
|
||||
let cse_msl = "\
|
||||
#include <metal_stdlib>
|
||||
using namespace metal;
|
||||
kernel void xenora_compute(
|
||||
device const uint* input [[buffer(0)]],
|
||||
device uint* output [[buffer(1)]],
|
||||
uint index [[thread_position_in_grid]]) {
|
||||
#pragma clang fp contract(off)
|
||||
#pragma clang fp reassociate(off)
|
||||
uint t0 = 0x3f800000u;
|
||||
uint t1 = 0x40000000u;
|
||||
uint t2 = as_type<uint>(as_type<float>(t0) + as_type<float>(t1));
|
||||
uint t3 = t2;
|
||||
output[index] = t2;
|
||||
}
|
||||
";
|
||||
let folded = compile_options(&code, true, false);
|
||||
let both = compile_options(&code, true, true);
|
||||
assert_eq!(compile_options(&code, false, true).ir, cse_ir);
|
||||
assert_eq!(compile_options(&code, false, true).msl, cse_msl);
|
||||
assert_eq!(folded.ir, fold_ir);
|
||||
assert_eq!(both.ir, folded.ir);
|
||||
assert_eq!(both.msl, folded.msl);
|
||||
assert!(!cse_ir.contains("0x40400000"));
|
||||
assert_eq!(fold_ir.matches("const.u32 0x40400000").count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cse_does_not_bypass_inexact_float_verification() {
|
||||
// Same pair the folder refuses: 1.0 + 2^-24 is not an f32 value. Verify
|
||||
// rejects it before either optional pass.
|
||||
let code = binary_const_fixture(3, 0x3f80_0000, 0x3380_0000, false);
|
||||
for fold in [false, true] {
|
||||
for cse in [false, true] {
|
||||
let result = compile_with(
|
||||
Architecture::Gfx1030,
|
||||
&code,
|
||||
CompileOptions {
|
||||
fold_constants: fold,
|
||||
eliminate_common_subexpressions: cse,
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
matches!(result, Err(CompileError::Verify { .. })),
|
||||
"fold={fold} cse={cse} must reject at verify: {result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user