Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-index/src/addr.rs

//! Address lookups: which function, block, line or scope an address falls in, and which
//! call site an address is.
//!
//! A column of start addresses (and maybe ends) is searched with Ragnar Groot Koerkamp's
//! static search tree (`zoomies_stree::AddrTree`: 16 keys per 64-byte node, AVX-512/AVX2
//! compares, 32 queries in lockstep with prefetch). When the set's starts already rise
//! strictly the column is the set's own mapped buffer, no copy; otherwise the starts are
//! sorted once (psort) with the row each came from, an address seen twice keeping its
//! first row, and that sorted copy is what is stored. An end at or below its start means
//! the end is unknown: the range then runs to the next start.

use arrow_buffer::ScalarBuffer;
use zoomies_stree::AddrTree;

use crate::error::{Result, bad};

/// Sorted start addresses, the row of each, and each range's end when the table has one.
#[derive(Clone, Debug)]
pub struct AddrColumn {
    keys: ScalarBuffer<u64>,
    /// The table row of each key; `None`: key `i` is row `i` (the set's own column).
    rows: Option<ScalarBuffer<u32>>,
    ends: Option<ScalarBuffer<u64>>,
}

impl AddrColumn {
    /// The column of a table's `starts` (and `ends`, one per start): shared as it is when
    /// the starts rise strictly, else sorted with their rows.
    pub fn build(starts: ScalarBuffer<u64>, ends: Option<ScalarBuffer<u64>>) -> Result<Self> {
        if let Some(e) = &ends
            && e.len() != starts.len()
        {
            return Err(bad(format!("{} ends for {} starts", e.len(), starts.len())));
        }
        if u32::try_from(starts.len()).is_err() {
            return Err(bad("more than 2^32 rows"));
        }
        if starts.windows(2).all(|w| w[0] < w[1]) {
            return Ok(AddrColumn {
                keys: starts,
                rows: None,
                ends,
            });
        }
        if starts.windows(2).all(|w| w[0] <= w[1]) {
            // Already in order with repeats (a line table): keep each address's first row.
            let mut keys: Vec<u64> = Vec::with_capacity(starts.len());
            let mut rows: Vec<u32> = Vec::with_capacity(starts.len());
            for (row, &k) in starts.iter().enumerate() {
                if keys.last() != Some(&k) {
                    keys.push(k);
                    rows.push(row as u32);
                }
            }
            let ends = ends.map(|e| {
                ScalarBuffer::from(rows.iter().map(|&r| e[r as usize]).collect::<Vec<_>>())
            });
            return Ok(AddrColumn {
                keys: keys.into(),
                rows: Some(rows.into()),
                ends,
            });
        }
        // (start, row) records sorted by start on all cores; the sign flip makes the
        // signed sort order the unsigned one.
        let mut recs: Vec<[u8; 16]> = starts
            .iter()
            .enumerate()
            .map(|(row, &a)| {
                let mut r = [0u8; 16];
                r[..8].copy_from_slice(&((a ^ (1 << 63)) as i64).to_le_bytes());
                r[8..].copy_from_slice(&(row as u64).to_le_bytes());
                r
            })
            .collect();
        znippy_zoomies::psort::samplesort_aos_by_i64_key(&mut recs);
        let rec = |r: &[u8; 16]| {
            let k = i64::from_le_bytes(r[..8].try_into().expect("8 bytes")) as u64 ^ (1 << 63);
            let row = u64::from_le_bytes(r[8..].try_into().expect("8 bytes")) as u32;
            (k, row)
        };
        let mut keys: Vec<u64> = Vec::with_capacity(recs.len());
        let mut rows: Vec<u32> = Vec::with_capacity(recs.len());
        for r in &recs {
            let (k, row) = rec(r);
            if keys.last() == Some(&k) {
                let last = rows.last_mut().expect("a row per key");
                *last = (*last).min(row);
            } else {
                keys.push(k);
                rows.push(row);
            }
        }
        let ends = ends
            .map(|e| ScalarBuffer::from(rows.iter().map(|&r| e[r as usize]).collect::<Vec<_>>()));
        Ok(AddrColumn {
            keys: keys.into(),
            rows: Some(rows.into()),
            ends,
        })
    }

    /// A column from its stored parts (as [`AddrColumn::parts`] gave them).
    pub fn from_parts(
        keys: ScalarBuffer<u64>,
        rows: Option<ScalarBuffer<u32>>,
        ends: Option<ScalarBuffer<u64>>,
    ) -> Result<Self> {
        if rows.as_ref().is_some_and(|r| r.len() != keys.len())
            || ends.as_ref().is_some_and(|e| e.len() != keys.len())
        {
            return Err(bad("address column parts of unequal length"));
        }
        Ok(AddrColumn { keys, rows, ends })
    }

    /// The keys, the rows (none when key `i` is row `i`) and the ends.
    pub fn parts(
        &self,
    ) -> (
        &ScalarBuffer<u64>,
        Option<&ScalarBuffer<u32>>,
        Option<&ScalarBuffer<u64>>,
    ) {
        (&self.keys, self.rows.as_ref(), self.ends.as_ref())
    }

    /// Whether the keys are the set's own buffer (nothing was sorted or copied).
    pub fn is_shared(&self) -> bool {
        self.rows.is_none()
    }

    /// The number of distinct start addresses.
    pub fn len(&self) -> usize {
        self.keys.len()
    }

    /// Whether there are no addresses.
    pub fn is_empty(&self) -> bool {
        self.keys.is_empty()
    }

    /// The search tree over the column: its inner nodes are built here (one key in 16),
    /// once; the column is the leaf layer.
    pub fn lookup(&self) -> Result<AddrLookup<'_>> {
        let base = self.keys.first().copied().unwrap_or(0);
        let search = match AddrTree::open(&self.keys, base) {
            Ok(tree) => Search::Tree(tree),
            // Wider than 4 GiB: a plain binary search over the same column.
            Err(zoomies_stree::KeyError::OutOfSpan { .. }) => Search::Binary(&self.keys),
            Err(e) => return Err(bad(e.to_string())),
        };
        Ok(AddrLookup {
            search,
            rows: self.rows.as_deref(),
            ends: self.ends.as_deref(),
        })
    }
}

enum Search<'a> {
    Tree(AddrTree<'a>),
    Binary(&'a [u64]),
}

/// Lookups on an [`AddrColumn`]; none allocates.
pub struct AddrLookup<'a> {
    search: Search<'a>,
    rows: Option<&'a [u32]>,
    ends: Option<&'a [u64]>,
}

/// Which floors a batched lookup keeps.
#[derive(Clone, Copy)]
enum Keep {
    Floor,
    Covering,
    Exact,
}

/// Queries per round of the batched lookups (their scratch lives on the stack).
const BATCH: usize = 256;

impl AddrLookup<'_> {
    /// Whether the static search tree answers (else the column is wider than 4 GiB and a
    /// binary search does).
    pub fn is_tree(&self) -> bool {
        matches!(self.search, Search::Tree(_))
    }

    fn row(&self, at: usize) -> u32 {
        match self.rows {
            Some(r) => r[at],
            None => at as u32,
        }
    }

    fn floor_at(&self, addr: u64) -> Option<usize> {
        match &self.search {
            Search::Tree(t) => t.floor(addr),
            Search::Binary(k) => k.partition_point(|&x| x <= addr).checked_sub(1),
        }
    }

    fn covers(&self, at: usize, addr: u64) -> bool {
        // an end at or below its start is unknown: the range runs to the next start
        self.ends
            .is_none_or(|e| addr < e[at] || e[at] <= self.key(at))
    }

    fn key(&self, at: usize) -> u64 {
        match &self.search {
            Search::Tree(t) => t.keys()[at],
            Search::Binary(k) => k[at],
        }
    }

    /// The row of the last start at or below `addr`.
    #[inline]
    pub fn floor(&self, addr: u64) -> Option<u32> {
        self.floor_at(addr).map(|at| self.row(at))
    }

    /// The row whose range `start..end` holds `addr` (the floor, checked against its end;
    /// a column without ends answers as [`AddrLookup::floor`]).
    #[inline]
    pub fn covering(&self, addr: u64) -> Option<u32> {
        self.floor_at(addr)
            .filter(|&at| self.covers(at, addr))
            .map(|at| self.row(at))
    }

    /// The row whose start is `addr`.
    #[inline]
    pub fn exact(&self, addr: u64) -> Option<u32> {
        self.floor_at(addr)
            .filter(|&at| self.key(at) == addr)
            .map(|at| self.row(at))
    }

    fn batch(&self, qs: &[u64], out: &mut [Option<u32>], keep: Keep) {
        assert_eq!(qs.len(), out.len(), "one answer slot per query");
        let mut at = [None; BATCH];
        for (q, o) in qs.chunks(BATCH).zip(out.chunks_mut(BATCH)) {
            let at = &mut at[..q.len()];
            match &self.search {
                Search::Tree(t) => t.floor_batch(q, at),
                Search::Binary(_) => {
                    for (a, &x) in at.iter_mut().zip(q) {
                        *a = self.floor_at(x);
                    }
                }
            }
            for ((o, a), &x) in o.iter_mut().zip(at.iter()).zip(q) {
                *o = a
                    .filter(|&a| match keep {
                        Keep::Floor => true,
                        Keep::Covering => self.covers(a, x),
                        Keep::Exact => self.key(a) == x,
                    })
                    .map(|a| self.row(a));
            }
        }
    }

    /// [`AddrLookup::floor`] for every query, into `out` (one slot per query): the descents
    /// run 32 at a time in lockstep.
    pub fn floor_batch(&self, qs: &[u64], out: &mut [Option<u32>]) {
        self.batch(qs, out, Keep::Floor);
    }

    /// [`AddrLookup::covering`] for every query, into `out` (one slot per query).
    pub fn covering_batch(&self, qs: &[u64], out: &mut [Option<u32>]) {
        self.batch(qs, out, Keep::Covering);
    }

    /// [`AddrLookup::exact`] for every query, into `out` (one slot per query): which call
    /// site, of many addresses at once.
    pub fn exact_batch(&self, qs: &[u64], out: &mut [Option<u32>]) {
        self.batch(qs, out, Keep::Exact);
    }
}